Files
gabrielvidalandClaude Opus 5.5 a4f9d69549 refactor(workers): the harness CLIs' Setup rows come from harness plugins (workerSetup)
- typed_manifest: harness.workerSetup {tool, order, guestAllowed, update,
  enablesHarness, installerEnv, recipe}; in the capability fingerprint.
- worker/tools.sh keeps gh, ask-form and the helpers; the claude / pi recipes
  are the plugins' (sourced from WORKER_TOOL_RECIPES), opencode / agy go
  through WORKER_INSTALLER_TOOLS.
- sidecar tools_check / tools_install read the rows off the loaded harness
  drivers (setup_check hook); backend workers/tools.py off the registry.
- A guest's computer: gh + guestAllowed harness tools (claude) — pi's plugin
  never reaches it, so pi left its checklist.

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

255 lines
11 KiB
Bash
Executable File

#!/usr/bin/env bash
# tools.sh — install or update a worker's tools for the hub: the worker page's
# Setup checklist → Install / Update / Install all missing
# (sidecar/tools_install.py starts it detached, its own session, so the
# service restart a harness install causes doesn't take it down).
#
# tools.sh install|update <tool>...
#
# User space only, never sudo: ~/.local/bin (and ~/.local/share/ai-agent-worker),
# or brew on a Mac that has it. Downloads are checksum-checked.
#
# Core's own tools:
#
# gh the GitHub CLI's release build into ~/.local/bin (brew on a Mac);
# `update` only moves a gh this script (or brew) installed
# ask-form what the installer sets up: `install.sh update` with
# WORKER_ASKFORM=1
#
# A harness's CLI (claude, pi, opencode, agy) is its harness plugin's — its
# `harness.workerSetup` (sidecar/tools_install.py hands them over):
#
# WORKER_TOOL_RECIPES lines "<tool>\t<recipe.sh>": a bash recipe in the
# plugin's sidecar dir, sourced here (these helpers and
# $ACTION, $BIN_DIR… in scope), then its `tool_main`
# (harness-claude: claude.ai/install.sh; harness-pi:
# the pi CLI on a Node of its own)
# WORKER_INSTALLER_TOOLS lines "<tool>\t<WORKER_ENV>": one `install.sh update`
# with each WORKER_<X>=1 installs the binary, declares
# the harness in the service and restarts the worker
# (runs survive) — opencode, agy. They run last,
# together with ask-form: one restart.
#
# Each tool's progress is $STATE/tools/<tool>.json ({tool, action, state:
# queued|running|done|failed, startedAt, finishedAt, error, pid}) and its
# output $STATE/tools/<tool>.log — what /health's `toolJobs` reads back,
# across that restart. One batch at a time ($STATE/tools/lock).
#
# Plain bash 3.2 (macOS's /bin/bash): no associative arrays, no ${x,,}.
set -uo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SHARE="${WORKER_SHARE_DIR:-$HOME/.local/share/ai-agent-worker}"
STATE="${WORKER_STATE_DIR:-$HOME/.config/ai-agent-worker}"
BIN_DIR="${WORKER_TOOLS_BIN:-$HOME/.local/bin}"
DIR="$STATE/tools"
PY="$SHARE/venv/bin/python"; [[ -x "$PY" ]] || PY="$(command -v python3 || true)"
OS="$(uname -s)"; ARCH="$(uname -m)"
# tool → recipe / installer env, from the sidecar (and ask-form's own).
RECIPES="${WORKER_TOOL_RECIPES:-}"
INSTALLERS="$(printf 'ask-form\tWORKER_ASKFORM\n%s' "${WORKER_INSTALLER_TOOLS:-}")"
lookup() { # lookup <table> <tool>: its value, or nothing
printf '%s\n' "$1" | awk -F'\t' -v t="$2" '$1 == t { print $2; exit }'
}
# What this script installs is found by the checks that follow it — last, so a
# tool the machine already had keeps its place.
case ":$PATH:" in *":$BIN_DIR:"*) ;; *) PATH="$PATH:$BIN_DIR" ;; esac
export PATH
ACTION="${1:-}"; [[ $# -gt 0 ]] && shift
case "$ACTION" in install|update) ;; *)
echo "usage: tools.sh install|update <tool>... (gh ask-form, and the harness plugins' tools)" >&2; exit 2 ;;
esac
[[ $# -gt 0 ]] || { echo "error: no tool named" >&2; exit 2; }
for t in "$@"; do
[[ "$t" == gh || -n "$(lookup "$INSTALLERS" "$t")" ]] && continue
r="$(lookup "$RECIPES" "$t")"
[[ -n "$r" && -f "$r" ]] || { echo "error: unknown tool: $t" >&2; exit 2; }
done
[[ -n "$PY" ]] || { echo "error: no python3 to write the progress with" >&2; exit 1; }
mkdir -p "$DIR"
# ── progress files ────────────────────────────────────────────────────────────
state() { # state <tool> <queued|running|done|failed> [error]
T_TOOL="$1" T_STATE="$2" T_ERROR="${3:-}" T_ACTION="$ACTION" T_PID="$$" \
"$PY" - "$DIR/$1.json" "$DIR/$1.log" <<'PY'
import json, os, re, sys, time
e = os.environ
path, log = sys.argv[1], sys.argv[2]
now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
try:
prev = json.load(open(path))
except (OSError, ValueError):
prev = {}
st = e["T_STATE"]
err = e.get("T_ERROR") or None
if st == "failed" and not err:
# The tool's own last word: its last `error:` line, else its last line.
try:
lines = [re.sub(r"\x1b\[[0-9;?]*[A-Za-z]", "", l).strip()
for l in open(log, errors="replace").read().splitlines()]
except OSError:
lines = []
lines = [l for l in lines if l]
errs = [l for l in lines if l.lower().startswith("error")]
err = (errs or lines or ["failed"])[-1]
out = {"tool": e["T_TOOL"], "action": e["T_ACTION"], "state": st,
"startedAt": now if st in ("queued", "running") else prev.get("startedAt"),
"finishedAt": now if st in ("done", "failed") else None,
"error": (err or "")[:300] or None, "pid": int(e["T_PID"])}
if st == "running" and prev.get("state") == "queued":
out["queuedAt"] = prev.get("startedAt")
tmp = path + ".tmp"
with open(tmp, "w") as f:
json.dump(out, f)
os.replace(tmp, path)
PY
}
LOCK="$DIR/lock"
if ! mkdir "$LOCK" 2>/dev/null; then
pid="$(cat "$LOCK/pid" 2>/dev/null || true)"
if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then
echo "error: tools are already being installed (pid $pid)" >&2; exit 75
fi
rm -rf "$LOCK"; mkdir "$LOCK"
fi
echo $$ > "$LOCK/pid"
UPDATE_LOCK=""
cleanup() {
rm -rf "$LOCK"
[[ -n "$UPDATE_LOCK" ]] && rm -rf "$UPDATE_LOCK"
return 0
}
trap cleanup EXIT
# ── helpers ───────────────────────────────────────────────────────────────────
say() { echo "==> $*"; }
fetch() { curl -fsSL --retry 2 --connect-timeout 20 --max-time 600 -o "$2" "$1"; }
sha256() {
if command -v sha256sum >/dev/null; then sha256sum "$1"; else shasum -a 256 "$1"; fi | awk '{print $1}'
}
verify() { # verify <file> <checksums file> <name in it>
local want got
want="$(awk -v f="$3" '{n=$2; sub(/^\*/, "", n)} n==f {print $1; exit}' "$2")"
got="$(sha256 "$1")"
[[ -n "$want" ]] || { echo "error: $3 isn't in the release's checksums" >&2; return 1; }
[[ "$want" == "$got" ]] || { echo "error: checksum mismatch for $3" >&2; return 1; }
}
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" ]]
}
latest_tag() { # latest_tag <owner/repo>: its latest release's tag, off the redirect (no API quota)
local u
u="$(curl -fsSLI -o /dev/null -w '%{url_effective}' "https://github.com/$1/releases/latest")" || return 1
[[ "$u" == */tag/* ]] || { echo "error: no release found for $1" >&2; return 1; }
echo "${u##*/}"
}
arch_of() { # arch_of <x86_64 spelling> <arm64 spelling>
case "$ARCH" in
x86_64|amd64) echo "$1" ;;
arm64|aarch64) echo "$2" ;;
*) echo "error: no build for $ARCH" >&2; return 1 ;;
esac
}
mine() { # mine <tool>: the copy on PATH is the one in $BIN_DIR
[[ "$(command -v "$1" 2>/dev/null)" == "$BIN_DIR/$1" ]]
}
# ── gh ────────────────────────────────────────────────────────────────────────
do_gh() {
local cur tag v os ext arch name tmp
cur="$(command -v gh 2>/dev/null || true)"
if [[ "$OS" == Darwin ]] && command -v brew >/dev/null && ! mine gh; then
if [[ -z "$cur" ]]; then say "brew install gh"; brew install --quiet gh </dev/null; return; fi
if brew list --formula gh >/dev/null 2>&1; then say "brew upgrade gh"; brew upgrade --quiet gh </dev/null || true; return; fi
fi
if [[ -n "$cur" ]] && ! mine gh; then
if [[ "$ACTION" == update ]]; then
echo "error: $cur wasn't installed by the worker — update it with the package manager that did" >&2
return 1
fi
say "gh is already at $cur"; return 0
fi
tag="$(latest_tag cli/cli)" || return 1
v="${tag#v}"
case "$OS" in Linux) os=linux ext=tar.gz ;; Darwin) os=macOS ext=zip ;; esac
arch="$(arch_of amd64 arm64)" || return 1
if [[ "$ACTION" == update && -n "$cur" ]] && "$cur" --version 2>/dev/null | head -1 | grep -qF " $v "; then
say "gh is already $v"; return 0
fi
name="gh_${v}_${os}_${arch}"
tmp="$(mktemp -d)"
say "downloading gh $v ($name.$ext)"
if fetch "https://github.com/cli/cli/releases/download/$tag/$name.$ext" "$tmp/$name.$ext" \
&& fetch "https://github.com/cli/cli/releases/download/$tag/gh_${v}_checksums.txt" "$tmp/sums" \
&& verify "$tmp/$name.$ext" "$tmp/sums" "$name.$ext"; then
if [[ "$ext" == zip ]]; then unzip -q "$tmp/$name.$ext" -d "$tmp"; else tar -xzf "$tmp/$name.$ext" -C "$tmp"; fi \
&& mkdir -p "$BIN_DIR" \
&& install -m 755 "$tmp/$name/bin/gh" "$BIN_DIR/gh.new" \
&& mv -f "$BIN_DIR/gh.new" "$BIN_DIR/gh" \
|| { rm -rf "$tmp"; echo "error: couldn't unpack $name.$ext into $BIN_DIR" >&2; return 1; }
rm -rf "$tmp"
say "gh $v → $BIN_DIR/gh"
else
rm -rf "$tmp"; return 1
fi
}
# ── the harnesses: one `install.sh update` ────────────────────────────────────
run_installer() { # run_installer <tool>...
local t envs="WORKER_PULLED=1"
# The auto-update rewrites the same service: never both at once.
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
UPDATE_LOCK=""
echo "error: the worker is updating itself — try again in a minute" >&2; return 1
fi
rm -rf "$UPDATE_LOCK"; mkdir "$UPDATE_LOCK"
fi
echo $$ > "$UPDATE_LOCK/pid"
for t in "$@"; do
envs="$envs $(lookup "$INSTALLERS" "$t")=1"
done
say "ai-agent-worker update with $envs (installs, declares, restarts the worker)"
# shellcheck disable=SC2086
env $envs bash "$ROOT/worker/install.sh" update </dev/null
local rc=$?
rm -rf "$UPDATE_LOCK"; UPDATE_LOCK=""
return $rc
}
# ── the batch ─────────────────────────────────────────────────────────────────
PLAIN=""; HARNESS=""
for t in "$@"; do
if [[ -n "$(lookup "$INSTALLERS" "$t")" ]]; then HARNESS="$HARNESS $t"; else PLAIN="$PLAIN $t"; fi
state "$t" queued
done
rc=0
for t in $PLAIN; do
: > "$DIR/$t.log"
state "$t" running
# A subshell, so a recipe's cd / variables stay its own. No `set -e`: an
# `if` condition ignores it — every recipe returns its own failures.
if [[ "$t" == gh ]]; then
( do_gh ) >>"$DIR/$t.log" 2>&1; ok=$?
else
# shellcheck disable=SC1090
( source "$(lookup "$RECIPES" "$t")" && tool_main ) >>"$DIR/$t.log" 2>&1; ok=$?
fi
if [[ "$ok" == 0 ]]; then state "$t" done
else state "$t" failed; rc=1; fi
done
if [[ -n "$HARNESS" ]]; then
first="${HARNESS# }"; first="${first%% *}"
for t in $HARNESS; do : > "$DIR/$t.log"; state "$t" running; done
if run_installer $HARNESS >>"$DIR/$first.log" 2>&1; then ok=1; else ok=0; rc=1; fi
for t in $HARNESS; do
[[ "$t" != "$first" ]] && cp "$DIR/$first.log" "$DIR/$t.log"
if [[ "$ok" == 1 ]]; then state "$t" done; else state "$t" failed; fi
done
fi
exit $rc