Files
ai-agent/sidecar/proxy_pair.py
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

195 lines
8.1 KiB
Python

"""
The hub's Claude proxy pair where it doesn't belong — a guest's own-login
run that still bills the host.
On a guest's computer, a run on the guest's own Claude (``guest-<uid>``,
``claude_env.machine_login``) launches with the machine's login and no
proxy pair. Claude Code still reads ``env`` from its settings files, and
**those outrank the process environment**: a ``~/.claude/settings.json`` (or
a project's ``.claude/settings*.json``) holding the pair the hub's proxy
uses — ``ANTHROPIC_BASE_URL=<hub>/proxy/claude/<account>`` +
``CLAUDE_CODE_OAUTH_TOKEN=<proxy token>``, what an *ai-agent Claude* session
has in its environment and can copy there — sends every call of that run
through the proxy on the host's account. Akira's computer did that for 21
runs the hub had routed to his own Pro (2026-11-06 → 11-10, $274;
homelab ``data/log/2026-11-10-akira-budget-proxy-leak.md``).
The ``--settings`` flag outranks the files, and an empty value there unsets
the variable for the CLI (checked on 2.1.x: the run then signs in with the
machine's credentials). So an own-login run, and *My own Claude* in the
terminal launcher, carry ``{"env": {key: ""}}`` for each key a source sets
to the hub's pair (:func:`neutraliser`), and drop it from the process env
(:func:`strip_env`). Managed settings outrank the flag too — they're only
reported.
Only the hub's own pair is touched: a base URL on the hub's ``/proxy/claude``
path, the token beside it in the same source, and the proxy token wherever
it appears. A login of the machine's own (a ``CLAUDE_CODE_OAUTH_TOKEN`` from
``claude setup-token``, a gateway of theirs) is left alone.
Stdlib only: the terminal launcher (``worker/claude_launcher.py``) imports it.
"""
from __future__ import annotations
import json
import os
import pathlib
import sys
from urllib.parse import urlsplit
BASE_KEY = "ANTHROPIC_BASE_URL"
TOKEN_KEYS = ("CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_AUTH_TOKEN")
PROXY_PATH = "/proxy/claude"
MANAGED = (pathlib.Path("/Library/Application Support/ClaudeCode/managed-settings.json")
if sys.platform == "darwin"
else pathlib.Path("/etc/claude-code/managed-settings.json"))
def hub_hosts(*urls: str | None) -> set[str]:
"""The hosts (``netloc``, lowercased) the hub's proxy is reached at."""
return {urlsplit(u).netloc.lower() for u in urls if u and urlsplit(u).netloc}
def is_hub_url(value, hosts: set[str]) -> bool:
"""A base URL on the hub's Claude proxy path — on one of ``hosts`` (any
host when none is known: the path is ours alone)."""
if not isinstance(value, str) or not value.strip():
return False
u = urlsplit(value.strip())
if not u.path.rstrip("/").startswith(PROXY_PATH):
return False
return not hosts or u.netloc.lower() in hosts
def _env_of(path: pathlib.Path) -> dict:
try:
data = json.loads(path.read_text())
except (OSError, ValueError):
return {}
env = data.get("env") if isinstance(data, dict) else None
return env if isinstance(env, dict) else {}
def settings_files(config_dir: pathlib.Path, cwd: str | None) -> list[tuple[str, pathlib.Path]]:
"""Every settings file a run in ``cwd`` may read ``env`` from, labelled:
the user's, the project's (``cwd`` and the folders above it, up to the
home folder — more than the CLI reads, which only costs a needless
override) and the managed one."""
out = [("user", config_dir / "settings.json")]
home = pathlib.Path.home().resolve()
if cwd:
try:
d = pathlib.Path(cwd).expanduser().resolve()
except OSError:
d = None
seen = {out[0][1]}
while d is not None and d != home and d != d.parent:
for name in ("settings.json", "settings.local.json"):
if d / ".claude" / name not in seen:
out.append(("project", d / ".claude" / name))
d = d.parent
out.append(("managed", MANAGED))
return out
def _keys_in(env: dict, hosts: set[str], tokens: set[str]) -> list[str]:
"""The keys of one ``env`` that make up the hub's pair."""
keys = []
if is_hub_url(env.get(BASE_KEY), hosts):
keys.append(BASE_KEY)
keys += [k for k in TOKEN_KEYS if env.get(k)]
keys += [k for k in TOKEN_KEYS if k not in keys and env.get(k) and env[k] in tokens]
return keys
def find(config_dir: pathlib.Path, cwd: str | None, hosts: set[str],
tokens: set[str], environ: dict | None = None) -> list[dict]:
"""Where the hub's pair is set: ``[{source, path, keys}]`` — ``source``
one of ``user`` / ``project`` / ``managed`` / ``env`` (the process
environment, ``path`` None)."""
tokens = {t for t in tokens if t}
hits = []
for source, path in settings_files(config_dir, cwd):
keys = _keys_in(_env_of(path), hosts, tokens)
if keys:
hits.append({"source": source, "path": str(path), "keys": keys})
keys = _keys_in(environ if environ is not None else dict(os.environ), hosts, tokens)
if keys:
hits.append({"source": "env", "path": None, "keys": keys})
return hits
def neutraliser(hits: list[dict]) -> dict[str, str]:
"""``--settings`` ``env`` that unsets what the settings files set (the
process env is :func:`strip_env`'s; managed settings can't be beaten)."""
return {k: "" for h in hits if h["source"] in ("user", "project") for k in h["keys"]}
def strip_env(env: dict, hits: list[dict]) -> dict:
"""``env`` without the pair the process environment carries, in place."""
for h in hits:
if h["source"] == "env":
for k in h["keys"]:
env.pop(k, None)
return env
def with_env(args: list[str], extra: dict[str, str]) -> list[str]:
"""``args`` with ``extra`` merged into its ``--settings`` JSON (added when
there is none). A ``--settings`` given as a file path (or ``=``-joined)
is the caller's: left alone, ``extra`` dropped — None says so."""
if not extra:
return args
if any(a.startswith("--settings=") for a in args):
return None
if "--settings" in args:
i = args.index("--settings") + 1
try:
s = json.loads(args[i])
except (IndexError, ValueError):
return None
if not isinstance(s, dict):
return None
s["env"] = {**(s.get("env") or {}), **extra}
return [*args[:i], json.dumps(s, separators=(",", ":")), *args[i + 1:]]
return ["--settings", json.dumps({"env": extra}, separators=(",", ":")), *args]
def origin(ppid: int, keys: list[str]) -> dict:
"""Where a process that carries the pair got it — ``startedBy`` (its
parent's name: ``systemd`` / ``launchd`` for the service, a shell or
``claude`` when it was started by hand) and ``serviceManager`` (True when
``systemctl --user show-environment`` holds one of ``keys``: every user
service started since inherits it; None when it can't tell). Names only,
never values."""
import subprocess
out: dict = {"startedBy": None, "serviceManager": None}
try:
out["startedBy"] = pathlib.Path(f"/proc/{ppid}/comm").read_text().strip() or None
except OSError:
try:
out["startedBy"] = subprocess.run(["ps", "-o", "comm=", "-p", str(ppid)],
capture_output=True, text=True,
timeout=3).stdout.strip() or None
except (OSError, subprocess.SubprocessError):
pass
if sys.platform != "darwin":
try:
r = subprocess.run(["systemctl", "--user", "show-environment"],
capture_output=True, text=True, timeout=3)
if r.returncode == 0:
names = {line.split("=", 1)[0] for line in r.stdout.splitlines()}
out["serviceManager"] = any(k in names for k in keys)
except (OSError, subprocess.SubprocessError):
pass
return out
def public(hits: list[dict]) -> list[dict]:
"""``/health``'s view of :func:`find`: sources and keys, never values."""
return [{"source": h["source"], "path": h["path"], "keys": list(h["keys"]),
**{k: h[k] for k in ("startedBy", "serviceManager") if k in h}}
for h in hits]