Files
ai-agent/worker/install.sh
gabrielvidalandClaude Opus 5.5 e425f10358 feat(workers): the ai-agent CLI back on workers, through the outbox — any harness
On 2026-11-28 an agy run on the EVOX2 (2ca176fc) had no way to start a
conversation: since 2026-11-18 a worker's CLI kept only `past`, and the
hub's MCP — its stand-in — existed in Claude Code only. It shelled out to
three `claude -p --model haiku` relays to call start_conversation, which
named the worker EVOX2 (refused), had no parent to report to and polled
wait_for_conversation for 10+ minutes. Another agy run (25c32ca5) gave up
delegating. Gabriel's call: the CLI back on workers, the MCP stays.

The 2026-11-16 path, on today's code:
- cli/ai_agent.py: on a worker (AI_AGENT_OUTBOX_URL) the WORKER_COMMANDS
  go into the outbox as a `cli` item {argv, sessionId}; what the hub's run
  printed comes back (≈ 2–4 s, a `wait` when the run ends). The hub's run
  sends X-AIA-As-Worker + X-AIA-As-Worker-Mode.
- backend/workers/cli.py: CliJobs runs the same CLI in a clean env (host
  token, AIA_AS_WORKER, its switch as the mode, CLAUDE_SESSION_ID = the
  sending session → the parent of what it starts: children nest and report
  back). The narrowing is workers/bound.py worker_caller — the same caller
  as a worker-bound MCP connection, worker.read / worker.run scopes.
- The per-worker switch: workers.json `cli` off | read | run (unset = run,
  a guest's computer always off), PATCH /api/workers/{id} {cli}, Machines →
  the worker → Details → "ai-agent CLI".
- sidecar/outbox.py: the `cli` kind (results dropped 10 min after they end);
  outbox_mirror answers it; worker/install.sh writes the `ai-agent` terminal
  shim again.
- The conv-ref hook names the CLI on a worker; `past`'s lookup follows the
  switch. The bound MCP connection stays, optional.
- Docs: CLAUDE.md, docs/mcp.md, worker/README.md.

Tests: test_worker_cli.py (new), test_worker_bound.py, test_worker_routing.py,
sidecar test_outbox.py, cli test_ai_agent.py / test_conv_ref.py; the whole
backend per module matches main (test_typed_plugins' git-clone case fails on
both). A live local hub answered every worker command through the gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 12:57:34 +01:00

995 lines
46 KiB
Bash
Executable File

#!/usr/bin/env bash
#
# install.sh — run this machine as an ai-agent **worker**: a user service
# (launchd agent on macOS, systemd --user unit on Linux) serving the same
# sidecar the homelab runs on its own host (spawn / resume / fork / interrupt
# `claude -p`), plus the transcript feed the hub pulls and the one-time pairing
# endpoint. Sessions run natively under your user, so they get this machine's
# Claude login and whatever its shell has (mise, gcloud, op, gh…) exactly like
# a terminal session.
#
# install.sh [install] install (or refresh) + print a pairing string
# install.sh pair print a new pairing string (re-pair / new hub)
# install.sh update fetch the latest main, reinstall deps, restart
# install.sh status service state, /health, version, last auto-update
# install.sh logs follow the worker log
# install.sh uninstall stop + remove the service (state kept)
#
# Once installed, `ai-agent-worker <command>` (in ~/.local/bin) is the same
# script. The `--update`-style spellings still work. `auto-update <commit>` is
# what the worker's own POST /update runs — the hub keeps every worker on the
# commit the hub itself is deployed at (see "Auto-update" below).
#
# Nothing is published beyond the tailnet: the listener binds the machine's
# Tailscale address only. The hub always calls in; the worker never calls the
# hub (it only fetches this repo from Gitea when told to update).
#
# Bootstrap on a fresh machine (clones the repo, then runs the installer from it):
# curl -fsSL https://git.gabvdl.xyz/gabrielvidal/ai-agent/raw/branch/main/worker/install.sh | bash
# The hub's Settings → Profiles → Pair a worker builds that line with every
# answer below already filled in (WORKER_* variables before `bash`).
#
# Where new runs start (the default cwd) is asked interactively: the directory
# you run the installer from, confirmed with `y`, or any path you type. Without
# a terminal (`curl | bash`) the current directory is taken as is. `update`
# keeps whatever the installed service already uses.
#
# No Claude login is needed: by default the worker's Claude Code bills the
# Homelab's accounts through the hub's Claude proxy (the hub sends the proxy
# config once paired, and writes the machine's default account into
# ~/.claude/settings.json so a terminal `claude` uses it too). A machine that
# is signed in can run on its own login instead (the switch on its page in the
# hub); its account is then guessed from `claude auth status` (a gmail login →
# `personal`, anything else → `work`) — WORKER_ACCOUNT overrides the guess.
#
# The opencode harness (GPT models on a ChatGPT seat) is offered too: opencode
# is installed when missing (Homebrew's anomalyco/tap/opencode-v2, else the
# official script), and its account declared under the hub's id for it
# (`chatgpt-work`). Its login is made from the hub (Settings → Accounts → Log
# in: a device code to enter on auth.openai.com), and its sessions — terminal
# ones included, it shares opencode's own data dir — are mirrored to the hub.
#
# The agy harness (Gemini on a Google AI Pro / Ultra login, Google's
# Antigravity CLI) is offered too, off by default: agy is installed when
# missing (https://antigravity.google/cli/install.sh → ~/.local/bin/agy) and
# its account declared as `google-personal`. Its Google sign-in is made from the
# hub (Settings → Accounts → Sign in: a Google link, then paste the code), and
# its conversations — terminal ones included — are mirrored to the hub.
#
# ask-form (the standalone forms tool a run's `ask-form` skill drives) is
# installed on every worker of the owner's (not a guest's computer) unless
# WORKER_ASKFORM=0: when it isn't on PATH,
# https://ask-form.xyz/install.sh (it checks the release's checksums) puts it in
# ~/.local/bin, then `ask-form setup --events-url http://<bind>:<port>/ask-form/events`
# points its serve at this sidecar, so the hub sees the forms asked here. An
# `update` re-runs setup only when that events URL isn't the one wanted.
#
# Auto-update: the hub compares each worker's commit (its /health) with the
# commit the hub was deployed from and, when the worker is behind, calls the
# worker's POST /update. That starts `install.sh auto-update <commit>`
# detached: fetch that exact commit, check it out, and — only when sidecar/,
# cli/, worker/ or the notify skill changed — reinstall deps and restart the
# service, then wait for /health to report the new commit. If it doesn't come
# up, the previous commit is checked out and restarted again (a rollback). The
# outcome is in ~/.config/ai-agent-worker/update.json (and /health), the log in
# update.log next to worker.log. In-flight runs survive the restart (they are
# detached). Only the installer's own clone (~/.local/share/ai-agent-worker/src)
# auto-updates; a worker run from a dev checkout never moves its HEAD.
#
# A guest's computer (the hub's Settings → My computers → Add): the portal hands
# out WORKER_HUB (its guest address) and WORKER_ENROLL (a one-time code). Such a
# worker needs no Tailscale: it listens on 127.0.0.1 only and dials out to the
# hub over HTTPS (sidecar/link.py), which pairs with it through that link. Its
# Claude Code bills the hub owner's account through the hub, within the limits
# the owner set — no Claude login needed here, and nothing written into this
# machine's own ~/.claude/settings.json.
#
# An owner's machine the hub can't reach over the tailnet (a company devbox on
# another tailnet, a cloud VM) dials out the same way: the hub's Settings →
# Profiles → Pair a worker → "It dials out" hands out WORKER_HUB, a one-time
# WORKER_ENROLL code and WORKER_ACCOUNT. The hub's answer to that code says
# it is the owner's (link.json keeps `owner`), so it is set up as one of the owner's
# workers — on its own Claude login, `notify` in a terminal — not as a guest's.
#
# Env overrides (each skips its prompt): WORKER_CWD, WORKER_ACCOUNT,
# WORKER_PORT (8790), WORKER_BIND (the Tailscale IPv4), WORKER_SRC (clone dir
# for the bootstrap), WORKER_REF (branch the bootstrap and `update` follow,
# main), WORKER_OPENCODE (1 = set it up, 0 = don't), WORKER_OPENCODE_ACCOUNT
# (the hub's id for the ChatGPT login, chatgpt-work), WORKER_AGY (1 = set up
# agy, 0 = don't), WORKER_AGY_ACCOUNT (the hub's id for the Google login,
# google-personal), WORKER_ASKFORM (0 = don't install / set up ask-form).
set -euo pipefail
REPO_URL="https://git.gabvdl.xyz/gabrielvidal/ai-agent.git"
REF="${WORKER_REF:-main}"
LABEL="xyz.gabvdl.ai-agent-worker"
UNIT="ai-agent-worker.service"
SHARE="$HOME/.local/share/ai-agent-worker"
SRC="${WORKER_SRC:-$SHARE/src}"
VENV="$SHARE/venv"
STATE="${WORKER_STATE_DIR:-$HOME/.config/ai-agent-worker}"
BIN_DIR="$HOME/.local/bin"
CWD="${WORKER_CWD:-}"
ACCOUNT="${WORKER_ACCOUNT:-}"
OPENCODE="${WORKER_OPENCODE:-}"
OPENCODE_ACCOUNT="${WORKER_OPENCODE_ACCOUNT:-}"
OPENCODE_BIN=""
AGY="${WORKER_AGY:-}"
AGY_ACCOUNT="${WORKER_AGY_ACCOUNT:-}"
AGY_BIN=""
ASKFORM="${WORKER_ASKFORM:-}"
ASKFORM_BIN=""
HUB="${WORKER_HUB:-}"
ENROLL="${WORKER_ENROLL:-}"
# What changes on a worker when these paths change: the rest of the repo
# (frontend, backend, docs) is the hub's business, so an update touching only
# that moves the checkout without restarting anything.
WORKER_PATHS=(sidecar cli worker .claude/skills/notify)
die() { echo "error: $*" >&2; exit 1; }
say() { echo "==> $*"; }
case "$(uname -s)" in
Darwin) OS=macos
LOGS="$HOME/Library/Logs/ai-agent-worker"
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
DOMAIN="gui/$(id -u)" ;;
Linux) OS=linux
LOGS="${XDG_STATE_HOME:-$HOME/.local/state}/ai-agent-worker"
UNIT_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/$UNIT"
ENV_FILE="$STATE/worker.env" ;;
*) die "this installer is for macOS or Linux" ;;
esac
# The command: `update`, `--update` and `-update` are the same thing.
CMD="${1:-install}"; CMD="${CMD#--}"; CMD="${CMD#-}"
[[ $# -gt 0 ]] && shift
case "$CMD" in
install|pair|update|status|logs|uninstall|version|auto-update|help|h) ;;
sync|unsync|claude) ;;
*) die "unknown command: $CMD (install | pair | update | status | logs | uninstall | sync | unsync | claude)" ;;
esac
if [[ "$CMD" == help || "$CMD" == h ]]; then
sed -n '2,/^set -euo/p' "${BASH_SOURCE[0]}" | sed '$d; s/^# \{0,1\}//'
exit 0
fi
# Fetch <ref> (a branch or an exact commit) from origin and check it out
# detached. Shallow either way: the clone never needs history, and a detached
# HEAD is what an exact commit is anyway (a later `update` just moves it).
checkout_ref() {
git -C "$1" fetch --quiet --depth 1 origin "$2" \
&& git -C "$1" -c advice.detachedHead=false checkout --quiet --detach FETCH_HEAD
}
# ── locate the checkout (or bootstrap one) ─────────────────────────────────────
HERE="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd || true)"
if [[ -n "$HERE" && -f "$HERE/../sidecar/sidecar.py" ]]; then
ROOT="$(cd "$HERE/.." && pwd -P)"
else
command -v git >/dev/null || die "git not found ($([[ $OS == macos ]] && echo 'xcode-select --install' || echo 'install it with your package manager'))"
if [[ -d "$SRC/.git" ]]; then
checkout_ref "$SRC" "$REF"
else
say "cloning $REPO_URL ($REF) → $SRC"
mkdir -p "$(dirname "$SRC")"
git clone --quiet --depth 1 --branch "$REF" "$REPO_URL" "$SRC"
fi
exec bash "$SRC/worker/install.sh" "$CMD" "$@"
fi
SIDECAR="$ROOT/sidecar"
# Dialling out (a guest's computer): asked for now, or set up before.
LINK=0
[[ -n "$HUB" || -f "$STATE/link.json" ]] && LINK=1
# …for the hub's owner (Pair a worker → It dials out): an owner worker, not
# a guest's computer. Read from link.json once enrolled; on an install the
# hub's answer to the code says so (check_enroll_code).
OWNER_LINK=0
[[ -f "$STATE/link.json" ]] && grep -Eq '"owner": *true' "$STATE/link.json" && OWNER_LINK=1
# Only the installer's own clone follows the hub: a dev checkout keeps its HEAD.
MANAGED=0
[[ -d "$SRC" && "$ROOT" == "$(cd "$SRC" && pwd -P)" ]] && MANAGED=1
tailscale_bin() {
if command -v tailscale >/dev/null; then command -v tailscale
elif [[ -x /Applications/Tailscale.app/Contents/MacOS/Tailscale ]]; then
echo /Applications/Tailscale.app/Contents/MacOS/Tailscale
fi
}
py() { WORKER_STATE_DIR="$STATE" "$VENV/bin/python" "$@"; }
# Would the hub take the portal's code? Asked before the minutes-long build,
# so a dead code (replaced, used, over an hour old) fails now instead of at
# the very end; it isn't consumed. A hub without the check (404) or out of
# reach: carry on, the enroll at the end says it anyway. No python here —
# the venv doesn't exist yet.
check_enroll_code() {
[[ "$ENROLL" =~ ^[A-Za-z0-9]+$ ]] || die "WORKER_ENROLL doesn't look like a code from your portal"
local out st msg
out="$(curl -sS --max-time 15 -w $'\n%{http_code}' -X POST -H 'Content-Type: application/json' \
-d "{\"code\":\"$ENROLL\"}" "${HUB%/}/worker-link/enroll/check" 2>/dev/null)" || return 0
st="${out##*$'\n'}"
if [[ "$st" == 200 ]]; then
local mine='"owner": *true'
[[ "$out" =~ $mine ]] && OWNER_LINK=1
return 0
fi
[[ "$st" == 403 || "$st" == 429 ]] || return 0
[[ "$out" == *'"enroll_code"'* ]] && code_refused
msg="$(sed -n 's/.*"message": *"\([^"]*\)".*/\1/p' <<<"${out%$'\n'*}")"
die "${msg:-the hub refused this code (HTTP $st)}"
}
# The hub doesn't know the portal's code (link.py exits 3 on the same).
code_refused() {
echo "error: the hub refused this code — it was replaced, used, or is over an hour old." >&2
echo "Get a new line — Settings → My computers → Add a computer (a guest), or Settings →" >&2
echo "Profiles → Pair a worker → It dials out (the hub's owner) — and run it:" >&2
echo "the install is reused, so it takes seconds." >&2
exit 1
}
health() { curl -fsS --max-time 3 "http://$BIND:$PORT/health" 2>/dev/null; }
# A field of /health (`health_field commit`), "" when it's down or has none.
health_field() {
health | "$VENV/bin/python" -c 'import json,sys
try: v = json.load(sys.stdin).get(sys.argv[1])
except Exception: v = None
print("" if v is None else v)' "$1" 2>/dev/null || true
}
# The pid of the process serving :$PORT, "" when nothing does — /health's
# own `pid`, else the socket's owner (a sidecar from before /health had one).
listener_pid() {
local p; p="$(health_field pid)"
if [[ -z "$p" ]] && command -v lsof >/dev/null; then
p="$(lsof -nP -iTCP:"$PORT" -sTCP:LISTEN -t 2>/dev/null | head -1 || true)"
fi
if [[ -z "$p" ]] && command -v ss >/dev/null; then
p="$(ss -ltnpH "sport = :$PORT" 2>/dev/null | grep -o 'pid=[0-9]*' | head -1 | cut -d= -f2 || true)"
fi
echo "$p"
}
# A value the installed service already runs with, "" if none: the plist's
# EnvironmentVariables on macOS, the unit's EnvironmentFile on Linux.
installed() {
if [[ $OS == macos ]]; then
[[ -f "$PLIST" ]] || return 0
plutil -extract "EnvironmentVariables.$1" raw -o - "$PLIST" 2>/dev/null || true
else
[[ -f "$ENV_FILE" ]] || return 0
local v; v="$(sed -n "s/^$1=//p" "$ENV_FILE" | tail -1)"
v="${v#\"}"; v="${v%\"}"; v="${v//\\\"/\"}"; printf '%s' "${v//\\\\/\\}"
fi
}
# Ask on the terminal even under `curl … | bash`, where stdin is the script.
# The local must not be named like the caller's variable: `printf -v` would
# fill the shadowing local and leave the caller's unset (set -u then dies).
ask() { # ask <prompt> <var>
local _ask_reply=""
if [[ -r /dev/tty && -w /dev/tty ]] && { : </dev/tty; } 2>/dev/null; then
read -r -p "$1" _ask_reply </dev/tty || true
fi
printf -v "$2" '%s' "$_ask_reply"
}
# Where new runs start: the directory this installer was launched from (the
# bootstrap `exec` keeps it), confirmed with `y`/Enter, or a path typed instead.
pick_cwd() {
if [[ -n "$CWD" ]]; then CWD="${CWD/#\~/$HOME}"; return; fi
local here reply=""; here="$(installed SIDECAR_CWD)"
if [[ "$CMD" == update && -n "$here" && -d "$here" ]]; then
CWD="$here"; say "keeping cwd $CWD (set WORKER_CWD to change)"; return
fi
[[ -n "$here" && -d "$here" ]] || here="$(pwd -P)"
while :; do
ask "Default working dir for new runs — $here ? [y / a path] " reply
case "$reply" in
""|y|Y|yes|YES) CWD="$here"; break ;;
*) reply="${reply/#\~/$HOME}"
if [[ -d "$reply" ]]; then CWD="$(cd "$reply" && pwd -P)"; break; fi
echo " no such directory: $reply" >&2 ;;
esac
done
}
# The email this machine's `claude` is signed in with, "" if unknown.
claude_login() {
"$CLAUDE_BIN" auth status 2>/dev/null \
| "$VENV/bin/python" -c 'import json,sys
try: print(json.load(sys.stdin).get("email") or "")
except Exception: print("")' 2>/dev/null || true
}
# The hub-side id of this machine's own Claude login (`personal`, `work`…),
# for a worker that runs on it rather than through the hub. Kept across
# `update`; otherwise guessed from the login itself — a gmail address is
# Gabriel's own plan, anything else a company seat; no login: `personal`.
pick_account() {
[[ -n "$ACCOUNT" ]] && return
local prev email; prev="$(installed SIDECAR_DEFAULT_ACCOUNT)"
if [[ -n "$prev" ]]; then
ACCOUNT="$prev"; say "keeping account $ACCOUNT (set WORKER_ACCOUNT to change)"; return
fi
email="$(claude_login)"
case "$email" in
"") ACCOUNT="personal" ;;
*@gmail.com|*@googlemail.com) ACCOUNT="personal" ;;
*) ACCOUNT="work" ;;
esac
if [[ -n "$email" ]]; then say "own Claude login: $email (account $ACCOUNT)"
else say "no Claude login here: it will bill the Homelab accounts through the hub"; fi
}
# The opencode harness: kept as it is on `update` (the service env says whether
# it is on); otherwise asked. Installs opencode when it isn't there yet.
# The opencode the harness was last checked against (sidecar/opencode_*.py read
# its database and its CLI's output): an older one is brought up to it.
OPENCODE_TESTED="2.0.32"
opencode_version() {
"$1" --version 2>/dev/null | grep -Eo '[0-9]+\.[0-9]+\.[0-9]+' | head -1 || true
}
older() { # older <a> <b>: version a sorts before version b
[[ "$1" != "$2" && "$(printf '%s\n%s\n' "$1" "$2" | sort -t. -k1,1n -k2,2n -k3,3n | head -1)" == "$1" ]]
}
opencode_bin() {
if command -v opencode >/dev/null; then command -v opencode
elif [[ -x "$HOME/.opencode/bin/opencode" ]]; then echo "$HOME/.opencode/bin/opencode"
fi
}
pick_opencode() {
local prev decided reply=""
prev="$(installed SIDECAR_OPENCODE_ACCOUNTS)"; decided="$(installed WORKER_OPENCODE)"
if [[ -z "$OPENCODE" ]]; then
if [[ "$CMD" == update && -n "$decided" ]]; then
OPENCODE="$decided" # asked once already: kept
elif [[ "$CMD" == update && -f "${PLIST:-${UNIT_FILE:-}}" ]]; then
# An install from before the question: it had opencode iff it declared
# an account. Never asked here — an auto-update has no one to answer.
[[ -n "$prev" ]] && OPENCODE=1 || OPENCODE=0
else
ask "Also run opencode here (GPT models on a ChatGPT seat)? [Y/n] " reply
case "$reply" in n|N|no|NO) OPENCODE=0 ;; *) OPENCODE=1 ;; esac
fi
fi
[[ "$OPENCODE" == 1 ]] || return 0
OPENCODE_ACCOUNT="${OPENCODE_ACCOUNT:-${prev%%=*}}"
OPENCODE_ACCOUNT="${OPENCODE_ACCOUNT:-chatgpt-work}"
OPENCODE_BIN="$(opencode_bin)"
if [[ -z "$OPENCODE_BIN" ]]; then
if command -v brew >/dev/null; then
say "installing opencode (brew install anomalyco/tap/opencode-v2)"
brew install --quiet anomalyco/tap/opencode-v2 || true
fi
OPENCODE_BIN="$(opencode_bin)"
fi
if [[ -z "$OPENCODE_BIN" ]]; then
say "installing opencode (https://opencode.ai/v2/install)"
curl -fsSL https://opencode.ai/v2/install | bash >/dev/null || true
OPENCODE_BIN="$(opencode_bin)"
fi
[[ -n "$OPENCODE_BIN" ]] || die "couldn't install opencode — install it, then re-run (or WORKER_OPENCODE=0)"
local v; v="$(opencode_version "$OPENCODE_BIN")"
if [[ -n "$v" ]] && older "$v" "$OPENCODE_TESTED"; then
say "upgrading opencode $v → $OPENCODE_TESTED"
"$OPENCODE_BIN" upgrade "$OPENCODE_TESTED" </dev/null >/dev/null 2>&1 || true
v="$(opencode_version "$OPENCODE_BIN")"
if older "$v" "$OPENCODE_TESTED"; then
echo "warning: opencode is still $v — run: $OPENCODE_BIN upgrade $OPENCODE_TESTED" >&2
fi
fi
say "opencode: $OPENCODE_BIN ($("$OPENCODE_BIN" --version 2>/dev/null || echo '?')), account $OPENCODE_ACCOUNT"
}
# The agy harness: kept as it is on `update` (the service env says whether it
# is on); otherwise asked, default no. Installs agy when it isn't there yet (it
# updates itself afterwards).
pick_agy() {
local prev decided reply=""
prev="$(installed SIDECAR_AGY_ACCOUNTS)"; decided="$(installed WORKER_AGY)"
if [[ -z "$AGY" ]]; then
if [[ "$CMD" == update && -n "$decided" ]]; then
AGY="$decided"
elif [[ "$CMD" == update ]]; then
[[ -n "$prev" ]] && AGY=1 || AGY=0
else
ask "Also run Antigravity here (agy: Gemini on a Google AI Pro plan)? [y/N] " reply
case "$reply" in y|Y|yes|YES) AGY=1 ;; *) AGY=0 ;; esac
fi
fi
[[ "$AGY" == 1 ]] || return 0
AGY_ACCOUNT="${AGY_ACCOUNT:-${prev%%=*}}"
AGY_ACCOUNT="${AGY_ACCOUNT:-google-personal}"
AGY_BIN="$(command -v agy || true)"
[[ -z "$AGY_BIN" && -x "$HOME/.local/bin/agy" ]] && AGY_BIN="$HOME/.local/bin/agy"
if [[ -z "$AGY_BIN" ]]; then
say "installing agy (https://antigravity.google/cli/install.sh)"
curl -fsSL https://antigravity.google/cli/install.sh | bash >/dev/null || true
[[ -x "$HOME/.local/bin/agy" ]] && AGY_BIN="$HOME/.local/bin/agy"
fi
[[ -n "$AGY_BIN" ]] || die "couldn't install agy — install it, then re-run (or WORKER_AGY=0)"
say "agy: $AGY_BIN ($("$AGY_BIN" --version 2>/dev/null || echo '?')), account $AGY_ACCOUNT"
}
# ask-form: installed and pointed at this sidecar unless WORKER_ASKFORM=0 (the
# answer is kept in the service env, so `update` remembers it). Never fatal: a
# worker without forms still runs. `ask-form setup` re-registers serve and
# restarts it (an open `ask-form wait` would be cut), so it only runs when
# ask-form is new here or its events URL isn't this sidecar's.
askform_config_dir() {
if [[ -n "${ASK_FORM_CONFIG:-}" ]]; then echo "$ASK_FORM_CONFIG"
elif [[ -n "${XDG_CONFIG_HOME:-}" ]]; then echo "$XDG_CONFIG_HOME/ask-form"
else echo "$HOME/.config/ask-form"; fi
}
askform_bin() { # the real binary, never this repo's cli/ask-form install hint
local b
for b in "$(command -v ask-form || true)" "$BIN_DIR/ask-form"; do
[[ -n "$b" && -x "$b" ]] || continue
grep -qF "the ask-form tool isn't installed" "$b" 2>/dev/null && continue
echo "$b"; return 0
done
}
pick_askform() {
local want cfg cur=""
[[ -n "$ASKFORM" ]] || ASKFORM="$(installed WORKER_ASKFORM)"
ASKFORM="${ASKFORM:-1}"
[[ "$ASKFORM" == 0 ]] && return 0
# A guest's computer runs an ask-form its owner installed, if any
# (sidecar/askform.py wire_events): nothing is installed there.
[[ "$LINK" == 1 && "$OWNER_LINK" == 0 ]] && return 0
ASKFORM_BIN="$(askform_bin)"
if [[ -z "$ASKFORM_BIN" ]]; then
say "installing ask-form (https://ask-form.xyz/install.sh)"
curl -fsSL https://ask-form.xyz/install.sh </dev/null \
| ASK_FORM_BIN_DIR="$BIN_DIR" sh -s -- --no-setup >/dev/null 2>&1 || true
ASKFORM_BIN="$(askform_bin)"
if [[ -z "$ASKFORM_BIN" ]]; then
echo "warning: couldn't install ask-form — forms won't work here (curl -fsSL https://ask-form.xyz/install.sh | sh, then \`ai-agent-worker update\`)" >&2
return 0
fi
fi
want="http://$BIND:$PORT/ask-form/events"
cfg="$(askform_config_dir)"
[[ -f "$cfg/serve.env" ]] \
&& cur="$(sed -n 's/^[[:space:]]*\(export[[:space:]]*\)\{0,1\}ASK_FORM_EVENTS_URL=//p' "$cfg/serve.env" | tail -1 | tr -d "\"'")"
if [[ -s "$cfg/admin-token" && "$cur" == "$want" ]]; then
say "ask-form: $ASKFORM_BIN, events → $want"
return 0
fi
say "ask-form setup --events-url $want"
"$ASKFORM_BIN" setup --events-url "$want" </dev/null >/dev/null 2>&1 \
|| echo "warning: \`ask-form setup\` failed — run it by hand: $ASKFORM_BIN setup --events-url $want" >&2
}
# The address: an install re-reads Tailscale (and takes 8790 unless told);
# everything else keeps what the service already binds — an update moving the
# port would strand the hub's pairing.
resolve_bind() {
BIND="${WORKER_BIND:-$(installed SIDECAR_BIND)}"
PORT="${WORKER_PORT:-$(installed SIDECAR_PORT)}"
if [[ "$CMD" == install ]]; then BIND="${WORKER_BIND:-}"; PORT="${WORKER_PORT:-}"; fi
PORT="${PORT:-8790}"
if [[ -z "$BIND" && "$LINK" == 1 ]]; then
BIND=127.0.0.1 # the hub is reached through the link, never called in
fi
if [[ -z "$BIND" ]]; then
local ts; ts="$(tailscale_bin)"
[[ -n "$ts" ]] || die "Tailscale not found — install it and log in to the tailnet"
BIND="$("$ts" ip -4 2>/dev/null | head -1 || true)"
# Only the auto-detected address is checked: WORKER_BIND=127.0.0.1 behind
# `tailscale serve` is a documented setup.
[[ "$BIND" =~ ^100\. ]] || die "no Tailscale IPv4 (got '${BIND:-nothing}') — is Tailscale up?"
fi
}
pairing_string() {
local code email
code="$(py "$SIDECAR/pairing.py" new-code)"
# The login this machine's `claude` already has, if any: the hub matches
# it to one of its accounts should the worker run on its own login.
email="$(claude_login)"
echo
echo "Paste this in the hub → Settings → Profiles → Pair a worker (one use):"
echo
echo " $BIND:$PORT/$code${email:+/$email}"
echo
}
# ── the service (launchd / systemd --user) ─────────────────────────────────────
svc_loaded() {
if [[ $OS == macos ]]; then launchctl print "$DOMAIN/$LABEL" >/dev/null 2>&1
else systemctl --user is-active --quiet "$UNIT"; fi
}
svc_remove() {
if [[ $OS == macos ]]; then
launchctl bootout "$DOMAIN/$LABEL" 2>/dev/null || true
rm -f "$PLIST"
else
systemctl --user disable --now --quiet "$UNIT" 2>/dev/null || true
rm -f "$UNIT_FILE"
systemctl --user daemon-reload 2>/dev/null || true
fi
}
svc_status() {
if [[ $OS == macos ]]; then
launchctl print "$DOMAIN/$LABEL" 2>/dev/null | grep -E "state|pid|last exit" || echo "not loaded"
else
systemctl --user --no-pager --lines=0 status "$UNIT" 2>/dev/null | sed -n '1,4p' || echo "not loaded"
fi
}
# (Re)start the service from the file make_service.py just wrote.
svc_start() {
if [[ $OS == linux ]]; then
systemctl --user daemon-reload
systemctl --user enable --quiet "$UNIT"
systemctl --user restart "$UNIT"
return
fi
# bootout is asynchronous: bootstrapping while launchd is still tearing the
# old agent down fails with "Bootstrap failed: 5: Input/output error" and
# leaves the worker DOWN. Wait for the label to disappear, then retry the
# bootstrap a few times (a plist error would fail every time — die loudly).
launchctl bootout "$DOMAIN/$LABEL" 2>/dev/null || true
for _ in $(seq 1 40); do
launchctl print "$DOMAIN/$LABEL" >/dev/null 2>&1 || break
sleep 0.5
done
local booted=0 attempt
for attempt in 1 2 3 4 5 6; do
if launchctl bootstrap "$DOMAIN" "$PLIST" 2>/dev/null; then booted=1; break; fi
# already loaded (a racing KeepAlive restart) counts as success
launchctl print "$DOMAIN/$LABEL" >/dev/null 2>&1 && { booted=1; break; }
sleep $attempt
done
[[ "$booted" == 1 ]] || {
launchctl bootstrap "$DOMAIN" "$PLIST" || true # once more, loudly, for the error text
die "launchd refused to load $LABEL — see above; retry with: launchctl bootstrap $DOMAIN $PLIST"
}
launchctl kickstart -k "$DOMAIN/$LABEL" >/dev/null 2>&1 || true
}
# A user unit needs a user manager, and one that outlives the login session
# (lingering) to keep serving after you log out or the box reboots.
linux_preflight() {
# A shell without a login session (some SSH setups) has no XDG_RUNTIME_DIR,
# though a lingering user's manager is running: point systemctl --user at it.
if [[ -z "${XDG_RUNTIME_DIR:-}" && -d "/run/user/$(id -u)" ]]; then
export XDG_RUNTIME_DIR="/run/user/$(id -u)"
fi
systemctl --user show-environment >/dev/null 2>&1 \
|| die "no systemd user manager here (systemctl --user) — log in on this machine's own session, or: sudo loginctl enable-linger $USER, then re-login"
if [[ "$(loginctl show-user "$USER" -p Linger --value 2>/dev/null || true)" != yes ]]; then
loginctl enable-linger "$USER" 2>/dev/null \
|| echo "warning: lingering is off — the worker stops when you log out; fix: sudo loginctl enable-linger $USER" >&2
fi
}
# ── auto-update ────────────────────────────────────────────────────────────────
# update.json: what the last auto-update did — /health serves it to the hub.
update_state() { # update_state <state> <from> <to> [error]
U_STATE="$1" U_FROM="$2" U_TO="$3" U_ERROR="${4:-}" U_STARTED="${U_STARTED:-}" \
"$VENV/bin/python" - "$STATE/update.json" <<'PY'
import json, os, sys, time
e = os.environ
now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
out = {"state": e["U_STATE"], "from": e["U_FROM"], "to": e["U_TO"],
"startedAt": e.get("U_STARTED") or now,
"finishedAt": None if e["U_STATE"] == "updating" else now,
"error": e.get("U_ERROR") or None, "pid": os.getppid()}
tmp = sys.argv[1] + ".tmp"
with open(tmp, "w") as f:
json.dump(out, f)
os.replace(tmp, sys.argv[1])
PY
echo "[$(date '+%F %T')] $1 ${2:0:9} → ${3:0:9}${4:+ — $4}"
}
# Run the checked-out installer's own `update` (deps, service file, restart)
# and wait until /health reports <commit>. A subprocess, not an exec: this
# copy decides about the rollback whatever the new one does.
apply_commit() { # apply_commit <commit>
WORKER_PULLED=1 WORKER_EXPECT_COMMIT="$1" bash "$ROOT/worker/install.sh" update </dev/null
}
auto_update() {
local to="${1:-}" from err
# A full sha: a server only hands out a commit by its whole name.
[[ "$to" =~ ^[0-9a-f]{40}$ ]] || die "auto-update wants a full 40-hex commit sha, got '${to}'"
[[ "$MANAGED" == 1 ]] || die "$ROOT is not the installer's clone ($SRC) — not moving its HEAD"
[[ -x "$VENV/bin/python" ]] || die "not installed yet"
mkdir -p "$STATE"
# One at a time: a second request while one runs is a no-op.
# (A global: the EXIT trap runs after this function's locals are gone.)
UPDATE_LOCK="$STATE/update.lock"
if ! mkdir "$UPDATE_LOCK" 2>/dev/null; then
local pid; pid="$(cat "$UPDATE_LOCK/pid" 2>/dev/null || true)"
if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then
echo "an update is already running (pid $pid)"; exit 0
fi
rm -rf "$UPDATE_LOCK"; mkdir "$UPDATE_LOCK"
fi
echo $$ > "$UPDATE_LOCK/pid"
trap 'rm -rf "$UPDATE_LOCK"' EXIT
from="$(git -C "$ROOT" rev-parse HEAD)"
U_STARTED="$(date -u +%Y-%m-%dT%H:%M:%SZ)"; export U_STARTED
if [[ "$from" == "$to" ]]; then update_state done "$from" "$from"; return 0; fi
update_state updating "$from" "$to"
if ! checkout_ref "$ROOT" "$to"; then
update_state failed "$from" "$to" "couldn't fetch $to from origin (not pushed yet?)"
return 1
fi
to="$(git -C "$ROOT" rev-parse HEAD)"
if git -C "$ROOT" diff --quiet "$from" "$to" -- "${WORKER_PATHS[@]}"; then
update_state done "$from" "$to" ""
echo " nothing the worker runs changed — checkout moved, no restart"
return 0
fi
if apply_commit "$to"; then update_state done "$from" "$to"; return 0; fi
err="the new version didn't come up on ${to:0:9}"
git -C "$ROOT" -c advice.detachedHead=false checkout --quiet --detach "$from" \
|| { update_state failed "$from" "$to" "$err; checkout of $from failed too"; return 1; }
if apply_commit "$from"; then
update_state rolledback "$from" "$to" "$err"
else
update_state failed "$from" "$to" "$err, and $from didn't come back either"
fi
return 1
}
# ── the terminal's `claude` (a guest's computer) ───────────────────────────────
# `claude` typed in a terminal asks which Claude to use — the computer's own
# login or the hub's (synced to the app) — worker/claude_launcher.py. A shell
# function, sourced from one marked line in the shell's rc file: the real
# `claude` binary is untouched, and `command claude` skips the question.
SHELL_HOOK="$STATE/claude-shell.sh"
RC_MARK='# ai-agent-worker: `claude` asks which Claude to use'
rc_files() {
local f
for f in "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.bash_profile"; do
[[ -f "$f" ]] && echo "$f"
done
# the login shell's own, even before it exists
case "$(basename "${SHELL:-}")" in
zsh) [[ -f "$HOME/.zshrc" ]] || echo "$HOME/.zshrc" ;;
bash) [[ -f "$HOME/.bashrc" ]] || echo "$HOME/.bashrc" ;;
esac
return 0
}
install_launcher() {
local rc
{
echo '#!/usr/bin/env bash'
echo '# ai-agent-claude — `claude` asking which Claude to use (written by'
echo "# $ROOT/worker/install.sh; the shell's \`claude\` function calls it)."
printf 'WORKER_STATE_DIR=%q exec %q %q "$@"\n' "$STATE" "$VENV/bin/python" \
"$ROOT/worker/claude_launcher.py"
} > "$BIN_DIR/ai-agent-claude"
chmod 755 "$BIN_DIR/ai-agent-claude"
{
echo '# Written by ai-agent-worker: `claude` asks which Claude to use — your own'
echo '# login or ai-agent Claude (synced to the app). `command claude` skips it;'
echo '# `ai-agent-worker claude off` turns the question off.'
printf 'if [ -x %q ]; then\n' "$BIN_DIR/ai-agent-claude"
printf ' claude() { %q "$@"; }\n' "$BIN_DIR/ai-agent-claude"
echo 'fi'
} > "$SHELL_HOOK"
while IFS= read -r rc; do
grep -qF "$RC_MARK" "$rc" 2>/dev/null && continue
printf '\n[ -f %q ] && . %q %s\n' "$SHELL_HOOK" "$SHELL_HOOK" "$RC_MARK" >> "$rc"
done < <(rc_files)
if [[ -d "$HOME/.config/fish" ]]; then
mkdir -p "$HOME/.config/fish/conf.d"
{
echo '# Written by ai-agent-worker: `claude` asks which Claude to use.'
printf 'if test -x "%s"\n' "$BIN_DIR/ai-agent-claude"
printf ' function claude; "%s" $argv; end\n' "$BIN_DIR/ai-agent-claude"
echo 'end'
} > "$HOME/.config/fish/conf.d/ai-agent-claude.fish"
fi
}
uninstall_launcher() {
local rc
for rc in "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.bash_profile"; do
[[ -f "$rc" ]] && grep -qF "$RC_MARK" "$rc" || continue
# the marked line and the blank line the installer put before it
awk -v mark="$RC_MARK" '
index($0, mark) { if (held) held = 0; next }
held { print ""; held = 0 }
/^$/ { held = 1; next }
{ print }
END { if (held) print "" }' "$rc" > "$rc.ai-agent.tmp" && mv "$rc.ai-agent.tmp" "$rc"
done
rm -f "$BIN_DIR/ai-agent-claude" "$SHELL_HOOK" "$HOME/.config/fish/conf.d/ai-agent-claude.fish"
}
# ── `ai-agent` + `notify` in a terminal (the owner's workers) ──────────────────
# A run this worker launches finds the CLIs on its PATH and the outbox in its
# environment (sidecar claude_env._run_env). A `claude` typed in a
# terminal here had neither. These shims give it the same: the outbox this
# service listens on, and its run token read at call time (0600, in $STATE).
# Nothing calls the hub — it collects the outbox. A file of the same name that
# isn't ours is left alone; a guest's computer (the link) gets none: its
# `ai-agent` CLI is off and its terminal `claude` has the launcher.
SHIM_MARK='# ai-agent-worker shim:'
SHIMS=(ai-agent notify notify-done notify-ask)
write_shims() {
local name f
mkdir -p "$BIN_DIR"
for name in "${SHIMS[@]}"; do
f="$BIN_DIR/$name"
if [[ -e "$f" ]] && ! grep -qF "$SHIM_MARK" "$f" 2>/dev/null; then
echo "note: $f isn't the worker's — left alone, so \`$name\` in a terminal isn't the worker's either" >&2
continue
fi
cat > "$f" <<EOF
#!/usr/bin/env bash
$SHIM_MARK \`$name\` for a terminal session on this worker (written by
# $ROOT/worker/install.sh) — through its outbox, like the runs it launches.
if [ -z "\${AI_AGENT_OUTBOX_URL:-}" ]; then
export AI_AGENT_OUTBOX_URL="http://$BIND:$PORT"
AI_AGENT_OUTBOX_TOKEN="\$(cat "$STATE/outbox-token" 2>/dev/null)"
export AI_AGENT_OUTBOX_TOKEN
fi
exec "$ROOT/cli/$name" "\$@"
EOF
chmod 755 "$f"
done
}
remove_shims() {
local name
for name in "${SHIMS[@]}"; do
grep -qF "$SHIM_MARK" "${BIN_DIR:?}/${name:?}" 2>/dev/null && rm -f "${BIN_DIR:?}/${name:?}"
done
return 0
}
# ── one-shot commands ──────────────────────────────────────────────────────────
case "$CMD" in
sync|unsync|claude)
# A terminal session shared with the hub, or the launcher's choices
# (worker/claude_launcher.py).
[[ -x "$VENV/bin/python" ]] || die "not installed yet"
AI_AGENT_LAUNCHER_CMD="$CMD" WORKER_STATE_DIR="$STATE" \
exec "$VENV/bin/python" "$ROOT/worker/claude_launcher.py" "$@" ;;
uninstall)
svc_remove
uninstall_launcher
remove_shims
rm -f "$BIN_DIR/ai-agent-worker"
# The lab sync's links (sidecar/labsync.py) — only symlinks into its dir.
LABSYNC="${WORKER_LABSYNC_DIR:-$SHARE/lab-sync}"
for cfg in "${CLAUDE_CONFIG_DIR:-$HOME/.claude}" "$HOME"/.claude-*; do
for link in "$cfg"/skills/* "$cfg"/agents/*.md; do
[[ -L "$link" && "$(readlink "$link")" == "$LABSYNC"/* ]] && rm -f "$link"
done
done
rm -rf "$LABSYNC"
# Files attached in the hub's composer, copied here for runs (sidecar/uploads.py).
rm -rf "${WORKER_UPLOADS_DIR:-$SHARE/uploads}"
say "removed the worker service, the lab's synced skills and the copied attachments (state kept in $STATE — delete it to forget the pairing)"
exit 0 ;;
status)
svc_status
resolve_bind
if h="$(health)"; then echo "$h"; else echo "no /health on $BIND:$PORT"; fi
echo "commit: $(git -C "$ROOT" rev-parse --short HEAD 2>/dev/null || echo '?')$([[ $MANAGED == 1 ]] && echo ' (auto-updated by the hub)')"
[[ -f "$STATE/update.json" ]] && echo "last auto-update: $(cat "$STATE/update.json")"
exit 0 ;;
version)
git -C "$ROOT" rev-parse HEAD; exit 0 ;;
logs)
exec tail -n 50 -F "$LOGS/worker.log" "$LOGS/update.log" ;;
auto-update)
auto_update "${1:-}"; exit $? ;;
update)
# bash goes on executing the copy it opened: run the fetched installer, so
# a change to this script applies on this update rather than the next.
if [[ -z "${WORKER_PULLED:-}" ]]; then
if [[ "$MANAGED" == 1 ]]; then checkout_ref "$ROOT" "$REF"
else git -C "$ROOT" pull --ff-only; fi
WORKER_PULLED=1 exec bash "$ROOT/worker/install.sh" update "$@"
fi
;;
pair)
[[ -x "$VENV/bin/python" ]] || die "not installed yet — run without 'pair'"
[[ "$OWNER_LINK" == 1 ]] && die "this machine pairs through the hub — Settings → Profiles → Pair a worker → It dials out gives a new line to run"
[[ "$LINK" == 1 ]] && die "this computer pairs through its portal — Settings → My computers → Add gives a new line to run"
resolve_bind
CLAUDE_BIN="$(command -v claude || echo claude)"
pairing_string
exit 0 ;;
esac
# ── prerequisites ──────────────────────────────────────────────────────────────
CLAUDE_BIN="$(command -v claude || true)"
[[ -n "$CLAUDE_BIN" ]] || die "claude not found on PATH — install Claude Code first: curl -fsSL https://claude.ai/install.sh | bash"
[[ "$LINK" == 1 && "$CMD" == install && -n "$ENROLL" && -n "$HUB" ]] && check_enroll_code
if [[ "$OWNER_LINK" == 1 ]]; then
# The owner's own machine, off the tailnet: its own login, like a Mac in
# `own` mode (the hub's proxy is on the tailnet host — out of its reach).
"$CLAUDE_BIN" auth status 2>/dev/null | grep -q '"loggedIn": *true' \
|| echo "warning: \`claude auth status\` doesn't say logged in — runs will fail until you \`claude auth login\`" >&2
if [[ "$CMD" == install ]]; then
echo
echo "This machine will be one of your workers, dialling out to $HUB:"
echo " · nothing listens beyond 127.0.0.1 — it long-polls the hub over HTTPS;"
echo " · its runs use this machine's own Claude login (account ${ACCOUNT:-?})."
echo
fi
elif [[ "$LINK" == 1 ]]; then
ACCOUNT="${ACCOUNT:-personal}"; OPENCODE="${OPENCODE:-0}"
if [[ "$CMD" == install ]]; then
echo
echo "This computer will run the conversations you start from your portal ($HUB)."
echo " · Their Claude calls go through the hub, on its owner's account, within your limits."
echo " · The hub's owner can read those conversations; a run can read your files"
echo " (it only edits inside the folder below and /tmp)."
echo " · \`claude\` in a terminal asks which Claude to use: yours (its sessions stay"
echo " here unless you sync one) or the hub's (synced to the app, on its owner's plan)."
echo
fi
else
"$CLAUDE_BIN" auth status 2>/dev/null | grep -q '"loggedIn": *true' \
|| echo "warning: \`claude auth status\` doesn't say logged in — runs will fail until you /login" >&2
fi
pick_cwd
[[ -d "$CWD" ]] || die "default cwd $CWD doesn't exist (set WORKER_CWD)"
resolve_bind
[[ $OS == linux ]] && linux_preflight
# ── venv ───────────────────────────────────────────────────────────────────────
say "venv + deps ($VENV)"
mkdir -p "$SHARE" "$STATE" "$LOGS/runs"
chmod 700 "$STATE"
# `command -v uv` alone is not enough on a mise-managed Mac: mise installs a
# `uv` shim that errors out ("No version is set for shim") when no global
# version is pinned, so only take the uv path when it actually runs.
if command -v uv >/dev/null && uv --version >/dev/null 2>&1; then
[[ -x "$VENV/bin/python" ]] || uv venv --quiet "$VENV"
uv pip install --quiet --python "$VENV/bin/python" -r "$SIDECAR/requirements.txt"
else
[[ -x "$VENV/bin/python" ]] || python3 -m venv "$VENV" \
|| die "python3 -m venv failed — install uv, or your distro's python3-venv"
"$VENV/bin/pip" install --quiet -r "$SIDECAR/requirements.txt"
fi
pick_account
pick_opencode
pick_agy
pick_askform
# ── the notify skill ───────────────────────────────────────────────────────────
# A session here reaches Gabriel through this repo's `notify` CLI (cli/, put on
# every run's PATH by the sidecar; it queues into the worker's outbox and the
# hub collects it). Its SKILL.md is linked into the user-level skills dir so
# `claude` knows the command whatever repo the run starts in.
SKILLS_DIR="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/skills"
mkdir -p "$SKILLS_DIR"
ln -sfn "$ROOT/.claude/skills/notify" "$SKILLS_DIR/notify"
say "linked $SKILLS_DIR/notify → $ROOT/.claude/skills/notify"
# ── the ai-agent-worker command ────────────────────────────────────────────────
mkdir -p "$BIN_DIR"
cat > "$BIN_DIR/ai-agent-worker" <<EOF
#!/usr/bin/env bash
# ai-agent-worker — this machine's ai-agent worker: status, update, pair, logs,
# uninstall (written by $ROOT/worker/install.sh, which it runs).
exec bash "$ROOT/worker/install.sh" "\$@"
EOF
chmod 755 "$BIN_DIR/ai-agent-worker"
case ":$PATH:" in
*":$BIN_DIR:"*) ;;
*) echo "note: $BIN_DIR isn't on your PATH — add it to use \`ai-agent-worker\`" >&2 ;;
esac
if [[ "$LINK" == 1 && "$OWNER_LINK" == 0 ]]; then
remove_shims
else
write_shims
say "\`ai-agent\` and \`notify\` work in a terminal here too, through the outbox (${SHIMS[*]} in $BIN_DIR)"
fi
if [[ "$LINK" == 1 && "$OWNER_LINK" == 0 ]]; then
install_launcher
say "\`claude\` in a new terminal asks which Claude to use (\`ai-agent-worker claude off\` stops it)"
fi
# ── the service ────────────────────────────────────────────────────────────────
# PATH is the one this installer runs with (your login shell's), so a session
# finds the same tools (mise shims, gcloud, op, gh…) a terminal does. An
# auto-update runs with the service's own PATH, so drop the repeats.
RUN_PATH="$(dirname "$CLAUDE_BIN"):$PATH"
[[ -n "$OPENCODE_BIN" ]] && RUN_PATH="$(dirname "$OPENCODE_BIN"):$RUN_PATH"
[[ -n "$AGY_BIN" ]] && RUN_PATH="$(dirname "$AGY_BIN"):$RUN_PATH"
# ask-form's dir (~/.local/bin) goes last: a devbox's systemd PATH lacks it.
[[ -n "$ASKFORM_BIN" ]] && RUN_PATH="$RUN_PATH:$(dirname "$ASKFORM_BIN")"
RUN_PATH="$(awk -v RS=: -v ORS=: '$0 != "" && !seen[$0]++' <<<"$RUN_PATH")"
RUN_PATH="${RUN_PATH%:}"; RUN_PATH="${RUN_PATH%$'\n'}"; RUN_PATH="${RUN_PATH%:}"
say "writing the $OS service (bind $BIND:$PORT, cwd $CWD, account $ACCOUNT$([[ $MANAGED == 1 ]] && echo ', auto-update on'))"
OS="$OS" LABEL="$LABEL" PY="$VENV/bin/python" SIDECAR="$SIDECAR" BIND="$BIND" PORT="$PORT" \
CWD="$CWD" ACCOUNT="$ACCOUNT" CLAUDE_BIN="$CLAUDE_BIN" STATE="$STATE" LOGS="$LOGS" \
OPENCODE_BIN="$OPENCODE_BIN" OPENCODE_ACCOUNTS="${OPENCODE_BIN:+$OPENCODE_ACCOUNT=default}" \
WORKER_OPENCODE="${OPENCODE:-0}" \
AGY_BIN="$AGY_BIN" AGY_ACCOUNTS="${AGY_BIN:+$AGY_ACCOUNT=default}" WORKER_AGY="${AGY:-0}" \
WORKER_ASKFORM="${ASKFORM:-1}" \
UPDATER="$([[ $MANAGED == 1 ]] && echo "$ROOT/worker/install.sh")" \
RUN_PATH="$RUN_PATH" PLIST="${PLIST:-}" UNIT_FILE="${UNIT_FILE:-}" ENV_FILE="${ENV_FILE:-}" \
"$VENV/bin/python" "$ROOT/worker/make_service.py"
[[ $OS == macos ]] && plutil -lint "$PLIST" >/dev/null
OLD_PID="$(listener_pid)"
svc_start
say "waiting for http://$BIND:$PORT/health"
for _ in $(seq 1 30); do health >/dev/null && break; sleep 1; done
health >/dev/null || die "worker didn't come up — see $LOGS/worker.log"
# An update only counts once the *new* code answers. /health's `commit` is
# the checkout's HEAD, which a process that never restarted reports too — so
# the process serving the port must have changed. One that outlived the
# restart (started by hand, or a launchd job that didn't let go) is stopped:
# the new job is waiting on the port, and the runs it launched are detached
# daemons that survive it.
if [[ -n "$OLD_PID" ]]; then
for _ in $(seq 1 10); do [[ "$(listener_pid)" != "$OLD_PID" ]] && break; sleep 1; done
if [[ "$(listener_pid)" == "$OLD_PID" ]] \
&& ps -o command= -p "$OLD_PID" 2>/dev/null | grep -q sidecar; then
say "the old worker process ($OLD_PID) still serves :$PORT — stopping it"
kill "$OLD_PID" 2>/dev/null || true
for _ in $(seq 1 30); do
NEW_PID="$(listener_pid)"; [[ -n "$NEW_PID" && "$NEW_PID" != "$OLD_PID" ]] && health >/dev/null && break
sleep 1
done
fi
[[ "$(listener_pid)" != "$OLD_PID" ]] \
|| die "the old worker process ($OLD_PID) is still the one answering — the restart didn't take; see $LOGS/worker.log"
fi
if [[ -n "${WORKER_EXPECT_COMMIT:-}" ]]; then
for _ in $(seq 1 30); do
[[ "$(health_field commit)" == "$WORKER_EXPECT_COMMIT"* ]] && break
sleep 1
done
[[ "$(health_field commit)" == "$WORKER_EXPECT_COMMIT"* ]] \
|| die "the worker answers but on commit '$(health_field commit)', not $WORKER_EXPECT_COMMIT"
fi
echo " $(health)"
if [[ "$CMD" == update ]] && py "$SIDECAR/pairing.py" status | grep -q '"paired": true'; then
say "updated to $(git -C "$ROOT" rev-parse --short HEAD); still paired"
exit 0
fi
if [[ "$LINK" == 1 ]]; then
if [[ -n "$ENROLL" ]]; then
[[ -n "$HUB" ]] || die "WORKER_ENROLL needs WORKER_HUB"
say "connecting to $HUB"
rc=0; WORKER_STATE_DIR="$STATE" py "$SIDECAR/link.py" enroll "$HUB" "$ENROLL" >/dev/null || rc=$?
[[ $rc == 3 ]] && code_refused
[[ $rc == 0 ]] || exit "$rc"
for _ in $(seq 1 60); do
py "$SIDECAR/pairing.py" status | grep -q '"paired": true' && break
sleep 1
done
if py "$SIDECAR/pairing.py" status | grep -q '"paired": true'; then
if [[ "$OWNER_LINK" == 1 ]]; then
say "connected — this machine is now one of the hub's workers (Settings → Profiles)"
else
say "connected — this computer is now in your portal (Settings → My computers)"
fi
else
echo "warning: enrolled, but the hub hasn't paired yet — check \`ai-agent-worker logs\`" >&2
fi
else
say "linked to $(WORKER_STATE_DIR="$STATE" py "$SIDECAR/link.py" status)"
fi
exit 0
fi
pairing_string