Files
ai-agent/backend/workers/outbox_mirror.py
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

212 lines
9.7 KiB
Python

"""
The outbox mirror — the hub's side of a worker's outbox (sidecar/outbox.py).
A session on a remote worker can't reach the hub (the worker holds no hub URL
or credential — the hub always calls in). So its ``notify`` CLI queues the
push / ask in the worker's own sidecar (and its ``ask-form serve`` its form
events, its ``ai-agent past`` its lookups), and this thread — one more poller
next to ``FeedMirror`` — collects them:
every tick, per online worker:
GET /outbox → queued items + open ones + cancels
queued → create it here (the same functions /api/notify and /api/ask
run), then POST /outbox/{id}/ack {hub: result}
meta → the session's own resources / title (`conv add`), applied
through a whitelist (resource_view.apply_recorded), then acked
— which ends it on the worker (`applied`)
lookup → `ai-agent past INS-2229` (conversations/past.py): the answer
rides in the ack's ``result``, which ends it the same way
report → a plugin path shim's out-of-band report (plugins/hubreports.py):
stored for its conversation and plugin, acked the same way
cli → any other `ai-agent …` the worker's CLI switch allows
(workers/cli.py): run here; what it printed rides in the ack's
``result`` when it ends within a second and a half (which ends
it), else in the answer pushed once it does (a `wait`)
sent → look the record up; once answered / acted / expired, POST
/outbox/{id}/answer {…} so the worker's long-polling
`notify wait` (or `ai-agent wait`) returns
cancelled (cancel requested after collection) → cancel the hub record
(a kind with a ``cancel`` function), ack
Everything is idempotent against a restart on either side: a queued item is
created at most once (the ack flips it to ``sent`` on the worker; a create
that already exists answers the existing id), and an answer is pushed again
until the worker confirms it. A worker that stops answering is backed off
(2 s → 60 s) until the monitor sees it again.
"""
from __future__ import annotations
import json
import threading
import time
import urllib.error
import urllib.request
from typing import Callable
from fastapi import HTTPException
class WorkerDown(Exception):
pass
# A worker on the link (workers/link.py) is polled this often instead.
LINK_EVERY_S = 4.0
class OutboxMirror(threading.Thread):
def __init__(self, store, *, create: dict[str, Callable[[dict], dict]],
status: dict[str, Callable[[str], dict | None]],
cancel: dict[str, Callable[[str], dict | None]],
publish: Callable[[dict], None] | None = None,
interval: float = 2.0,
allow: Callable[[dict, str, dict], bool] | None = None):
super().__init__(daemon=True, name="outbox-mirror")
self.store = store
self.create, self.status, self.cancel = create, status, cancel
# ``allow(worker, kind, payload)``: may this item be created? (a
# guest's machine only into its own sessions — workers/guests.py)
self.allow = allow
self.publish = publish or (lambda ev: None)
self.interval = interval
self._backoff: dict[str, tuple[float, float]] = {}
self._link_next: dict[str, float] = {}
self._stop = threading.Event()
def stop(self) -> None:
self._stop.set()
# ── HTTP ──────────────────────────────────────────────────────────────
def _call(self, w: dict, path: str, payload: dict | None = None, *,
method: str = "POST", timeout: float = 10) -> dict:
data = json.dumps(payload).encode() if payload is not None else None
req = urllib.request.Request(
f"{w['url']}{path}", data=data, method=method,
headers={"Content-Type": "application/json",
"Authorization": f"Bearer {w['token']}"})
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode() or "{}")
except urllib.error.HTTPError as e:
if e.code == 404:
raise FileNotFoundError(path)
raise WorkerDown(f"HTTP {e.code} on {path}")
except (urllib.error.URLError, OSError, ValueError) as e:
raise WorkerDown(str(e))
# ── one item ──────────────────────────────────────────────────────────
@staticmethod
def terminal(kind: str, rec: dict | None) -> dict | None:
"""The answer payload to push for a record that has ended, else None."""
if not rec:
return None
st = rec.get("status") or ""
if kind == "ask" and st in ("answered", "expired"):
return {"status": st, "answer": rec.get("answer"),
"answerIndex": rec.get("answerIndex")}
if kind == "ntf" and st == "acted":
return {"status": st, "actionIndex": rec.get("actionIndex"),
"actionTitle": rec.get("actionTitle")}
if kind == "cli" and st in ("applied", "failed"):
return {"status": st, "result": rec.get("result"), "error": rec.get("error")}
return None
def _handle(self, w: dict, item: dict) -> None:
oid = str(item.get("id") or "")
kind = str(item.get("kind") or "")
st = item.get("status")
if st == "queued":
fn = self.create.get(kind)
if not fn:
self._call(w, f"/outbox/{oid}/ack", {"hub": {"failed": True,
"error": f"unknown kind {kind!r}"}})
return
payload = dict(item.get("payload") or {})
payload["id"] = oid
payload["worker"] = w["id"]
if self.allow and not self.allow(w, kind, payload):
self._call(w, f"/outbox/{oid}/ack", {"hub": {
"failed": True, "error": "not a session of this worker"}})
return
try:
# The record may already exist (ack lost on a previous pass):
# a create then 400s on the duplicate id → treat as created.
# A `meta` item has no record: re-applying it is a no-op merge.
status = self.status.get(oid[:3])
existing = status(oid) if status else None
res = existing and {"id": oid, "ok": True, "existing": True} \
or fn(payload)
except HTTPException as e:
res = {"failed": True, "error": str(e.detail)[:300]}
self._call(w, f"/outbox/{oid}/ack", {"hub": {
k: v for k, v in res.items() if k in ("id", "ok", "url", "focusUrl",
"delivered", "failed", "error",
"existing", "result")}})
elif st == "sent":
fn = self.status.get(oid[:3])
rec = fn(oid) if fn else None
if rec is None:
self._call(w, f"/outbox/{oid}/answer",
{"status": "expired"})
return
done = self.terminal(oid[:3], rec)
if done:
self._call(w, f"/outbox/{oid}/answer", done)
elif st == "cancelled":
fn = self.cancel.get(oid[:3])
rec = fn(oid) if fn else None
if rec is not None and oid.startswith("frm_"):
self.publish({"type": "form", "id": oid,
"sessionId": rec.get("sessionId") or ""})
self._call(w, f"/outbox/{oid}/ack", {"hub": {"cancelled": True}})
# ── loop ──────────────────────────────────────────────────────────────
def sync(self, w: dict) -> int:
try:
listing = self._call(w, "/outbox", method="GET")
except FileNotFoundError:
return 0 # a worker that predates the outbox — nothing to collect
n = 0
for item in listing.get("items") or []:
try:
self._handle(w, item)
n += 1
except FileNotFoundError:
continue
return n
def tick(self) -> int:
n = 0
now = time.monotonic()
for w in self.store.list():
wid = w["id"]
if not self.store.online(wid):
continue
until, step = self._backoff.get(wid, (0.0, 0.0))
if now < until:
continue
if w.get("link"):
# A computer on the worker link: each call is two HTTPS
# requests across the internet — every LINK_EVERY_S, not 2 s.
if now < self._link_next.get(wid, 0.0):
continue
self._link_next[wid] = now + LINK_EVERY_S
try:
n += self.sync(w)
self._backoff.pop(wid, None)
except WorkerDown as e:
step = min(60.0, max(2.0, step * 2))
self._backoff[wid] = (now + step, step)
self.store.set_status(wid, lastError=f"outbox: {e}"[:200])
except Exception as e: # never let one bad item kill the thread
self.store.set_status(wid, lastError=f"outbox: {e}"[:200])
return n
def run(self) -> None:
while not self._stop.wait(self.interval):
try:
self.tick()
except Exception:
pass