#!/usr/bin/env bash # OpenLLM installer — installs the single `openllm` binary (the CLI, plus the # `ollm` alias, AND the local daemon as `openllm daemon`). Ordered setup: # binary → OpenLLM authentication (or reuse a usable credential) → full-mode # vendor CLI provisioning → optional daemon start. Minimal mode authenticates # only. # # Two auto-detected modes (override with --interactive / --non-interactive): # Interactive (controlling tty): today's walkthrough; Full by default; starts # the daemon when a key is available. # Headless: Full with no prompts; does NOT start/register the daemon unless # --start / OPENLLM_START_DAEMON=1; ends with a fixed parseable summary. # Key presence does not change the start decision. Updates restart a RUNNING # daemon and never start a stopped one. # # curl -fsSL https://www.openllm.sh/install | bash # curl -fsSL https://www.openllm.sh/install | OPENLLM_API_KEY=sk-llm-... bash # curl -fsSL https://www.openllm.sh/install | bash -s -- --non-interactive # # Flags (fail on unknown/contradiction BEFORE installing anything): # --help --dry-run # --interactive | --non-interactive | -y OPENLLM_INTERACTIVE=1|0 # --full (default) | --minimal OPENLLM_SETUP_MODE # Full only: --start | --no-start OPENLLM_START_DAEMON=1|0 # --vendors=a,b | --no-vendors OPENLLM_ONLY_VENDOR_CLIS / # OPENLLM_SKIP_VENDOR_CLIS # --origin= --port= --no-shell-setup OPENLLM_SKIP_SHELL_SETUP # Precedence: flag > env > ~/.openllm/.env > default. No --key flag (keys stay # OPENLLM_API_KEY only — argv shows up in ps / shell history). # # Env (all optional): # OPENLLM_CLOUD_ORIGIN gateway origin (env → existing ~/.openllm/.env → # default https://www.openllm.sh; a re-run keeps your origin) # OPENLLM_API_KEY pair the daemon now; otherwise pair from the dashboard. # The dashboard's command carries a device trust anchor # after the key (`sk-llm-.`): it is split # off here and stored as its own line, # OPENLLM_DEVICE_ANCHOR, in the env file (0600) next # to the BARE key. It is never exported, logged, or # sent — only the bare `sk-llm-` is the bearer. # Re-running install with a new anchor rotates it. # The trust anchor pins device-control. Sessions default # on when it is present (`OPENLLM_DEVICE_SESSIONS` # defaults on; disable writes 0 — the anchor stays). # OPENLLM_DAEMON_PORT local daemon port (default 8787). # OPENLLM_SKIP_SHELL_SETUP skip `openllm setup` + completion install # OPENLLM_SKIP_VENDOR_CLIS skip vendor CLI provisioning # OPENLLM_ONLY_VENDOR_CLIS comma-separated subscription slugs to provision # OPENLLM_SETUP_MODE `full` or `minimal` (see --full / --minimal) # OPENLLM_INTERACTIVE 1|0 force interactive / headless # OPENLLM_START_DAEMON 1|0 force daemon start / no-start (Full only) # OPENLLM_VENDOR_WAIT_SECS headless vendor wait ceiling (default 600) # OPENLLM_INSTALL_MODE install | update | vendors # `vendors` only provisions missing vendor CLIs # (used by `openllm start` in Full mode) # # Exit status: 0 when the install worked and next steps were printed (keyless # included). Nonzero only on a real failure, including an explicitly requested # start that failed. Vendor CLI failures are reported in the summary and do # not fail the run. # # This is the ONLY shell installer. In full mode it also provisions any missing # vendor subscription CLIs (claude / codex / kimi / grok / cursor-agent / muse) # via each vendor's official installer — skip if already present. Google # Antigravity is Google's official `agy` CLI (its own installer, which verifies # its download and places ~/.local/bin/agy). It never edits a # third-party client config: `openllm ` applies OpenLLM at run time. # The only files it writes outside ~/.openllm (besides what a vendor installer # itself does) are the PATH symlinks and the ONE marked block in your shell rc # that `openllm setup` / `openllm daemon completion` manage. set -euo pipefail # ORIGIN is resolved in preflight (env → existing ~/.openllm/.env → default), # mirroring the CLI's cliConfig() precedence — see below. OPENLLM_DIR="$HOME/.openllm" BIN_DIR="$OPENLLM_DIR/bin" ENV_FILE="${OPENLLM_DAEMON_ENV_FILE:-$OPENLLM_DIR/.env}" # DAEMON_PORT is resolved in preflight (env → existing env-file value → default), # once `env_file_value`/`die` are defined — see below. # `install` (default) is a first-time install; `update` is a manual full-product # rerun (`openllm update`). Update mode converges the verified binaries + config # but must NOT repeat first-install side effects: no vendor-CLI provisioning, no # shell/PATH/completion edits, and no teardown of an existing healthy service. # (Validated in preflight, once `die` is defined.) INSTALL_MODE="${OPENLLM_INSTALL_MODE:-install}" # Product setup mode (`full`|`minimal`). Distinct from INSTALL_MODE. Resolved # after argv parse + env-file helpers exist — see below. SETUP_MODE="" SETUP_MODE_EXPLICIT=0 # Space-delimited list of components whose on-disk bytes were actually replaced # this run (see install_component). Update mode reads it to skip a pointless # daemon restart when nothing changed. INSTALLED_COMPONENTS="" # Flag / mode resolution state (parsed below; resolved after env-file helpers). FLAG_HELP=0 FLAG_DRY_RUN=0 FLAG_INTERACTIVE="" FLAG_SETUP_MODE="" FLAG_START="" FLAG_VENDORS_ONLY="" FLAG_NO_VENDORS=0 FLAG_ORIGIN="" FLAG_PORT="" FLAG_NO_SHELL_SETUP=0 WANT_START=0 INTERACTIVE=0 has_command() { command -v "$1" >/dev/null 2>&1; } # True only when PATH resolves to an executable regular file. bash's # `command -v` can return a non-executable PATH hit; vendor presence must # not treat that as "already installed". has_executable_command() { local resolved resolved="$(command -v "$1" 2>/dev/null)" || return 1 [ -n "$resolved" ] && [ -f "$resolved" ] && [ -x "$resolved" ] } die() { echo "Error: $*" >&2; exit 1; } print_installer_help() { cat <<'EOF' OpenLLM installer Usage: curl -fsSL https://www.openllm.sh/install | bash curl -fsSL https://www.openllm.sh/install | bash -s -- [options] Options: --help Show this help and exit --dry-run Print the resolved plan; install nothing --interactive Force interactive mode (prompts + start) --non-interactive, -y Force headless mode (no prompts; no start) --full Full setup (default) --minimal Minimal setup (no vendors, no daemon start) --start Start the daemon (Full only) --no-start Do not start the daemon (Full only) --vendors=a,b Only provision these vendor slugs (claude_code,chatgpt,kimi_code,grok, cursor,muse,antigravity) --no-vendors Skip vendor CLI provisioning --origin=URL Gateway origin (OPENLLM_CLOUD_ORIGIN) --port=N Daemon port (OPENLLM_DAEMON_PORT) --no-shell-setup Skip PATH / shell rc / completion wiring Env aliases (flag > env > ~/.openllm/.env > default): OPENLLM_INTERACTIVE=1|0 OPENLLM_SETUP_MODE=full|minimal OPENLLM_START_DAEMON=1|0 OPENLLM_ONLY_VENDOR_CLIS / OPENLLM_SKIP_VENDOR_CLIS OPENLLM_SKIP_SHELL_SETUP OPENLLM_API_KEY (no --key flag) OPENLLM_VENDOR_WAIT_SECS headless vendor wait (default 600) OPENLLM_INSTALL_MODE=install|update|vendors EOF } # Slugs accepted by --vendors= / OPENLLM_ONLY_VENDOR_CLIS (provision_clis + # antigravity). Keep in sync with the --vendors help line above. INSTALLER_VENDOR_SLUGS="claude_code,chatgpt,kimi_code,grok,cursor,muse,antigravity" # Reject unknown --vendors= entries before any install side effect. validate_vendor_slugs() { local raw="$1" slug rest rest="$raw" while [ -n "$rest" ]; do case "$rest" in *,*) slug="${rest%%,*}" rest="${rest#*,}" ;; *) slug="$rest" rest="" ;; esac [ -n "$slug" ] || die "--vendors= entries must be non-empty (got: $raw)" case ",${INSTALLER_VENDOR_SLUGS}," in *",$slug,"*) ;; *) die "unknown --vendors= slug: $slug (expected one of: $INSTALLER_VENDOR_SLUGS)" ;; esac done } # Parse argv first so unknown / contradictory flags fail before any install work. for arg in "$@"; do case "$arg" in --help|-h) FLAG_HELP=1 ;; --dry-run) FLAG_DRY_RUN=1 ;; --interactive) if [ "$FLAG_INTERACTIVE" = 0 ]; then die "contradictory options: --interactive and --non-interactive" fi FLAG_INTERACTIVE=1 ;; --non-interactive|-y) if [ "$FLAG_INTERACTIVE" = 1 ]; then die "contradictory options: --interactive and --non-interactive" fi FLAG_INTERACTIVE=0 ;; --full) if [ "$FLAG_SETUP_MODE" = minimal ]; then die "contradictory options: --full and --minimal" fi FLAG_SETUP_MODE=full ;; --minimal) if [ "$FLAG_SETUP_MODE" = full ]; then die "contradictory options: --full and --minimal" fi FLAG_SETUP_MODE=minimal ;; --start) if [ "$FLAG_START" = 0 ]; then die "contradictory options: --start and --no-start" fi FLAG_START=1 ;; --no-start) if [ "$FLAG_START" = 1 ]; then die "contradictory options: --start and --no-start" fi FLAG_START=0 ;; --no-vendors) if [ -n "$FLAG_VENDORS_ONLY" ]; then die "contradictory options: --vendors and --no-vendors" fi FLAG_NO_VENDORS=1 ;; --vendors=*) if [ "$FLAG_NO_VENDORS" = 1 ]; then die "contradictory options: --vendors and --no-vendors" fi FLAG_VENDORS_ONLY="${arg#--vendors=}" [ -n "$FLAG_VENDORS_ONLY" ] || die "--vendors= requires a comma-separated list" validate_vendor_slugs "$FLAG_VENDORS_ONLY" ;; --origin=*) FLAG_ORIGIN="${arg#--origin=}" [ -n "$FLAG_ORIGIN" ] || die "--origin= requires a URL" ;; --port=*) FLAG_PORT="${arg#--port=}" [ -n "$FLAG_PORT" ] || die "--port= requires a port number" ;; --no-shell-setup) FLAG_NO_SHELL_SETUP=1 ;; --key|--key=*|--api-key|--api-key=*) die "no --key flag — set OPENLLM_API_KEY in the environment instead" ;; -*) die "unknown installer option: $arg" ;; *) die "unknown installer option: $arg" ;; esac done if [ "$FLAG_HELP" = 1 ]; then print_installer_help exit 0 fi # Apply flag overrides onto env vars immediately (flag > env). if [ -n "$FLAG_SETUP_MODE" ]; then OPENLLM_SETUP_MODE="$FLAG_SETUP_MODE" SETUP_MODE_EXPLICIT=1 fi if [ "$FLAG_INTERACTIVE" = 1 ]; then OPENLLM_INTERACTIVE=1 elif [ "$FLAG_INTERACTIVE" = 0 ]; then OPENLLM_INTERACTIVE=0 fi if [ "$FLAG_START" = 1 ]; then OPENLLM_START_DAEMON=1 elif [ "$FLAG_START" = 0 ]; then OPENLLM_START_DAEMON=0 fi if [ "$FLAG_NO_VENDORS" = 1 ]; then OPENLLM_SKIP_VENDOR_CLIS=1 fi if [ -n "$FLAG_VENDORS_ONLY" ]; then OPENLLM_ONLY_VENDOR_CLIS="$FLAG_VENDORS_ONLY" unset OPENLLM_SKIP_VENDOR_CLIS 2>/dev/null || true fi # The env alias gets the same check as the flag: an unknown slug would # otherwise silently select no vendors. if [ -n "${OPENLLM_ONLY_VENDOR_CLIS:-}" ]; then validate_vendor_slugs "$OPENLLM_ONLY_VENDOR_CLIS" fi if [ -n "$FLAG_ORIGIN" ]; then OPENLLM_CLOUD_ORIGIN="$FLAG_ORIGIN" fi if [ -n "$FLAG_PORT" ]; then OPENLLM_DAEMON_PORT="$FLAG_PORT" fi if [ "$FLAG_NO_SHELL_SETUP" = 1 ]; then OPENLLM_SKIP_SHELL_SETUP=1 fi # The terminal the human is on. A piped `curl … | bash` leaves the script's own # stdin as the download stream; answers must come from this path, never stdin. installer_tty() { printf '%s' /dev/tty } # Can we prompt the human running this install? `openllm login`'s credential gate # reads the key from the controlling tty yet decides interactivity from # stdin/stderr being TTYs — so we only hand off when stderr is a real terminal # AND the controlling tty is openable. In a non-interactive install (CI, a pipe # with no terminal) this is false and we fall back to printing the manual # `openllm login` next step. has_controlling_tty() { local tty tty="$(installer_tty)" [ -t 2 ] || return 1 { true < "$tty"; } 2>/dev/null } # Ask Full vs Minimal on the controlling tty. Empty Enter → full. EOF / cancel # → nonzero so the caller aborts before persistence or vendor consent. Prompts # go to stderr (visible under curl|bash); the answer is read from installer_tty. # FD 9 is opened ONCE for the whole retry loop (bash 3.2-safe fixed FD — macOS # ships 3.2; `{fd}` alloc needs bash 4+). Reopening a regular file (hermetic # mock tty) on each iteration would re-read the first invalid line forever; # a real /dev/tty stays correct either way. prompt_setup_mode() { local tty reply normalized tty="$(installer_tty)" if ! exec 9<"$tty"; then return 1 fi trap 'exec 9<&-; trap - RETURN' RETURN echo >&2 echo "Choose installation setup:" >&2 echo " Full install supported vendor CLIs and start the local daemon" >&2 echo " Minimal OpenLLM only — no vendor CLIs and no daemon" >&2 while true; do printf "Setup [Full/Minimal] (default Full): " >&2 if ! IFS= read -r reply <&9; then echo >&2 return 1 fi reply="$(trim_whitespace "$reply")" normalized="$(printf '%s' "$reply" | tr '[:upper:]' '[:lower:]')" case "$normalized" in ""|f|full) SETUP_MODE=full break ;; m|min|minimal) SETUP_MODE=minimal break ;; *) echo "Please enter Full or Minimal (Enter accepts Full)." >&2 ;; esac done echo " using $SETUP_MODE setup" >&2 return 0 } # Bash strings cannot contain NUL bytes: command substitution and shell variables # discard them before this script can inspect a value. Do not add `$'\0'` to this # glob — Bash expands it to an empty string, turning the glob into `**` and # matching every input. has_line_break() { [[ "$1" == *$'\n'* || "$1" == *$'\r'* ]]; } trim_whitespace() { local value="$1" value="${value#"${value%%[![:space:]]*}"}" value="${value%"${value##*[![:space:]]}"}" printf '%s' "$value" } # Read one KEY's LAST-occurrence value from the shared env file, mirroring # `parseEnvLines` (packages/cli/daemon/src/env.ts): trim the whole line, skip # blank/`#` lines, split at the first `=`, trim both sides. `parseEnvLines` # folds lines into a `Map` via `.set(key, value)`, so a later duplicate # OVERWRITES an earlier one — the last matching line must win here too (the # bug this replaces: every reader below used to return on its first match). # No quote/comment stripping here — that's a per-caller decision below. env_file_lookup() { local wanted="$1" line trimmed key value result="" found=0 [ -f "$ENV_FILE" ] || return 0 while IFS= read -r line || [ -n "$line" ]; do trimmed="$(trim_whitespace "$line")" case "$trimmed" in ""|\#*) continue ;; esac case "$trimmed" in *=*) ;; *) continue ;; esac key="$(trim_whitespace "${trimmed%%=*}")" [ -n "$key" ] || continue [ "$key" = "$wanted" ] || continue value="$(trim_whitespace "${trimmed#*=}")" result="$value" found=1 done < "$ENV_FILE" [ "$found" = 1 ] && printf '%s' "$result" return 0 } # Read one KEY's value from the shared env file (last match wins — see # `env_file_lookup`), additionally stripping one layer of surrounding quotes # so it matches how the CLI resolves the same file (`parseEnvFile` in # packages/cli/src/env.ts, which underlies `cliConfig()`). Used only to seed # the effective origin below; empty/absent → empty string. env_file_value() { local wanted="$1" value value="$(env_file_lookup "$wanted")" value="${value#[\"\']}" value="${value%[\"\']}" printf '%s' "$value" } # Read one KEY's RAW value from the shared env file (last match wins) — # outer-whitespace trimmed only, no quote or comment stripping — for the # port, whose protocol-compatible parsing (`normalize_daemon_port`) needs the # untouched value: whether a comment sits inside or outside the quotes # changes the correct strip order, so `env_file_value`'s single fixed order # (quotes always stripped first) cannot be reused here. env_file_raw_value() { env_file_lookup "$1" } is_usable_api_key() { local key="$1" # Minted keys are `sk-llm-` + a 10-byte base64url id (14 chars) + `.` + # a 32-byte base64url secret (43 chars). Restricting this shell boundary to # the wire grammar keeps values safe to persist in KEY=value config files. [[ "$key" =~ ^sk-llm-[A-Za-z0-9_-]{14}[.][A-Za-z0-9_-]{43}$ ]] } # A device trust anchor: base64url of 64 bytes (86 chars, unpadded). is_device_anchor() { [[ "$1" =~ ^[A-Za-z0-9_-]{86}$ ]] } sha256_of() { if has_command shasum; then shasum -a 256 "$1" 2>/dev/null | cut -d' ' -f1 elif has_command sha256sum; then sha256sum "$1" 2>/dev/null | cut -d' ' -f1 fi } # --- preflight ------------------------------------------------------------- # A custom env-file override must be absolute: the daemon + CLI only honour # OPENLLM_DAEMON_ENV_FILE when it is absolute (see packages/cli/src/env.ts), so a # relative value here would write config the runtime never reads. Validate this # BEFORE reading the file for the origin fallback, so we never read a relative # path resolved against the caller's cwd. if [ -n "${OPENLLM_DAEMON_ENV_FILE:-}" ]; then case "$OPENLLM_DAEMON_ENV_FILE" in /*) ;; *) die "OPENLLM_DAEMON_ENV_FILE must be an absolute path" ;; esac fi # Effective origin — process env, else the origin already recorded in the shared # env file, else the compiled production default. This mirrors the CLI's # cliConfig() precedence (packages/cli/src/env.ts), so re-running the installer # (or `openllm update`) from a preview/self-host origin does NOT silently reset a # user's persisted OPENLLM_CLOUD_ORIGIN back to production. An explicit # OPENLLM_CLOUD_ORIGIN in the environment still wins. ORIGIN="${OPENLLM_CLOUD_ORIGIN:-}" [ -n "$ORIGIN" ] || ORIGIN="$(env_file_value OPENLLM_CLOUD_ORIGIN)" [ -n "$ORIGIN" ] || ORIGIN="https://www.openllm.sh" ORIGIN="${ORIGIN%/}" has_line_break "$ORIGIN" && die "OPENLLM_CLOUD_ORIGIN must not contain a line break" [ -n "$ORIGIN" ] || die "OPENLLM_CLOUD_ORIGIN must not be empty" # Effective port — explicit env, else the port already persisted in the shared # env file, else the default. Mirrors the ORIGIN precedence above. A malformed # selected value falls back to the default rather than partially parsing. # # `normalize_daemon_port` mirrors packages/sdk/protocol/daemon-port.ts's # `parseOpenllmDaemonPort` byte-for-byte: strip an inline `# comment` and one # layer of quotes, in the order that depends on whether the comment sits # INSIDE or OUTSIDE the quotes (`"59321 # local"` vs `"59321" # local` vs a # bare `59321 # local`), then require a plain decimal in 1-65535. No eval, no # sourcing, no octal interpretation (a leading-zero string like `"08787"` # still parses as decimal here, matching `Number.parseInt(_, 10)`), and the # digit-count bound below keeps `[ ... -ge ... ]` from ever seeing a string # long enough to trip a shell integer-overflow diagnostic. normalize_daemon_port() { local raw="$1" trimmed value decommented stripped trimmed="$(trim_whitespace "$raw")" if [[ "$trimmed" =~ ^\".*\"$ || "$trimmed" =~ ^\'.*\'$ ]] && [ "${#trimmed}" -ge 2 ]; then value="${trimmed:1:${#trimmed}-2}" if [[ "$value" =~ ^(.*)[[:space:]]#.*$ ]]; then value="$(trim_whitespace "${BASH_REMATCH[1]}")" fi else decommented="$trimmed" if [[ "$trimmed" =~ ^(.*)[[:space:]]#.*$ ]]; then decommented="$(trim_whitespace "${BASH_REMATCH[1]}")" fi if { [[ "$decommented" =~ ^\".*\"$ || "$decommented" =~ ^\'.*\'$ ]] && [ "${#decommented}" -ge 2 ]; }; then value="${decommented:1:${#decommented}-2}" else value="$decommented" fi fi stripped="$(trim_whitespace "$value")" case "$stripped" in ''|*[!0-9]*) return 1 ;; esac [ "${#stripped}" -le 7 ] || return 1 { [ "$stripped" -ge 1 ] && [ "$stripped" -le 65535 ]; } || return 1 printf '%s' "$stripped" } # Compiled default when OPENLLM_DAEMON_PORT is unset in both the process env # and the env file. An explicit or persisted port is never probed or changed. DEFAULT_DAEMON_PORT=8787 # Kept for the port_is_free / find_available_port helpers (tests + diagnostics); # missing-port resolution no longer scans — it uses DEFAULT_DAEMON_PORT. PORT_SCAN_LIMIT=10 # Is 127.0.0.1:$port free to bind? Returns 0 free, 1 occupied, 2 unverifiable # — a tier returns 2 (rather than falling through) the moment it gets an # answer it cannot confidently classify, so a shaky result never gets # silently reinterpreted as "free" by a later tier. No single tool is # guaranteed present, so this tries, in order: # 1. python3 — an actual bind() attempt; the only reliable tier. Its exit # code is explicit: 0 free, 1 EADDRINUSE (occupied), 2 any other error # (permission denied, missing socket support, …) — never guessed. # 2. bash's /dev/tcp, bounded by `timeout` so a filtered/backlogged port # can't hang the install — skipped outright without `timeout`, since an # unbounded connect is not an acceptable fallback. A connect success or # a reset both mean something is already there (occupied); "Connection # refused" is the ordinary free-port result. Anything else (including a # build without /dev/tcp support) falls through to the next tier. # 3. nc -z -v with a 1s timeout, tried only if 2 gave no answer. A ZERO # exit always means connected (occupied) regardless of output. A # nonzero exit is free ONLY on an explicit "Connection refused" in the # (C-locale, so the text is predictable) output; a reset is occupied; # anything else — timeout, an invalid flag this nc build rejected, a # permission failure — is unverifiable, NOT free. # 4. no reliable probe at all — unverifiable; the caller refuses to # install rather than silently gamble. # Every tier is TCP-only on 127.0.0.1 (never 0.0.0.0/UDP) and closes its probe # socket immediately, so nothing here holds a port — a bind/start race # against another process remains inherent to any check-then-act port pick. port_is_free() { local port="$1" if has_command python3; then local py_rc # The heredoc runs as the tested command of this `if` so a nonzero exit # (1 = EADDRINUSE, 2 = any other error) is read via `$?` in the `else` # branch instead of tripping `set -e` — bash exempts the whole command a # conditional tests from errexit, including everything a function it # calls (here, none — it's a direct external command) runs. if python3 - "$port" >/dev/null 2>&1 <<'PY' import errno import socket import sys s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind(("127.0.0.1", int(sys.argv[1]))) except OSError as e: sys.exit(1 if e.errno == errno.EADDRINUSE else 2) else: sys.exit(0) finally: s.close() PY then py_rc=0 else py_rc=$? fi case "$py_rc" in 0) return 0 ;; 1) return 1 ;; *) return 2 ;; esac fi if has_command timeout; then local probe probe="$(timeout 1 bash -c "exec 3<>'/dev/tcp/127.0.0.1/$port' && printf OK" 2>&1)" || true case "$probe" in OK) return 1 ;; *[Rr]efused*) return 0 ;; *"eset"*) return 1 ;; esac fi if has_command nc; then local out # Same if/else exit-code capture as the python3 tier above (a bare # failing assignment would otherwise trip `set -e` on the common "nc # exited nonzero because the port is free" case). if out="$(LC_ALL=C LANG=C nc -z -v -w 1 127.0.0.1 "$port" 2>&1)"; then return 1 fi case "$out" in *"Connection refused"*) return 0 ;; *"onnection reset"*|*"eset by peer"*) return 1 ;; esac return 2 fi return 2 } # Bounded scan for a free port starting at $1, trying at most $2 candidates # ($start, $start+1, … capped at 65535). Prints the first free port and # returns 0; returns 1 once exhausted, or 2 the moment a probe can't verify. find_available_port() { local start="$1" limit="$2" port attempt rc port="$start" attempt=0 while [ "$attempt" -lt "$limit" ]; do port_is_free "$port" rc=$? [ "$rc" -eq 0 ] && { printf '%s' "$port"; return 0; } [ "$rc" -eq 2 ] && return 2 attempt=$((attempt + 1)) port=$((port + 1)) [ "$port" -le 65535 ] || break done return 1 } # Is an OpenLLM daemon (this machine's, sharing ~/.openllm) answering on $1? # `/status` is its unauthenticated loopback route and reports its own port. openllm_daemon_on_port() { local body has_command curl || return 1 body="$(curl -fsS --noproxy '*' --max-time 2 "http://127.0.0.1:$1/status" 2>/dev/null)" || return 1 case "$body" in *"\"port\":$1,"*|*"\"port\":$1}"*) return 0 ;; esac return 1 } DAEMON_PORT="${OPENLLM_DAEMON_PORT:-}" if [ -n "$DAEMON_PORT" ]; then if NORMALIZED_PORT="$(normalize_daemon_port "$DAEMON_PORT")"; then DAEMON_PORT="$NORMALIZED_PORT" else # Warn, but never echo the raw value: it is untrusted external input # (env var content) and could carry control/escape sequences into the # user's terminal. echo "Warning: ignoring an invalid OPENLLM_DAEMON_PORT (must be a plain port number 1-65535); falling back" >&2 DAEMON_PORT="" fi fi if [ -z "$DAEMON_PORT" ]; then RAW_PERSISTED_PORT="$(env_file_raw_value OPENLLM_DAEMON_PORT)" if [ -n "$RAW_PERSISTED_PORT" ]; then NORMALIZED_PORT="$(normalize_daemon_port "$RAW_PERSISTED_PORT")" && DAEMON_PORT="$NORMALIZED_PORT" fi fi # Neither an explicit nor a persisted port exists yet — use the compiled # default. Mirrors ORIGIN above: an env file that only holds some values # (e.g. a hand-set OPENLLM_CLOUD_ORIGIN) must leave every other setting at # its default. Never scan, and never die with "no free port" for a missing # setting — that is what an origin-only ~/.openllm/.env used to trigger. if [ -z "$DAEMON_PORT" ]; then DAEMON_PORT="$DEFAULT_DAEMON_PORT" fi case "$INSTALL_MODE" in install|update|vendors) ;; *) die "OPENLLM_INSTALL_MODE must be 'install', 'update', or 'vendors'" ;; esac # Resolve interactive mode: flag/env > controlling tty. # Blank OPENLLM_INTERACTIVE is treated as unset (harness may clear it). resolve_interactive() { local raw if [ "$FLAG_INTERACTIVE" = 1 ] || [ "$FLAG_INTERACTIVE" = 0 ]; then INTERACTIVE="$FLAG_INTERACTIVE" return 0 fi if [ "${OPENLLM_INTERACTIVE+set}" = set ]; then raw="$(trim_whitespace "${OPENLLM_INTERACTIVE}")" case "$raw" in 1|true|yes|YES|True) INTERACTIVE=1; return 0 ;; 0|false|no|NO|False) INTERACTIVE=0; return 0 ;; "") ;; *) die "OPENLLM_INTERACTIVE must be 1 or 0" ;; esac fi if has_controlling_tty; then INTERACTIVE=1 else INTERACTIVE=0 fi } resolve_interactive # Product setup mode. Explicit env / --minimal|--full wins and never prompts. A # saved OPENLLM_SETUP_MODE in the env file is preserved on re-run / update. # Fresh install with no saved mode: interactive terminals ask Full vs Minimal; # headless never hangs and picks Full silently. `--dry-run` also defaults to # Full without prompting — a plan print must not block on a chooser. # `${VAR+set}` (not `-n`) so an explicit empty / whitespace-only value is still # treated as supplied. if [ "${OPENLLM_SETUP_MODE+set}" = set ]; then SETUP_MODE_EXPLICIT=1 SETUP_MODE="$(trim_whitespace "$OPENLLM_SETUP_MODE")" else SETUP_MODE="$(trim_whitespace "$(env_file_value OPENLLM_SETUP_MODE || true)")" if [ -z "$SETUP_MODE" ] && [ "$INSTALL_MODE" != update ] && [ "$INSTALL_MODE" != vendors ]; then if [ "$FLAG_DRY_RUN" = 1 ]; then SETUP_MODE=full elif [ "$INTERACTIVE" = 1 ]; then if ! prompt_setup_mode; then die "setup cancelled — re-run and choose Full or Minimal (or pass --minimal / OPENLLM_SETUP_MODE=…)" fi else SETUP_MODE=full fi fi fi case "$SETUP_MODE" in "" ) if [ "$SETUP_MODE_EXPLICIT" = 1 ]; then die "OPENLLM_SETUP_MODE must be 'full' or 'minimal'" fi # vendors mode with no saved setup defaults to full provisioning. if [ "$INSTALL_MODE" = vendors ]; then SETUP_MODE=full fi ;; full|minimal) ;; *) die "OPENLLM_SETUP_MODE must be 'full' or 'minimal'" ;; esac # Minimal install implies no vendor provisioning and no daemon start for this # run. An explicit OPENLLM_SKIP_VENDOR_CLIS remains honored for full installs. # Full-only sub-flags with Minimal fail here — before mkdir / download / env # writes — so a contradiction never leaves side effects behind. if [ "$SETUP_MODE" = minimal ]; then if [ "$FLAG_START" = 1 ]; then die "--start cannot be combined with --minimal (pass --full to override a saved Minimal setup)" fi if [ "$FLAG_START" = 0 ]; then die "--no-start cannot be combined with --minimal (pass --full to override a saved Minimal setup)" fi if [ -n "$FLAG_VENDORS_ONLY" ]; then die "--vendors cannot be combined with --minimal (pass --full to override a saved Minimal setup)" fi if [ "$FLAG_NO_VENDORS" = 1 ]; then die "--no-vendors cannot be combined with --minimal (pass --full to override a saved Minimal setup)" fi # Explicit `--minimal` + OPENLLM_START_DAEMON=1 is the env equivalent of # `--minimal --start` and must fail the same way. A saved Minimal mode with # a harness/desktop OPENLLM_START_DAEMON=1 is ignored (WANT_START stays 0). if [ "$FLAG_SETUP_MODE" = minimal ] && [ "${OPENLLM_START_DAEMON+set}" = set ]; then raw_start="$(trim_whitespace "${OPENLLM_START_DAEMON}")" case "$raw_start" in 1|true|yes|YES|True) die "OPENLLM_START_DAEMON=1 cannot be combined with --minimal (pass --full to override a saved Minimal setup)" ;; 0|false|no|NO|False|"") ;; *) die "OPENLLM_START_DAEMON must be 1 or 0" ;; esac fi OPENLLM_SKIP_VENDOR_CLIS=1 fi # Resolve whether this run should start the daemon (Full only). # Blank OPENLLM_START_DAEMON is treated as unset so tests can clear the harness # default and exercise the true interactive/headless default. resolve_want_start() { local raw WANT_START=0 if [ "$SETUP_MODE" = minimal ]; then # Full-only start requests already rejected above (flags + OPENLLM_START_DAEMON). WANT_START=0 return 0 fi if [ "$FLAG_START" = 1 ]; then WANT_START=1 return 0 fi if [ "$FLAG_START" = 0 ]; then WANT_START=0 return 0 fi if [ "${OPENLLM_START_DAEMON+set}" = set ]; then raw="$(trim_whitespace "${OPENLLM_START_DAEMON}")" case "$raw" in 1|true|yes|YES|True) WANT_START=1; return 0 ;; 0|false|no|NO|False) WANT_START=0; return 0 ;; "") ;; *) die "OPENLLM_START_DAEMON must be 1 or 0" ;; esac fi # Interactive Full starts; headless Full does not. if [ "$INTERACTIVE" = 1 ]; then WANT_START=1 else WANT_START=0 fi } resolve_want_start if [ "$FLAG_DRY_RUN" = 1 ]; then cat <.`: split on the LAST dot. The anchor never leaves this # machine — from here on SUPPLIED_KEY is the bare key, and the exported # OPENLLM_API_KEY every child process inherits is overwritten with it. if ! is_usable_api_key "$SUPPLIED_KEY"; then candidate_anchor="${SUPPLIED_KEY##*.}" candidate_key="${SUPPLIED_KEY%.*}" if is_usable_api_key "$candidate_key" && is_device_anchor "$candidate_anchor"; then SUPPLIED_ANCHOR="$candidate_anchor" SUPPLIED_KEY="$candidate_key" fi unset candidate_anchor candidate_key fi is_usable_api_key "$SUPPLIED_KEY" || die "OPENLLM_API_KEY has an invalid format" export OPENLLM_API_KEY="$SUPPLIED_KEY" fi API_KEY="" mkdir -p "$BIN_DIR" "$(dirname "$ENV_FILE")" # --- the ONE install entry point ------------------------------------------ # `vendors` mode only provisions missing vendor CLIs (used by `openllm start`). # It requires an already-installed binary and never downloads or starts anything. if [ "$INSTALL_MODE" = vendors ]; then [ -x "$BIN_DIR/openllm" ] || die "OpenLLM is not installed yet — run the installer first" CLI_VERSION="$("$BIN_DIR/openllm" --version 2>/dev/null | head -n 1 | tr -d '\r' || true)" CLI_VERSION="${CLI_VERSION#openllm }" CLI_VERSION="${CLI_VERSION#v}" [ -n "$CLI_VERSION" ] || CLI_VERSION="unknown" API_KEY="$(trim_whitespace "$(env_file_lookup OPENLLM_API_KEY || true)")" if [ -n "$API_KEY" ] && is_usable_api_key "$API_KEY"; then export OPENLLM_API_KEY="$API_KEY" else API_KEY="" fi ENV_DIGEST_BEFORE="$(sha256_of "$ENV_FILE" 2>/dev/null || true)" else # /api/install validates the committed daemon + CLI release pins in TypeScript # (allow-listed repo, well-formed digests, a published tag for this target) and # fails closed. Hitting it first means a mis-pinned or half-published release is # refused BEFORE we download anything. No query parameters. echo "Resolving the current OpenLLM release..." MANIFEST="$(curl -fsSL "$ORIGIN/api/install" 2>/dev/null)" \ || die "could not reach $ORIGIN/api/install — check OPENLLM_CLOUD_ORIGIN and your network" # Extract one "key": "value" string field. The document is small, flat, and # machine-generated by us, so a scoped sed is enough — no jq dependency on a # fresh machine. json_field() { printf '%s' "$MANIFEST" \ | tr -d '\n' \ | sed -n "s/.*\"$1\"[[:space:]]*:[[:space:]]*\"\([^\"]*\)\".*/\1/p" } CLI_VERSION="$(json_field cli_version)" [ -n "$CLI_VERSION" ] || die "no OpenLLM release is published yet" # --- the update lease ------------------------------------------------------- # One process at a time may replace the `openllm` binary: the daemon's # auto-update, the CLI's self-update, this installer (also what `openllm update` # and the desktop app run). `$BIN_DIR/.update.lock` is created exclusively # (a hard link of its finished body — no flock on fresh installs) and its JSON # body is the progress the daemon's /status and the desktop app show. Format # and staleness rules: packages/cli/src/update-lease.ts — keep in step. UPDATE_LOCK="$BIN_DIR/.update.lock" UPDATE_LEASE_STALE_SEC=900 # The desktop app passes OPENLLM_UPDATE_SOURCE=app so its update is named. case "${OPENLLM_UPDATE_SOURCE:-}" in app) UPDATE_SOURCE=app ;; *) UPDATE_SOURCE=installer ;; esac UPDATE_LEASE_HELD=0 UPDATE_STARTED_MS=0 now_ms() { printf '%s000' "$(date +%s)"; } # A numeric field of the lock body ("pid", "updated_at"). update_lock_num() { sed -n "s/.*\"$1\"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p" "$UPDATE_LOCK" 2>/dev/null | head -n 1 } update_lock_str() { sed -n "s/.*\"$1\"[[:space:]]*:[[:space:]]*\"\([^\"]*\)\".*/\1/p" "$UPDATE_LOCK" 2>/dev/null | head -n 1 } update_lease_body() { local version_json=null [ -n "$2" ] && version_json="\"$2\"" printf '{"pid":%s,"source":"%s","version":%s,"phase":"%s","received":null,"total":null,"started_at":%s,"updated_at":%s}' \ "$$" "$UPDATE_SOURCE" "$version_json" "$1" "$UPDATE_STARTED_MS" "$(now_ms)" } # Whether the lock names a live holder with a fresh heartbeat. update_lock_live() { local pid updated now pid="$(update_lock_num pid)" updated="$(update_lock_num updated_at)" [ -n "$pid" ] && [ -n "$updated" ] || return 1 now="$(now_ms)" [ $(( (now - updated) / 1000 )) -le "$UPDATE_LEASE_STALE_SEC" ] || return 1 kill -0 "$pid" 2>/dev/null } # create_update_lock : create the lock with its whole body, # or fail when it exists. Written to a temp file, then hard-linked into place # (`ln` refuses an existing target), so a reader never sees an empty lock and # mistakes it for a stale one. # # A filesystem without hard links (some FUSE / network mounts, exFAT) can't # do that: there it falls back to an O_EXCL create (`set -C`), whose empty- # until-written window is the price of still being able to install at all. create_update_lock() { local tmp="$UPDATE_LOCK.$$.new" rc=1 update_lease_body "$1" "$2" > "$tmp" 2>/dev/null || { rm -f "$tmp"; return 1; } if ln "$tmp" "$UPDATE_LOCK" 2>/dev/null; then rc=0 elif [ ! -e "$UPDATE_LOCK" ]; then # `ln` failed with no lock in the way: no hard links here. (set -C; cat "$tmp" > "$UPDATE_LOCK") 2>/dev/null && rc=0 fi rm -f "$tmp" return "$rc" } # remove_stale_lock: take a stale lock out of the way without ever deleting a # live one. Another installer may have replaced the stale body we judged with # its own fresh lease in the meantime, so the lock is renamed aside (atomic) # and only discarded if it is still the body we judged stale; otherwise it is # put back (`ln` never overwrites a newer lock). remove_stale_lock() { local judged aside="$UPDATE_LOCK.$$.stale" judged="$(cat "$UPDATE_LOCK" 2>/dev/null)" || return 0 mv -f "$UPDATE_LOCK" "$aside" 2>/dev/null || return 0 if [ "$(cat "$aside" 2>/dev/null)" != "$judged" ]; then ln "$aside" "$UPDATE_LOCK" 2>/dev/null || { [ -e "$UPDATE_LOCK" ] || mv -f "$aside" "$UPDATE_LOCK" 2>/dev/null; } || true fi rm -f "$aside" } # acquire_update_lease : take the lease or die naming who holds it. acquire_update_lease() { local attempt UPDATE_STARTED_MS="$(now_ms)" for attempt in 1 2; do if create_update_lock download "$1"; then UPDATE_LEASE_HELD=1 trap release_update_lease EXIT return 0 fi if update_lock_live; then local holder case "$(update_lock_str source)" in daemon) holder="the OpenLLM daemon" ;; app) holder="the OpenLLM desktop app" ;; cli) holder="another openllm command" ;; *) holder="another installer" ;; esac die "openllm is already being updated by $holder — try again when it finishes" fi # Stale (holder gone or silent): take it over. remove_stale_lock done die "could not take the update lock: $UPDATE_LOCK" } # update_lease_phase : record progress while holding the lease. update_lease_phase() { [ "$UPDATE_LEASE_HELD" = 1 ] || return 0 [ "$(update_lock_num pid)" = "$$" ] || return 0 local tmp="$UPDATE_LOCK.$$.tmp" update_lease_body "$1" "$2" > "$tmp" 2>/dev/null && mv -f "$tmp" "$UPDATE_LOCK" 2>/dev/null || rm -f "$tmp" } release_update_lease() { [ "$UPDATE_LEASE_HELD" = 1 ] || return 0 UPDATE_LEASE_HELD=0 if [ "$(update_lock_num pid)" = "$$" ]; then rm -f "$UPDATE_LOCK"; fi } # --- fetch + verify + install one component ------------------------------- # The asset URL and digest come from the `/api/install` manifest (the same # read that named the version), never from a second pin lookup. install_component() { local name="$1" url="$2" published="$3" version="$4" local dest="$BIN_DIR/$name" local installed stamp="$BIN_DIR/.$name.sha256.stamp" # Skip a tens-of-MB download when what's installed already matches. # Developer-ID-signed + notarized binaries keep their published digest on # disk (we no longer force ad-hoc re-sign when codesign --verify passes). # The stamp remains for the fallback ad-hoc path (unsigned/invalid) where # re-signing rewrites bytes after the published digest check. # Also require the on-disk `--version` to match the pinned `$version` so a # stale cached digest cannot claim "up to date" while `/api/install` already # names a newer release. if [ -x "$dest" ]; then local on_disk_version="" on_disk_version="$("$dest" --version 2>/dev/null | head -n 1 | tr -d '\r' || true)" on_disk_version="${on_disk_version#openllm }" on_disk_version="${on_disk_version#v}" installed="$(sha256_of "$dest" || true)" # When `$version` is pinned, require a verified on-disk `--version` match # before any digest/stamp short-circuit. An empty `--version` is not a match. if [ -n "$installed" ] && { [ -z "$version" ] || [ "$on_disk_version" = "$version" ] }; then if [ "$installed" = "$published" ]; then echo " $name is already up to date" return 0 fi if [ -f "$stamp" ]; then local sp si read -r sp si < "$stamp" || true if [ "$sp" = "$published" ] && [ "$si" = "$installed" ]; then echo " $name is already up to date" return 0 fi fi elif [ -n "$version" ] && [ "$on_disk_version" != "$version" ]; then if [ -n "$on_disk_version" ]; then echo " $name on disk is v$on_disk_version; pinned release is v$version — downloading" else echo " $name on disk has no usable --version; pinned release is v$version — downloading" fi fi fi # Only the shared binary is leased; it is the file every updater replaces. [ "$name" = openllm ] && acquire_update_lease "$version" echo "Downloading $name ${version:+$version }($TARGET)..." # Stage inside $BIN_DIR: same filesystem as $dest (so the final mv is an # atomic rename, not a cross-device copy) and on the roomy root disk — minimal # cloud images mount a tiny RAM-backed /tmp where a download this size fails. local dl="$BIN_DIR/.$name.download.$$" local bin="$BIN_DIR/.$name.bin.$$" trap 'rm -f "$dl" "$bin"' RETURN # Bounded download: a stalled mirror must not hang the installer (or the # desktop pair waiter) indefinitely. Progress goes to stderr so a non-TTY # desktop log still shows movement; -s would hide it. local dl_connect_sec="${OPENLLM_DOWNLOAD_CONNECT_TIMEOUT_SEC:-30}" local dl_max_sec="${OPENLLM_DOWNLOAD_MAX_TIME_SEC:-600}" case "$dl_connect_sec" in ''|*[!0-9]*) dl_connect_sec=30 ;; esac case "$dl_max_sec" in ''|*[!0-9]*) dl_max_sec=600 ;; esac echo " fetching $name (connect ≤${dl_connect_sec}s, total ≤${dl_max_sec}s)…" if ! curl -fL --connect-timeout "$dl_connect_sec" --max-time "$dl_max_sec" \ --progress-bar "$url" -o "$dl"; then die "download failed or timed out after ${dl_max_sec}s: $url" fi # Assets are gzipped; the pinned digest is over the DECOMPRESSED binary, so # the integrity gate is independent of gzip's non-determinism. if gzip -t "$dl" >/dev/null 2>&1; then gzip -dc "$dl" > "$bin" || die "could not decompress $name" else mv "$dl" "$bin" fi update_lease_phase verify "$version" local actual actual="$(sha256_of "$bin")" [ -n "$actual" ] || die "could not hash the downloaded $name" if [ "$actual" != "$published" ]; then die "checksum mismatch for $name (expected $published, got $actual) — refusing to install" fi update_lease_phase install "$version" chmod 0755 "$bin" # A matching checksum alone can be a stale cached asset. When a version is # pinned, require the staged binary's `--version` to equal it before replacing # the destination — leave the installed binary unchanged on mismatch. if [ -n "$version" ]; then local staged_version="" staged_version="$("$bin" --version 2>/dev/null | head -n 1 | tr -d '\r' || true)" staged_version="${staged_version#openllm }" staged_version="${staged_version#v}" if [ "$staged_version" != "$version" ]; then die "downloaded $name reports version '${staged_version:-unknown}' but pin is '$version' — refusing to replace $dest" fi fi mv -f "$bin" "$dest" # macOS: strip quarantine. Preserve a valid Developer ID / notarized # signature (codesign --verify). Only ad-hoc sign when the signature is # missing/invalid — force ad-hoc would strip notarization and rewrite bytes. if [ "$OS" = "darwin" ]; then xattr -d com.apple.quarantine "$dest" >/dev/null 2>&1 || true if ! codesign --verify "$dest" >/dev/null 2>&1; then codesign --force --sign - "$dest" >/dev/null 2>&1 || true printf '%s %s\n' "$published" "$(sha256_of "$dest")" > "$stamp" 2>/dev/null || true fi fi echo " $name installed → $dest" INSTALLED_COMPONENTS="$INSTALLED_COMPONENTS $name" release_update_lease } # Version, asset and digest all come from the ONE `/api/install` response read # above. Resolving the bytes through a second request let a deploy rollout # answer the two with different pins ("pin vN, bytes vN+1"). The asset URL names # an immutable release tag, so the bytes cannot drift after this read. CLI_URL="$(json_field "cli_url_$TARGET")" CLI_SHA256="$(json_field "cli_sha256_$TARGET")" if [ -z "$CLI_URL" ] || [ -z "$CLI_SHA256" ]; then # The pin's `targets` arrays (under cli/daemon) name what this release # published. Absent from them → this arch was omitted. (A target listed # without cli_url_* can't happen: /api/install builds both from the same # valid-digest list.) if printf '%s' "$MANIFEST" | tr -d '\n' \ | grep -oE '"targets"[[:space:]]*:[[:space:]]*\[[^]]*\]' \ | grep -q . \ && ! printf '%s' "$MANIFEST" | tr -d '\n' \ | grep -oE '"targets"[[:space:]]*:[[:space:]]*\[[^]]*\]' \ | grep -q "\"$TARGET\""; then case "$CLI_VERSION" in *-*) die "this release has no build for $TARGET; use the stable installer (https://www.openllm.sh/install)" ;; esac die "this release has no build for $TARGET" fi die "$ORIGIN/api/install names no openllm binary for $TARGET — a release may be rolling out; try again in a minute" fi [[ "$CLI_SHA256" =~ ^[0-9a-f]{64}$ ]] || die "malformed checksum for openllm" [ "$CLI_URL" = "https://github.com/openllmsh/cli/releases/download/v$CLI_VERSION/openllm-$TARGET.gz" ] \ || die "unexpected openllm asset URL in $ORIGIN/api/install: $CLI_URL" install_component openllm "$CLI_URL" "$CLI_SHA256" "$CLI_VERSION" # The pre-merge daemon name stays as a symlink: existing launchd/systemd units # and scripts that exec `openllmd` keep working — the binary routes an # `openllmd`-named invocation to its daemon half. ln -sfn openllm "$BIN_DIR/openllmd" fi # --- the shared config file ------------------------------------------------ # Re-read under the same exclusive `$ENV_FILE.lock` protocol as the daemon's # writeEnvFileVars. Never rebuild this file from a pre-download snapshot: a daemon # can mint a device id or update credentials while binaries are downloading. # Delegates to `env_file_lookup` for the same last-match-wins, trim/skip # semantics as `parseEnvLines` (packages/cli/daemon/src/env.ts) — the values read # here (API key, device id, PTY flag) are exactly what that parser resolves # on the daemon's own next boot. read_env_value() { env_file_lookup "$1" } write_env_file() { local lock="$ENV_FILE.lock" attempt=0 acquired=0 # `noclobber` opens with O_EXCL. This intentionally uses the daemon's lock-file # shape rather than flock, which is unavailable on some supported fresh installs. while [ "$attempt" -lt 500 ]; do if (set -C; : > "$lock") 2>/dev/null; then acquired=1; break; fi attempt=$((attempt + 1)) sleep 0.01 done [ "$acquired" = 1 ] || die "could not acquire config lock: $lock" local current_key current_device current_anchor desired_key desired_anchor tmp line key current_key="$(trim_whitespace "$(read_env_value OPENLLM_API_KEY || true)")" current_device="$(read_env_value OPENLLM_DEVICE_ID || true)" current_anchor="$(trim_whitespace "$(read_env_value OPENLLM_DEVICE_ANCHOR || true)")" if [ -n "$SUPPLIED_KEY" ]; then desired_key="$SUPPLIED_KEY" else desired_key="$current_key" if [ -n "$desired_key" ] && ! is_usable_api_key "$desired_key"; then echo "Ignoring the persisted API key because its format is invalid; OpenLLM will install without starting the daemon." >&2 desired_key="" fi fi # The device trust anchor is its own line, OPENLLM_DEVICE_ANCHOR, beside the # BARE key. A supplied anchor replaces it (re-running install is rotation). # A bare supplied key drops an existing anchor only when its public key id # differs from the saved key's id (or either cannot be parsed). The anchor's # pair secret is bound to that id, so a new secret for the same id leaves it. # Keyless install keeps the current line untouched. local supplied_key_id current_key_id supplied_key_id="${SUPPLIED_KEY#sk-llm-}" supplied_key_id="${supplied_key_id%%.*}" current_key_id="${current_key#sk-llm-}" current_key_id="${current_key_id%%.*}" if [ -n "$SUPPLIED_ANCHOR" ]; then desired_anchor="$SUPPLIED_ANCHOR" elif [ -n "$SUPPLIED_KEY" ] && { ! is_usable_api_key "$current_key" || [ "$supplied_key_id" != "$current_key_id" ]; }; then desired_anchor="" else desired_anchor="$current_anchor" fi tmp="$ENV_FILE.tmp.$$" # Install the RETURN cleanup only after all nested reads have completed: Bash # runs a RETURN trap for nested functions too. trap 'rm -f "$tmp" "$lock"' RETURN # Tighten umask only for the temp-file creation window (closing the race # before `chmod 0600`), then restore it so later installer steps and child # processes keep the caller's umask. local saved_umask saved_umask="$(umask)" umask 077 : > "$tmp" # Keep unrelated lines byte-for-byte, but replace every installer-owned key with # one canonical occurrence. An ignored invalid persisted key is therefore removed. local wrote_origin=0 wrote_port=0 wrote_key=0 wrote_device=0 wrote_anchor=0 wrote_setup=0 # Only rewrite setup mode when we have a resolved value to persist. An update # with no prior/explicit mode leaves any existing line (or its absence) alone. local desired_setup="$SETUP_MODE" if [ -f "$ENV_FILE" ]; then while IFS= read -r line || [ -n "$line" ]; do key="${line%%=*}" case "$key" in OPENLLM_CLOUD_ORIGIN) [ "$wrote_origin" = 1 ] || { printf 'OPENLLM_CLOUD_ORIGIN=%s\n' "$ORIGIN" >> "$tmp"; wrote_origin=1; } ;; OPENLLM_DAEMON_PORT) [ "$wrote_port" = 1 ] || { printf 'OPENLLM_DAEMON_PORT=%s\n' "$DAEMON_PORT" >> "$tmp"; wrote_port=1; } ;; OPENLLM_API_KEY) if [ -n "$desired_key" ] && [ "$wrote_key" = 0 ]; then printf 'OPENLLM_API_KEY=%s\n' "$desired_key" >> "$tmp"; wrote_key=1; fi ;; OPENLLM_DEVICE_ANCHOR) if [ -n "$desired_anchor" ] && [ "$wrote_anchor" = 0 ]; then printf 'OPENLLM_DEVICE_ANCHOR=%s\n' "$desired_anchor" >> "$tmp"; wrote_anchor=1; fi ;; OPENLLM_DEVICE_ID) if [ -n "$current_device" ] && [ "$wrote_device" = 0 ]; then printf 'OPENLLM_DEVICE_ID=%s\n' "$current_device" >> "$tmp"; wrote_device=1; fi ;; OPENLLM_SETUP_MODE) if [ -n "$desired_setup" ] && [ "$wrote_setup" = 0 ]; then printf 'OPENLLM_SETUP_MODE=%s\n' "$desired_setup" >> "$tmp" wrote_setup=1 elif [ -z "$desired_setup" ]; then # Preserve the existing line byte-for-byte on an update that did not # resolve a mode (neither explicit nor previously present after trim). printf '%s\n' "$line" >> "$tmp" wrote_setup=1 fi ;; *) printf '%s\n' "$line" >> "$tmp" ;; esac done < "$ENV_FILE" fi [ "$wrote_origin" = 1 ] || printf 'OPENLLM_CLOUD_ORIGIN=%s\n' "$ORIGIN" >> "$tmp" [ "$wrote_port" = 1 ] || printf 'OPENLLM_DAEMON_PORT=%s\n' "$DAEMON_PORT" >> "$tmp" [ -z "$desired_key" ] || [ "$wrote_key" = 1 ] || printf 'OPENLLM_API_KEY=%s\n' "$desired_key" >> "$tmp" [ -z "$current_device" ] || [ "$wrote_device" = 1 ] || printf 'OPENLLM_DEVICE_ID=%s\n' "$current_device" >> "$tmp" [ -z "$desired_anchor" ] || [ "$wrote_anchor" = 1 ] || printf 'OPENLLM_DEVICE_ANCHOR=%s\n' "$desired_anchor" >> "$tmp" [ -z "$desired_setup" ] || [ "$wrote_setup" = 1 ] || printf 'OPENLLM_SETUP_MODE=%s\n' "$desired_setup" >> "$tmp" chmod 0600 "$tmp" # Abort with a clear error if the atomic replace fails — never fall through to # announce success (or set API_KEY) on a config that was not written. The # RETURN trap still cleans up the temp file + lock. mv -f "$tmp" "$ENV_FILE" || die "could not write config file: $ENV_FILE" chmod 0600 "$ENV_FILE" umask "$saved_umask" rm -f "$lock" trap - RETURN API_KEY="$desired_key" echo " gateway config written → $ENV_FILE" } # Fingerprint the config before this run touches it: a running daemon is # restarted at the end only when what it runs on changed — the binary # (INSTALLED_COMPONENTS) or this file (key, origin, port, anchor from the # sign-in below or this rewrite). if [ "$INSTALL_MODE" != vendors ]; then ENV_DIGEST_BEFORE="$(sha256_of "$ENV_FILE" 2>/dev/null || true)" write_env_file fi # --- shell wiring ---------------------------------------------------------- # Delegated to the binaries themselves so the installer and a human run the # SAME code path: `openllm setup` creates the openllm + ollm PATH symlinks, # writes the one marked rc block (PATH + `alias ollm=openllm`), and installs # completion for both names. Best-effort — a sandboxed or read-only environment # leaves the binary usable by absolute path. # First-install only: a manual update must not touch PATH symlinks, the shell # rc block, or completion — those are the user's environment, already wired. if [ "$INSTALL_MODE" != update ] && [ "$INSTALL_MODE" != vendors ]; then # OPENLLM_SKIP_SHELL_SETUP — leave PATH symlinks, shell rc, and completion alone # (useful for CI / non-interactive hosts that already manage the environment). if [ -z "${OPENLLM_SKIP_SHELL_SETUP:-}" ]; then "$BIN_DIR/openllm" setup || echo " note: run '$BIN_DIR/openllm setup' yourself to finish shell setup" "$BIN_DIR/openllm" daemon completion install >/dev/null 2>&1 || true fi fi # --- device trust anchor --------------------------------------------------- # Pin the account device-control key from the anchor the dashboard put after # the key — a local trust root, so the cloud never chooses it. write_env_file # already stored it as OPENLLM_DEVICE_ANCHOR (never exported); `daemon anchor` # validates it, re-writes the same two lines and pins. The anchored key goes # over stdin (never argv); the daemon prints only the bare key, discarded. # Installing with the anchor is the sessions opt-in, so turn them on here # (a re-install after a Turn off included); disable writes 0 and keeps the # anchor. A Routebox refuses the enable and keeps them off — that refusal # alone (exit code 3) is soft; any other enable failure (disk / permissions) # fails install. if [ -n "$SUPPLIED_ANCHOR" ]; then printf '%s.%s' "$SUPPLIED_KEY" "$SUPPLIED_ANCHOR" \ | "$BIN_DIR/openllm" daemon anchor >/dev/null \ || die "the device trust anchor was rejected — copy the install command from the dashboard again" enable_out="$("$BIN_DIR/openllm" daemon device enable 2>&1)" && enable_rc=0 || enable_rc=$? # 3 = the Routebox refusal (soft). if [ "$enable_rc" -ne 0 ] && [ "$enable_rc" -ne 3 ]; then printf '%s\n' "$enable_out" >&2 die "could not enable device sessions" fi fi SUPPLIED_ANCHOR="" # --- authenticate before vendor install / daemon start --------------------- # Ordered setup: binary first (already done), then OpenLLM authentication / # reuse of a usable credential, then (full mode only) vendor provisioning and # daemon startup. Minimal mode authenticates only. # Re-read the shared env after `openllm login` so a successful auth continues # the same installer run without requiring a second command. refresh_api_key_from_env() { local refreshed refreshed="$(trim_whitespace "$(env_file_lookup OPENLLM_API_KEY || true)")" if [ -n "$refreshed" ] && is_usable_api_key "$refreshed"; then API_KEY="$refreshed" export OPENLLM_API_KEY="$refreshed" else API_KEY="" fi } AUTH_ATTEMPTED=0 AUTH_FAILED=0 if [ -z "$API_KEY" ] && [ "$INSTALL_MODE" != update ] && [ "$INSTALL_MODE" != vendors ]; then # Authenticate via `openllm login` only in interactive mode with a controlling # tty. `--non-interactive` on a PTY must not hang on login — headless keyless # prints `Next: openllm login --non-interactive` in the summary and exits 0. if [ "$INTERACTIVE" = 1 ] && has_controlling_tty && [ -x "$BIN_DIR/openllm" ]; then AUTH_ATTEMPTED=1 echo if "$BIN_DIR/openllm" login --no-restart < /dev/tty; then refresh_api_key_from_env else AUTH_FAILED=1 fi fi fi # --- provision the vendor subscription CLIs (background, never awaited) ---- # The daemon RUNS the official vendor CLIs but never INSTALLS them (it runs # under an OS sandbox that intentionally can't touch shell rc files). So THIS # script — run by the user, unsandboxed, with a real HOME/PATH/rc — is where a # missing CLI gets installed: launch each official installer in the background # and move on. The daemon starts as soon as the binary + env are ready; vendor # CLIs must never delay that. Each native installer does its own normal # rc/PATH edit. The daemon only LINKS its isolated run-view to whatever lands # (see cli-install.ts) — symlink self-heal is separate and needs no write grant # on the host CLI dirs. Logged to ~/.openllm/cli-install.log. Full setup only, # and only AFTER authentication succeeds (or a usable key was already present). # Minimal / update / keyless installs never reach here. # # Progress is tracked in per-provider JSON under # `$OPENLLM_DIR/vendor-cli-install/.json` (protocol subscription slugs). # Process identity / paths stay local; the daemon reader maps them to wire # `cli_install` without PIDs or logs. Ownership locks are SEPARATE from # `$ENV_FILE.lock` so installer concurrency never contends with config writes. vendor_cli_now_ms() { # Bash 3.2 / macOS date has no %N — second resolution * 1000 is enough. # Inline arithmetic avoids a nested `$(date)` subshell on top of the caller's. local _secs _secs="$(date +%s)" echo $((_secs * 1000)) } vendor_cli_json_escape() { # Values we emit are attempt ids / stages / ps lstart — keep escaping tight. # Pure parameter expansion (no sed fork) — hot path during progress writes. local s="$1" s="${s//\\/\\\\}" s="${s//\"/\\\"}" printf '%s' "$s" } vendor_cli_attempt_id() { # This id reaches the cloud; process identity belongs only in local fields. local _secs _secs="$(date +%s)" printf 'vci-%s-%s-%s-%s-%s' "$_secs" \ "${RANDOM:-0}" "${RANDOM:-0}" "${RANDOM:-0}" "${RANDOM:-0}" } # Remove only the attempt-scoped handshake/pid pair passed in. Never a # provider-wide path or glob — a completed worker must not wipe a newer attempt. vendor_cli_cleanup_attempt_files() { local worker_pid_file="$1" handshake_file="$2" rm -f "$worker_pid_file" "$handshake_file" 2>/dev/null || true } # Tiny create-or-truncate seam for the post-spawn handshake file. Extracted so # tests can force a failure after the worker is already running without racing # directory permissions. vendor_cli_touch() { : >"$1" } vendor_cli_process_start() { local pid="$1" raw # Portable PID-reuse guard (same idea as daemon child-supervisor lstart). # Locale/TZ pinned: daemon processStartTime compares this from another env. raw="$(LC_ALL=C TZ=UTC ps -o lstart= -p "$pid" 2>/dev/null)" || return 0 raw="${raw#"${raw%%[![:space:]]*}"}" raw="${raw%"${raw##*[![:space:]]}"}" printf '%s' "$raw" } vendor_cli_pid_live() { local pid="$1" expected_start="${2:-}" live_start [ -n "$pid" ] || return 1 kill -0 "$pid" 2>/dev/null || return 1 if [ -n "$expected_start" ]; then live_start="$(vendor_cli_process_start "$pid" || true)" [ -n "$live_start" ] || return 1 [ "$live_start" = "$expected_start" ] || return 1 fi return 0 } # Cached once per process — every progress write used to re-printf + re-mkdir. VENDOR_CLI_STATE_DIR="" VENDOR_CLI_STATE_DIR_READY=0 vendor_cli_state_dir() { if [ -z "$VENDOR_CLI_STATE_DIR" ]; then VENDOR_CLI_STATE_DIR="$OPENLLM_DIR/vendor-cli-install" fi printf '%s' "$VENDOR_CLI_STATE_DIR" } vendor_cli_ensure_state_dir() { local dir dir="$(vendor_cli_state_dir)" if [ "$VENDOR_CLI_STATE_DIR_READY" = 1 ] && [ -d "$dir" ]; then printf '%s' "$dir" return 0 fi mkdir -p "$dir" || return 1 chmod 700 "$dir" 2>/dev/null || true VENDOR_CLI_STATE_DIR_READY=1 printf '%s' "$dir" } # Atomic JSON replace for one provider. Returns nonzero on any write failure. # Temp names use mktemp — NOT `$$` — because Bash 3.2 subshells share the # parent's `$$`, so parent/worker handoff would clobber the same tmp path. vendor_cli_write_state() { local slug="$1" json="$2" local dir tmp final saved_umask dir="$(vendor_cli_ensure_state_dir)" || return 1 final="$dir/${slug}.json" saved_umask="$(umask)" umask 077 tmp="$(mktemp "$dir/.${slug}.json.tmp.XXXXXX")" || { umask "$saved_umask" return 1 } if ! printf '%s\n' "$json" >"$tmp"; then umask "$saved_umask" rm -f "$tmp" return 1 fi # umask 077 already makes the tmp 0600 — skip an extra chmod fork. if ! mv -f "$tmp" "$final"; then umask "$saved_umask" rm -f "$tmp" return 1 fi umask "$saved_umask" return 0 } vendor_cli_read_field() { # Tiny key extractor — files are ours and bounded; no jq dependency. local file="$1" key="$2" [ -f "$file" ] || return 1 sed -n "s/.*\"${key}\"[[:space:]]*:[[:space:]]*\"\\([^\"]*\\)\".*/\\1/p" "$file" | head -n 1 } vendor_cli_read_num_field() { local file="$1" key="$2" [ -f "$file" ] || return 1 sed -n "s/.*\"${key}\"[[:space:]]*:[[:space:]]*\\([0-9][0-9]*\\).*/\\1/p" "$file" | head -n 1 } # True when an in-progress installer for this slug still owns a live worker. vendor_cli_active_worker() { local slug="$1" file pid start stage file="$(vendor_cli_state_dir)/${slug}.json" [ -f "$file" ] || return 1 stage="$(vendor_cli_read_field "$file" stage || true)" [ "$stage" = "installing" ] || return 1 pid="$(vendor_cli_read_num_field "$file" pid || true)" start="$(vendor_cli_read_field "$file" process_start || true)" vendor_cli_pid_live "$pid" "$start" } # Per-provider launch lock via mkdir (atomic). Ownership is the `owner` file # inside the lock dir (pid + lstart + token). Incomplete/missing owner is # treated as INITIALIZING for a bounded mtime grace — never immediate reclaim # (that stole locks while birth existed but owner was still unwritten). Stale # reclaim takes an inner `reclaim/` mkdir sublock, re-validates owner+grace, # then `mv`s the whole dir. release must match token. VENDOR_CLI_LOCK_INIT_GRACE_SEC=45 # Pid-less stage=installing JSON is a parent reservation before worker identity # is published. Headless wait honors it only within this mtime grace. VENDOR_CLI_PIDLESS_RESERVATION_GRACE_SEC=60 vendor_cli_lock_dir() { printf '%s/%s.lock.d' "$(vendor_cli_state_dir)" "$1" } # Capture a single portable `stat` field without mixing Darwin/Linux stdout. # GNU `stat -f %m` can print filesystem prose to stdout AND exit nonzero; a # naive `stat -f … || stat -c …` then concatenates junk + epoch in one # substitution. Try each form alone; accept only a pure positive integer. vendor_cli_stat_uint() { local path="$1" darwin_fmt="$2" linux_fmt="$3" raw raw="$(stat -f "$darwin_fmt" "$path" 2>/dev/null)" && { raw="$(printf '%s' "$raw" | tr -d '[:space:]')" if [ -n "$raw" ] && [ "$raw" -gt 0 ] 2>/dev/null; then printf '%s' "$raw" return 0 fi } raw="$(stat -c "$linux_fmt" "$path" 2>/dev/null)" && { raw="$(printf '%s' "$raw" | tr -d '[:space:]')" if [ -n "$raw" ] && [ "$raw" -gt 0 ] 2>/dev/null; then printf '%s' "$raw" return 0 fi } return 1 } # Fail-closed: unavailable/invalid mtime → age 0 (still in grace; never steal). # (A literal mtime of 0 previously made age≈epoch and stole locks.) vendor_cli_path_mtime_age_sec() { local path="$1" mtime now mtime="$(vendor_cli_stat_uint "$path" %m %Y || true)" if [ -z "$mtime" ] || ! [ "$mtime" -gt 0 ] 2>/dev/null; then echo 0 return 0 fi now="$(date +%s)" echo $((now - mtime)) } # Prefer immutable birth time; a parent may die before writing it. Fall back # to directory mtime, whose unavailable/invalid value still fails closed. vendor_cli_lock_init_age_sec() { local lock="$1" created raw now created="$lock/created" if [ -f "$created" ]; then raw="$(head -n 1 "$created" 2>/dev/null || true)" raw="$(printf '%s' "$raw" | tr -d '[:space:]')" if [ -n "$raw" ] && [ "$raw" -gt 0 ] 2>/dev/null; then now="$(date +%s)" echo $((now - raw)) return 0 fi fi vendor_cli_path_mtime_age_sec "$lock" } # Portable inode identity; empty on failure (caller must not reclaim). vendor_cli_lock_inode() { local path="$1" vendor_cli_stat_uint "$path" %i %i || true } # Drop an orphan `$lock/reclaim` left by a crashed reclaimer (mkdir succeeded, # then SIGKILL before mv). Only when the reclaim dir itself is aged — never # steal a live reclaimer's young sublock. vendor_cli_clear_orphan_reclaim() { local lock="$1" reclaim_dir age reclaim_dir="$lock/reclaim" [ -d "$reclaim_dir" ] || return 0 age="$(vendor_cli_path_mtime_age_sec "$reclaim_dir")" if [ "$age" -ge "$VENDOR_CLI_LOCK_INIT_GRACE_SEC" ]; then rm -rf "$reclaim_dir" 2>/dev/null || true fi } # True when owner file has pid + token (lstart may be empty on odd hosts). vendor_cli_owner_complete() { local file="$1" pid token [ -f "$file" ] || return 1 pid="$(head -n 1 "$file" 2>/dev/null || true)" token="$(sed -n '3p' "$file" 2>/dev/null || true)" [ -n "$pid" ] && [ -n "$token" ] } vendor_cli_acquire_lock() { local slug="$1" dir lock owner_file attempt=0 local owner_pid owner_start reclaim age pre_age pre_inode post_inode local my_start my_token dir="$(vendor_cli_ensure_state_dir)" || return 1 lock="$(vendor_cli_lock_dir "$slug")" owner_file="$lock/owner" my_start="$(vendor_cli_process_start "$$" || true)" my_token="$$.${RANDOM:-0}.$(vendor_cli_now_ms)" VENDOR_CLI_LOCK_TOKEN="$my_token" while [ "$attempt" -lt 400 ]; do if mkdir "$lock" 2>/dev/null; then # Immutable birth timestamp — reclaim/child ops must not reset init age. if ! printf '%s\n' "$(date +%s)" >"$lock/created"; then rm -rf "$lock" 2>/dev/null || true VENDOR_CLI_LOCK_TOKEN="" return 1 fi if ! { printf '%s\n' "$$" printf '%s\n' "$my_start" printf '%s\n' "$my_token" } >"$owner_file"; then rm -rf "$lock" 2>/dev/null || true VENDOR_CLI_LOCK_TOKEN="" return 1 fi # Failed owner write must not report success — re-read our token. if [ "$(sed -n '3p' "$owner_file" 2>/dev/null || true)" != "$my_token" ]; then rm -rf "$lock" 2>/dev/null || true VENDOR_CLI_LOCK_TOKEN="" return 1 fi return 0 fi # Contended. Live complete owner → give up (do not steal). if vendor_cli_owner_complete "$owner_file"; then owner_pid="$(head -n 1 "$owner_file" 2>/dev/null || true)" owner_start="$(sed -n '2p' "$owner_file" 2>/dev/null || true)" if vendor_cli_pid_live "$owner_pid" "$owner_start"; then VENDOR_CLI_LOCK_TOKEN="" return 1 fi else # Missing/partial owner: INITIALIZING while birth age is young. age="$(vendor_cli_lock_init_age_sec "$lock")" if [ "$age" -lt "$VENDOR_CLI_LOCK_INIT_GRACE_SEC" ]; then attempt=$((attempt + 1)) sleep 0.05 continue fi fi # Clear aged orphan reclaim sublock (crashed reclaimer) before retrying. vendor_cli_clear_orphan_reclaim "$lock" # Snapshot birth-age + inode BEFORE mkdir reclaim (dir mtime may refresh). pre_age="$(vendor_cli_lock_init_age_sec "$lock")" pre_inode="$(vendor_cli_lock_inode "$lock")" if [ -z "$pre_inode" ]; then attempt=$((attempt + 1)) sleep 0.05 continue fi if ! vendor_cli_owner_complete "$owner_file"; then if [ "$pre_age" -lt "$VENDOR_CLI_LOCK_INIT_GRACE_SEC" ]; then attempt=$((attempt + 1)) sleep 0.05 continue fi fi # Inner reclaim sublock. If this lands in a replacement dir, inode check aborts. if ! mkdir "$lock/reclaim" 2>/dev/null; then vendor_cli_clear_orphan_reclaim "$lock" attempt=$((attempt + 1)) sleep 0.05 continue fi post_inode="$(vendor_cli_lock_inode "$lock")" if [ -z "$post_inode" ] || [ "$post_inode" != "$pre_inode" ]; then rmdir "$lock/reclaim" 2>/dev/null || true attempt=$((attempt + 1)) sleep 0.02 continue fi # Re-validate owner liveness; use PRE-reclaim birth age for incomplete grace. if vendor_cli_owner_complete "$owner_file"; then owner_pid="$(head -n 1 "$owner_file" 2>/dev/null || true)" owner_start="$(sed -n '2p' "$owner_file" 2>/dev/null || true)" if vendor_cli_pid_live "$owner_pid" "$owner_start"; then rmdir "$lock/reclaim" 2>/dev/null || true VENDOR_CLI_LOCK_TOKEN="" return 1 fi elif [ "$pre_age" -lt "$VENDOR_CLI_LOCK_INIT_GRACE_SEC" ]; then rmdir "$lock/reclaim" 2>/dev/null || true attempt=$((attempt + 1)) sleep 0.05 continue fi reclaim="${lock}.stale.$$.${RANDOM:-0}" if mv "$lock" "$reclaim" 2>/dev/null; then rm -rf "$reclaim" 2>/dev/null || true else rmdir "$lock/reclaim" 2>/dev/null || true fi attempt=$((attempt + 1)) sleep 0.02 done VENDOR_CLI_LOCK_TOKEN="" return 1 } vendor_cli_release_lock() { local slug="$1" lock owner_file token lock="$(vendor_cli_lock_dir "$slug")" owner_file="$lock/owner" token="${VENDOR_CLI_LOCK_TOKEN:-}" VENDOR_CLI_LOCK_TOKEN="" [ -n "$token" ] || return 0 [ -d "$lock" ] || return 0 # Only the acquiring token may remove the lock — never an unconditional unlink. if [ "$(sed -n '3p' "$owner_file" 2>/dev/null || true)" = "$token" ]; then rm -rf "$lock" 2>/dev/null || true fi } vendor_cli_build_json() { local attempt_id="$1" provider="$2" stage="$3" started="$4" updated="$5" local reason="${6:-}" pid="${7:-}" process_start="${8:-}" exit_code="${9:-}" local esc_attempt esc_provider esc_stage esc_reason esc_start esc_attempt="$(vendor_cli_json_escape "$attempt_id")" esc_provider="$(vendor_cli_json_escape "$provider")" esc_stage="$(vendor_cli_json_escape "$stage")" printf '{' printf '"attempt_id":"%s","provider":"%s","stage":"%s","started_at_ms":%s,"updated_at_ms":%s' \ "$esc_attempt" "$esc_provider" "$esc_stage" "$started" "$updated" if [ -n "$reason" ]; then esc_reason="$(vendor_cli_json_escape "$reason")" printf ',"reason":"%s"' "$esc_reason" fi if [ -n "$pid" ]; then printf ',"pid":%s' "$pid" fi if [ -n "$process_start" ]; then esc_start="$(vendor_cli_json_escape "$process_start")" printf ',"process_start":"%s"' "$esc_start" fi if [ -n "$exit_code" ]; then printf ',"exit_code":%s' "$exit_code" fi printf '}' } # List direct children of a pid (macOS + Linux). Bash 3.2 portable. vendor_cli_children() { local root="$1" pid ppid # `ps -axo` works on Darwin; `-eo` on Linux. Prefer axo, fall back. # `read` already splits IFS whitespace — do NOT per-line `printf|tr` (that # forks ~2N subshells per walk; nested stop_tree on a busy host then spends # seconds in ps post-processing and can hang installer timeout finalization). (ps -axo pid=,ppid= 2>/dev/null || ps -eo pid=,ppid= 2>/dev/null || true) \ | while read -r pid ppid; do [ "$ppid" = "$root" ] && [ -n "$pid" ] && printf '%s\n' "$pid" done } # Recursively TERM/KILL a process tree (children first, then root). vendor_cli_stop_tree() { local root="$1" sig="${2:-TERM}" kid [ -n "$root" ] || return 0 for kid in $(vendor_cli_children "$root"); do vendor_cli_stop_tree "$kid" "$sig" done kill "-$sig" "$root" 2>/dev/null || true } vendor_cli_reap_tree() { local root="$1" i [ -n "$root" ] || return 0 vendor_cli_stop_tree "$root" TERM for i in 1 2 3 4 5 6 7 8 9 10; do kill -0 "$root" 2>/dev/null || return 0 sleep 0.05 done vendor_cli_stop_tree "$root" KILL for i in 1 2 3 4 5; do kill -0 "$root" 2>/dev/null || return 0 sleep 0.05 done } # Persist a terminal progress record from the PARENT after reaping a worker. # A timed-out parent can kill the worker before its on_signal trap finishes # nested-child cleanup (~0.75s) and writes interrupted — without this, the # JSON can be left forever at stage=installing. Reason MUST stay on the wire # enum (`installer_failed` | `interrupted` | `detection_timeout`); wall-clock # timeout is reported separately on stderr / exit status, not as a new reason. vendor_cli_mark_interrupted() { local slug="$1" pid="${2:-}" local file attempt started json now file="$(vendor_cli_state_dir)/${slug}.json" [ -f "$file" ] || return 1 # Another installer may have replaced this provider's attempt while we # reaped. Never finalize a record that no longer belongs to this worker. if [ -n "$pid" ] && [ "$(vendor_cli_read_num_field "$file" pid || true)" != "$pid" ]; then return 1 fi attempt="$(vendor_cli_read_field "$file" attempt_id || true)" started="$(vendor_cli_read_num_field "$file" started_at_ms || true)" [ -n "$attempt" ] || return 1 [ -n "$started" ] || started="$(vendor_cli_now_ms)" now="$(vendor_cli_now_ms)" if [ -n "$pid" ]; then json="$(vendor_cli_build_json "$attempt" "$slug" interrupted "$started" "$now" interrupted "$pid" "$(vendor_cli_process_start "$pid" || true)")" else json="$(vendor_cli_build_json "$attempt" "$slug" interrupted "$started" "$now" interrupted)" fi vendor_cli_write_state "$slug" "$json" } # Args: display, command, slug, dest launcher, installer URL, run PATH, curl, # and an OPTIONAL installer function. With the function set, the tracked worker # runs ` ` in a subshell instead of `curl | bash` — every # other step (lock, reservation, handshake, progress JSON, signal reaping) is # shared, so a non-script vendor install is tracked exactly like the others. # Returns 0 when this run launched (and owns) a worker, 3 when another # installer already has this provider in flight (skipped — pending, not a # failure), and 1 when the launch itself failed. VENDOR_CLI_DUPLICATE_RC=3 launch_vendor_cli_install() { local name="$1" cmd="$2" slug="$3" dest="$4" url="$5" run_path="$6" curl_bin="$7" local installer_fn="${8:-}" local attempt_id started json worker_pid worker_start file local worker_pid_file handshake_file VENDOR_LAST_PID="" if ! vendor_cli_acquire_lock "$slug"; then echo " $name CLI: installer already running — skipping duplicate; retry after it completes." echo "$name CLI: duplicate launch skipped (live lock)." \ >>"$OPENLLM_DIR/cli-install.log" 2>/dev/null || true return "$VENDOR_CLI_DUPLICATE_RC" fi if vendor_cli_active_worker "$slug"; then echo " $name CLI: installer already running — skipping duplicate; retry after it completes." echo "$name CLI: duplicate launch skipped (live worker)." \ >>"$OPENLLM_DIR/cli-install.log" 2>/dev/null || true vendor_cli_release_lock "$slug" return "$VENDOR_CLI_DUPLICATE_RC" fi # A previous installing record whose worker is dead: mark interrupted before # starting a replacement so the UI never keeps a zombie "installing". file="$(vendor_cli_state_dir)/${slug}.json" if [ -f "$file" ]; then local prev_stage prev_attempt prev_started prev_stage="$(vendor_cli_read_field "$file" stage || true)" if [ "$prev_stage" = "installing" ]; then prev_attempt="$(vendor_cli_read_field "$file" attempt_id || true)" prev_started="$(vendor_cli_read_num_field "$file" started_at_ms || true)" if [ -n "$prev_attempt" ] && [ -n "$prev_started" ]; then json="$(vendor_cli_build_json "$prev_attempt" "$slug" interrupted "$prev_started" "$(vendor_cli_now_ms)" interrupted)" vendor_cli_write_state "$slug" "$json" || true fi fi fi attempt_id="$(vendor_cli_attempt_id)" started="$(vendor_cli_now_ms)" # Reserve BEFORE launch (no pid yet). A write failure must not start work. json="$(vendor_cli_build_json "$attempt_id" "$slug" installing "$started" "$started")" if ! vendor_cli_write_state "$slug" "$json"; then echo " $name CLI: could not track install — skipping to avoid untracked work." >&2 echo "$name CLI: state write failed before launch — skipped." \ >>"$OPENLLM_DIR/cli-install.log" 2>/dev/null || true vendor_cli_release_lock "$slug" return 1 fi echo " $name CLI: installing…" # Handshake/pid files are attempt-scoped. A completed older worker must not # `rm` a newer attempt's handshake (provider-only paths caused that race). worker_pid_file="$(vendor_cli_state_dir)/.${slug}.${attempt_id}.worker_pid" handshake_file="$(vendor_cli_state_dir)/.${slug}.${attempt_id}.handshake" vendor_cli_cleanup_attempt_files "$worker_pid_file" "$handshake_file" # Capture the launching shell's pid for the worker's parent-liveness guard # (Bash 3.2: `$$` inside `( )&` is still this value — pass it explicitly). local launcher_pid=$$ ( # Background worker: parent may exit; this job continues and owns terminal # state transitions. pipefail so a nonzero curl fails the pipeline. set -euo pipefail # A vendor's installer never needs the OpenLLM key: keep it out of its # environment (this subshell only; the parent install still pairs). unset OPENLLM_API_KEY SUPPLIED_KEY API_KEY my_pid="" # Bounded wall deadline (~10s), not a fixed short iteration count — slow # parent `ps`/JSON write under load must still complete the handshake. _hs_deadline=$(($(date +%s) + 10)) while [ "$(date +%s)" -lt "$_hs_deadline" ]; do if [ -f "$handshake_file" ] && [ -f "$worker_pid_file" ]; then my_pid="$(head -n 1 "$worker_pid_file" 2>/dev/null || true)" [ -n "$my_pid" ] && break fi # Abort early only when the launcher is gone AND handshake never arrived. # If handshake already landed, a later parent exit is fine. if [ -z "$my_pid" ] && ! kill -0 "$launcher_pid" 2>/dev/null; then break fi sleep 0.05 done if [ -z "$my_pid" ]; then # No handshake — parent failed or died. Do NOT run the vendor installer # untracked, and do NOT invent a PPID identity. echo "$name CLI: missing handshake — worker exiting without vendor start." >&2 exit 1 fi my_start="$(vendor_cli_process_start "$my_pid" || true)" child_pid="" write_progress() { local stage="$1" reason="${2:-}" exit_code="${3:-}" local now payload now="$(vendor_cli_now_ms)" payload="$(vendor_cli_build_json "$attempt_id" "$slug" "$stage" "$started" "$now" "$reason" "$my_pid" "$my_start" "$exit_code")" vendor_cli_write_state "$slug" "$payload" || true } on_signal() { # Stop installer descendants BEFORE claiming interrupted / exiting, so a # duplicate launcher cannot observe "stopped" while curl|bash still runs. # Do NOT reap my_pid here — that would kill this trap before write_progress. if [ -n "${child_pid:-}" ]; then vendor_cli_reap_tree "$child_pid" else # Fallback: any children of this worker subshell (bash 3.2: use handshake pid). for _kid in $(vendor_cli_children "$my_pid"); do vendor_cli_reap_tree "$_kid" done fi write_progress interrupted interrupted vendor_cli_cleanup_attempt_files "$worker_pid_file" "$handshake_file" exit 130 } trap on_signal HUP INT TERM set +e # Single waitable child wrapping the pipeline so signal cleanup has a root. if [ -n "$installer_fn" ]; then ( set -euo pipefail PATH="$run_path" "$installer_fn" "$curl_bin" "$url" ) & else PATH="$run_path" bash -c ' set -euo pipefail PATH="$1" "$2" -fsSL "$3" | PATH="$1" bash ' bash "$run_path" "$curl_bin" "$url" & fi child_pid=$! wait "$child_pid" rc=$? set -e trap - HUP INT TERM if [ "$rc" -eq 0 ]; then write_progress awaiting_detection elif [ "$rc" -ge 128 ]; then write_progress interrupted interrupted "$rc" else write_progress failed installer_failed "$rc" fi vendor_cli_cleanup_attempt_files "$worker_pid_file" "$handshake_file" exit "$rc" ) >>"$OPENLLM_DIR/cli-install.log" 2>&1 & worker_pid=$! # Parent: persist pid-bearing installing JSON FIRST, then publish handshake. # Never handshake before JSON — a fast worker must not finish, then get # overwritten back to installing by a late parent write. worker_start="$(vendor_cli_process_start "$worker_pid" || true)" json="$(vendor_cli_build_json "$attempt_id" "$slug" installing "$started" "$(vendor_cli_now_ms)" "" "$worker_pid" "$worker_start")" if ! vendor_cli_write_state "$slug" "$json"; then echo " $name CLI: lost track after launch — stopping untracked worker." >&2 # Persist terminal state BEFORE reaping so a slow on_signal cannot leave # stage=installing after the parent already gave up. json="$(vendor_cli_build_json "$attempt_id" "$slug" interrupted "$started" "$(vendor_cli_now_ms)" interrupted "$worker_pid" "$worker_start")" vendor_cli_write_state "$slug" "$json" || true vendor_cli_reap_tree "$worker_pid" wait "$worker_pid" 2>/dev/null || true vendor_cli_cleanup_attempt_files "$worker_pid_file" "$handshake_file" vendor_cli_release_lock "$slug" VENDOR_LAST_PID="" return 1 fi printf '%s\n' "$worker_pid" >"$worker_pid_file" || { json="$(vendor_cli_build_json "$attempt_id" "$slug" interrupted "$started" "$(vendor_cli_now_ms)" interrupted "$worker_pid" "$worker_start")" vendor_cli_write_state "$slug" "$json" || true vendor_cli_reap_tree "$worker_pid" wait "$worker_pid" 2>/dev/null || true vendor_cli_cleanup_attempt_files "$worker_pid_file" "$handshake_file" vendor_cli_release_lock "$slug" VENDOR_LAST_PID="" return 1 } # Handshake last — worker may proceed to curl only after this exists. # `vendor_cli_touch` is a tiny seam so tests can force a post-spawn failure # without inventing filesystem races around chmod. if ! vendor_cli_touch "$handshake_file"; then json="$(vendor_cli_build_json "$attempt_id" "$slug" interrupted "$started" "$(vendor_cli_now_ms)" interrupted "$worker_pid" "$worker_start")" vendor_cli_write_state "$slug" "$json" || true vendor_cli_reap_tree "$worker_pid" wait "$worker_pid" 2>/dev/null || true vendor_cli_cleanup_attempt_files "$worker_pid_file" "$handshake_file" vendor_cli_release_lock "$slug" VENDOR_LAST_PID="" return 1 fi vendor_cli_release_lock "$slug" # Detach from this shell's job table so a later exit (or the desktop app # closing its wait on this script) cannot SIGHUP the vendor installer. The # worker already redirects to cli-install.log; disown only drops job control. disown "$worker_pid" 2>/dev/null || true VENDOR_LAST_PID="$worker_pid" } # ── Google Antigravity (official `agy` CLI) ───────────────────────────────── # `agy` is the one Antigravity binary and the single source of truth for its # sign-in: headless chat and its built-in ACP server (`agy acp`, images / tools) # both run it under the daemon's isolated HOME. Google's own installer # verifies the download's SHA-512 against Google's manifest and places `agy` at # ~/.local/bin/agy, which the daemon resolves # (packages/cli/daemon/src/native-runtime/antigravity-headless.ts). It is # installed like every other vendor CLI: `curl -fsSL | bash` under # launch_vendor_cli_install. ANTIGRAVITY_CLI_INSTALLER_URL="https://antigravity.google/cli/install.sh" ANTIGRAVITY_CLI_BIN="$HOME/.local/bin/agy" # The retired opt-out marker lived where the daemon read it: its state dir # (`stateDir()` in packages/cli/daemon/src/env.ts — an absolute # OPENLLM_DAEMON_STATE_DIR, else ~/.openllm). # Read like the other persisted settings: the shell env first, else the # daemon's env file (a state dir set only there is the one it uses). ANTIGRAVITY_STATE_DIR="${OPENLLM_DAEMON_STATE_DIR:-$(env_file_lookup OPENLLM_DAEMON_STATE_DIR 2>/dev/null || true)}" case "$ANTIGRAVITY_STATE_DIR" in /*) ANTIGRAVITY_DISABLED_MARKER="$ANTIGRAVITY_STATE_DIR/antigravity-disabled" ;; *) ANTIGRAVITY_DISABLED_MARKER="$OPENLLM_DIR/antigravity-disabled" ;; esac # OPENLLM_ONLY_VENDOR_CLIS — comma-separated subscription slugs to provision # (e.g. claude_code,chatgpt). Unset/empty selects every vendor. vendor_cli_selected() { [ -z "${OPENLLM_ONLY_VENDOR_CLIS:-}" ] && return 0 case ",${OPENLLM_ONLY_VENDOR_CLIS}," in *",$1,"*) return 0 ;; *) return 1 ;; esac } # Resolve an absolute curl for vendor installers. Empty when none is usable — # callers must treat that as failure (never silently skip provisioning). vendor_cli_resolve_curl() { local run_path="$1" curl_bin c curl_bin="$(PATH="$run_path" command -v curl 2>/dev/null || true)" if [ -z "$curl_bin" ]; then for c in /usr/bin/curl /bin/curl /usr/local/bin/curl /opt/homebrew/bin/curl; do [ -x "$c" ] && { curl_bin="$c"; break; } done fi printf '%s' "$curl_bin" } # True when `$1` is an `agy` at or above 1.5.1 — 1.5.0 added the built-in # ACP server (`agy acp`) the daemon uses for images, tools and its fallback, # and 1.5.1 offers every model the account has to every ACP client (the # daemon's rule: packages/cli/daemon/src/agy-version.ts). Run with a throwaway HOME: `--version` never touches the user's # own `agy` profile. agy_version_ok() { local v major minor out # A nonzero exit is not a version, whatever it printed (matches the # daemon's own probe). Capped at 5 s (macOS has no `timeout`): a hung # binary is unknown (kept); only a version read below the minimum is old. # Output goes to a file, not a pipe: a child the probe left behind can # hold a pipe open, never a finished read of a file. local tmp probe watchdog rc tmp="$(mktemp "${TMPDIR:-/tmp}/agy-version.XXXXXX")" || return 1 # A private HOME per probe (nothing one probe writes is seen by the next), # and the probe never sees the pairing key (the parent still pairs). local probe_home probe_home="$(mktemp -d "${TMPDIR:-/tmp}/agy-version-home.XXXXXX")" || { rm -f "$tmp" return 1 } env -u OPENLLM_API_KEY -u SUPPLIED_KEY -u API_KEY HOME="$probe_home" \ "$1" --version >"$tmp" 2>/dev/null /dev/null 2>&1 /dev/null rc=$? kill "$watchdog" 2>/dev/null wait "$watchdog" 2>/dev/null out="$(cat "$tmp" 2>/dev/null)" rm -f "$tmp" rm -rf "$probe_home" # Killed at the cap (SIGKILL = 137): slow, not broken — its version is # unknown, and the daemon treats unknown as usable (agyVersionUsable), so a # healthy launcher is kept rather than moved aside and reinstalled. [ "$rc" -eq 137 ] && return 0 [ "$rc" -eq 0 ] || return 1 # The daemon's rule (agy-version.ts): the WHOLE output is one version # (`1.5.13`, `agy 1.5.13`, `v1.5.13`, optional -pre / +build), and a # prerelease of 1.5.1 is older than 1.5.1. # Exactly one nonblank line: a version plus a diagnostic is no version. [ "$(printf '%s\n' "$out" | grep -c '[^[:space:]]')" -eq 1 ] || return 1 out="$(printf '%s\n' "$out" | grep '[^[:space:]]' | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" printf '%s' "$out" | grep -Eq '^(agy[[:space:]]+)?v?[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$' || return 1 v="$(printf '%s' "$out" | grep -Eo '[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?' | head -n 1)" local core patch pre="" core="${v%%-*}" [ "$core" != "$v" ] && pre=1 major="${core%%.*}" minor="${core#*.}" patch="${minor#*.}" minor="${minor%%.*}" [ "$major" -gt 1 ] && return 0 [ "$major" -eq 1 ] || return 1 [ "$minor" -gt 5 ] && return 0 [ "$minor" -eq 5 ] || return 1 [ "$patch" -gt 1 ] && return 0 [ "$patch" -eq 1 ] || return 1 [ -z "$pre" ] } # Launch the tracked Antigravity install unless a usable `agy` is present. provision_antigravity() { local run_path="$1" curl_bin="$2" local name="Google Antigravity" dest="$ANTIGRAVITY_CLI_BIN" found="" # The daemon's precedence: a home launcher that EXISTS decides (even an # unusable one — it is repaired); only without it may an `agy` on PATH # serve (a second copy would shadow it). # `-e` follows the link, as the daemon's existsSync does: a dangling # launcher is absent and an `agy` on PATH may serve. if [ -e "$dest" ]; then found="$dest" elif has_executable_command agy; then found="$(command -v agy)" fi # An older build (no `agy acp`) is upgraded by Google's installer, which # replaces ~/.local/bin/agy — the path the daemon resolves first. if [ -n "$found" ] && { [ ! -f "$found" ] || ! agy_version_ok "$found"; }; then echo " $name CLI: $found is unusable or older than 1.5.1 — updating." found="" fi if [ -n "$found" ]; then echo " $name CLI: already installed." echo "$name CLI: already installed — skipping install." \ >>"$OPENLLM_DIR/cli-install.log" 2>/dev/null || true return 0 fi launch_vendor_cli_install "$name" agy antigravity "$dest" \ "$ANTIGRAVITY_CLI_INSTALLER_URL" "$run_path" "$curl_bin" install_agy_cli } # The tracked worker's installer for `agy` (`launch_vendor_cli_install`'s # installer_fn): Google's installer, with the upgrade it can't do itself. # Its script leaves an existing ~/.local/bin/agy untouched ("already # installed"), so an outdated launcher is moved aside HERE, inside the worker, # and restored if the install fails or is interrupted — a user's working # 1.4.x is never left without a launcher. A successful upgrade keeps the old # build beside it (`agy.pre-1.5`), never deleted. install_agy_cli() { local curl_bin="$1" url="$2" dest="$ANTIGRAVITY_CLI_BIN" backup="" failed="" # Roll back THIS attempt: a replacement it left (even a partial one) is # moved aside, and the launcher it saved goes back. Nothing to do when it # saved none (a signal before the move leaves the original in place). rollback_agy() { [ -n "$backup" ] && [ -e "$backup" ] || return 0 if [ -e "$dest" ] || [ -L "$dest" ]; then failed="$dest.failed-$$" mv -f "$dest" "$failed" 2>/dev/null || true fi mv -f "$backup" "$dest" 2>/dev/null || true } # Armed BEFORE the move, so no signal can land between the two. trap 'rollback_agy; exit 130' HUP INT TERM if [ -e "$dest" ] && ! { [ -f "$dest" ] && agy_version_ok "$dest"; }; then # Never overwrite an earlier attempt's backup. backup="$dest.pre-1.5" [ -e "$backup" ] && backup="$dest.pre-1.5.$(date +%s).$$" mv "$dest" "$backup" || { backup=""; trap - HUP INT TERM; return 1; } fi # Success is a USABLE launcher (a 1.5.1+ file), not merely the # installer's exit status: anything less takes the rollback path. if "$curl_bin" -fsSL --proto '=https' "$url" | bash \ && [ -f "$dest" ] && [ -x "$dest" ] && agy_version_ok "$dest"; then trap - HUP INT TERM return 0 fi rollback_agy trap - HUP INT TERM return 1 } # Outcome of the last provision_clis run, by display name (", "-joined) — the # caller's summary names what failed, timed out, or is still being installed # by another installer. VENDOR_FAILED_NAMES="" # Slugs whose worker could not be launched (e.g. the initial state write # failed). The summary reports them as failed, never as skipped. VENDOR_LAUNCH_FAILED_SLUGS="" VENDOR_PENDING_NAMES="" VENDOR_REAPED_NAMES="" # How to retry vendor provisioning after a skip / failure / interrupt. vendor_cli_retry_hint() { local origin="${ORIGIN:-https://www.openllm.sh}" printf 're-run the installer: curl -fsSL %s/install | bash' "$origin" } # Stop the still-live workers in provision_clis's owned_pids / owned_slugs / # owned_names (read through bash's dynamic scope — call it only from # provision_clis or a trap that fires inside it) and persist wire-valid # `interrupted` for each. Never touches a record this run does not own. vendor_cli_reap_owned() { local idx=0 own_pid own_slug while [ "$idx" -lt "${#owned_pids[@]}" ]; do own_pid="${owned_pids[$idx]}" own_slug="${owned_slugs[$idx]}" if kill -0 "$own_pid" 2>/dev/null; then vendor_cli_reap_tree "$own_pid" wait "$own_pid" 2>/dev/null || true vendor_cli_mark_interrupted "$own_slug" "$own_pid" || true VENDOR_REAPED_NAMES="${VENDOR_REAPED_NAMES:+$VENDOR_REAPED_NAMES, }${owned_names[$idx]}" fi idx=$((idx + 1)) done } # INT / TERM during provision_clis's wait (installed as a trap scoped to the # wait). The daemon starts only after the vendors, so it is not running yet; # the key and the binary already are in place. vendor_cli_on_wait_signal() { local sig="$1" trap - INT TERM echo >&2 echo "Interrupted — stopping the vendor CLI installers this run started..." >&2 vendor_cli_reap_owned if [ -n "$VENDOR_REAPED_NAMES" ]; then echo "Stopped: $VENDOR_REAPED_NAMES." >&2 fi echo "OpenLLM is installed and your API key is saved (${ENV_FILE:-$OPENLLM_DIR/.env}), but the daemon was not started." >&2 echo " Start it now: ${BIN_DIR:-$OPENLLM_DIR/bin}/openllm start" >&2 echo " Install vendor CLIs: $(vendor_cli_retry_hint)" >&2 echo " Installer log: $OPENLLM_DIR/cli-install.log" >&2 if [ "$sig" = INT ]; then exit 130 fi exit 143 } # Antigravity is part of the product — there is no opt-out. Older installers # wrote an `antigravity-disabled` marker (with OPENLLM_ANTIGRAVITY=0); remove # any leftover so it can't keep the provider off. The daemon does the same on # start (packages/cli/daemon/src/legacy-antigravity-marker.ts). Idempotent. remove_legacy_antigravity_marker() { rm -f "$ANTIGRAVITY_DISABLED_MARKER" "$OPENLLM_DIR/antigravity-disabled" 2>/dev/null || true return 0 } provision_clis() { VENDOR_FAILED_NAMES="" VENDOR_PENDING_NAMES="" VENDOR_REAPED_NAMES="" # display | command | protocol slug | dest launcher | official installer URL. # Dest launchers match VENDOR-DEFAULT `hostCliCandidates` in # packages/cli/daemon/src/cli-paths.ts; URLs match `VENDOR_CLI_INSTALL_CMD` in # lib/hooks/use-daemon.ts + `installHint` in packages/cli/src/clients/registry.ts. # Slugs are the protocol SubscriptionProviderSlug literals. local specs=( "Claude Code|claude|claude_code|$HOME/.local/bin/claude|https://claude.ai/install.sh" "Codex|codex|chatgpt|$HOME/.local/bin/codex|https://chatgpt.com/codex/install.sh" "Kimi|kimi|kimi_code|$HOME/.kimi-code/bin/kimi|https://code.kimi.com/kimi-code/install.sh" "Grok|grok|grok|$HOME/.grok/bin/grok|https://x.ai/cli/install.sh" # ⚠️ RESEARCH-UNVERIFIED: Cursor's official installer/launcher path. "Cursor Agent|cursor-agent|cursor|$HOME/.local/bin/cursor-agent|https://cursor.com/install" # Official Muse Code installer (https://dev.meta.ai/docs/muse-code/). "Muse Code|muse|muse|$HOME/.local/bin/muse|https://dev.meta.ai/install.sh" ) # Build a PATH that (a) puts the STANDARD system dirs FIRST — covering # curl/bash/tar/gzip/uname/sed/grep on macOS AND Linux (all live in # /usr/bin + /bin on both) plus Homebrew — so a real `curl` always wins over # any shim the OUTER process prepended, and (b) APPENDS the caller's own # PATH so Homebrew/nix/snap tools a vendor installer needs stay reachable. # The backgrounded jobs outlive this script, so they must not depend on the # outer PATH: the dev dist-installer prepends an ephemeral `curl` shim it # deletes on exit, and a bare `curl` in a detached job would then resolve to # nothing (or a coreutils multicall). Resolving curl absolutely + running the # job under this PATH makes the primitive robust on every major platform. local sys_path="/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/opt/homebrew/bin" local run_path="${sys_path}:${PATH:-}" local curl_bin curl_bin="$(vendor_cli_resolve_curl "$run_path")" if [ -z "$curl_bin" ]; then echo " Vendor CLIs: curl not found — install them by hand from their official installers." >&2 return 1 fi local spec name cmd slug dest url failed=0 pending=0 launch_rc # Parallel pid↔slug↔name ownership for the wait, timeout finalization and # signal cleanup. Never glob the state dir — that would rewrite unrelated / # stale / sibling records. local owned_pids=() local owned_slugs=() local owned_names=() for spec in "${specs[@]}"; do IFS='|' read -r name cmd slug dest url <<<"$spec" vendor_cli_selected "$slug" || continue if has_executable_command "$cmd" || [ -x "$dest" ]; then echo " $name CLI: already installed." # Mirror the skip into the log too — previously only the backgrounded # installer output landed there, so a skipped provider left the log # silent about why nothing was installed. No progress record is written # for an already-present binary (do not invent a finished job). echo "$name CLI: already installed ($(command -v "$cmd" 2>/dev/null || echo "$dest")) — skipping install." \ >>"$OPENLLM_DIR/cli-install.log" 2>/dev/null || true continue fi launch_rc=0 launch_vendor_cli_install "$name" "$cmd" "$slug" "$dest" "$url" "$run_path" "$curl_bin" || launch_rc=$? case "$launch_rc" in 0) if [ -n "$VENDOR_LAST_PID" ]; then owned_pids+=("$VENDOR_LAST_PID") owned_slugs+=("$slug") owned_names+=("$name") fi ;; "$VENDOR_CLI_DUPLICATE_RC") pending=1 VENDOR_PENDING_NAMES="${VENDOR_PENDING_NAMES:+$VENDOR_PENDING_NAMES, }$name" ;; *) failed=1 VENDOR_FAILED_NAMES="${VENDOR_FAILED_NAMES:+$VENDOR_FAILED_NAMES, }$name" VENDOR_LAUNCH_FAILED_SLUGS="${VENDOR_LAUNCH_FAILED_SLUGS},$slug," ;; esac done if vendor_cli_selected antigravity; then VENDOR_LAST_PID="" launch_rc=0 provision_antigravity "$run_path" "$curl_bin" || launch_rc=$? case "$launch_rc" in 0) if [ -n "$VENDOR_LAST_PID" ]; then owned_pids+=("$VENDOR_LAST_PID") owned_slugs+=("antigravity") owned_names+=("Google Antigravity") fi ;; "$VENDOR_CLI_DUPLICATE_RC") pending=1 VENDOR_PENDING_NAMES="${VENDOR_PENDING_NAMES:+$VENDOR_PENDING_NAMES, }Google Antigravity" ;; *) failed=1 VENDOR_FAILED_NAMES="${VENDOR_FAILED_NAMES:+$VENDOR_FAILED_NAMES, }Google Antigravity" VENDOR_LAUNCH_FAILED_SLUGS="${VENDOR_LAUNCH_FAILED_SLUGS},antigravity," ;; esac fi # Never await vendor installers — the daemon must start as soon as the # binary and env are ready. Workers are already backgrounded + disowned; # progress lives in ~/.openllm/vendor-cli-install/*.json and cli-install.log. if [ "${#owned_pids[@]}" -gt 0 ]; then local running="" idx=0 while [ "$idx" -lt "${#owned_pids[@]}" ]; do running="${running:+$running, }${owned_names[$idx]}" idx=$((idx + 1)) done echo " Vendor CLIs: installing in the background (${running}) — see $OPENLLM_DIR/cli-install.log" >&2 fi # Launch-time failures only (a worker that could not be started). In-flight # workers are not failures of this install. [ "$failed" = 0 ] || return 1 [ "$pending" = 0 ] || return 3 return 0 } # Background vendor install. Skipped on a manual update. Full setup provisions # vendors even when keyless (unless OPENLLM_SKIP_VENDOR_CLIS / --no-vendors). # Headless waits for launched workers AFTER daemon start (OPENLLM_VENDOR_WAIT_SECS, # default 600) so the summary is accurate without delaying a requested start; # interactive leaves them in the background. # `OPENLLM_INSTALL_MODE=vendors` is the same provision path without download. VENDOR_PROVISIONED=0 VENDOR_FAILED=0 VENDOR_PENDING=0 VENDOR_BACKGROUND=0 VENDOR_WAITED=0 # Every mode clears the retired Antigravity opt-out marker. remove_legacy_antigravity_marker if { [ "$INSTALL_MODE" != update ]; } && [ "$SETUP_MODE" != minimal ] && [ -z "${OPENLLM_SKIP_VENDOR_CLIS:-}" ]; then VENDOR_PROVISIONED=1 # `||` keeps a nonzero provision_clis status off the `set -e` path so we # still start the daemon and report launch-failure/pending distinctly. VENDOR_RC=0 provision_clis || VENDOR_RC=$? case "$VENDOR_RC" in 0) VENDOR_BACKGROUND=1 ;; 3) VENDOR_PENDING=1 ;; *) VENDOR_FAILED=1 ;; esac # Vendor wait runs AFTER the daemon start block below when start is wanted # (desktop headless sets OPENLLM_START_DAEMON=1). Waiting here would delay # serving for up to OPENLLM_VENDOR_WAIT_SECS on a stuck vendor install. fi # Is a daemon answering on this install's port? `/status` is the daemon's # unauthenticated loopback health route (what `openllm daemon status` probes). daemon_is_running() { curl -fsS --noproxy '*' --max-time 2 "http://127.0.0.1:$DAEMON_PORT/status" >/dev/null 2>&1 } # Restart a daemon so it runs the binary this update just installed. Only when # the binary actually changed; credentials are already persisted. # hold_restart_lease : take the update lease again for the restart # step, so every surface (Manage device, the desktop app, `openllm status`) # shows "Restarting" until the daemon is back — the same step the daemon's own # auto-update reports. Best-effort: a live holder is left alone (never die # here, the binary is already installed); a stale one is taken over once. hold_restart_lease() { local attempt UPDATE_STARTED_MS="$(now_ms)" for attempt in 1 2; do if create_update_lock restart "$1"; then UPDATE_LEASE_HELD=1 trap release_update_lease EXIT return 0 fi update_lock_live && return 1 remove_stale_lock done return 1 } # How long the restart waits out another update's lease (see below). RESTART_LEASE_WAIT_SEC=180 # Wait (bounded) for the restarted daemon to answer, so the restart step lasts # until it is back rather than ending at the kickstart. wait_for_daemon_back() { local i for i in $(seq 1 30); do daemon_is_running && return 0 sleep 1 done return 1 } # The version the running daemon reports on its loopback /status, or empty. running_daemon_version() { curl -fsS --noproxy '*' --max-time 2 "http://127.0.0.1:$DAEMON_PORT/status" 2>/dev/null | grep -o '"version"[[:space:]]*:[[:space:]]*"[^"]*"' | head -n 1 | sed 's/.*"\([^"]*\)"$/\1/' } restart_for_new_binary() { echo "Restarting the daemon to pick up the new binary..." # Another update took the lease since our swap: restarting now would kill # it mid-update, and it may still fail without restarting. Wait for it to # finish — bounded well inside the desktop app's 10-minute install timeout, # so a long competing update never fails the app's Update — then restart # only if the daemon still isn't on what we installed. local waited=0 while ! hold_restart_lease "$CLI_VERSION"; do if [ "$waited" = 0 ]; then echo " another update is in progress — waiting for it to finish" fi if [ "$waited" -ge "$RESTART_LEASE_WAIT_SEC" ]; then echo "Warning: another update is still running — run '$BIN_DIR/openllm daemon restart' once it finishes" >&2 DAEMON_STARTED=1 return 0 fi sleep 2 waited=$((waited + 2)) done if [ "$waited" -gt 0 ] && [ -n "$CLI_VERSION" ] && [ "$(running_daemon_version)" = "$CLI_VERSION" ]; then release_update_lease DAEMON_STARTED=1 return 0 fi if "$BIN_DIR/openllm" daemon restart; then DAEMON_STARTED=1 wait_for_daemon_back || true release_update_lease else release_update_lease DAEMON_START_FAILED=1 echo "Warning: daemon restart failed — run '$BIN_DIR/openllm daemon status' to diagnose" >&2 fi } # --- start / reconcile the service (after auth; vendors may still be running) - # Start decision is WANT_START (interactive Full / --start), not key presence. # Updates restart a RUNNING daemon when the binary changed and never start a # stopped one. vendors mode never starts. Minimal never starts a stopped daemon. DAEMON_STARTED=0 DAEMON_START_FAILED=0 DAEMON_STATE="not started" case " $INSTALLED_COMPONENTS " in *" openllm "*) BINARY_CHANGED=1 ;; *) BINARY_CHANGED=0 ;; esac if [ "$INSTALL_MODE" = vendors ]; then # Never start/restart in vendors mode — only report the current probe. if daemon_is_running; then DAEMON_STATE="running" else DAEMON_STATE="not started" fi elif [ "$INSTALL_MODE" = update ]; then if [ "$BINARY_CHANGED" = 1 ] && daemon_is_running; then restart_for_new_binary if [ "$DAEMON_STARTED" = 1 ]; then DAEMON_STATE="running" else DAEMON_STATE="failed" fi else if daemon_is_running; then DAEMON_STATE="running" echo " daemon already current — no restart needed" else DAEMON_STATE="not started" echo "OpenLLM updated (daemon left as-is)." fi fi elif [ "$SETUP_MODE" = minimal ]; then # Minimal never starts a daemon, but one may already be running. if daemon_is_running; then DAEMON_STATE="running" echo "Minimal setup — daemon left running as-is." else DAEMON_STATE="not started" echo "Minimal setup — daemon not started. Run \`openllm start\` later if you want this machine to serve." fi elif [ "$WANT_START" = 1 ]; then if [ -z "$API_KEY" ]; then # Nothing to pair yet — print Next: login/start and exit 0. A later # `openllm start` (or a re-run with a key) performs the real start. if daemon_is_running; then DAEMON_STATE="running" else DAEMON_STATE="not started" fi elif [ "$BINARY_CHANGED" = 0 ] \ && [ -n "$ENV_DIGEST_BEFORE" ] \ && [ "$ENV_DIGEST_BEFORE" = "$(sha256_of "$ENV_FILE" 2>/dev/null || true)" ] \ && daemon_is_running; then DAEMON_STARTED=1 DAEMON_STATE="running" echo " daemon already running and current — no restart needed" else echo "Starting the daemon..." if "$BIN_DIR/openllm" daemon start; then DAEMON_STARTED=1 DAEMON_STATE="running" else DAEMON_START_FAILED=1 DAEMON_STATE="failed" echo "Warning: daemon start failed — run '$BIN_DIR/openllm daemon status' to diagnose" >&2 fi fi else # No start requested: report what is actually there, never start one. if daemon_is_running; then DAEMON_STATE="running" else DAEMON_STATE="not started" fi fi # Headless (and vendors-only): wait for workers so the summary is accurate. # Runs AFTER daemon start when start was wanted, so a stuck vendor never delays # serving (desktop pairs with OPENLLM_START_DAEMON=1 under headless). if [ "$VENDOR_PROVISIONED" = 1 ] && { [ "$INTERACTIVE" = 0 ] || [ "$INSTALL_MODE" = vendors ]; }; then wait_secs="$(trim_whitespace "${OPENLLM_VENDOR_WAIT_SECS:-600}")" case "$wait_secs" in ''|*[!0-9]*) wait_secs=600 ;; esac VENDOR_WAITED=1 deadline=$(( $(date +%s) + wait_secs )) while [ "$(date +%s)" -lt "$deadline" ]; do any=0 if [ -d "$OPENLLM_DIR/vendor-cli-install" ]; then for f in "$OPENLLM_DIR/vendor-cli-install"/*.json; do [ -f "$f" ] || continue stage="$(vendor_cli_read_field "$f" stage || true)" [ "$stage" = "installing" ] || continue # Dead workers are not active. A pid-less record is a brief parent # reservation (identity not published yet) — keep waiting while fresh, # but ignore once stale so an abandoned pre-handoff file cannot block # the wait forever. pid="$(vendor_cli_read_num_field "$f" pid || true)" if [ -n "$pid" ]; then start="$(vendor_cli_read_field "$f" process_start || true)" vendor_cli_pid_live "$pid" "$start" || continue else age="$(vendor_cli_path_mtime_age_sec "$f" || true)" # Fail-closed age 0 (unreadable mtime) stays in grace. [ -n "$age" ] && [ "$age" -lt "$VENDOR_CLI_PIDLESS_RESERVATION_GRACE_SEC" ] 2>/dev/null || continue fi any=1 break done fi [ "$any" = 0 ] && break sleep 1 done fi # vendors mode runs right after `openllm start`, so the daemon may still be # booting: re-probe after the wait, retrying briefly. Never starts anything. if [ "$INSTALL_MODE" = vendors ] && [ "$DAEMON_STATE" != "running" ]; then probe_tries=0 while [ "$probe_tries" -lt 5 ]; do if daemon_is_running; then DAEMON_STATE="running" break fi probe_tries=$((probe_tries + 1)) [ "$probe_tries" -lt 5 ] && sleep 1 done fi # Fixed, parseable install summary (agents and humans both read this). build_vendor_status_line() { # display|PATH name|slug|dest launcher — dests match provision_clis. local parts="" name bin slug dest stage reason path body agy_candidate for entry in \ "claude|claude|claude_code|$HOME/.local/bin/claude" \ "codex|codex|chatgpt|$HOME/.local/bin/codex" \ "kimi|kimi|kimi_code|$HOME/.kimi-code/bin/kimi" \ "grok|grok|grok|$HOME/.grok/bin/grok" \ "cursor-agent|cursor-agent|cursor|$HOME/.local/bin/cursor-agent" \ "muse|muse|muse|$HOME/.local/bin/muse" \ "antigravity|agy|antigravity|$HOME/.local/bin/agy" do IFS='|' read -r name bin slug dest <<<"$entry" if [ -n "${OPENLLM_SKIP_VENDOR_CLIS:-}" ] || [ "$SETUP_MODE" = minimal ] || [ "$INSTALL_MODE" = update ]; then stage="skipped" reason="" elif [ "$VENDOR_PROVISIONED" != 1 ]; then stage="skipped" reason="" # Prefer a live binary over a stale progress record (e.g. leftover # stage=installing / failed after a successful vendor install). # An `agy` older than 1.5.1 is not installed (it is being, or failed to # be, upgraded): fall through to the worker's own record. # Antigravity: the daemon's precedence (an existing home launcher # decides; PATH only without it), and only a usable 1.5+ file counts. elif if [ "$slug" = antigravity ]; then agy_candidate="$(if [ -e "$dest" ]; then printf '%s' "$dest"; else command -v "$bin" 2>/dev/null; fi)" [ -n "$agy_candidate" ] && [ -f "$agy_candidate" ] && agy_version_ok "$agy_candidate" else has_executable_command "$bin" || [ -x "$dest" ] || [ -x "$HOME/.local/bin/$bin" ] fi; then stage="installed" reason="" elif case "$VENDOR_LAUNCH_FAILED_SLUGS" in *",$slug,"*) true ;; *) false ;; esac; then stage="failed" reason="launch_failed" else path="$OPENLLM_DIR/vendor-cli-install/${slug}.json" if [ -f "$path" ]; then body="$(cat "$path" 2>/dev/null || true)" case "$body" in *'"stage":"installed"'*|*'"stage": "installed"'*) # Progress claimed installed but has_executable_command/dest checks # above already failed — report the mismatch instead of lying. stage="pending" ; reason="awaiting_detection" ;; *'"stage":"awaiting_detection"'*|*'"stage": "awaiting_detection"'*) stage="pending" ; reason="awaiting_detection" ;; *'"stage":"installing"'*|*'"stage": "installing"'*) stage="pending" ; reason="still installing" ;; *'"stage":"failed"'*|*'"stage": "failed"'*) stage="failed" reason="$(printf '%s' "$body" | sed -n 's/.*"reason":"\([^"]*\)".*/\1/p' | head -n 1)" [ -n "$reason" ] || reason="installer_failed" ;; *'"stage":"interrupted"'*|*'"stage": "interrupted"'*) stage="failed" ; reason="interrupted" ;; *) stage="pending" ; reason="unknown" ;; esac elif [ -n "${OPENLLM_ONLY_VENDOR_CLIS:-}" ]; then case ",${OPENLLM_ONLY_VENDOR_CLIS}," in *",${slug},"*) stage="failed"; reason="not launched" ;; *) stage="skipped"; reason="" ;; esac else stage="skipped" reason="" fi fi if [ -n "$reason" ]; then parts="${parts:+$parts }${name}=${stage}(${reason})" else parts="${parts:+$parts }${name}=${stage}" fi done printf '%s' "$parts" } path_hint_line() { # `openllm` is installed at $BIN_DIR (~/.openllm/bin); PATH symlinks into # ~/.local/bin or /usr/local/bin are best-effort. Report "on PATH" only when # `command -v openllm` resolves to this install (same inode), otherwise print # the session export that matches `sessionPathExportLine` / llms.txt. local resolved resolved="$(command -v openllm 2>/dev/null || true)" if [ -n "$resolved" ] && [ -e "$BIN_DIR/openllm" ] && [ "$resolved" -ef "$BIN_DIR/openllm" ]; then printf 'path: on PATH\n' else printf 'path: export PATH="$HOME/.openllm/bin:$PATH"\n' fi } supervisor_usable() { case "$(uname -s)" in Linux) command -v systemctl >/dev/null 2>&1 && systemctl --user show-environment >/dev/null 2>&1 ;; Darwin) command -v launchctl >/dev/null 2>&1 && launchctl print "gui/$(id -u)" >/dev/null 2>&1 ;; *) return 1 ;; esac } print_start_hint() { if [ "$INSTALL_MODE" = install ] && [ "$INTERACTIVE" = 0 ] && ! supervisor_usable; then if [ "$(uname -s)" = Linux ]; then echo "Next: openllm start (no systemd user bus here: runs detached, no restart at boot)" else echo "Next: openllm start" fi echo "Next: on an agent sandbox or ephemeral box, re-run the installer with --non-interactive --minimal instead (cloud-only)" else echo "Next: openllm start" fi } print_install_summary() { local vendor_line on_disk="" vendor_line="$(build_vendor_status_line)" if [ -x "$BIN_DIR/openllm" ]; then on_disk="$("$BIN_DIR/openllm" --version 2>/dev/null | head -n 1 | tr -d '\r' || true)" on_disk="${on_disk#openllm }" on_disk="${on_disk#v}" fi echo echo "OpenLLM install summary" echo "installed: openllm v${on_disk:-${CLI_VERSION:-unknown}} ($BIN_DIR/openllm)" echo "vendors: ${vendor_line:-none}" echo "daemon: $DAEMON_STATE" path_hint_line if [ "$INSTALL_MODE" = update ]; then echo "Next: openllm status" elif [ "${AUTH_FAILED:-0}" = 1 ]; then echo "auth: failed" echo "Next: openllm login" elif [ -z "$API_KEY" ]; then echo "Next: openllm login --non-interactive" echo "Next: after approval, run the printed resume command" if [ "$SETUP_MODE" != minimal ] && [ "$DAEMON_STATE" != "running" ]; then print_start_hint fi elif [ "$SETUP_MODE" != minimal ] && [ "$DAEMON_STATE" != "running" ]; then print_start_hint fi } if [ "$INSTALL_MODE" = update ]; then if [ "${BINARY_CHANGED:-0}" = 1 ]; then cat <