Files
Gabriel VidalandClaude Opus 5.5 1574ccd388 sidecar: strict plugin-only cutover (Wave 3C)
Delete the built-in bridges and the legacy harness / usage modules now owned
by ai-agent-plugins (harness_builtin, claude_cli, claude_accounts,
claude_usage, pi_runs, opencode_{cli,mirror,tools,usage},
agy_{cli,mirror,tools,usage}). routes_runs / fork keep only the routes; the
harness-* plugins' drivers launch.

- harness_loader: no builtins; the first read boots the registry; a live dir
  never materialized falls back to .lkg, then (host only) the seed plugins
  (SIDECAR_SEED_PLUGINS_DIR, default ~/projects/ai-agent-plugins/plugins);
  codeless provider entries keep their manifest + config.json; module() and
  forget_status() accessors; hub-written absolute dirs resolved by name.
- usage_loader: provider_configs() covers every provider plugin, evox2()
  reads servers + Wake-on-LAN from provider-evox2 (local_ready, gen_progress
  use it — no duplicated EVOX2 constants).
- core helpers kept self-contained: claude_env.py (run env, account env,
  machine login), run_errors.py (typed errors); launch._stop_run calls the
  driver's stop_extra; /accounts?fresh=1 and guest listing go through drivers;
  gen_progress reads the opencode db via harness_loader.module; tools_check
  via driver status; tools_install has its own gh device-login pump.
- /sync accepts a provider bundle without a usage reader.
- backend workers/labsync: always send harnesses + providers maps ({} clears
  a worker); guests only get harnesses whose own plugin.json says
  guestAllowed.
- tests + A/B scripts run the real plugins (conftest live index + legacy-name
  import hook; launch-dump / _mirror_worker load the plugins for a tree with
  no bridges). install.sh points the host unit at the hub's live dirs.

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

429 lines
17 KiB
Python

"""
The Claude proxy, the worker's half — a worker's Claude Code bills the hub's
logins instead of one of its own.
The hub (``backend/claudeproxy/``) is an Anthropic API proxy: it takes a
worker's requests, checks the worker may use the account named in the path,
swaps the worker's bearer for that account's real OAuth token and streams the
reply back. So a new machine needs no Claude login at all — the logins live
on the lab, signed in once from Settings → Accounts.
When this worker's ``/health`` reports a different ``claudeProxy.hash``, the
hub POSTs its side of the deal (each liveness probe, like the lab sync):
POST /claude-proxy {url, token, accounts, default}
kept in the worker's state dir (``claude-proxy.json``, 0600 — next to the
pairing bearer); ``DELETE /claude-proxy`` (the worker switched back to its own
login) drops it. A claude run on one of those accounts launches with
(``env_for``)::
ANTHROPIC_BASE_URL=<url>/<account>
CLAUDE_CODE_OAUTH_TOKEN=<token>
``CLAUDE_CODE_OAUTH_TOKEN`` makes the CLI behave as a subscription client (the
``oauth-2025-04-20`` beta, the plan's models and limits) without a login of
its own, and the base URL sends every model call to the hub. The config dir
stays the account's on this machine — ``~/.claude`` unless the worker
declares one — with its settings, skills and the ``projects/`` the hub
mirrors over ``/feed``.
**The machine default.** ``default`` (the worker's ★ account) is written into
``~/.claude/settings.json``'s ``env`` too, so a ``claude`` typed in a terminal
there bills it without any login. The CLI ranks that ``env`` *above* the
process environment, so a hub run on another account carries its pair in the
``--settings`` flag as well (:func:`with_settings_env` — the flag outranks
the file). Only the keys written here are ever removed again, and a value
the user had there before comes back.
Refused on the host sidecar: its accounts are config dirs.
"""
from __future__ import annotations
import hashlib
import json
import os
import pathlib
import re
from typing import Callable
from fastapi import APIRouter, Header, HTTPException
from pydantic import BaseModel
import pairing
import proxy_pair
from config import CLAUDE_PROJECTS, IS_WORKER
_ACCOUNT_RE = re.compile(r"^[a-z][a-z0-9_-]{0,31}$")
_URL_RE = re.compile(r"^https?://[A-Za-z0-9.:\[\]-]+(/[A-Za-z0-9._~/-]*)?$")
_TOKEN_RE = re.compile(r"^[A-Za-z0-9_-]{24,128}$")
# What a proxied run must not inherit: any other way to authenticate would
# win over (or fight with) the hub's — an API key bills the API, a login
# token of the machine's own bills that login. (A config dir may stay: the
# env token wins over the login stored in it.)
_STRIP = ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN",
"ANTHROPIC_BASE_URL")
# What the machine default writes into settings.json's env.
_DEFAULT_KEYS = ("ANTHROPIC_BASE_URL", "CLAUDE_CODE_OAUTH_TOKEN")
_cache: tuple[float, dict] | None = None
def _path() -> pathlib.Path:
return pairing.state_dir() / "claude-proxy.json"
def settings_path() -> pathlib.Path:
"""The user-level settings a terminal ``claude`` reads (``~/.claude``)."""
return CLAUDE_PROJECTS.parent / "settings.json"
def config() -> dict:
"""``{url, token, accounts, default, settings}`` as last saved ({} =
none), read again only when the file changed."""
global _cache
try:
mtime = _path().stat().st_mtime
except OSError:
_cache = None
return {}
if _cache and _cache[0] == mtime:
return _cache[1]
try:
cfg = json.loads(_path().read_text())
if not isinstance(cfg, dict):
cfg = {}
except (OSError, ValueError):
cfg = {}
_cache = (mtime, cfg)
return cfg
def fingerprint(url: str, token: str, accounts: list[str], default: str | None = None) -> str:
"""What ``/health`` shows of the config: the hub computes the same from
what it would send, and pushes when the two differ. The token only enters
hashed (``/health`` is open)."""
raw = json.dumps([url, hashlib.sha256(token.encode()).hexdigest(), sorted(accounts),
default or ""])
return hashlib.sha256(raw.encode()).hexdigest()[:16]
def accounts() -> list[str]:
return list(config().get("accounts") or []) if IS_WORKER else []
def proxied(account: str | None) -> bool:
"""Does a claude run on ``account`` go through the hub? Only on a worker,
for an account the hub said this machine may use."""
return bool(account) and account in accounts()
def env_for(account: str, cfg: dict | None = None) -> dict[str, str]:
"""The pair a run on ``account`` launches with (from the saved config, or
``cfg`` about to be saved)."""
cfg = cfg if cfg is not None else config()
return {"ANTHROPIC_BASE_URL": f"{cfg['url'].rstrip('/')}/{account}",
"CLAUDE_CODE_OAUTH_TOKEN": cfg["token"]}
def apply_env(env: dict[str, str], account: str) -> dict[str, str]:
"""``env`` turned into a proxied run's environment, in place."""
for k in _STRIP:
env.pop(k, None)
env.update(env_for(account))
return env
def own_login_leak(cwd: str | None = None, environ: dict | None = None) -> list[dict]:
"""Where this machine sets the hub's pair a run on its own login must not
inherit (``proxy_pair.find``): its settings files for a run in ``cwd``,
and the process environment."""
import link
cfg = config()
hosts = proxy_pair.hub_hosts(cfg.get("url"), (link.config() or {}).get("hub"))
return proxy_pair.find(CLAUDE_PROJECTS.parent, cwd, hosts, {cfg.get("token") or ""},
environ)
# ── secrets out of the command line ──────────────────────────────────────────
# A run's ``--settings`` JSON can carry a credential in its ``env`` — the
# hub's proxy token here, a guest's tools token (``launch._scope_settings``) —
# and a command line is readable by every process that can list this one
# (other users of a Mac, a container sharing the host's pids). So a settings
# value holding one goes to a 0600 file of ours and the flag names the file.
RUN_SETTINGS_DIR = pathlib.Path(os.path.expanduser(os.environ.get(
"SIDECAR_RUN_SETTINGS_DIR", "~/.cache/ai-agent/run-settings")))
_SECRET_ENV_RE = re.compile(r"TOKEN|SECRET|PASSWORD|API_?KEY", re.I)
_SID_ARG_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
# A file is kept at least this long (it is written a moment before its run
# starts), then goes once no run of its session is alive.
RUN_SETTINGS_KEEP_S = 900
_swept_at = 0.0
def _session_of(args: list[str]) -> str | None:
for flag in ("--session-id", "--resume"):
if flag in args:
i = args.index(flag) + 1
if i < len(args) and _SID_ARG_RE.match(args[i]):
return args[i]
return None
def _sweep_run_settings(now: float | None = None) -> None:
"""Drop the settings files of runs that ended (at most every 5 min)."""
global _swept_at
import time
now = time.time() if now is None else now
if now - _swept_at < 300:
return
_swept_at = now
try:
entries = list(os.scandir(RUN_SETTINGS_DIR))
except OSError:
return
import pids
for e in entries:
try:
if not e.name.endswith(".json") or now - e.stat().st_mtime < RUN_SETTINGS_KEEP_S:
continue
sid = e.name[:36]
if _SID_ARG_RE.match(sid) and pids._live_record(sid) is not None:
continue
os.unlink(e.path)
except OSError:
continue
def secrets_out_of_argv(args: list[str]) -> list[str]:
"""``args`` with a ``--settings <json>`` whose ``env`` holds a credential
rewritten as ``--settings <0600 file>``. Anything else is returned as it
came; so is everything when the file can't be written (the run matters
more than its command line)."""
if "--settings" not in args:
return args
i = args.index("--settings") + 1
try:
s = json.loads(args[i])
except (IndexError, ValueError):
return args
env = s.get("env") if isinstance(s, dict) else None
if not isinstance(env, dict) or not any(v and _SECRET_ENV_RE.search(str(k))
for k, v in env.items()):
return args
raw = args[i]
name = f"{_session_of(args) or 'run'}-{hashlib.sha256(raw.encode()).hexdigest()[:16]}.json"
path = RUN_SETTINGS_DIR / name
try:
RUN_SETTINGS_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
os.chmod(RUN_SETTINGS_DIR, 0o700)
tmp = path.with_name(f"{name}.{os.getpid()}.tmp")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
f.write(raw)
os.replace(tmp, path)
except OSError as e:
print(f"[claude-proxy] run settings kept on the command line: {e}", flush=True)
return args
_sweep_run_settings()
return [*args[:i], str(path), *args[i + 1:]]
def with_settings_env(args: list[str], account: str | None,
cwd: str | None = None) -> list[str]:
"""A claude run's final args: :func:`_with_pair`, then any credential in
its ``--settings`` moved off the command line
(:func:`secrets_out_of_argv`). The last thing done to a run's args —
nothing after it can read the flag as JSON."""
return secrets_out_of_argv(_with_pair(args, account, cwd))
def _with_pair(args: list[str], account: str | None,
cwd: str | None = None) -> list[str]:
"""A proxied claude run's args with its pair in the ``--settings`` flag
too — settings.json's ``env`` (the machine default) outranks the process
environment, the flag outranks settings.json.
A run on a guest computer's own login (``claude_env.machine_login``)
gets the opposite: the hub's pair, wherever a settings file in reach of
``cwd`` sets it, unset in the flag — or that file would send the run
through the proxy on the host's account (``proxy_pair``)."""
if not proxied(account):
from claude_env import machine_login # it imports this module
if not machine_login(account):
return args
hits = own_login_leak(cwd)
if hits:
print(f"[claude-proxy] own-login run: unsetting the hub's pair from "
f"{', '.join(h['path'] or 'the environment' for h in hits)}", flush=True)
out = proxy_pair.with_env(args, proxy_pair.neutraliser(hits))
return args if out is None else out
if "--settings" not in args:
return args
i = args.index("--settings") + 1
try:
s = json.loads(args[i])
except (IndexError, ValueError):
return args
s["env"] = {**(s.get("env") or {}), **env_for(account)}
return [*args[:i], json.dumps(s, separators=(",", ":")), *args[i + 1:]]
# ── the machine default in settings.json ────────────────────────────────────
def _read_settings() -> dict:
p = settings_path()
if not p.exists():
return {}
data = json.loads(p.read_text()) # ValueError: not ours to fix
if not isinstance(data, dict):
raise ValueError("settings.json is not an object")
return data
def _write_settings(data: dict) -> None:
p = settings_path()
p.parent.mkdir(parents=True, exist_ok=True)
mode = p.stat().st_mode & 0o777 if p.exists() else 0o600
env = data.get("env") if isinstance(data.get("env"), dict) else {}
if any(v and _SECRET_ENV_RE.search(str(k)) for k, v in env.items()):
mode = 0o600 # it now holds the hub's token: the owner's eyes only
tmp = p.with_name(p.name + ".ai-agent.tmp")
tmp.unlink(missing_ok=True) # a leftover would keep its old, wider mode
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
with os.fdopen(fd, "w") as f:
f.write(json.dumps(data, indent=2) + "\n")
os.chmod(tmp, mode) # whatever the umask made of it
os.replace(tmp, p)
def _drop_default(rec: dict | None) -> None:
"""Take out what :func:`_write_default` put in — only keys still holding
the value written, and the user's own value back where there was one."""
if not rec or not rec.get("keys"):
return
data = _read_settings()
env = data.get("env") if isinstance(data.get("env"), dict) else {}
prev = rec.get("prev") or {}
for k, v in rec["keys"].items():
if env.get(k) != v:
continue
if k in prev:
env[k] = prev[k]
else:
env.pop(k, None)
if env:
data["env"] = env
else:
data.pop("env", None)
_write_settings(data)
def _write_default(cfg: dict, prev_rec: dict | None) -> dict:
data = _read_settings()
env = data.get("env") if isinstance(data.get("env"), dict) else {}
want = env_for(cfg["default"], cfg)
ours = (prev_rec or {}).get("keys") or {}
# What the user had there before us (kept from the first write).
prev = dict((prev_rec or {}).get("prev") or {})
for k in _DEFAULT_KEYS:
if k in env and env[k] != ours.get(k) and k not in prev:
prev[k] = env[k]
env.update(want)
data["env"] = env
_write_settings(data)
return {"account": cfg["default"], "keys": want, "prev": prev}
def _apply_default(cfg: dict, old: dict) -> dict:
"""Bring settings.json in line with ``cfg["default"]``; the record goes
into the saved config (``settings``), an error into ``settingsError``."""
rec = old.get("settings")
try:
if cfg.get("default"):
if rec and rec.get("keys") == env_for(cfg["default"], cfg):
return {"settings": rec}
return {"settings": _write_default(cfg, rec)}
_drop_default(rec)
return {}
except (OSError, ValueError) as e:
return {"settings": rec, "settingsError": f"{settings_path()}: {e}"[:300]}
def public() -> dict | None:
"""``/health``'s ``claudeProxy`` (workers only): which accounts this
machine runs through the hub, its terminal default, and the fingerprint
the hub compares."""
if not IS_WORKER:
return None
cfg = config()
if not cfg.get("url"):
return {"hash": None, "accounts": []}
rec = cfg.get("settings") or {}
return {"hash": fingerprint(cfg["url"], cfg.get("token") or "", cfg.get("accounts") or [],
cfg.get("default")),
"url": cfg["url"], "accounts": cfg.get("accounts") or [],
"default": cfg.get("default"),
"settings": {"account": rec.get("account"), "path": str(settings_path()),
"error": cfg.get("settingsError")}}
def clear() -> None:
"""Forget the hub's proxy (unpair, or back to the machine's own login):
the config and the settings.json default."""
try:
_drop_default(config().get("settings"))
except (OSError, ValueError):
pass
_path().unlink(missing_ok=True)
class ProxyBody(BaseModel):
url: str
token: str
accounts: list[str] = []
default: str | None = None
def save(body: ProxyBody) -> dict:
if not _URL_RE.match(body.url or ""):
raise HTTPException(400, "bad proxy url")
if not _TOKEN_RE.match(body.token or ""):
raise HTTPException(400, "bad proxy token")
accts = sorted({a for a in body.accounts if _ACCOUNT_RE.match(a or "")})
if not accts:
clear()
return public() or {}
cfg = {"url": body.url.rstrip("/"), "token": body.token, "accounts": accts,
"default": body.default if body.default in accts else None}
cfg.update(_apply_default(cfg, config()))
pairing._write_private(_path(), json.dumps(cfg))
return public() or {}
def make_router(auth: Callable[[str | None], None]) -> APIRouter:
router = APIRouter()
@router.post("/claude-proxy")
def set_proxy(body: ProxyBody,
authorization: str | None = Header(default=None)) -> dict:
auth(authorization)
if not IS_WORKER:
raise HTTPException(409, "the host sidecar runs on its own logins")
out = save(body)
print(f"[worker] claude proxy: {', '.join(out.get('accounts') or []) or 'no account'}"
f"{' · terminal default ' + out['default'] if out.get('default') else ''}",
flush=True)
return {"claudeProxy": out}
@router.delete("/claude-proxy")
def drop_proxy(authorization: str | None = Header(default=None)) -> dict:
auth(authorization)
if not IS_WORKER:
raise HTTPException(409, "the host sidecar runs on its own logins")
clear()
print("[worker] claude proxy: off (own login)", flush=True)
return {"claudeProxy": public()}
return router