install.sh 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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. # In non-interactive mode, use default strategy (skip existing files)
  736. if [ "$NON_INTERACTIVE" = true ]; then
  737. print_info "Found ${#collisions[@]} existing file(s) - using 'skip' strategy (non-interactive mode)"
  738. print_info "To overwrite, download script and run interactively, or delete existing files first"
  739. install_strategy="skip"
  740. else
  741. show_collision_report ${#collisions[@]} "${collisions[@]}"
  742. install_strategy=$(get_install_strategy)
  743. if [ "$install_strategy" = "cancel" ]; then
  744. print_info "Installation cancelled by user"
  745. cleanup_and_exit 0
  746. fi
  747. fi
  748. # Handle backup strategy
  749. if [ "$install_strategy" = "backup" ]; then
  750. local backup_dir="${INSTALL_DIR}.backup.$(date +%Y%m%d-%H%M%S)"
  751. print_step "Creating backup..."
  752. # Only backup files that will be overwritten
  753. local backup_count=0
  754. for file in "${collisions[@]}"; do
  755. if [ -f "$file" ]; then
  756. local backup_file="${backup_dir}/${file}"
  757. mkdir -p "$(dirname "$backup_file")"
  758. if cp "$file" "$backup_file" 2>/dev/null; then
  759. backup_count=$((backup_count + 1))
  760. else
  761. print_warning "Failed to backup: $file"
  762. fi
  763. fi
  764. done
  765. if [ $backup_count -gt 0 ]; then
  766. print_success "Backed up ${backup_count} file(s) to $backup_dir"
  767. install_strategy="overwrite" # Now we can overwrite
  768. else
  769. print_error "Backup failed. Installation cancelled."
  770. cleanup_and_exit 1
  771. fi
  772. fi
  773. fi
  774. # Perform installation
  775. print_step "Installing components..."
  776. local installed=0
  777. local skipped=0
  778. local failed=0
  779. for comp in "${SELECTED_COMPONENTS[@]}"; do
  780. local type="${comp%%:*}"
  781. local id="${comp##*:}"
  782. # Get the correct registry key (handles singular/plural)
  783. local registry_key=$(get_registry_key "$type")
  784. # Get component path
  785. local path=$(jq_exec ".components.${registry_key}[] | select(.id == \"${id}\") | .path" "$TEMP_DIR/registry.json")
  786. if [ -z "$path" ] || [ "$path" = "null" ]; then
  787. print_warning "Could not find path for ${comp}"
  788. failed=$((failed + 1))
  789. continue
  790. fi
  791. # Convert registry path to installation path
  792. local dest=$(get_install_path "$path")
  793. # Check if file exists before we install (for proper messaging)
  794. local file_existed=false
  795. if [ -f "$dest" ]; then
  796. file_existed=true
  797. fi
  798. # Check if file exists and we're in skip mode
  799. if [ "$file_existed" = true ] && [ "$install_strategy" = "skip" ]; then
  800. print_info "Skipped existing: ${type}:${id}"
  801. skipped=$((skipped + 1))
  802. continue
  803. fi
  804. # Download component
  805. local url="${RAW_URL}/${path}"
  806. # Create parent directory if needed
  807. mkdir -p "$(dirname "$dest")"
  808. if curl -fsSL "$url" -o "$dest"; then
  809. # Transform paths for global installation (any non-local path)
  810. # Local paths: .opencode or */.opencode
  811. if [[ "$INSTALL_DIR" != ".opencode" ]] && [[ "$INSTALL_DIR" != *"/.opencode" ]]; then
  812. # Expand tilde and get absolute path for transformation
  813. local expanded_path="${INSTALL_DIR/#\~/$HOME}"
  814. # Transform @.opencode/context/ references to actual install path
  815. sed -i.bak -e "s|@\.opencode/context/|@${expanded_path}/context/|g" \
  816. -e "s|\.opencode/context|${expanded_path}/context|g" "$dest" 2>/dev/null || true
  817. rm -f "${dest}.bak" 2>/dev/null || true
  818. fi
  819. # Show appropriate message based on whether file existed before
  820. if [ "$file_existed" = true ]; then
  821. print_success "Updated ${type}: ${id}"
  822. else
  823. print_success "Installed ${type}: ${id}"
  824. fi
  825. installed=$((installed + 1))
  826. else
  827. print_error "Failed to install ${type}: ${id}"
  828. failed=$((failed + 1))
  829. fi
  830. done
  831. # Handle additional paths for advanced profile
  832. if [ "$PROFILE" = "advanced" ]; then
  833. local additional_paths=$(jq_exec '.profiles.advanced.additionalPaths[]?' "$TEMP_DIR/registry.json")
  834. if [ -n "$additional_paths" ]; then
  835. print_step "Installing additional paths..."
  836. while IFS= read -r path; do
  837. # For directories, we'd need to recursively download
  838. # For now, just note them
  839. print_info "Additional path: $path (manual download required)"
  840. done <<< "$additional_paths"
  841. fi
  842. fi
  843. echo ""
  844. print_success "Installation complete!"
  845. echo -e " Installed: ${GREEN}${installed}${NC}"
  846. [ $skipped -gt 0 ] && echo -e " Skipped: ${CYAN}${skipped}${NC}"
  847. [ $failed -gt 0 ] && echo -e " Failed: ${RED}${failed}${NC}"
  848. show_post_install
  849. }
  850. #############################################################################
  851. # Post-Installation
  852. #############################################################################
  853. show_post_install() {
  854. echo ""
  855. print_step "Next Steps"
  856. echo "1. Review the installed components in ${CYAN}${INSTALL_DIR}/${NC}"
  857. # Check if env.example was installed
  858. if [ -f "${INSTALL_DIR}/env.example" ] || [ -f "env.example" ]; then
  859. echo "2. Copy env.example to .env and configure:"
  860. echo " ${CYAN}cp env.example .env${NC}"
  861. echo "3. Start using OpenCode agents:"
  862. else
  863. echo "2. Start using OpenCode agents:"
  864. fi
  865. echo " ${CYAN}opencode${NC}"
  866. echo ""
  867. # Show installation location info
  868. print_info "Installation directory: ${CYAN}${INSTALL_DIR}${NC}"
  869. if [ -d "${INSTALL_DIR}.backup."* ] 2>/dev/null; then
  870. print_info "Backup created - you can restore files from ${INSTALL_DIR}.backup.* if needed"
  871. fi
  872. print_info "Documentation: ${REPO_URL}"
  873. echo ""
  874. cleanup_and_exit 0
  875. }
  876. #############################################################################
  877. # Component Listing
  878. #############################################################################
  879. list_components() {
  880. clear
  881. print_header
  882. echo -e "${BOLD}Available Components${NC}\n"
  883. local categories=("agents" "subagents" "commands" "tools" "plugins" "contexts")
  884. for category in "${categories[@]}"; do
  885. local cat_display=$(echo "$category" | awk '{print toupper(substr($0,1,1)) tolower(substr($0,2))}')
  886. echo -e "${CYAN}${BOLD}${cat_display}:${NC}"
  887. local components=$(jq_exec ".components.${category}[] | \"\(.id)|\(.name)|\(.description)\"" "$TEMP_DIR/registry.json")
  888. while IFS='|' read -r id name desc; do
  889. echo -e " ${GREEN}${name}${NC} (${id})"
  890. echo -e " ${desc}"
  891. done <<< "$components"
  892. echo ""
  893. done
  894. read -p "Press Enter to continue..."
  895. }
  896. #############################################################################
  897. # Cleanup
  898. #############################################################################
  899. cleanup_and_exit() {
  900. rm -rf "$TEMP_DIR"
  901. exit "$1"
  902. }
  903. trap 'cleanup_and_exit 1' INT TERM
  904. #############################################################################
  905. # Main
  906. #############################################################################
  907. main() {
  908. # Parse command line arguments
  909. while [ $# -gt 0 ]; do
  910. case "$1" in
  911. --install-dir=*)
  912. CUSTOM_INSTALL_DIR="${1#*=}"
  913. # Basic validation - check not empty
  914. if [ -z "$CUSTOM_INSTALL_DIR" ]; then
  915. echo "Error: --install-dir requires a non-empty path"
  916. exit 1
  917. fi
  918. shift
  919. ;;
  920. --install-dir)
  921. if [ -n "$2" ] && [ "${2:0:1}" != "-" ]; then
  922. CUSTOM_INSTALL_DIR="$2"
  923. shift 2
  924. else
  925. echo "Error: --install-dir requires a path argument"
  926. exit 1
  927. fi
  928. ;;
  929. essential|--essential)
  930. INSTALL_MODE="profile"
  931. PROFILE="essential"
  932. NON_INTERACTIVE=true
  933. shift
  934. ;;
  935. developer|--developer)
  936. INSTALL_MODE="profile"
  937. PROFILE="developer"
  938. NON_INTERACTIVE=true
  939. shift
  940. ;;
  941. business|--business)
  942. INSTALL_MODE="profile"
  943. PROFILE="business"
  944. NON_INTERACTIVE=true
  945. shift
  946. ;;
  947. full|--full)
  948. INSTALL_MODE="profile"
  949. PROFILE="full"
  950. NON_INTERACTIVE=true
  951. shift
  952. ;;
  953. advanced|--advanced)
  954. INSTALL_MODE="profile"
  955. PROFILE="advanced"
  956. NON_INTERACTIVE=true
  957. shift
  958. ;;
  959. list|--list)
  960. check_dependencies
  961. fetch_registry
  962. list_components
  963. cleanup_and_exit 0
  964. ;;
  965. --help|-h|help)
  966. print_header
  967. echo "Usage: $0 [PROFILE] [OPTIONS]"
  968. echo ""
  969. echo -e "${BOLD}Profiles:${NC}"
  970. echo " essential, --essential Minimal setup with core agents"
  971. echo " developer, --developer Code-focused development tools"
  972. echo " business, --business Content and business-focused tools"
  973. echo " full, --full Everything except system-builder"
  974. echo " advanced, --advanced Complete system with all components"
  975. echo ""
  976. echo -e "${BOLD}Options:${NC}"
  977. echo " --install-dir PATH Custom installation directory"
  978. echo " (default: .opencode)"
  979. echo " list, --list List all available components"
  980. echo " help, --help, -h Show this help message"
  981. echo ""
  982. echo -e "${BOLD}Environment Variables:${NC}"
  983. echo " OPENCODE_INSTALL_DIR Installation directory"
  984. echo " OPENCODE_BRANCH Git branch to install from (default: main)"
  985. echo ""
  986. echo -e "${BOLD}Examples:${NC}"
  987. echo ""
  988. echo " ${CYAN}# Interactive mode (choose location and components)${NC}"
  989. echo " $0"
  990. echo ""
  991. echo " ${CYAN}# Quick install with default location (.opencode/)${NC}"
  992. echo " $0 developer"
  993. echo ""
  994. echo " ${CYAN}# Install to global location (Linux/macOS)${NC}"
  995. echo " $0 developer --install-dir ~/.config/opencode"
  996. echo ""
  997. echo " ${CYAN}# Install to global location (Windows Git Bash)${NC}"
  998. echo " $0 developer --install-dir ~/.config/opencode"
  999. echo ""
  1000. echo " ${CYAN}# Install to custom location${NC}"
  1001. echo " $0 essential --install-dir ~/my-agents"
  1002. echo ""
  1003. echo " ${CYAN}# Using environment variable${NC}"
  1004. echo " export OPENCODE_INSTALL_DIR=~/.config/opencode"
  1005. echo " $0 developer"
  1006. echo ""
  1007. echo " ${CYAN}# Install from URL (non-interactive)${NC}"
  1008. echo " curl -fsSL https://raw.githubusercontent.com/darrenhinde/OpenAgents/main/install.sh | bash -s developer"
  1009. echo ""
  1010. echo -e "${BOLD}Platform Support:${NC}"
  1011. echo " ✓ Linux (bash 3.2+)"
  1012. echo " ✓ macOS (bash 3.2+)"
  1013. echo " ✓ Windows (Git Bash, WSL)"
  1014. echo ""
  1015. exit 0
  1016. ;;
  1017. *)
  1018. echo "Unknown option: $1"
  1019. echo "Run '$0 --help' for usage information"
  1020. exit 1
  1021. ;;
  1022. esac
  1023. done
  1024. # Apply custom install directory if specified (CLI arg overrides env var)
  1025. if [ -n "$CUSTOM_INSTALL_DIR" ]; then
  1026. local normalized_path=$(normalize_and_validate_path "$CUSTOM_INSTALL_DIR")
  1027. if [ $? -eq 0 ]; then
  1028. INSTALL_DIR="$normalized_path"
  1029. if ! validate_install_path "$INSTALL_DIR"; then
  1030. print_warning "Installation path may have issues, but continuing..."
  1031. fi
  1032. else
  1033. print_error "Invalid installation directory: $CUSTOM_INSTALL_DIR"
  1034. exit 1
  1035. fi
  1036. fi
  1037. check_bash_version
  1038. check_dependencies
  1039. fetch_registry
  1040. if [ -n "$PROFILE" ]; then
  1041. # Non-interactive mode (compatible with bash 3.2+)
  1042. SELECTED_COMPONENTS=()
  1043. local temp_file="$TEMP_DIR/components.tmp"
  1044. get_profile_components "$PROFILE" > "$temp_file"
  1045. while IFS= read -r component; do
  1046. [ -n "$component" ] && SELECTED_COMPONENTS+=("$component")
  1047. done < "$temp_file"
  1048. show_installation_preview
  1049. else
  1050. # Interactive mode - show location menu first
  1051. show_install_location_menu
  1052. show_main_menu
  1053. if [ "$INSTALL_MODE" = "profile" ]; then
  1054. show_profile_menu
  1055. elif [ "$INSTALL_MODE" = "custom" ]; then
  1056. show_custom_menu
  1057. fi
  1058. fi
  1059. }
  1060. main "$@"