#!/usr/bin/env bash set -euo pipefail APP=cubic STORAGE_URL="${CUBIC_STORAGE_URL:-https://mcafvrhahbqdwfrtncql.supabase.co/storage/v1/object/public/releases}" RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' ORANGE='\033[38;2;255;140;0m' NC='\033[0m' # Same flag file as GitAI's DISABLED_FLAG; honored by every git-ai install path. git_ai_disabled_flag() { echo "${XDG_STATE_HOME:-$HOME/.local/state}/cubic/git-ai-disabled" } git_ai_opt_out_env() { local value value=$(echo "${CUBIC_DISABLE_GIT_AI:-}" | tr '[:upper:]' '[:lower:]') [[ "$value" == "true" || "$value" == "1" ]] } persist_git_ai_opt_out() { git_ai_opt_out_env || return 0 local flag flag=$(git_ai_disabled_flag) if ! { mkdir -p "$(dirname "$flag")" && : >"$flag"; } 2>/dev/null; then echo -e "${YELLOW}Could not save the git-ai opt-out to $flag; set CUBIC_DISABLE_GIT_AI again on future installs.${NC}" fi } git_ai_opted_out() { git_ai_opt_out_env || [[ -e "$(git_ai_disabled_flag)" ]] } # Saved before anything can exit early, so a failed install still remembers it. persist_git_ai_opt_out XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-$HOME/.config} requested_version=${VERSION:-} # Check required dependencies for cmd in curl unzip; do if ! command -v "$cmd" &>/dev/null; then echo -e "${RED}Error: '${cmd}' is required but not installed.${NC}" case "$(uname -s)" in Linux*) if command -v apt-get &>/dev/null; then echo -e "${YELLOW}Install it with: sudo apt-get update && sudo apt-get install -y ${cmd}${NC}" elif command -v yum &>/dev/null; then echo -e "${YELLOW}Install it with: sudo yum install -y ${cmd}${NC}" elif command -v apk &>/dev/null; then echo -e "${YELLOW}Install it with: sudo apk add ${cmd}${NC}" fi ;; esac exit 1 fi done raw_os=$(uname -s) os=$(echo "$raw_os" | tr '[:upper:]' '[:lower:]') case "$raw_os" in Darwin*) os="darwin" ;; Linux*) os="linux" ;; MINGW*|MSYS*|CYGWIN*) os="windows" ;; esac arch=$(uname -m) if [[ "$arch" == "aarch64" ]]; then arch="arm64" elif [[ "$arch" == "x86_64" ]]; then arch="x64" fi # A shell under Rosetta 2 reports x86_64 on Apple Silicon. The native build is # faster, and the x64 one needs AVX2, which Rosetta may not provide. if [[ "$os" == "darwin" && "$arch" == "x64" && "$(sysctl -n sysctl.proc_translated 2>/dev/null)" == "1" ]]; then echo -e "${GREEN}This shell runs under Rosetta 2, so installing the native Apple Silicon build.${NC}" arch="arm64" fi # Linux x64 builds need AVX2, so older CPUs and some VMs get the -baseline build. # musl distros like Alpine can't run the glibc builds and get the -musl one. variant="" if [[ "$os" == "linux" ]]; then if [[ "$arch" == "x64" ]] && ! grep -qw avx2 /proc/cpuinfo 2>/dev/null; then variant="-baseline" fi if [[ -f /etc/alpine-release || "$(ldd --version 2>&1)" == *musl* ]]; then variant="$variant-musl" fi fi case "$os/$arch" in linux/x64|linux/arm64|darwin/x64|darwin/arm64|windows/x64) ;; *) echo -e "${RED}Unsupported OS/Arch: $os/$arch${NC}" exit 1 ;; esac filename="$APP-$os-$arch$variant.zip" # The macOS builds need macOS 13 (Ventura) or later. if [[ "$os" == "darwin" ]]; then macos_version=$(SYSTEM_VERSION_COMPAT=0 sw_vers -productVersion 2>/dev/null || true) macos_major=${macos_version%%.*} if [[ "$macos_major" =~ ^[0-9]+$ ]] && (( macos_major < 13 )); then echo -e "${RED}cubic needs macOS 13 (Ventura) or later. This Mac runs macOS $macos_version.${NC}" exit 1 fi fi if [[ "$variant" == *-musl ]] && command -v apk &>/dev/null && ! apk info -e libstdc++ libgcc &>/dev/null; then echo -e "${YELLOW}cubic needs libstdc++ and libgcc. Install them with: sudo apk add libstdc++ libgcc${NC}" fi default_install="${HOME}/.cubic/bin" INSTALL_DIR="${CUBIC_INSTALL_DIR:-${OPENCODE_INSTALL_DIR:-$default_install}}" # Reject install paths containing unsafe shell metacharacters, but allow spaces and common path characters. if [[ "$INSTALL_DIR" =~ [\"\'\\\`\$\&\;\|\>\<\(\)\{\}\*\?] ]]; then echo -e "${RED}Invalid install directory (contains unsafe characters): $INSTALL_DIR${NC}" exit 1 fi mkdir -p "$INSTALL_DIR" if [ -z "$requested_version" ]; then # Fetch latest version from manifest file specific_version=$(curl -sfS "${STORAGE_URL}/latest.txt") if [[ $? -ne 0 || -z "$specific_version" ]]; then echo -e "${RED}Failed to fetch version information${NC}" exit 1 fi else specific_version=$requested_version fi # Validate version format to prevent path traversal attacks # Allows: 1.2.3, 1.2.3-rc1, 1.2.3-beta.1, 0.0.0-branch/name-timestamp if [[ ! "$specific_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9._/-]+)?$ ]]; then echo -e "${RED}Invalid version format: $specific_version${NC}" exit 1 fi url="${STORAGE_URL}/v${specific_version}/$filename" print_message() { local level=$1 local message=$2 local color="" case $level in info) color="${GREEN}" ;; warning) color="${YELLOW}" ;; error) color="${RED}" ;; esac echo -e "${color}${message}${NC}" } check_version() { # Check the binary at INSTALL_DIR specifically, not just any cubic in PATH # This avoids confusion when user has multiple cubic installations (e.g., Homebrew, npm) local target_binary="${INSTALL_DIR}/cubic" if [[ -x "$target_binary" ]]; then local installed_version="$("$target_binary" --version 2>/dev/null | head -1 || true)" if [[ -n "$installed_version" ]]; then if [[ "$installed_version" == "$specific_version" ]]; then print_message info "Version ${YELLOW}$specific_version${GREEN} already installed at ${INSTALL_DIR}" return 0 fi print_message info "Upgrading from ${YELLOW}$installed_version${GREEN} to ${YELLOW}$specific_version" fi fi return 1 } download_and_install() { print_message info "Downloading ${ORANGE}cubic ${GREEN}version: ${YELLOW}$specific_version ${GREEN}..." # Create secure temp directory tmp_dir=$(mktemp -d 2>/dev/null || mktemp -d -t 'cubic-install') # Ensure cleanup on exit (success or failure) trap 'rm -rf "$tmp_dir"' EXIT cd "$tmp_dir" curl -# -L -o "$filename" "$url" # Verify download succeeded and file is not empty if [[ ! -s "$filename" ]]; then print_message error "Download failed or file is empty" exit 1 fi unzip -q "$filename" # Verify binary exists after extraction if [[ ! -f "cubic" ]]; then print_message error "Binary not found in archive" exit 1 fi mv cubic "$INSTALL_DIR" chmod 755 "${INSTALL_DIR}/cubic" } already_installed=false if check_version; then already_installed=true fi if [[ "$already_installed" != "true" ]]; then download_and_install fi # git-ai version — keep in sync with packages/cubic/src/constants/git-ai.json GIT_AI_VERSION="v1.7.5" GIT_AI_COMPATIBLE_MAJOR=1 GIT_AI_BINARY="${HOME}/.git-ai/bin/git-ai" GIT_AI_REPO_URL="https://github.com/git-ai-project/git-ai" # True when git-ai version $1 is older than $2 (both [v]X.Y.Z). Unparseable # versions are never "older", so a surprising --version output never triggers # a reinstall. git_ai_version_older_than() { local pattern='s/^v*\([0-9][0-9]*\)\.\([0-9][0-9]*\)\.\([0-9][0-9]*\)$/\1 \2 \3/p' local a b a=$(echo "$1" | sed -n "$pattern") b=$(echo "$2" | sed -n "$pattern") if [[ -z "$a" || -z "$b" ]]; then return 1 fi local a1 a2 a3 b1 b2 b3 read -r a1 a2 a3 <<<"$a" read -r b1 b2 b3 <<<"$b" if [[ $a1 -ne $b1 ]]; then [[ $a1 -lt $b1 ]]; return; fi if [[ $a2 -ne $b2 ]]; then [[ $a2 -lt $b2 ]]; return; fi [[ $a3 -lt $b3 ]] } # Check if an existing git-ai installation is compatible (major version match) # and at least the pinned version. check_git_ai_version() { if [[ ! -x "$GIT_AI_BINARY" ]]; then return 1 # not installed fi local installed_version installed_version=$("$GIT_AI_BINARY" --version 2>/dev/null || echo "") if [[ -z "$installed_version" ]]; then return 1 # can't determine version, treat as not installed fi local major major=$(echo "$installed_version" | sed -n 's/^v*\([0-9]*\)\..*/\1/p') if [[ -z "$major" ]]; then return 1 fi if [[ "$major" -eq "$GIT_AI_COMPATIBLE_MAJOR" ]]; then if git_ai_version_older_than "$installed_version" "$GIT_AI_VERSION"; then return 3 # compatible but older than the pinned version fi return 0 # compatible fi # Incompatible version — warn and skip print_message warning "git-ai is already installed (${installed_version}), but this version is incompatible with cubic AI stats." print_message warning "Please uninstall git-ai and run 'cubic stats enable' to install a compatible version." print_message info " ${GIT_AI_REPO_URL}" return 2 # incompatible } # Run git-ai with the given args, killed after $1 seconds by a pure-bash # watchdog (stock macOS ships no `timeout`) so a wedged binary cannot hang the # installer. /dev/null 2>&1 & local cmd_pid=$! ( sleep "$timeout"; kill "$cmd_pid" 2>/dev/null; sleep 2; kill -KILL "$cmd_pid" 2>/dev/null ) & local watchdog_pid=$! wait "$cmd_pid" 2>/dev/null || status=$? kill "$watchdog_pid" 2>/dev/null || true wait "$watchdog_pid" 2>/dev/null || true [[ $status -lt 128 ]] } run_git_ai_config_set() { run_git_ai_bounded 5 config set "$1" "$2" } # Set a git-ai feature flag only when the user hasn't set it: the flag name # appearing as a property (`"name":`) in ~/.git-ai/config.json counts as theirs # (no jq to parse it; git-ai writes each `"key": value` on one line). Returns nonzero only on a # timeout kill, like run_git_ai_config_set. set_git_ai_default_flag() { local config="${HOME}/.git-ai/config.json" if [[ -e "$config" ]] && { [[ ! -r "$config" ]] || grep -q "\"$1\"[[:space:]]*:" "$config"; }; then return 0 fi run_git_ai_config_set "feature_flags.$1" "$2" || return 1 GIT_AI_DEFAULTS_CHANGED=true } # Apply cubic's git-ai config. # Keep keys in sync with packages/cubic/src/constants/git-ai.json (single # source of truth) and packages/cubic/script/postinstall.mjs. # Best-effort: config failures must never break the install. A timed-out key # means the binary is wedged, so stop instead of stalling on every remaining one. apply_git_ai_config() { run_git_ai_config_set quiet true || return 0 run_git_ai_config_set disable_auto_updates true || return 0 run_git_ai_config_set telemetry_oss off || return 0 run_git_ai_config_set disable_version_checks true || return 0 apply_git_ai_default_flags } # cubic's defaults for git-ai settings the user may own (keep in sync with the # `defaults` map in packages/cubic/src/constants/git-ai.json). Flags are read at # daemon startup, so restart it when one was written. apply_git_ai_default_flags() { GIT_AI_DEFAULTS_CHANGED=false set_git_ai_default_flag token_usage_metrics false || return 0 set_git_ai_default_flag daemon_log_upload false || return 0 if [[ "$GIT_AI_DEFAULTS_CHANGED" == "true" ]]; then run_git_ai_bounded 20 bg restart || true fi } # Install git-ai silently using official installer setup_git_ai() { local status=0 check_git_ai_version || status=$? # 0 = compatible already installed — re-assert cubic's config (repairs # installs that predate full config application), skip reinstall. if [[ $status -eq 0 ]]; then apply_git_ai_config return fi # 2 = incompatible (warned above) — do not touch it if [[ $status -eq 2 ]]; then return fi # 1 = not installed, 3 = older than the pinned version (the installer # upgrades in place) — install silently. --fail makes an HTTP error a non-zero exit # (the script's pipefail then fails the pipe) instead of piping an error page # into bash and reporting success; --max-time bounds a stalled download. if curl --fail --silent --show-error --location --max-time 110 "https://github.com/git-ai-project/git-ai/releases/download/${GIT_AI_VERSION}/install.sh" | bash >/dev/null 2>&1; then apply_git_ai_config GIT_AI_INSTALLED=true else print_message warning "cubic AI stats use git-ai under the hood. git-ai failed to install." print_message warning "Make sure git-ai installation succeeds in order to use cubic AI stats." print_message info " ${GIT_AI_REPO_URL}" fi } if ! git_ai_opted_out; then setup_git_ai fi add_to_path() { local config_file=$1 local command=$2 # A new account may not have this file yet (macOS doesn't create ~/.zshrc). if [[ ! -e $config_file ]]; then { mkdir -p "$(dirname "$config_file")" && touch "$config_file"; } 2>/dev/null || true fi if [[ -f $config_file ]] && grep -Fxq "$command" "$config_file"; then print_message info "Command already exists in $config_file, skipping write." elif [[ -f $config_file && -w $config_file ]]; then echo -e "\n# cubic" >> "$config_file" echo "$command" >> "$config_file" print_message info "Successfully added ${ORANGE}cubic ${GREEN}to \$PATH in $config_file" else print_message warning "Manually add the directory to $config_file (or similar):" print_message info " $command" fi } current_shell=$(basename "$SHELL") # When none of config_files exist yet, the PATH line goes in default_config_file. case $current_shell in fish) config_files="$HOME/.config/fish/config.fish" default_config_file="$XDG_CONFIG_HOME/fish/config.fish" ;; zsh) config_files="$HOME/.zshrc $HOME/.zshenv $XDG_CONFIG_HOME/zsh/.zshrc $XDG_CONFIG_HOME/zsh/.zshenv" default_config_file="${ZDOTDIR:-$HOME}/.zshrc" ;; bash) config_files="$HOME/.bashrc $HOME/.bash_profile $HOME/.profile $XDG_CONFIG_HOME/bash/.bashrc $XDG_CONFIG_HOME/bash/.bash_profile" default_config_file="$HOME/.bashrc" # macOS terminals open login shells, which read ~/.bash_profile but not ~/.bashrc. if [[ $os == "darwin" ]]; then default_config_file="$HOME/.bash_profile" fi ;; ash|sh) config_files="$HOME/.ashrc $HOME/.profile /etc/profile" default_config_file="$HOME/.profile" ;; *) config_files="$HOME/.bashrc $HOME/.bash_profile $XDG_CONFIG_HOME/bash/.bashrc $XDG_CONFIG_HOME/bash/.bash_profile" default_config_file="$HOME/.bashrc" ;; esac config_file=$default_config_file for file in $config_files; do if [[ -f $file ]]; then config_file=$file break fi done if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then case $current_shell in fish) add_to_path "$config_file" "fish_add_path \"$INSTALL_DIR\"" ;; zsh|bash|ash|sh) add_to_path "$config_file" "export PATH=\"$INSTALL_DIR\":\$PATH" ;; *) export PATH="$INSTALL_DIR":$PATH print_message warning "Manually add the directory to $config_file (or similar):" print_message info " export PATH=\"$INSTALL_DIR\":\$PATH" ;; esac fi if [ -n "${GITHUB_ACTIONS-}" ] && [ "${GITHUB_ACTIONS}" == "true" ]; then echo "$INSTALL_DIR" >> "$GITHUB_PATH" print_message info "Added $INSTALL_DIR to \$GITHUB_PATH" fi print_message info "" print_message info "✓ cubic CLI installed successfully" print_message info "" should_prompt_wizard() { [[ "${CUBIC_DISABLE_INSTALL_WIZARD:-}" == "true" ]] && return 1 [[ -n "${CI:-}" && "${CI}" != "false" ]] && return 1 [[ "${TERM:-}" == "dumb" ]] && return 1 [[ ! -t 1 ]] && return 1 [[ ! -e /dev/tty ]] && return 1 return 0 } if should_prompt_wizard; then # Don't use 'exec