Files
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

424 lines
19 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Remote workers: pair, list, patch, probe, unpair."""
import re
import time
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
import accounts as accounts_mod
import schemas
import workers as workers_mod
from claudeproxy import opencode as oc_proxy, service as proxy
from profiles import runners as runners_mod
from workers import cli as worker_cli, guests, updates as updates_mod
from core.config import HUB_NAME
from core.http import _r
from core.state import AppState, State
from runs.sidecar_client import _sidecar_get
router = APIRouter()
# ── remote workers (workers.py): pair, list, probe, unpair ────────────────────
class PairWorkerBody(BaseModel):
pairing: str # host:port/code[/login] from the installer
account: str | None = None # override the login → account match
# How it runs Claude Code: "proxy" (the hub's logins — default) or "own"
# (its machine's login, which must match one of the hub's accounts), and
# the accounts a proxied one may bill (unset ⇒ its own login's account,
# else the default).
claudeMode: str = "proxy"
claudeAccounts: list[str] | None = None
name: str | None = None
# The profile it joins (Settings → Profiles); unset ⇒ the one that had it
# before an unpair, else the default profile.
profile: str | None = None
# Make it that profile's default runner (its new prompts go here).
default: bool = False
# Legacy (before profiles held runners): the same as ``default``.
autoRoute: bool = False
class EnrollWorkerBody(BaseModel):
"""*Pair a worker* → *It dials out*: the installer's answers, and what the
worker becomes once its pairing comes through the link."""
cwd: str | None = None
opencode: bool = False
# The hub's account its own Claude login is (it runs on that login).
account: str
name: str | None = None
profile: str | None = None
default: bool = False
class WorkerPatchBody(BaseModel):
name: str | None = None
account: str | None = None
# "proxy" | "own" and the hub's Claude accounts a proxied worker may
# bill — the whole list (Settings → Profiles → the worker).
claudeMode: str | None = None
claudeAccounts: list[str] | None = None
# The Homelab's opencode (ChatGPT) accounts it bills through the opencode
# proxy — the whole list; only accounts the Homelab holds a login for.
opencodeProxyAccounts: list[str] | None = None
autoRoute: bool | None = None
# Follow the hub's version on its own (workers/updates.py). Default on.
autoUpdate: bool | None = None
# What its sessions' `ai-agent` CLI may do (workers/cli.py):
# "off" | "read" | "run".
cli: str | None = None
def _account_for_login(login: str) -> str | None:
"""Which of the hub's accounts is signed in as ``login`` (an email, or an
org name), per the host sidecar's ``claude auth status`` of each."""
want = (login or "").strip().lower()
if not want:
return None
live = _sidecar_get("/accounts", timeout=10) or {}
for a in live.get("accounts") or []:
for k in ("email", "orgName"):
if (a.get(k) or "").strip().lower() == want:
return accounts_mod.valid(a.get("id"))
return None
def _workers_payload(deps: AppState) -> dict:
return {"workers": [deps.worker_store.public(w) for w in deps.worker_store.list()]}
def _worker_or_404(deps: AppState, worker_id: str) -> dict:
w = deps.worker_store.get(worker_id)
if not w:
raise HTTPException(404, {"message": f"unknown worker: {worker_id!r}",
"kind": "worker_unknown"})
return w
@router.get("/api/workers", responses=_r(schemas.WorkersResponse))
def list_workers(deps: State):
"""Paired remote runners with their live status (online / offline /
unauthorized), last seen, running-run count and mirror progress."""
return _workers_payload(deps, )
@router.post("/api/workers", responses=_r(schemas.Worker))
def pair_worker(deps: State, body: PairWorkerBody):
"""Pair with a worker from the string its installer printed. It bills
``claudeAccounts`` through the hub's Claude proxy — unset, the account its
own Claude login matches (if the string names one), else the default.
Re-pairing a known machine replaces its record."""
w = workers_mod.pair(deps.worker_store, body.pairing, account=body.account,
name=body.name, hub_name=HUB_NAME,
resolve_login=_account_for_login,
valid_account=accounts_mod.valid,
auto_route=body.autoRoute,
claude_accounts=body.claudeAccounts,
claude_mode=body.claudeMode)
if body.profile and not deps.profile_store.get(body.profile):
body.profile = None
deps.profile_store.assign_worker(w, body.profile)
if body.default or body.autoRoute:
deps.profile_store.patch_runner(w["id"], {"default": True})
_push_proxy(deps, w)
deps.hub.publish({"type": "workers"})
deps.hub.publish({"type": "profiles"})
return deps.worker_store.public(w)
def _shq(v: str) -> str:
"""One shell word, single-quoted (a leading ``~`` stays for the installer
to expand on the machine)."""
return "'" + v.replace("'", "'\\''") + "'"
def enroll_command(code: str, *, account: str, cwd: str | None, opencode: bool) -> str:
"""The one line that installs a dial-out worker and enrolls it."""
from users.computers import INSTALL_URL
from users.deliver import GUEST_PUBLIC_URL
env = [f"WORKER_HUB={GUEST_PUBLIC_URL}", f"WORKER_ENROLL={code}",
f"WORKER_ACCOUNT={account}"]
if (cwd or "").strip():
env.append(f"WORKER_CWD={_shq(cwd.strip())}")
env.append(f"WORKER_OPENCODE={1 if opencode else 0}")
return f"curl -fsSL {INSTALL_URL} | {' '.join(env)} bash"
@router.post("/api/workers/enroll", responses=_r(schemas.ComputerEnroll))
def enroll_worker(deps: State, body: EnrollWorkerBody):
"""A one-time code (an hour) and the line that installs a worker which
**dials out** to the hub instead of listening on the tailnet — a machine
the hub can't reach (a company devbox on another tailnet, a cloud VM).
It runs on its own Claude login (``account``) and joins ``profile`` once
its pairing comes through the link (workers/link.py)."""
from workers import link
acct = accounts_mod.valid_for(body.account, "claude")
if not acct:
raise HTTPException(400, {"message": f"no Claude account {body.account!r} on this hub",
"kind": "account"})
profile = body.profile if body.profile and deps.profile_store.get(body.profile) else None
out = link.ENROLL.mint(link.OWNER, {
"account": acct, "name": (body.name or "").strip()[:60] or None,
"profile": profile, "default": bool(body.default)})
return {**out, "command": enroll_command(out["code"], account=acct, cwd=body.cwd,
opencode=body.opencode)}
@router.patch("/api/workers/{worker_id}", responses=_r(schemas.Worker))
def patch_worker(deps: State, worker_id: str, body: WorkerPatchBody):
w0 = _worker_or_404(deps, worker_id)
if guests.is_guest(w0) and (body.model_dump(exclude_none=True).keys()
- {"name", "autoUpdate"}):
# What a guest's computer bills and runs is the guest policy's
# (users/computers.py), not a per-machine setting.
raise HTTPException(400, {"message": "a guest's computer only takes a name here",
"kind": "worker_guest"})
if w0.get("link") and (body.claudeMode == proxy.PROXY or body.claudeAccounts
or body.opencodeProxyAccounts):
# The proxy lives on the tailnet host, and the public one takes no
# owner token (claudeproxy/routes.py): a machine that dials out
# couldn't reach it.
raise HTTPException(400, {"message": "a worker that dials out runs on its own "
"login — the hub's proxy is on the tailnet",
"kind": "worker_link"})
changes: dict = {}
if body.name is not None and body.name.strip():
changes["name"] = body.name.strip()[:60]
if body.account is not None:
a = accounts_mod.valid(body.account)
if not a:
raise HTTPException(400, {"message": f"unknown account: "
f"{body.account!r}",
"kind": "account"})
changes["account"] = a
if body.claudeMode is not None:
if body.claudeMode not in (proxy.OWN, proxy.PROXY):
raise HTTPException(400, f"claudeMode is {proxy.PROXY!r} or {proxy.OWN!r}")
if body.claudeMode == proxy.OWN and not accounts_mod.valid_for(
changes.get("account") or w0.get("account"), "claude"):
raise HTTPException(400, {"message": "this worker has no Claude login of its "
"own the hub knows — sign it in on the "
"machine and re-pair it",
"kind": "account"})
changes["claudeMode"] = body.claudeMode
if body.claudeAccounts is not None:
changes["claudeAccounts"] = proxy.clean_accounts(body.claudeAccounts)
if body.opencodeProxyAccounts is not None:
lab = set(runners_mod.lab_logins(deps).get("opencode") or [])
bad = [a for a in body.opencodeProxyAccounts if a not in lab or not oc_proxy.proxyable(a)]
if bad:
raise HTTPException(400, {"message": f"the Homelab holds no ChatGPT login for "
f"{', '.join(bad)}",
"kind": "account"})
changes["opencodeProxyAccounts"] = oc_proxy.clean_accounts(body.opencodeProxyAccounts)
if body.autoRoute is not None:
changes["autoRoute"] = bool(body.autoRoute)
if body.autoUpdate is not None:
changes["autoUpdate"] = bool(body.autoUpdate)
if body.cli is not None:
if body.cli not in worker_cli.MODES:
raise HTTPException(400, f"cli is one of {', '.join(worker_cli.MODES)}")
changes["cli"] = body.cli
w = deps.worker_store.patch(worker_id, changes)
logins = {"account", "claudeMode", "claudeAccounts", "opencodeProxyAccounts"} & changes.keys()
if logins: # its ★ follows the logins it holds now
deps.profile_store.assign_worker(w)
deps.hub.publish({"type": "profiles"})
_push_proxy(deps, w)
deps.hub.publish({"type": "workers"})
return deps.worker_store.public(w)
def _push_proxy(deps: AppState, w: dict) -> None:
"""Send the worker its proxy configs (Claude's, opencode's) now rather
than at the next probe, where they changed — best-effort: the probe
retries."""
store = deps.worker_store
if not store.online(w["id"]):
return
w = store.get(w["id"]) or w
st = store.status(w["id"])
todo = [(proxy.push, proxy.status(store, w, st)), (oc_proxy.push, oc_proxy.status(w, st))]
for push, state in todo:
if state in (proxy.CURRENT, proxy.OFF):
continue
try:
push(store, w)
except HTTPException:
pass
_worker_skills_cache: dict[str, tuple[float, list[dict]]] = {}
_WORKER_SKILLS_TTL_S = 60.0
@router.get("/api/workers/{worker_id}/skills")
def worker_skills(deps: State, worker_id: str, fresh: bool = False):
"""The skills a run on that worker can use — its sidecar's ``/skills``
(user-level + default-cwd skills on *that* machine), cached a minute. The
composer lists these instead of the lab catalog when "Runs on" resolves
to the worker. An offline or pre-``/skills`` worker answers an empty list
rather than an error: the chips simply don't show."""
w = deps.worker_store.get(worker_id)
if not w:
raise HTTPException(404, "unknown worker")
hit = _worker_skills_cache.get(worker_id)
if hit and not fresh and time.monotonic() - hit[0] < _WORKER_SKILLS_TTL_S:
return {"skills": hit[1], "count": len(hit[1]), "worker": worker_id}
skills: list[dict] = []
if deps.worker_store.online(worker_id):
try:
out = workers_mod.sidecar_request(
w["url"], w["token"], "/skills", method="GET", timeout=6,
label=f"worker {w.get('name') or worker_id}")
skills = [s for s in (out.get("skills") or []) if isinstance(s, dict)]
except HTTPException:
skills = []
_worker_skills_cache[worker_id] = (time.monotonic(), skills)
return {"skills": skills, "count": len(skills), "worker": worker_id}
@router.post("/api/workers/{worker_id}/probe", responses=_r(schemas.Worker))
def probe_worker(deps: State, worker_id: str):
"""Health-check one worker now instead of waiting for the next poll."""
_worker_or_404(deps, worker_id)
deps.worker_monitor.check(worker_id)
return deps.worker_store.public(deps.worker_store.get(worker_id))
@router.post("/api/workers/{worker_id}/update", responses=_r(schemas.Worker))
def update_worker(deps: State, worker_id: str):
"""*Update now*: move the worker to the hub's own commit, whatever its
auto-update setting or retry delay. It reports back through its /health
(the next probes): updating, then current — or failed / rolled back."""
w = _worker_or_404(deps, worker_id)
hub = updates_mod.hub_commit()
if not hub:
raise HTTPException(409, {"message": "this hub doesn't know its own "
"commit (no deploy wrote "
f"{updates_mod.DEPLOYED_COMMIT_FILE})",
"kind": "no_hub_commit"})
if not deps.worker_store.online(worker_id):
raise HTTPException(409, {"message": f"{w.get('name')} is offline",
"kind": "worker_offline", "worker": worker_id})
updates_mod.trigger(deps.worker_store, w, hub)
deps.hub.publish({"type": "workers"})
return deps.worker_store.public(deps.worker_store.get(worker_id))
@router.delete("/api/workers/{worker_id}")
def unpair_worker(deps: State, worker_id: str):
"""Forget a worker (and tell it to drop the bearer, if it's reachable).
Its mirrored conversations stay in the archive, read-only. On a guest's
computer this is *Revoke*: its tokens stop working at once."""
w = _worker_or_404(deps, worker_id)
if guests.is_guest(w):
from users import computers
computers.remove(deps, worker_id, None)
return {"ok": True}
workers_mod.unpair(deps.worker_store, worker_id)
deps.profile_store.forget_worker(worker_id)
deps.hub.publish({"type": "workers"})
deps.hub.publish({"type": "profiles"})
return {"ok": True}
# ── lab sync (workers/labsync.py): the lab's portable skills and agents ───────
class LabSyncBody(BaseModel):
# ``{"skill:<name>" | "agent:<name>": bool}`` — ticks/unticks against the
# frontmatter's ``portable`` flag; a value matching the flag is dropped.
overrides: dict[str, bool]
@router.get("/api/workers/{worker_id}/labsync", responses=_r(schemas.WorkerLabSync))
def get_worker_labsync(deps: State, worker_id: str):
"""The worker's *Lab skills & agents* checklist and where its copy stands."""
from workers import labsync
return labsync.view(deps.worker_store, _worker_or_404(deps, worker_id))
@router.put("/api/workers/{worker_id}/labsync", responses=_r(schemas.WorkerLabSync))
def put_worker_labsync(deps: State, worker_id: str, body: LabSyncBody):
"""Save the overrides, then push the new bundle at once when it's online."""
from workers import labsync
w = _worker_or_404(deps, worker_id)
ov = labsync.clean_overrides(body.overrides, labsync.all_items(), w.get("account"))
w = deps.worker_store.patch(worker_id, {"labSyncOverrides": ov or None})
if deps.worker_store.online(worker_id):
try:
labsync.push(deps.worker_store, w)
except HTTPException:
pass # kept as labSyncError; the probe retries
deps.hub.publish({"type": "workers"})
return labsync.view(deps.worker_store, deps.worker_store.get(worker_id))
@router.post("/api/workers/{worker_id}/labsync/push", responses=_r(schemas.WorkerLabSync))
def push_worker_labsync(deps: State, worker_id: str):
"""*Sync now*: send the bundle whatever the probe's retry delay."""
from workers import labsync
w = _worker_or_404(deps, worker_id)
if not deps.worker_store.online(worker_id):
raise HTTPException(409, {"message": f"{w.get('name')} is offline",
"kind": "worker_offline", "worker": worker_id})
labsync.push(deps.worker_store, w)
deps.hub.publish({"type": "workers"})
return labsync.view(deps.worker_store, deps.worker_store.get(worker_id))
# ── repo plugins (workers/repoplugins.py): a repo's own Claude Code plugins ───
class RepoPluginPicksBody(BaseModel):
# ``["<plugin>@<marketplace>", …]`` every worker of the account gets on.
plugins: list[str]
class RepoPluginOverridesBody(BaseModel):
# ``{"<plugin>@<marketplace>": bool}`` — this worker's ticks / unticks.
overrides: dict[str, bool]
def _push_plugins(deps: AppState, ws: list[dict]) -> None:
from workers import repoplugins
for w in ws:
try:
repoplugins.maybe_push(deps.worker_store, w, force=True)
except Exception:
pass # kept as repoPluginsError; the probe retries
@router.get("/api/repo-plugins", responses=_r(schemas.RepoPluginsView))
def get_repo_plugins(deps: State):
"""Settings → Skills & agents: every plugin the
workers' repos offer × every worker, and the account picks."""
from workers import repoplugins
return repoplugins.view(deps.worker_store)
@router.put("/api/repo-plugins/accounts/{account}", responses=_r(schemas.RepoPluginsView))
def put_repo_plugin_picks(deps: State, account: str, body: RepoPluginPicksBody):
"""An account's picks; its online workers get them at once."""
from workers import repoplugins
s = deps.worker_store.repo_plugins
if s is None:
raise HTTPException(503, "repo plugins aren't set up")
s.set_account(account, body.plugins)
_push_plugins(deps, [w for w in deps.worker_store.list() if w.get("account") == account])
deps.hub.publish({"type": "workers"})
return repoplugins.view(deps.worker_store)
@router.put("/api/workers/{worker_id}/repo-plugins", responses=_r(schemas.RepoPluginsView))
def put_worker_repo_plugins(deps: State, worker_id: str, body: RepoPluginOverridesBody):
"""Save the worker's overrides, then apply them at once when it's online."""
from workers import repoplugins
w = _worker_or_404(deps, worker_id)
if not repoplugins.eligible(w):
raise HTTPException(409, "a guest's computer gets no repo plugins")
ov = repoplugins.clean_overrides(body.overrides, w.get("account"),
repoplugins._picks(deps.worker_store))
w = deps.worker_store.patch(worker_id, {"repoPluginOverrides": ov or None})
_push_plugins(deps, [w])
deps.hub.publish({"type": "workers"})
return repoplugins.view(deps.worker_store)