Files
ai-agent/sidecar/validate.py
Gabriel VidalandClaude Opus 5.5 98b1fe85e9 fix(workers): harness plugins reach every worker — no more "invalid harness: 'claude'"
Since the strict plugin-only sidecar (Wave 3C) a worker runs only the
harness plugins the hub syncs to it, and every worker came up with none:

- the probe that asked a worker to update also pushed it the new bundle;
  the old sidecar took the bundle's hash and dropped the harness/provider
  maps it didn't know, then restarted onto the strict code empty — and the
  hub saw the hash "current" forever (a same-hash /sync was a no-op too);
- harness-pi ships runner/.gitignore, which the worker refuses, so every
  later /sync of the owner's workers failed whole (400 bad file path).

Hub: plugin bundles never ship a path the worker would refuse (hidden
parts, > 8 parts); labsync.plugins_drift makes a worker that holds the
bundle's hash without its maps "outdated", read off /health's new
pluginSync (or its harnesses list on an older sidecar); no lab-sync push
in the probe that triggers an update, nor while the worker is updating.

Sidecar: /health reports pluginSync ({kind: {version, loaded}}) and the
loaded usage readers; /sync re-applies plugin maps the worker doesn't
hold or run even under a hash it already has (labsync.plugins_stale);
a well-formed harness no driver runs is a 409 harness_unavailable on
spawn/resume/fork (only a malformed id stays a 400), and a worker with no
harness at all says its lab sync hasn't brought them yet.

Also fixes test_guest_computers' lab-sync test, broken on main since the
plugin maps (its stubbed bundle is a list).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:17:45 +01:00

101 lines
4.0 KiB
Python

"""
Request validation shared by the routes: the bearer check, and the per-field
checks that turn a body value into a command-line argument (session id, model,
harness, thinking / effort flags).
"""
import hmac
import re
import uuid as uuidlib
from fastapi import HTTPException
import pairing
from config import EFFORT_LEVELS, MODEL_RE, PI_MODEL_RE, THINKING_OFF, TOKEN
def _auth(authorization: str | None) -> None:
"""Bearer check. The token is SIDECAR_TOKEN (the host sidecar, the
in-container runner) or, on a paired worker, the one minted at pairing."""
token = TOKEN or pairing.token()
if not token:
raise HTTPException(500, "sidecar not configured (no SIDECAR_TOKEN, "
"not paired)")
if not hmac.compare_digest(authorization or "", f"Bearer {token}"):
raise HTTPException(401, "unauthorized")
def _valid_uuid(sid: str) -> str:
sid = (sid or "").strip()
try:
uuidlib.UUID(sid) # claude requires a valid UUID for --session-id/--resume
except ValueError:
raise HTTPException(400, "sessionId must be a valid UUID")
return sid
def _valid_model(model: str | None, harness: str = "claude") -> str | None:
"""Sanity-check a `--model` value (an alias or a model id). None = unset."""
model = (model or "").strip()
if not model:
return None
rx = PI_MODEL_RE if harness in ("pi", "opencode") else MODEL_RE
if not rx.match(model):
raise HTTPException(400, f"invalid model: {model!r}")
return model
_HARNESS_ID_RE = re.compile(r"^[a-z][a-z0-9_-]{0,63}$")
def _valid_harness(harness: str | None) -> str:
"""A well-formed harness id (harness_loader's id shape) — a malformed one
is a 400. Whether a live driver runs it is the route's check
(:func:`harness_unavailable`, a 409): a harness whose plugin isn't here
is a machine that lacks it, not a bad request."""
h = (harness or "claude").strip().lower()
if not _HARNESS_ID_RE.match(h):
raise HTTPException(400, f"invalid harness: {harness!r}")
return h
def harness_unavailable(harness: str) -> HTTPException:
"""The 409 ``harness_unavailable`` for a harness no live driver runs here.
A worker that has no harness plugin at all hasn't had them from the hub
yet (its lab sync brings them) — the message says so, since that is a
hub-side state to look at, not a missing install."""
import harness_loader
import run_errors
from config import IS_WORKER
if IS_WORKER and not harness_loader.ids():
msg = (f"the {harness} harness is not on this machine yet: it has no harness "
f"plugin from the hub (its lab sync brings them — see the machine's "
f"Lab sync status in Settings → Machines)")
else:
msg = (f"the {harness} harness is not installed on this runner "
f"(no harness-{harness} plugin)")
return HTTPException(409, run_errors.error_detail(msg, kind="harness_unavailable"))
def _thinking_args(thinking: bool | None, harness: str) -> list[str]:
"""The `--thinking` flag for a run, in the harness's own vocabulary.
Only *off* is expressible: thinking on (or unset) emits nothing, leaving each
CLI on its own default level. Both harnesses take the same flag name, so this
is a straight append onto either argv."""
if thinking is False and harness in THINKING_OFF:
return ["--thinking", THINKING_OFF[harness]]
return []
def _effort_args(effort: str | None, harness: str) -> list[str]:
"""The `--effort` flag for a run. Claude-only, and validated as an
allow-list (unlike `--model`, the CLI's scale is a closed set), so a bogus
value is a 400 here rather than a run that dies on an unknown flag value.
Unset — or any pi run — emits nothing and the CLI keeps its default."""
effort = (effort or "").strip().lower()
if not effort or harness != "claude":
return []
if effort not in EFFORT_LEVELS:
raise HTTPException(400, f"invalid effort: {effort!r}")
return ["--effort", effort]