Files
gabrielvidalandClaude Opus 5.5 58d091b1d9 feat(claudeproxy): /proxy/opencode — the Codex backend on the lab's ChatGPT login
A worker ticks the Homelab's opencode accounts (opencodeProxyAccounts); the
hub pushes the config and swaps Authorization and chatgpt-account-id on
responses[/compact] calls. The lab-held seat's usage is read from the lab
sidecar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 19:18:29 +01:00

149 lines
5.7 KiB
Python

"""
The opencode proxy — a worker's opencode bills the Homelab's ChatGPT login
(the Claude proxy's twin, ``service.py``).
A ChatGPT seat used to be a login on the machine that runs it (the Orus
MacBook's opencode database). A worker can now bill one the **Homelab**
holds instead — an opencode account its sidecar declares
(``SIDECAR_OPENCODE_ACCOUNTS``) with a real login, signed in from Settings →
Accounts — ticked on the worker's page (``opencodeProxyAccounts``):
* each probe compares ``/health``'s ``opencodeProxy.hash`` with what the hub
would send (``{url, token, accounts}`` — the worker's ``proxyToken``, the
same bearer as the Claude proxy) and POSTs ``/opencode-proxy`` (or
``DELETE``s it when nothing is ticked). The worker gives each such account
a database of its own holding a placeholder login (its proxy token, an
expiry opencode never refreshes) and runs it with the ChatGPT provider's
``baseURL`` at ``<url>/<account>`` (``sidecar/opencode_proxy.py``);
* ``routes.py`` takes ``/proxy/opencode/<account>/responses[/compact]``,
swaps the bearer for the account's access token and ``chatgpt-account-id``
— read through the host sidecar (``GET /opencode/accounts/{id}/access-token``;
opencode does every refresh) — and streams the Codex backend's reply.
A worker's own opencode logins (its ``/health`` ``opencodeAccounts``) are
untouched; terminal ``opencode`` on a worker keeps the machine's database.
"""
from __future__ import annotations
import json
import os
import time
from fastapi import HTTPException
import accounts as accounts_mod
from core.config import SIDECAR_TOKEN, SIDECAR_URL
from . import service
PROXY_URL = (os.environ.get("OPENCODE_PROXY_URL") or os.environ.get(
"AI_AGENT_VIEW_URL", "https://ai-agent.lab.gabvdl.xyz").rstrip("/") + "/proxy/opencode").rstrip("/")
UPSTREAM = os.environ.get("OPENCODE_PROXY_UPSTREAM",
"https://chatgpt.com/backend-api/codex").rstrip("/")
CURRENT, OUTDATED, FAILED, UNSUPPORTED, OFF, MISSING = (
"current", "outdated", "failed", "unsupported", "off", "no_opencode")
def proxyable(account: str | None) -> bool:
"""An opencode account with a real login (not a keyless one)."""
a = accounts_mod.valid_for(account, "opencode")
return bool(a) and not (accounts_mod.get(a) or {}).get("keyless")
def clean_accounts(raw) -> list[str]:
want = {a for a in (raw or []) if proxyable(a)}
return [a for a in accounts_mod.for_harness("opencode") if a in want]
def proxied_accounts(w: dict | None) -> list[str]:
return clean_accounts((w or {}).get("opencodeProxyAccounts"))
def desired(w: dict) -> dict:
return {"url": PROXY_URL, "token": w.get("proxyToken") or "", "accounts": proxied_accounts(w)}
def _hash(d: dict) -> str:
"""Identical to ``sidecar/opencode_proxy.fingerprint``."""
import hashlib
raw = json.dumps([d["url"], hashlib.sha256(d["token"].encode()).hexdigest(),
sorted(d["accounts"])])
return hashlib.sha256(raw.encode()).hexdigest()[:16]
def status(w: dict, st: dict) -> str:
held = st.get("opencodeProxy")
if not proxied_accounts(w):
return OFF if not (held or {}).get("accounts") else OUTDATED
if held is None:
return UNSUPPORTED
if held.get("available") is False:
return MISSING
d = desired(w)
if d["token"] and held.get("hash") == _hash(d) and not held.get("error"):
return CURRENT
return FAILED if (st.get("opencodeProxyError") or held.get("error")) else OUTDATED
_attempts: dict[str, tuple[str, float]] = {}
def push(store, w: dict) -> dict:
from workers.store import sidecar_request
w = service.ensure_token(store, w)
d = desired(w)
label = f"worker {w.get('name') or w['id']}"
try:
if d["accounts"]:
out = sidecar_request(w["url"], w["token"], "/opencode-proxy", d, timeout=90,
label=label)
else:
out = sidecar_request(w["url"], w["token"], "/opencode-proxy", None,
method="DELETE", timeout=10, label=label)
except HTTPException as e:
msg = e.detail.get("message") if isinstance(e.detail, dict) else str(e.detail)
store.set_status(w["id"], opencodeProxyError=(msg or "push failed")[:200])
raise
store.set_status(w["id"], opencodeProxy=out.get("opencodeProxy"), opencodeProxyError=None)
return out
def maybe_push(store, w: dict) -> bool:
if not store.online(w["id"]):
return False
w = service.ensure_token(store, w)
if status(w, store.status(w["id"])) not in (OUTDATED, FAILED):
return False
h = _hash(desired(w))
last = _attempts.get(w["id"])
if last and last[0] == h and time.time() - last[1] < service.RETRY_S:
return False
_attempts[w["id"]] = (h, time.time())
try:
push(store, w)
except HTTPException:
return False
return True
def public(w: dict, st: dict) -> dict:
held = st.get("opencodeProxy")
return {"accounts": proxied_accounts(w), "status": status(w, st),
"held": (held or {}).get("accounts") if held else None,
"available": (held or {}).get("available") if held else None,
"error": st.get("opencodeProxyError") or (held or {}).get("error"),
"lastUsedAt": st.get("opencodeProxyLastAt")}
def _fetch_token(account: str, refresh: bool = False) -> dict:
from workers.store import sidecar_request
if not SIDECAR_TOKEN:
raise HTTPException(503, {"message": "sidecar not configured", "kind": "sidecar"})
path = f"/opencode/accounts/{account}/access-token" + ("?refresh=1" if refresh else "")
return sidecar_request(SIDECAR_URL, SIDECAR_TOKEN, path, None, method="GET", timeout=90)
TOKENS = service.TokenCache(fetch=_fetch_token)