install.sh 40 KB

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