Files
gabrielvidalandClaude Opus 5.5 aee457cdbf Merge origin/main into hub-mcp-plugin
main moved cron jobs into the cron-jobs plugin (#37) and retired the core
Send later doors for the scheduled-conversations plugin's commands (#36),
both touching the core MCP files this branch moves into the hub-mcp plugin.

- The MCP stays out of core: backend/mcpserver/, cli/mcp_tools.py,
  cli/mcp_server.py, their tests and business/aiApps/ stay deleted (main's
  edits to them — no schedule group, no cron / schedule tools — are the
  plugin's to apply).
- Cron and Send later follow main: backend/cron/routes.py gone (its
  by-name worker pick is runs.start's at fire time now), no ai-agent
  later / scheduled / unschedule — so a worker's narrowed CLI drops them
  from its command lists (workers/cli.py) and schedules nothing; Full
  reaches the plugin's commands.
- authz: neither runs.schedule nor mcp.connect.
- Settings: neither Scheduled jobs nor AI apps in the registry; both old
  addresses redirect to their plugin's page.
- Regenerated openapi.json, src/generated, rolesCatalog.json,
  matrix.golden.txt and telemetry features.json.
- cli/test_library_surface.py: parse_when left with `ai-agent later`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:14:16 +01:00

300 lines
14 KiB
Python

"""
A worker's ``ai-agent`` CLI — the commands a session on one of the owner's
remote workers (the EVOX2, the Orus MacBook…) runs, carried by that worker's
outbox. Any harness's session: Claude Code, agy, opencode alike — it is a
shell command, the hub needs nothing per harness.
A worker never calls the hub: it holds no hub URL or credential, the hub
pulls (workers/store.py). So on a worker the CLI drops the command line it was
given into the worker's outbox as a ``cli`` item (``cli_`` + 12 hex), the
:class:`~workers.outbox_mirror.OutboxMirror` collects it, and
:class:`CliJobs` runs the **same CLI** here, as a subprocess, with
``AIA_AS_WORKER=<worker id>`` and ``AIA_AS_WORKER_MODE=<its switch>``. Every
call it makes carries those as headers, and the gate (core/auth.py) answers it
as :func:`workers.bound.worker_caller` — the owner, narrowed, exactly as for
an MCP connection bound to that worker (``worker.read`` / ``worker.run``
scope):
* the worker's switch (Settings → Profiles → <worker> → *ai-agent CLI*,
``workers.json`` ``cli``) is ``off``, ``read``, ``run`` or ``full``; unset,
``run`` for the owner's workers. A guest's computer never gets it;
* ``full`` (since 2026-11-28 — the EVOX2, the owner's own devbox) is **the
lab's CLI, as the owner**: every command but ``worktrees`` (the lab's own
checkout), every profile, any machine (``--on``), the plugins' commands.
Nothing narrows its calls — it is what the unbound MCP connection that
machine had until then could do. A run it starts still goes to that worker
unless ``--on`` names another, and still nests under the session it came
from;
* only the commands in :data:`READ_COMMANDS` (plus :data:`RUN_COMMANDS` under
``run``) are run, and only the routes their scope holds answer;
* reads see the conversations of the worker's own profile only
(users/access.py, ``Caller.profile``);
* writes stay on that worker: a new run (``new``) starts there (``--on``
may name it by id or name, workers/picks.py), and ``send`` / ``fork`` /
``stop`` / ``title`` / ``archive`` only touch conversations that live
there (Send later is the scheduled-conversations plugin's commands since
2026-11-28 — ``full`` only, like every plugin command);
* the session it came from (``sessionId``) is the parent of what it starts:
the child shows inside it and its answer comes back to it on its own.
What the command printed (``{rc, stdout, stderr}``) rides back in the ack when
it ends within :data:`ACK_WAIT_S` — or, for a ``wait``, in the answer the
mirror pushes once it does. A hub restart loses a running job: the mirror then
answers ``expired`` and the CLI says to run it again.
History: 2026-11-16 → 11-18 this path was replaced by the worker-bound MCP
connection (docs/mcp.md → "On a worker"); it came back on 2026-11-28 — only
Claude Code had that connection, so an agy run on the EVOX2 spawned
conversations through a ``claude -p`` relay, and named its worker ``EVOX2``
where the hub took ids only.
"""
from __future__ import annotations
import dataclasses
import os
import pathlib
import re
import subprocess
import sys
import threading
import time
from users.caller import Caller
from . import bound
from .bound import READ, RUN, Refused
OFF = "off"
FULL = "full"
MODES = (OFF, READ, RUN, FULL)
# Commands a worker's session may run. Everything else is the lab's: the
# browse commands read the lab's own files (projects, memories, plans…),
# `inbox` / `agents` / `cron` / `tags` / `worktrees` / `plugin` are about
# the lab and every profile.
READ_COMMANDS = ("ls", "show", "search", "past", "wait", "workers", "usage",
"budget", "models")
RUN_COMMANDS = ("new", "send", "fork", "stop", "archive", "title")
# What even a ``full`` worker can't run from afar: it works on the lab host's
# own checkout, which the hub's process doesn't have.
LAB_ONLY = ("worktrees",)
# The commands whose run goes to the asking worker unless ``--on`` says where.
_STARTS = ("new",)
# How long the mirror waits for a command before acking it as still running.
ACK_WAIT_S = float(os.environ.get("WORKER_CLI_ACK_WAIT_S", "1.5"))
# A command is killed past this (a `wait` defaults to 3600 s).
MAX_RUN_S = float(os.environ.get("WORKER_CLI_MAX_RUN_S", "3700"))
# At most this many running at once per worker.
MAX_JOBS = int(os.environ.get("WORKER_CLI_MAX_JOBS", "8"))
# What a command may print, each of stdout / stderr (the result is kept in the
# worker's outbox.json until it is read).
MAX_OUTPUT = int(os.environ.get("WORKER_CLI_MAX_OUTPUT", str(256 * 1024)))
# The command line: at most this many arguments, this many characters in all.
MAX_ARGS = 64
MAX_ARGV_CHARS = 200_000
# A finished job is forgotten this long after it ended.
KEEP_S = 3600
_SID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
_ID_RE = re.compile(r"^cli_[0-9a-f]{12}$")
_ROOT = pathlib.Path(__file__).resolve().parent.parent
CLI = next((d / "ai_agent.py" for d in (_ROOT / "cli", _ROOT.parent / "cli")
if (d / "ai_agent.py").is_file()), None)
# The backend's own port inside the container (docker-entrypoint.sh).
SELF_URL = (os.environ.get("HUB_SELF_URL")
or f"http://127.0.0.1:{os.environ.get('PORT', '8080')}").rstrip("/")
# ── the switch ───────────────────────────────────────────────────────────────
def mode(w: dict | None) -> str:
"""A worker's *ai-agent CLI* switch: its own, else ``run`` for one of the
owner's workers; ``off`` for a guest's computer, whatever it says."""
if not w or w.get("owner"):
return OFF
m = w.get("cli")
return m if m in MODES else RUN
def commands(m: str) -> tuple[str, ...]:
"""The commands a read / run switch allows (``full`` has no list: all but
:data:`LAB_ONLY`)."""
return () if m == OFF else READ_COMMANDS + (RUN_COMMANDS if m in (RUN, FULL) else ())
def _on_given(argv: list[str]) -> bool:
return any(a == "--on" or a.startswith("--on=") for a in argv)
def worker_caller(deps, wid: str) -> Caller:
"""The caller a worker's CLI call is: the owner, narrowed to that worker's
profile and switch (:func:`workers.bound.worker_caller`). :class:`Refused`
when the worker is unknown, a guest's or switched off."""
w = deps.worker_store.get((wid or "").strip())
m = mode(w)
if w and m == OFF and not w.get("owner"):
raise Refused(403, {"message": f"the ai-agent CLI is off for {w.get('name') or wid} "
"(Settings → Profiles → the worker)",
"kind": "worker_cli_off"})
return bound.worker_caller(deps, wid, m)
# ── the jobs ─────────────────────────────────────────────────────────────────
@dataclasses.dataclass
class Job:
id: str
worker: str
argv: list[str]
started: float
mode: str = READ
status: str = "running" # running | applied | failed
result: dict | None = None
error: str | None = None
ended: float | None = None
proc: subprocess.Popen | None = None
done: threading.Event = dataclasses.field(default_factory=threading.Event)
def record(self) -> dict:
return {"id": self.id, "status": self.status, "result": self.result,
"error": self.error}
def _clip(text: str) -> str:
if len(text) <= MAX_OUTPUT:
return text
return text[:MAX_OUTPUT] + f"\n… (cut at {MAX_OUTPUT // 1024} KB — ask for less: --tail N, --limit N)\n"
class CliJobs:
"""The commands workers' sessions sent, run here one subprocess each."""
def __init__(self, deps, *, cli: pathlib.Path | None = CLI,
self_url: str = SELF_URL):
self.deps = deps
self.cli = cli
self.self_url = self_url
self._jobs: dict[str, Job] = {}
self._lock = threading.Lock()
# The OutboxMirror's three hooks: create / status / cancel.
def create(self, payload: dict) -> dict:
oid = str(payload.get("id") or "")
wid = str(payload.get("worker") or "")
try:
argv, m = self._check(oid, wid, payload.get("argv"))
except Refused as e:
d = e.detail
return {"failed": True, "error": str(d.get("message") if isinstance(d, dict) else d)}
sid = str(payload.get("sessionId") or "")
job = Job(oid, wid, argv, time.time(), mode=m)
with self._lock:
self._gc()
if oid in self._jobs:
return {"id": oid, "ok": True, "existing": True}
if sum(1 for j in self._jobs.values()
if j.worker == wid and j.status == "running") >= MAX_JOBS:
return {"failed": True, "error": f"{MAX_JOBS} ai-agent commands already "
"running for this worker — wait for one"}
self._jobs[oid] = job
threading.Thread(target=self._run, args=(job, sid if _SID_RE.match(sid) else ""),
daemon=True, name=f"worker-cli-{oid}").start()
if job.done.wait(ACK_WAIT_S) and job.status == "applied":
return {"id": oid, "ok": True, "result": job.result}
return {"id": oid, "ok": True}
def get(self, oid: str) -> dict | None:
with self._lock:
j = self._jobs.get(oid)
return j.record() if j else None
def cancel(self, oid: str) -> dict | None:
with self._lock:
j = self._jobs.get(oid)
if not j:
return None
if j.proc and j.proc.poll() is None:
j.proc.kill()
return j.record()
# ── internals ─────────────────────────────────────────────────────────
def _check(self, oid: str, wid: str, argv) -> tuple[list[str], str]:
if not _ID_RE.match(oid):
raise Refused(400, "bad id")
if self.cli is None:
raise Refused(503, "this hub has no ai-agent CLI to run")
if not isinstance(argv, list) or not argv or len(argv) > MAX_ARGS \
or not all(isinstance(a, str) for a in argv) \
or sum(len(a) for a in argv) > MAX_ARGV_CHARS:
raise Refused(400, "argv: a list of strings (the command first)")
cmd = argv[0]
w = self.deps.worker_store.get((wid or "").strip())
if mode(w) == FULL and bound.bindable(w):
# The owner's own machine, trusted with the lab's CLI as he has it.
if cmd in LAB_ONLY:
raise Refused(403, f"`ai-agent {cmd}` works on the lab's own checkout — "
"run it there")
out = list(argv)
if cmd in _STARTS and not _on_given(out):
out += ["--on", w["id"]] # here, unless it says where
return out, FULL
caller = worker_caller(self.deps, wid)
if cmd not in commands(caller.worker_mode):
if caller.worker_mode == READ and cmd in RUN_COMMANDS:
raise Refused(403, f"`ai-agent {cmd}` needs the worker's ai-agent CLI "
"switch on *Read + run here* (Settings → Profiles)")
raise Refused(403, f"`ai-agent {cmd}` is the lab's — this worker's ai-agent CLI "
f"switch allows: {', '.join(commands(caller.worker_mode))} "
"(*Full* in Settings → Profiles → the worker opens the rest)")
return list(argv), caller.worker_mode
def _env(self, job: Job, sid: str) -> dict[str, str]:
# A clean environment: nothing of the hub's but the host token its
# loopback calls carry (as the MCP server's do — loopback alone isn't
# a credential), no HOME whose transcripts a session-id guess could
# pick from. The headers then narrow every call to the worker.
from core.auth import INTERNAL_API_TOKEN
env = {"PATH": os.environ.get("PATH", "/usr/local/bin:/usr/bin:/bin"),
"LANG": "C.UTF-8", "PYTHONIOENCODING": "utf-8",
"HOME": "/nonexistent", "CLAUDE_CONFIG_DIR": "/nonexistent",
"AI_AGENT_URL": self.self_url, "AI_AGENT_OUTBOX_URL": ""}
if job.mode != FULL: # full: the owner's CLI, nothing narrows it
env.update({"AIA_AS_WORKER": job.worker, "AIA_AS_WORKER_MODE": job.mode})
if INTERNAL_API_TOKEN:
env["AI_AGENT_TOKEN"] = INTERNAL_API_TOKEN
if os.environ.get("AI_AGENT_VIEW_URL"):
env["AI_AGENT_VIEW_URL"] = os.environ["AI_AGENT_VIEW_URL"]
if sid:
env["CLAUDE_SESSION_ID"] = sid
return env
def _run(self, job: Job, sid: str) -> None:
try:
job.proc = subprocess.Popen(
[sys.executable, "-I", str(self.cli), *job.argv],
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
env=self._env(job, sid), cwd="/", start_new_session=True)
try:
out, err = job.proc.communicate(timeout=MAX_RUN_S)
rc = job.proc.returncode
except subprocess.TimeoutExpired:
job.proc.kill()
out, err = job.proc.communicate()
rc = 4
err += f"\nai-agent: stopped after {int(MAX_RUN_S)} s on the hub — run it again".encode()
job.result = {"rc": rc, "stdout": _clip(out.decode(errors="replace")),
"stderr": _clip(err.decode(errors="replace"))}
job.status = "applied"
except Exception as e: # never leave a job running forever
job.status, job.error = "failed", f"the hub couldn't run it: {e}"[:300]
finally:
job.ended = time.time()
job.proc = None
job.done.set()
def _gc(self) -> None:
cutoff = time.time() - KEEP_S
for oid in [k for k, j in self._jobs.items() if j.ended and j.ended < cutoff]:
del self._jobs[oid]