install.sh 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  1. #!/usr/bin/env bash
  2. #############################################################################
  3. # OpenAgents Installer
  4. # Interactive installer for OpenCode agents, commands, tools, and plugins
  5. #
  6. # Compatible with:
  7. # - macOS (bash 3.2+)
  8. # - Linux (bash 3.2+)
  9. # - Windows (Git Bash, WSL)
  10. #############################################################################
  11. set -e
  12. # Detect platform
  13. PLATFORM="$(uname -s)"
  14. case "$PLATFORM" in
  15. Linux*) PLATFORM="Linux";;
  16. Darwin*) PLATFORM="macOS";;
  17. CYGWIN*|MINGW*|MSYS*) PLATFORM="Windows";;
  18. *) PLATFORM="Unknown";;
  19. esac
  20. # Colors for output (disable on Windows if not supported)
  21. if [ "$PLATFORM" = "Windows" ] && [ -z "$WT_SESSION" ] && [ -z "$ConEmuPID" ]; then
  22. # Basic Windows terminal without color support
  23. RED=''
  24. GREEN=''
  25. YELLOW=''
  26. BLUE=''
  27. MAGENTA=''
  28. CYAN=''
  29. BOLD=''
  30. NC=''
  31. else
  32. RED='\033[0;31m'
  33. GREEN='\033[0;32m'
  34. YELLOW='\033[1;33m'
  35. BLUE='\033[0;34m'
  36. MAGENTA='\033[0;35m'
  37. CYAN='\033[0;36m'
  38. BOLD='\033[1m'
  39. NC='\033[0m' # No Color
  40. fi
  41. # Configuration
  42. REPO_URL="https://github.com/darrenhinde/OpenAgents"
  43. BRANCH="${OPENCODE_BRANCH:-main}" # Allow override via environment variable
  44. RAW_URL="https://raw.githubusercontent.com/darrenhinde/OpenAgents/${BRANCH}"
  45. # Registry URL - supports local fallback for development
  46. # Priority: 1) REGISTRY_URL env var, 2) Local registry.json, 3) Remote GitHub
  47. if [ -n "$REGISTRY_URL" ]; then
  48. # Use explicitly set REGISTRY_URL (for testing)
  49. :
  50. elif [ -f "./registry.json" ]; then
  51. # Use local registry.json if it exists (for development)
  52. REGISTRY_URL="file://$(pwd)/registry.json"
  53. else
  54. # Default to remote GitHub registry
  55. REGISTRY_URL="${RAW_URL}/registry.json"
  56. fi
  57. INSTALL_DIR="${OPENCODE_INSTALL_DIR:-.opencode}" # Allow override via environment variable
  58. TEMP_DIR="/tmp/opencode-installer-$$"
  59. # Cleanup temp directory on exit (success or failure)
  60. trap 'rm -rf "$TEMP_DIR" 2>/dev/null || true' EXIT INT TERM
  61. # Global variables
  62. SELECTED_COMPONENTS=()
  63. INSTALL_MODE=""
  64. PROFILE=""
  65. NON_INTERACTIVE=false
  66. CUSTOM_INSTALL_DIR="" # Set via --install-dir argument
  67. #############################################################################
  68. # Utility Functions
  69. #############################################################################
  70. jq_exec() {
  71. local output
  72. output=$(jq -r "$@")
  73. local ret=$?
  74. printf "%s\n" "$output" | tr -d '\r'
  75. return $ret
  76. }
  77. print_header() {
  78. echo -e "${CYAN}${BOLD}"
  79. echo "╔════════════════════════════════════════════════════════════════╗"
  80. echo "║ ║"
  81. echo "║ OpenAgents Installer v1.0.0 ║"
  82. echo "║ ║"
  83. echo "╚════════════════════════════════════════════════════════════════╝"
  84. echo -e "${NC}"
  85. }
  86. print_success() {
  87. echo -e "${GREEN}✓${NC} $1"
  88. }
  89. print_error() {
  90. echo -e "${RED}✗${NC} $1"
  91. }
  92. print_info() {
  93. echo -e "${BLUE}ℹ${NC} $1"
  94. }
  95. print_warning() {
  96. echo -e "${YELLOW}⚠${NC} $1"
  97. }
  98. print_step() {
  99. echo -e "\n${MAGENTA}${BOLD}▶${NC} $1\n"
  100. }
  101. #############################################################################
  102. # Path Handling (Cross-Platform)
  103. #############################################################################
  104. normalize_and_validate_path() {
  105. local input_path="$1"
  106. local normalized_path
  107. # Handle empty path
  108. if [ -z "$input_path" ]; then
  109. echo ""
  110. return 1
  111. fi
  112. # Expand tilde to $HOME (works on Linux, macOS, Windows Git Bash)
  113. if [[ $input_path == ~* ]]; then
  114. normalized_path="${HOME}${input_path:1}"
  115. else
  116. normalized_path="$input_path"
  117. fi
  118. # Convert backslashes to forward slashes (Windows compatibility)
  119. normalized_path="${normalized_path//\\//}"
  120. # Remove trailing slashes
  121. normalized_path="${normalized_path%/}"
  122. # If path is relative, make it absolute based on current directory
  123. if [[ ! "$normalized_path" = /* ]] && [[ ! "$normalized_path" =~ ^[A-Za-z]: ]]; then
  124. normalized_path="$(pwd)/${normalized_path}"
  125. fi
  126. echo "$normalized_path"
  127. return 0
  128. }
  129. validate_install_path() {
  130. local path="$1"
  131. local parent_dir
  132. # Get parent directory
  133. parent_dir="$(dirname "$path")"
  134. # Check if parent directory exists
  135. if [ ! -d "$parent_dir" ]; then
  136. print_error "Parent directory does not exist: $parent_dir"
  137. return 1
  138. fi
  139. # Check if parent directory is writable
  140. if [ ! -w "$parent_dir" ]; then
  141. print_error "No write permission for directory: $parent_dir"
  142. return 1
  143. fi
  144. # If target directory exists, check if it's writable
  145. if [ -d "$path" ] && [ ! -w "$path" ]; then
  146. print_error "No write permission for directory: $path"
  147. return 1
  148. fi
  149. return 0
  150. }
  151. get_global_install_path() {
  152. # Return platform-appropriate global installation path
  153. case "$PLATFORM" in
  154. macOS)
  155. # macOS: Use XDG standard (consistent with Linux)
  156. echo "${HOME}/.config/opencode"
  157. ;;
  158. Linux)
  159. echo "${HOME}/.config/opencode"
  160. ;;
  161. Windows)
  162. # Windows Git Bash/WSL: Use same as Linux
  163. echo "${HOME}/.config/opencode"
  164. ;;
  165. *)
  166. echo "${HOME}/.config/opencode"
  167. ;;
  168. esac
  169. }
  170. #############################################################################
  171. # Dependency Checks
  172. #############################################################################
  173. check_bash_version() {
  174. # Check bash version (need 3.2+)
  175. local bash_version="${BASH_VERSION%%.*}"
  176. if [ "$bash_version" -lt 3 ]; then
  177. echo "Error: This script requires Bash 3.2 or higher"
  178. echo "Current version: $BASH_VERSION"
  179. echo ""
  180. echo "Please upgrade bash or use a different shell:"
  181. echo " macOS: brew install bash"
  182. echo " Linux: Use your package manager to update bash"
  183. echo " Windows: Use Git Bash or WSL"
  184. exit 1
  185. fi
  186. }
  187. check_dependencies() {
  188. print_step "Checking dependencies..."
  189. local missing_deps=()
  190. if ! command -v curl &> /dev/null; then
  191. missing_deps+=("curl")
  192. fi
  193. if ! command -v jq &> /dev/null; then
  194. missing_deps+=("jq")
  195. fi
  196. if [ ${#missing_deps[@]} -ne 0 ]; then
  197. print_error "Missing required dependencies: ${missing_deps[*]}"
  198. echo ""
  199. echo "Please install them:"
  200. case "$PLATFORM" in
  201. macOS)
  202. echo " brew install ${missing_deps[*]}"
  203. ;;
  204. Linux)
  205. echo " Ubuntu/Debian: sudo apt-get install ${missing_deps[*]}"
  206. echo " Fedora/RHEL: sudo dnf install ${missing_deps[*]}"
  207. echo " Arch: sudo pacman -S ${missing_deps[*]}"
  208. ;;
  209. Windows)
  210. echo " Git Bash: Install via https://git-scm.com/"
  211. echo " WSL: sudo apt-get install ${missing_deps[*]}"
  212. echo " Scoop: scoop install ${missing_deps[*]}"
  213. ;;
  214. *)
  215. echo " Use your package manager to install: ${missing_deps[*]}"
  216. ;;
  217. esac
  218. exit 1
  219. fi
  220. print_success "All dependencies found"
  221. }
  222. #############################################################################
  223. # Registry Functions
  224. #############################################################################
  225. fetch_registry() {
  226. print_step "Fetching component registry..."
  227. mkdir -p "$TEMP_DIR"
  228. # Handle local file:// URLs
  229. if [[ "$REGISTRY_URL" == file://* ]]; then
  230. local local_path="${REGISTRY_URL#file://}"
  231. if [ -f "$local_path" ]; then
  232. cp "$local_path" "$TEMP_DIR/registry.json"
  233. print_success "Using local registry: $local_path"
  234. else
  235. print_error "Local registry not found: $local_path"
  236. exit 1
  237. fi
  238. else
  239. # Fetch from remote URL
  240. if ! curl -fsSL "$REGISTRY_URL" -o "$TEMP_DIR/registry.json"; then
  241. print_error "Failed to fetch registry from $REGISTRY_URL"
  242. exit 1
  243. fi
  244. print_success "Registry fetched successfully"
  245. fi
  246. }
  247. get_profile_components() {
  248. local profile=$1
  249. jq_exec ".profiles.${profile}.components[]" "$TEMP_DIR/registry.json"
  250. }
  251. get_component_info() {
  252. local component_id=$1
  253. local component_type=$2
  254. jq_exec ".components.${component_type}[] | select(.id == \"${component_id}\")" "$TEMP_DIR/registry.json"
  255. }
  256. # Helper function to get the correct registry key for a component type
  257. get_registry_key() {
  258. local type=$1
  259. # Most types are pluralized, but 'config' stays singular
  260. case "$type" in
  261. config) echo "config" ;;
  262. *) echo "${type}s" ;;
  263. esac
  264. }
  265. # Helper function to convert registry path to installation path
  266. # Registry paths are like ".opencode/agent/foo.md"
  267. # We need to replace ".opencode" with the actual INSTALL_DIR
  268. get_install_path() {
  269. local registry_path=$1
  270. # Strip leading .opencode/ if present
  271. local relative_path="${registry_path#.opencode/}"
  272. # Return INSTALL_DIR + relative path
  273. echo "${INSTALL_DIR}/${relative_path}"
  274. }
  275. resolve_dependencies() {
  276. local component=$1
  277. local type="${component%%:*}"
  278. local id="${component##*:}"
  279. # Get the correct registry key (handles singular/plural)
  280. local registry_key=$(get_registry_key "$type")
  281. # Get dependencies for this component
  282. local deps=$(jq_exec ".components.${registry_key}[] | select(.id == \"${id}\") | .dependencies[]?" "$TEMP_DIR/registry.json" 2>/dev/null || echo "")
  283. if [ -n "$deps" ]; then
  284. for dep in $deps; do
  285. # Add dependency if not already in list
  286. if [[ ! " ${SELECTED_COMPONENTS[@]} " =~ " ${dep} " ]]; then
  287. SELECTED_COMPONENTS+=("$dep")
  288. # Recursively resolve dependencies
  289. resolve_dependencies "$dep"
  290. fi
  291. done
  292. fi
  293. }
  294. #############################################################################
  295. # Installation Mode Selection
  296. #############################################################################
  297. check_interactive_mode() {
  298. # Check if stdin is a terminal (not piped from curl)
  299. if [ ! -t 0 ]; then
  300. print_header
  301. print_error "Interactive mode requires a terminal"
  302. echo ""
  303. echo "You're running this script in a pipe (e.g., curl | bash)"
  304. echo "For interactive mode, download the script first:"
  305. echo ""
  306. echo -e "${CYAN}# Download the script${NC}"
  307. echo "curl -fsSL https://raw.githubusercontent.com/darrenhinde/OpenAgents/main/install.sh -o install.sh"
  308. echo ""
  309. echo -e "${CYAN}# Run interactively${NC}"
  310. echo "bash install.sh"
  311. echo ""
  312. echo "Or use a profile directly:"
  313. echo ""
  314. echo -e "${CYAN}# Quick install with profile${NC}"
  315. echo "curl -fsSL https://raw.githubusercontent.com/darrenhinde/OpenAgents/main/install.sh | bash -s essential"
  316. echo ""
  317. echo "Available profiles: essential, developer, business, full, advanced"
  318. echo ""
  319. cleanup_and_exit 1
  320. fi
  321. }
  322. show_install_location_menu() {
  323. check_interactive_mode
  324. clear
  325. print_header
  326. local global_path=$(get_global_install_path)
  327. echo -e "${BOLD}Choose installation location:${NC}\n"
  328. echo -e " ${GREEN}1) Local${NC} - Install to ${CYAN}.opencode/${NC} in current directory"
  329. echo " (Best for project-specific agents)"
  330. echo ""
  331. echo -e " ${BLUE}2) Global${NC} - Install to ${CYAN}${global_path}${NC}"
  332. echo " (Best for user-wide agents available everywhere)"
  333. echo ""
  334. echo -e " ${MAGENTA}3) Custom${NC} - Enter exact path"
  335. echo " Examples:"
  336. case "$PLATFORM" in
  337. Windows)
  338. echo " ${CYAN}C:/Users/username/my-agents${NC} or ${CYAN}~/my-agents${NC}"
  339. ;;
  340. *)
  341. echo " ${CYAN}/home/username/my-agents${NC} or ${CYAN}~/my-agents${NC}"
  342. ;;
  343. esac
  344. echo ""
  345. echo " 4) Back / Exit"
  346. echo ""
  347. read -p "Enter your choice [1-4]: " location_choice
  348. case $location_choice in
  349. 1)
  350. INSTALL_DIR=".opencode"
  351. print_success "Installing to local directory: .opencode/"
  352. sleep 1
  353. ;;
  354. 2)
  355. INSTALL_DIR="$global_path"
  356. print_success "Installing to global directory: $global_path"
  357. sleep 1
  358. ;;
  359. 3)
  360. echo ""
  361. read -p "Enter installation path: " custom_path
  362. if [ -z "$custom_path" ]; then
  363. print_error "No path entered"
  364. sleep 2
  365. show_install_location_menu
  366. return
  367. fi
  368. local normalized_path=$(normalize_and_validate_path "$custom_path")
  369. if [ $? -ne 0 ]; then
  370. print_error "Invalid path"
  371. sleep 2
  372. show_install_location_menu
  373. return
  374. fi
  375. if ! validate_install_path "$normalized_path"; then
  376. echo ""
  377. read -p "Continue anyway? [y/N]: " continue_choice
  378. if [[ ! $continue_choice =~ ^[Yy] ]]; then
  379. show_install_location_menu
  380. return
  381. fi
  382. fi
  383. INSTALL_DIR="$normalized_path"
  384. print_success "Installing to custom directory: $INSTALL_DIR"
  385. sleep 1
  386. ;;
  387. 4)
  388. cleanup_and_exit 0
  389. ;;
  390. *)
  391. print_error "Invalid choice"
  392. sleep 2
  393. show_install_location_menu
  394. return
  395. ;;
  396. esac
  397. }
  398. show_main_menu() {
  399. check_interactive_mode
  400. clear
  401. print_header
  402. echo -e "${BOLD}Choose installation mode:${NC}\n"
  403. echo " 1) Quick Install (Choose a profile)"
  404. echo " 2) Custom Install (Pick individual components)"
  405. echo " 3) List Available Components"
  406. echo " 4) Exit"
  407. echo ""
  408. read -p "Enter your choice [1-4]: " choice
  409. case $choice in
  410. 1) INSTALL_MODE="profile" ;;
  411. 2) INSTALL_MODE="custom" ;;
  412. 3) list_components; show_main_menu ;;
  413. 4) cleanup_and_exit 0 ;;
  414. *) print_error "Invalid choice"; sleep 2; show_main_menu ;;
  415. esac
  416. }
  417. #############################################################################
  418. # Profile Installation
  419. #############################################################################
  420. show_profile_menu() {
  421. clear
  422. print_header
  423. echo -e "${BOLD}Available Installation Profiles:${NC}\n"
  424. # Essential profile
  425. local essential_name=$(jq_exec '.profiles.essential.name' "$TEMP_DIR/registry.json")
  426. local essential_desc=$(jq_exec '.profiles.essential.description' "$TEMP_DIR/registry.json")
  427. local essential_count=$(jq_exec '.profiles.essential.components | length' "$TEMP_DIR/registry.json")
  428. echo -e " ${GREEN}1) ${essential_name}${NC}"
  429. echo -e " ${essential_desc}"
  430. echo -e " Components: ${essential_count}\n"
  431. # Developer profile
  432. local dev_desc=$(jq_exec '.profiles.developer.description' "$TEMP_DIR/registry.json")
  433. local dev_count=$(jq_exec '.profiles.developer.components | length' "$TEMP_DIR/registry.json")
  434. local dev_badge=$(jq_exec '.profiles.developer.badge // ""' "$TEMP_DIR/registry.json")
  435. if [ -n "$dev_badge" ]; then
  436. echo -e " ${BLUE}2) Developer ${GREEN}[${dev_badge}]${NC}"
  437. else
  438. echo -e " ${BLUE}2) Developer${NC}"
  439. fi
  440. echo -e " ${dev_desc}"
  441. echo -e " Components: ${dev_count}\n"
  442. # Business profile
  443. local business_name=$(jq_exec '.profiles.business.name' "$TEMP_DIR/registry.json")
  444. local business_desc=$(jq_exec '.profiles.business.description' "$TEMP_DIR/registry.json")
  445. local business_count=$(jq_exec '.profiles.business.components | length' "$TEMP_DIR/registry.json")
  446. echo -e " ${CYAN}3) ${business_name}${NC}"
  447. echo -e " ${business_desc}"
  448. echo -e " Components: ${business_count}\n"
  449. # Full profile
  450. local full_name=$(jq_exec '.profiles.full.name' "$TEMP_DIR/registry.json")
  451. local full_desc=$(jq_exec '.profiles.full.description' "$TEMP_DIR/registry.json")
  452. local full_count=$(jq_exec '.profiles.full.components | length' "$TEMP_DIR/registry.json")
  453. echo -e " ${MAGENTA}4) ${full_name}${NC}"
  454. echo -e " ${full_desc}"
  455. echo -e " Components: ${full_count}\n"
  456. # Advanced profile
  457. local adv_name=$(jq_exec '.profiles.advanced.name' "$TEMP_DIR/registry.json")
  458. local adv_desc=$(jq_exec '.profiles.advanced.description' "$TEMP_DIR/registry.json")
  459. local adv_count=$(jq_exec '.profiles.advanced.components | length' "$TEMP_DIR/registry.json")
  460. echo -e " ${YELLOW}5) ${adv_name}${NC}"
  461. echo -e " ${adv_desc}"
  462. echo -e " Components: ${adv_count}\n"
  463. echo " 6) Back to main menu"
  464. echo ""
  465. read -p "Enter your choice [1-6]: " choice
  466. case $choice in
  467. 1) PROFILE="essential" ;;
  468. 2) PROFILE="developer" ;;
  469. 3) PROFILE="business" ;;
  470. 4) PROFILE="full" ;;
  471. 5) PROFILE="advanced" ;;
  472. 6) show_main_menu; return ;;
  473. *) print_error "Invalid choice"; sleep 2; show_profile_menu; return ;;
  474. esac
  475. # Load profile components (compatible with bash 3.2+)
  476. SELECTED_COMPONENTS=()
  477. local temp_file="$TEMP_DIR/components.tmp"
  478. get_profile_components "$PROFILE" > "$temp_file"
  479. while IFS= read -r component; do
  480. [ -n "$component" ] && SELECTED_COMPONENTS+=("$component")
  481. done < "$temp_file"
  482. show_installation_preview
  483. }
  484. #############################################################################
  485. # Custom Component Selection
  486. #############################################################################
  487. show_custom_menu() {
  488. clear
  489. print_header
  490. echo -e "${BOLD}Select component categories to install:${NC}\n"
  491. echo "Use space to toggle, Enter to continue"
  492. echo ""
  493. local categories=("agents" "subagents" "commands" "tools" "plugins" "contexts" "config")
  494. local selected_categories=()
  495. # Simple selection (for now, we'll make it interactive later)
  496. echo "Available categories:"
  497. for i in "${!categories[@]}"; do
  498. local cat="${categories[$i]}"
  499. local count=$(jq_exec ".components.${cat} | length" "$TEMP_DIR/registry.json")
  500. local cat_display=$(echo "$cat" | awk '{print toupper(substr($0,1,1)) tolower(substr($0,2))}')
  501. echo " $((i+1))) ${cat_display} (${count} available)"
  502. done
  503. echo " $((${#categories[@]}+1))) Select All"
  504. echo " $((${#categories[@]}+2))) Continue to component selection"
  505. echo " $((${#categories[@]}+3))) Back to main menu"
  506. echo ""
  507. read -p "Enter category numbers (space-separated) or option: " -a selections
  508. for sel in "${selections[@]}"; do
  509. if [ "$sel" -eq $((${#categories[@]}+1)) ]; then
  510. selected_categories=("${categories[@]}")
  511. break
  512. elif [ "$sel" -eq $((${#categories[@]}+2)) ]; then
  513. break
  514. elif [ "$sel" -eq $((${#categories[@]}+3)) ]; then
  515. show_main_menu
  516. return
  517. elif [ "$sel" -ge 1 ] && [ "$sel" -le ${#categories[@]} ]; then
  518. selected_categories+=("${categories[$((sel-1))]}")
  519. fi
  520. done
  521. if [ ${#selected_categories[@]} -eq 0 ]; then
  522. print_warning "No categories selected"
  523. sleep 2
  524. show_custom_menu
  525. return
  526. fi
  527. show_component_selection "${selected_categories[@]}"
  528. }
  529. show_component_selection() {
  530. local categories=("$@")
  531. clear
  532. print_header
  533. echo -e "${BOLD}Select components to install:${NC}\n"
  534. local all_components=()
  535. local component_details=()
  536. for category in "${categories[@]}"; do
  537. local cat_display=$(echo "$category" | awk '{print toupper(substr($0,1,1)) tolower(substr($0,2))}')
  538. echo -e "${CYAN}${BOLD}${cat_display}:${NC}"
  539. local components=$(jq_exec ".components.${category}[] | .id" "$TEMP_DIR/registry.json")
  540. local idx=1
  541. while IFS= read -r comp_id; do
  542. local comp_name=$(jq_exec ".components.${category}[] | select(.id == \"${comp_id}\") | .name" "$TEMP_DIR/registry.json")
  543. local comp_desc=$(jq_exec ".components.${category}[] | select(.id == \"${comp_id}\") | .description" "$TEMP_DIR/registry.json")
  544. echo " ${idx}) ${comp_name}"
  545. echo " ${comp_desc}"
  546. all_components+=("${category}:${comp_id}")
  547. component_details+=("${comp_name}|${comp_desc}")
  548. idx=$((idx+1))
  549. done <<< "$components"
  550. echo ""
  551. done
  552. echo "Enter component numbers (space-separated), 'all' for all, or 'done' to continue:"
  553. read -a selections
  554. for sel in "${selections[@]}"; do
  555. if [ "$sel" = "all" ]; then
  556. SELECTED_COMPONENTS=("${all_components[@]}")
  557. break
  558. elif [ "$sel" = "done" ]; then
  559. break
  560. elif [ "$sel" -ge 1 ] && [ "$sel" -le ${#all_components[@]} ]; then
  561. SELECTED_COMPONENTS+=("${all_components[$((sel-1))]}")
  562. fi
  563. done
  564. if [ ${#SELECTED_COMPONENTS[@]} -eq 0 ]; then
  565. print_warning "No components selected"
  566. sleep 2
  567. show_custom_menu
  568. return
  569. fi
  570. # Resolve dependencies
  571. print_step "Resolving dependencies..."
  572. local original_count=${#SELECTED_COMPONENTS[@]}
  573. for comp in "${SELECTED_COMPONENTS[@]}"; do
  574. resolve_dependencies "$comp"
  575. done
  576. if [ ${#SELECTED_COMPONENTS[@]} -gt $original_count ]; then
  577. print_info "Added $((${#SELECTED_COMPONENTS[@]} - original_count)) dependencies"
  578. fi
  579. show_installation_preview
  580. }
  581. #############################################################################
  582. # Installation Preview & Confirmation
  583. #############################################################################
  584. show_installation_preview() {
  585. # Only clear screen in interactive mode
  586. if [ "$NON_INTERACTIVE" != true ]; then
  587. clear
  588. fi
  589. print_header
  590. echo -e "${BOLD}Installation Preview${NC}\n"
  591. if [ -n "$PROFILE" ]; then
  592. echo -e "Profile: ${GREEN}${PROFILE}${NC}"
  593. else
  594. echo -e "Mode: ${GREEN}Custom${NC}"
  595. fi
  596. echo -e "Installation directory: ${CYAN}${INSTALL_DIR}${NC}"
  597. echo -e "\nComponents to install (${#SELECTED_COMPONENTS[@]} total):\n"
  598. # Group by type
  599. local agents=()
  600. local subagents=()
  601. local commands=()
  602. local tools=()
  603. local plugins=()
  604. local contexts=()
  605. local configs=()
  606. for comp in "${SELECTED_COMPONENTS[@]}"; do
  607. local type="${comp%%:*}"
  608. case $type in
  609. agent) agents+=("$comp") ;;
  610. subagent) subagents+=("$comp") ;;
  611. command) commands+=("$comp") ;;
  612. tool) tools+=("$comp") ;;
  613. plugin) plugins+=("$comp") ;;
  614. context) contexts+=("$comp") ;;
  615. config) configs+=("$comp") ;;
  616. esac
  617. done
  618. [ ${#agents[@]} -gt 0 ] && echo -e "${CYAN}Agents (${#agents[@]}):${NC} ${agents[*]##*:}"
  619. [ ${#subagents[@]} -gt 0 ] && echo -e "${CYAN}Subagents (${#subagents[@]}):${NC} ${subagents[*]##*:}"
  620. [ ${#commands[@]} -gt 0 ] && echo -e "${CYAN}Commands (${#commands[@]}):${NC} ${commands[*]##*:}"
  621. [ ${#tools[@]} -gt 0 ] && echo -e "${CYAN}Tools (${#tools[@]}):${NC} ${tools[*]##*:}"
  622. [ ${#plugins[@]} -gt 0 ] && echo -e "${CYAN}Plugins (${#plugins[@]}):${NC} ${plugins[*]##*:}"
  623. [ ${#contexts[@]} -gt 0 ] && echo -e "${CYAN}Contexts (${#contexts[@]}):${NC} ${contexts[*]##*:}"
  624. [ ${#configs[@]} -gt 0 ] && echo -e "${CYAN}Config (${#configs[@]}):${NC} ${configs[*]##*:}"
  625. echo ""
  626. # Skip confirmation if profile was provided via command line
  627. if [ "$NON_INTERACTIVE" = true ]; then
  628. print_info "Installing automatically (profile specified)..."
  629. perform_installation
  630. else
  631. read -p "Proceed with installation? [Y/n]: " confirm
  632. if [[ $confirm =~ ^[Nn] ]]; then
  633. print_info "Installation cancelled"
  634. cleanup_and_exit 0
  635. fi
  636. perform_installation
  637. fi
  638. }
  639. #############################################################################
  640. # Collision Detection
  641. #############################################################################
  642. show_collision_report() {
  643. local collision_count=$1
  644. shift
  645. local collisions=("$@")
  646. echo ""
  647. print_warning "Found ${collision_count} file collision(s):"
  648. echo ""
  649. # Group by type
  650. local agents=()
  651. local subagents=()
  652. local commands=()
  653. local tools=()
  654. local plugins=()
  655. local contexts=()
  656. local configs=()
  657. for file in "${collisions[@]}"; do
  658. # Skip empty entries
  659. [ -z "$file" ] && continue
  660. if [[ $file == *"/agent/subagents/"* ]]; then
  661. subagents+=("$file")
  662. elif [[ $file == *"/agent/"* ]]; then
  663. agents+=("$file")
  664. elif [[ $file == *"/command/"* ]]; then
  665. commands+=("$file")
  666. elif [[ $file == *"/tool/"* ]]; then
  667. tools+=("$file")
  668. elif [[ $file == *"/plugin/"* ]]; then
  669. plugins+=("$file")
  670. elif [[ $file == *"/context/"* ]]; then
  671. contexts+=("$file")
  672. else
  673. configs+=("$file")
  674. fi
  675. done
  676. # Display grouped collisions
  677. [ ${#agents[@]} -gt 0 ] && echo -e "${YELLOW} Agents (${#agents[@]}):${NC}" && printf ' %s\n' "${agents[@]}"
  678. [ ${#subagents[@]} -gt 0 ] && echo -e "${YELLOW} Subagents (${#subagents[@]}):${NC}" && printf ' %s\n' "${subagents[@]}"
  679. [ ${#commands[@]} -gt 0 ] && echo -e "${YELLOW} Commands (${#commands[@]}):${NC}" && printf ' %s\n' "${commands[@]}"
  680. [ ${#tools[@]} -gt 0 ] && echo -e "${YELLOW} Tools (${#tools[@]}):${NC}" && printf ' %s\n' "${tools[@]}"
  681. [ ${#plugins[@]} -gt 0 ] && echo -e "${YELLOW} Plugins (${#plugins[@]}):${NC}" && printf ' %s\n' "${plugins[@]}"
  682. [ ${#contexts[@]} -gt 0 ] && echo -e "${YELLOW} Context (${#contexts[@]}):${NC}" && printf ' %s\n' "${contexts[@]}"
  683. [ ${#configs[@]} -gt 0 ] && echo -e "${YELLOW} Config (${#configs[@]}):${NC}" && printf ' %s\n' "${configs[@]}"
  684. echo ""
  685. }
  686. get_install_strategy() {
  687. echo -e "${BOLD}How would you like to proceed?${NC}\n" >&2
  688. echo " 1) ${GREEN}Skip existing${NC} - Only install new files, keep all existing files unchanged" >&2
  689. echo " 2) ${YELLOW}Overwrite all${NC} - Replace existing files with new versions (your changes will be lost)" >&2
  690. echo " 3) ${CYAN}Backup & overwrite${NC} - Backup existing files, then install new versions" >&2
  691. echo " 4) ${RED}Cancel${NC} - Exit without making changes" >&2
  692. echo "" >&2
  693. read -p "Enter your choice [1-4]: " strategy_choice
  694. case $strategy_choice in
  695. 1) echo "skip" ;;
  696. 2)
  697. echo "" >&2
  698. print_warning "This will overwrite existing files. Your changes will be lost!"
  699. read -p "Are you sure? Type 'yes' to confirm: " confirm
  700. if [ "$confirm" = "yes" ]; then
  701. echo "overwrite"
  702. else
  703. echo "cancel"
  704. fi
  705. ;;
  706. 3) echo "backup" ;;
  707. 4) echo "cancel" ;;
  708. *) echo "cancel" ;;
  709. esac
  710. }
  711. #############################################################################
  712. # Installation
  713. #############################################################################
  714. perform_installation() {
  715. print_step "Preparing installation..."
  716. # Create base directory only - subdirectories created on-demand when files are installed
  717. mkdir -p "$INSTALL_DIR"
  718. # Check for collisions
  719. local collisions=()
  720. for comp in "${SELECTED_COMPONENTS[@]}"; do
  721. local type="${comp%%:*}"
  722. local id="${comp##*:}"
  723. local registry_key=$(get_registry_key "$type")
  724. local path=$(jq_exec ".components.${registry_key}[] | select(.id == \"${id}\") | .path" "$TEMP_DIR/registry.json")
  725. if [ -n "$path" ] && [ "$path" != "null" ]; then
  726. local install_path=$(get_install_path "$path")
  727. if [ -f "$install_path" ]; then
  728. collisions+=("$install_path")
  729. fi
  730. fi
  731. done
  732. # Determine installation strategy
  733. local install_strategy="fresh"
  734. if [ ${#collisions[@]} -gt 0 ]; then
  735. show_collision_report ${#collisions[@]} "${collisions[@]}"
  736. install_strategy=$(get_install_strategy)
  737. if [ "$install_strategy" = "cancel" ]; then
  738. print_info "Installation cancelled by user"
  739. cleanup_and_exit 0
  740. fi
  741. # Handle backup strategy
  742. if [ "$install_strategy" = "backup" ]; then
  743. local backup_dir="${INSTALL_DIR}.backup.$(date +%Y%m%d-%H%M%S)"
  744. print_step "Creating backup..."
  745. # Only backup files that will be overwritten
  746. local backup_count=0
  747. for file in "${collisions[@]}"; do
  748. if [ -f "$file" ]; then
  749. local backup_file="${backup_dir}/${file}"
  750. mkdir -p "$(dirname "$backup_file")"
  751. if cp "$file" "$backup_file" 2>/dev/null; then
  752. backup_count=$((backup_count + 1))
  753. else
  754. print_warning "Failed to backup: $file"
  755. fi
  756. fi
  757. done
  758. if [ $backup_count -gt 0 ]; then
  759. print_success "Backed up ${backup_count} file(s) to $backup_dir"
  760. install_strategy="overwrite" # Now we can overwrite
  761. else
  762. print_error "Backup failed. Installation cancelled."
  763. cleanup_and_exit 1
  764. fi
  765. fi
  766. fi
  767. # Perform installation
  768. print_step "Installing components..."
  769. local installed=0
  770. local skipped=0
  771. local failed=0
  772. for comp in "${SELECTED_COMPONENTS[@]}"; do
  773. local type="${comp%%:*}"
  774. local id="${comp##*:}"
  775. # Get the correct registry key (handles singular/plural)
  776. local registry_key=$(get_registry_key "$type")
  777. # Get component path
  778. local path=$(jq_exec ".components.${registry_key}[] | select(.id == \"${id}\") | .path" "$TEMP_DIR/registry.json")
  779. if [ -z "$path" ] || [ "$path" = "null" ]; then
  780. print_warning "Could not find path for ${comp}"
  781. failed=$((failed + 1))
  782. continue
  783. fi
  784. # Convert registry path to installation path
  785. local dest=$(get_install_path "$path")
  786. # Check if file exists before we install (for proper messaging)
  787. local file_existed=false
  788. if [ -f "$dest" ]; then
  789. file_existed=true
  790. fi
  791. # Check if file exists and we're in skip mode
  792. if [ "$file_existed" = true ] && [ "$install_strategy" = "skip" ]; then
  793. print_info "Skipped existing: ${type}:${id}"
  794. skipped=$((skipped + 1))
  795. continue
  796. fi
  797. # Download component
  798. local url="${RAW_URL}/${path}"
  799. # Create parent directory if needed
  800. mkdir -p "$(dirname "$dest")"
  801. if curl -fsSL "$url" -o "$dest"; then
  802. # Transform paths for global installation (any non-local path)
  803. # Local paths: .opencode or */.opencode
  804. if [[ "$INSTALL_DIR" != ".opencode" ]] && [[ "$INSTALL_DIR" != *"/.opencode" ]]; then
  805. # Expand tilde and get absolute path for transformation
  806. local expanded_path="${INSTALL_DIR/#\~/$HOME}"
  807. # Transform @.opencode/context/ references to actual install path
  808. sed -i.bak -e "s|@\.opencode/context/|@${expanded_path}/context/|g" \
  809. -e "s|\.opencode/context|${expanded_path}/context|g" "$dest" 2>/dev/null || true
  810. rm -f "${dest}.bak" 2>/dev/null || true
  811. fi
  812. # Show appropriate message based on whether file existed before
  813. if [ "$file_existed" = true ]; then
  814. print_success "Updated ${type}: ${id}"
  815. else
  816. print_success "Installed ${type}: ${id}"
  817. fi
  818. installed=$((installed + 1))
  819. else
  820. print_error "Failed to install ${type}: ${id}"
  821. failed=$((failed + 1))
  822. fi
  823. done
  824. # Handle additional paths for advanced profile
  825. if [ "$PROFILE" = "advanced" ]; then
  826. local additional_paths=$(jq_exec '.profiles.advanced.additionalPaths[]?' "$TEMP_DIR/registry.json")
  827. if [ -n "$additional_paths" ]; then
  828. print_step "Installing additional paths..."
  829. while IFS= read -r path; do
  830. # For directories, we'd need to recursively download
  831. # For now, just note them
  832. print_info "Additional path: $path (manual download required)"
  833. done <<< "$additional_paths"
  834. fi
  835. fi
  836. echo ""
  837. print_success "Installation complete!"
  838. echo -e " Installed: ${GREEN}${installed}${NC}"
  839. [ $skipped -gt 0 ] && echo -e " Skipped: ${CYAN}${skipped}${NC}"
  840. [ $failed -gt 0 ] && echo -e " Failed: ${RED}${failed}${NC}"
  841. show_post_install
  842. }
  843. #############################################################################
  844. # Post-Installation
  845. #############################################################################
  846. show_post_install() {
  847. echo ""
  848. print_step "Next Steps"
  849. echo "1. Review the installed components in ${CYAN}${INSTALL_DIR}/${NC}"
  850. # Check if env.example was installed
  851. if [ -f "${INSTALL_DIR}/env.example" ] || [ -f "env.example" ]; then
  852. echo "2. Copy env.example to .env and configure:"
  853. echo " ${CYAN}cp env.example .env${NC}"
  854. echo "3. Start using OpenCode agents:"
  855. else
  856. echo "2. Start using OpenCode agents:"
  857. fi
  858. echo " ${CYAN}opencode${NC}"
  859. echo ""
  860. # Show installation location info
  861. print_info "Installation directory: ${CYAN}${INSTALL_DIR}${NC}"
  862. if [ -d "${INSTALL_DIR}.backup."* ] 2>/dev/null; then
  863. print_info "Backup created - you can restore files from ${INSTALL_DIR}.backup.* if needed"
  864. fi
  865. print_info "Documentation: ${REPO_URL}"
  866. echo ""
  867. cleanup_and_exit 0
  868. }
  869. #############################################################################
  870. # Component Listing
  871. #############################################################################
  872. list_components() {
  873. clear
  874. print_header
  875. echo -e "${BOLD}Available Components${NC}\n"
  876. local categories=("agents" "subagents" "commands" "tools" "plugins" "contexts")
  877. for category in "${categories[@]}"; do
  878. local cat_display=$(echo "$category" | awk '{print toupper(substr($0,1,1)) tolower(substr($0,2))}')
  879. echo -e "${CYAN}${BOLD}${cat_display}:${NC}"
  880. local components=$(jq_exec ".components.${category}[] | \"\(.id)|\(.name)|\(.description)\"" "$TEMP_DIR/registry.json")
  881. while IFS='|' read -r id name desc; do
  882. echo -e " ${GREEN}${name}${NC} (${id})"
  883. echo -e " ${desc}"
  884. done <<< "$components"
  885. echo ""
  886. done
  887. read -p "Press Enter to continue..."
  888. }
  889. #############################################################################
  890. # Cleanup
  891. #############################################################################
  892. cleanup_and_exit() {
  893. rm -rf "$TEMP_DIR"
  894. exit "$1"
  895. }
  896. trap 'cleanup_and_exit 1' INT TERM
  897. #############################################################################
  898. # Main
  899. #############################################################################
  900. main() {
  901. # Parse command line arguments
  902. while [ $# -gt 0 ]; do
  903. case "$1" in
  904. --install-dir=*)
  905. CUSTOM_INSTALL_DIR="${1#*=}"
  906. # Basic validation - check not empty
  907. if [ -z "$CUSTOM_INSTALL_DIR" ]; then
  908. echo "Error: --install-dir requires a non-empty path"
  909. exit 1
  910. fi
  911. shift
  912. ;;
  913. --install-dir)
  914. if [ -n "$2" ] && [ "${2:0:1}" != "-" ]; then
  915. CUSTOM_INSTALL_DIR="$2"
  916. shift 2
  917. else
  918. echo "Error: --install-dir requires a path argument"
  919. exit 1
  920. fi
  921. ;;
  922. essential|--essential)
  923. INSTALL_MODE="profile"
  924. PROFILE="essential"
  925. NON_INTERACTIVE=true
  926. shift
  927. ;;
  928. developer|--developer)
  929. INSTALL_MODE="profile"
  930. PROFILE="developer"
  931. NON_INTERACTIVE=true
  932. shift
  933. ;;
  934. business|--business)
  935. INSTALL_MODE="profile"
  936. PROFILE="business"
  937. NON_INTERACTIVE=true
  938. shift
  939. ;;
  940. full|--full)
  941. INSTALL_MODE="profile"
  942. PROFILE="full"
  943. NON_INTERACTIVE=true
  944. shift
  945. ;;
  946. advanced|--advanced)
  947. INSTALL_MODE="profile"
  948. PROFILE="advanced"
  949. NON_INTERACTIVE=true
  950. shift
  951. ;;
  952. list|--list)
  953. check_dependencies
  954. fetch_registry
  955. list_components
  956. cleanup_and_exit 0
  957. ;;
  958. --help|-h|help)
  959. print_header
  960. echo "Usage: $0 [PROFILE] [OPTIONS]"
  961. echo ""
  962. echo -e "${BOLD}Profiles:${NC}"
  963. echo " essential, --essential Minimal setup with core agents"
  964. echo " developer, --developer Code-focused development tools"
  965. echo " business, --business Content and business-focused tools"
  966. echo " full, --full Everything except system-builder"
  967. echo " advanced, --advanced Complete system with all components"
  968. echo ""
  969. echo -e "${BOLD}Options:${NC}"
  970. echo " --install-dir PATH Custom installation directory"
  971. echo " (default: .opencode)"
  972. echo " list, --list List all available components"
  973. echo " help, --help, -h Show this help message"
  974. echo ""
  975. echo -e "${BOLD}Environment Variables:${NC}"
  976. echo " OPENCODE_INSTALL_DIR Installation directory"
  977. echo " OPENCODE_BRANCH Git branch to install from (default: main)"
  978. echo ""
  979. echo -e "${BOLD}Examples:${NC}"
  980. echo ""
  981. echo " ${CYAN}# Interactive mode (choose location and components)${NC}"
  982. echo " $0"
  983. echo ""
  984. echo " ${CYAN}# Quick install with default location (.opencode/)${NC}"
  985. echo " $0 developer"
  986. echo ""
  987. echo " ${CYAN}# Install to global location (Linux/macOS)${NC}"
  988. echo " $0 developer --install-dir ~/.config/opencode"
  989. echo ""
  990. echo " ${CYAN}# Install to global location (Windows Git Bash)${NC}"
  991. echo " $0 developer --install-dir ~/.config/opencode"
  992. echo ""
  993. echo " ${CYAN}# Install to custom location${NC}"
  994. echo " $0 essential --install-dir ~/my-agents"
  995. echo ""
  996. echo " ${CYAN}# Using environment variable${NC}"
  997. echo " export OPENCODE_INSTALL_DIR=~/.config/opencode"
  998. echo " $0 developer"
  999. echo ""
  1000. echo " ${CYAN}# Install from URL (non-interactive)${NC}"
  1001. echo " curl -fsSL https://raw.githubusercontent.com/darrenhinde/OpenAgents/main/install.sh | bash -s developer"
  1002. echo ""
  1003. echo -e "${BOLD}Platform Support:${NC}"
  1004. echo " ✓ Linux (bash 3.2+)"
  1005. echo " ✓ macOS (bash 3.2+)"
  1006. echo " ✓ Windows (Git Bash, WSL)"
  1007. echo ""
  1008. exit 0
  1009. ;;
  1010. *)
  1011. echo "Unknown option: $1"
  1012. echo "Run '$0 --help' for usage information"
  1013. exit 1
  1014. ;;
  1015. esac
  1016. done
  1017. # Apply custom install directory if specified (CLI arg overrides env var)
  1018. if [ -n "$CUSTOM_INSTALL_DIR" ]; then
  1019. local normalized_path=$(normalize_and_validate_path "$CUSTOM_INSTALL_DIR")
  1020. if [ $? -eq 0 ]; then
  1021. INSTALL_DIR="$normalized_path"
  1022. if ! validate_install_path "$INSTALL_DIR"; then
  1023. print_warning "Installation path may have issues, but continuing..."
  1024. fi
  1025. else
  1026. print_error "Invalid installation directory: $CUSTOM_INSTALL_DIR"
  1027. exit 1
  1028. fi
  1029. fi
  1030. check_bash_version
  1031. check_dependencies
  1032. fetch_registry
  1033. if [ -n "$PROFILE" ]; then
  1034. # Non-interactive mode (compatible with bash 3.2+)
  1035. SELECTED_COMPONENTS=()
  1036. local temp_file="$TEMP_DIR/components.tmp"
  1037. get_profile_components "$PROFILE" > "$temp_file"
  1038. while IFS= read -r component; do
  1039. [ -n "$component" ] && SELECTED_COMPONENTS+=("$component")
  1040. done < "$temp_file"
  1041. show_installation_preview
  1042. else
  1043. # Interactive mode - show location menu first
  1044. show_install_location_menu
  1045. show_main_menu
  1046. if [ "$INSTALL_MODE" = "profile" ]; then
  1047. show_profile_menu
  1048. elif [ "$INSTALL_MODE" = "custom" ]; then
  1049. show_custom_menu
  1050. fi
  1051. fi
  1052. }
  1053. main "$@"