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

250 lines
9.1 KiB
Python

"""
The opencode proxy, the worker's half — a worker's opencode bills the
Homelab's ChatGPT login instead of one of its own (``claude_proxy.py``'s twin).
The hub (``backend/claudeproxy/opencode.py``) proxies the Codex backend
(``chatgpt.com/backend-api/codex``): it takes a worker's request, checks the
worker may use the account named in the path, swaps the worker's bearer for
the account's real access token and ChatGPT account id, and streams the reply
back. When ``/health``'s ``opencodeProxy.hash`` differs, the hub POSTs:
POST /opencode-proxy {url, token, accounts}
kept in the worker's state dir (``opencode-proxy.json``, 0600). Each proxied
account gets a database of its own (``WORKER_OPENCODE_PROXY_DIR/<account>``,
so a login of the machine's own is never touched) holding one placeholder
ChatGPT credential — the worker's proxy token as its access token, an expiry
far enough out that opencode never refreshes it — written through opencode's
own API (``opencode api POST /api/credential``). A run on the account then
carries (``run_provider``)::
{"provider": {"openai": {"options": {"baseURL": "<url>/<account>", "transport": "http"}}}}
— opencode 2.x keeps its Codex request shape (headers, body) behind a custom
base URL, and ``http`` skips its WebSocket attempt, so the hub only swaps
credentials. Measured on opencode 2.0.32 (2026-11-02): every request lands on
``<baseURL>/responses``. Terminal sessions aren't proxied: a terminal
``opencode`` uses the machine's own database.
Refused on the host sidecar: its opencode accounts are its own logins.
"""
from __future__ import annotations
import hashlib
import json
import os
import pathlib
import re
import sqlite3
import subprocess
from typing import Callable
from fastapi import APIRouter, Header, HTTPException
from pydantic import BaseModel
import pairing
from config import IS_WORKER, OPENCODE_BIN
_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}$")
# 2100-01-01: opencode refreshes a credential within 5 min of its expiry —
# never, then. The placeholder's refresh token is not one.
_FAR_EXPIRY_MS = 4102444800000
LABEL = "hub-proxy"
_cache: tuple[float, dict] | None = None
def _path() -> pathlib.Path:
return pairing.state_dir() / "opencode-proxy.json"
def data_root() -> pathlib.Path:
return pathlib.Path(os.path.expanduser(os.environ.get(
"WORKER_OPENCODE_PROXY_DIR", "~/.local/share/ai-agent-worker/opencode")))
def data_dir(account: str) -> pathlib.Path:
"""A proxied account's opencode data dir (its ``opencode.db``)."""
return data_root() / account
def config() -> dict:
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())
cfg = cfg if isinstance(cfg, dict) else {}
except (OSError, ValueError):
cfg = {}
_cache = (mtime, cfg)
return cfg
def fingerprint(url: str, token: str, accounts: list[str]) -> str:
"""Identical to the hub's (``claudeproxy/opencode.py``)."""
raw = json.dumps([url, hashlib.sha256(token.encode()).hexdigest(), sorted(accounts)])
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:
return bool(account) and account in accounts()
def run_provider(account: str) -> dict:
"""The ``provider`` block a proxied account's run config carries."""
url = config()["url"].rstrip("/")
return {"openai": {"options": {"baseURL": f"{url}/{account}", "transport": "http"}}}
def available() -> bool:
"""Is there an opencode on this machine to proxy at all?"""
from shutil import which
return bool(which(OPENCODE_BIN) or pathlib.Path(OPENCODE_BIN).is_file())
def public() -> dict | None:
"""``/health``'s ``opencodeProxy`` (workers only)."""
if not IS_WORKER:
return None
cfg = config()
out = {"available": available(), "hash": None, "accounts": []}
if cfg.get("url"):
out.update({"hash": fingerprint(cfg["url"], cfg.get("token") or "", cfg.get("accounts") or []),
"url": cfg["url"], "accounts": cfg.get("accounts") or [],
"error": cfg.get("error")})
return out
def _credential_env(account: str) -> dict[str, str]:
d = data_dir(account)
d.mkdir(parents=True, exist_ok=True)
env = {k: v for k, v in os.environ.items() if k not in ("OPENAI_API_KEY", "SIDECAR_TOKEN")}
env.update({"OPENCODE_DB": str(d / "opencode.db"), "OPENCODE_DISABLE_AUTOUPDATE": "1",
"NO_COLOR": "1"})
return env
def _credential(account: str) -> dict | None:
"""The proxied account's active ChatGPT credential row in its own
database (``value`` decoded), or None. Read-only."""
p = data_dir(account) / "opencode.db"
if not p.is_file():
return None
try:
db = sqlite3.connect(f"file:{p}?mode=ro", uri=True, timeout=5)
try:
rows = db.execute(
"SELECT value, active FROM credential WHERE integration_id='openai'"
" ORDER BY active DESC, time_updated DESC").fetchall()
finally:
db.close()
except sqlite3.Error:
return None
for value, active in rows:
try:
v = json.loads(value)
except ValueError:
continue
return {"active": bool(active), "value": v if isinstance(v, dict) else {}}
return None
def ensure_credential(account: str, token: str) -> None:
"""The placeholder ChatGPT login in the account's own database — added
(and made the active one) unless it already holds this token."""
cred = _credential(account)
if cred and (cred.get("value") or {}).get("access") == token and cred.get("active"):
return
body = {"integrationID": "openai", "label": LABEL, "activate": True,
"value": {"type": "oauth", "methodID": "chatgpt-headless", "refresh": LABEL,
"access": token, "expires": _FAR_EXPIRY_MS}}
try:
r = subprocess.run([OPENCODE_BIN, "api", "POST", "/api/credential", "--standalone",
"-d", json.dumps(body)],
capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL,
env=_credential_env(account), cwd=str(pathlib.Path.home()))
except (OSError, subprocess.TimeoutExpired) as e:
raise RuntimeError(f"opencode credential for {account}: {e}") from e
if r.returncode != 0:
raise RuntimeError(f"opencode credential for {account}: "
f"{(r.stderr or r.stdout or '').strip()[:200]}")
class ProxyBody(BaseModel):
url: str
token: str
accounts: list[str] = []
def save(body: ProxyBody, on_accounts: Callable[[list[str]], None] | None = None) -> 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}
errors = []
for a in accts:
try:
ensure_credential(a, body.token)
except RuntimeError as e:
errors.append(str(e))
if errors:
cfg["error"] = "; ".join(errors)[:300]
pairing._write_private(_path(), json.dumps(cfg))
if on_accounts:
on_accounts(accts)
return public() or {}
def clear() -> None:
"""Forget the hub's opencode proxy (unpair, or nothing ticked). The
accounts' databases stay — their sessions are the transcripts' history."""
_path().unlink(missing_ok=True)
def make_router(auth: Callable[[str | None], None],
on_accounts: Callable[[list[str]], None] | None = None) -> APIRouter:
router = APIRouter()
@router.post("/opencode-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")
if not available():
raise HTTPException(409, {"message": "opencode is not installed on this worker",
"kind": "opencode_missing",
"hint": "WORKER_OPENCODE=1 ai-agent-worker update"})
out = save(body, on_accounts)
print(f"[worker] opencode proxy: {', '.join(out.get('accounts') or []) or 'no account'}",
flush=True)
return {"opencodeProxy": out}
@router.delete("/opencode-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()
return {"opencodeProxy": public()}
return router