354 lines
16 KiB
Python
354 lines
16 KiB
Python
"""
|
|
harness-opencode's sidecar driver — the ``SidecarHarness`` that launches
|
|
``opencode run --standalone`` for ``/spawn`` / ``/resume`` / ``/fork``, answers
|
|
the routes of the opencode accounts (ChatGPT device-code login, status,
|
|
logout, the hub proxy's access token) and mirrors each account's
|
|
``opencode.db`` into v1 transcripts.
|
|
|
|
Self-contained (typed-plugins spec §3, Wave 2D): its own ``cli`` / ``mirror``
|
|
/ ``tools`` / ``usage`` / ``mcp`` (the hub's MCP servers) modules (relative imports, loaded by
|
|
``harness_loader`` under ``sidecar_ext.harness.harness_opencode``), and only
|
|
the sidecar's shared core besides — ``config``, ``launch``, ``pids``,
|
|
``run_errors`` (error bodies), ``claude_env._run_env``,
|
|
``opencode_proxy``, ``mirror_base``, ``transcript_v1``. It never imports the
|
|
sidecar's old ``opencode_cli`` / ``opencode_mirror`` / ``opencode_tools`` or
|
|
``harness_builtin``, so it runs with ``SIDECAR_HARNESS_BUILTINS=0``.
|
|
|
|
Everything it answers is what the built-in bridge answered: same argv, env,
|
|
status codes and bodies, same transcripts byte for byte.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import time
|
|
|
|
from fastapi import HTTPException
|
|
|
|
from harness_base import SidecarHarness
|
|
|
|
from . import cli
|
|
from . import mirror as oc_mirror
|
|
from . import usage
|
|
|
|
# A token this close to its expiry is refreshed first — inside opencode's own
|
|
# 5-minute window, so its `auth list` boot really does refresh it.
|
|
TOKEN_MARGIN_S = 240
|
|
|
|
|
|
def _no_scope(scope, harness: str = "opencode") -> None:
|
|
"""A scope confines a claude run: dropped here, the run would start with
|
|
the owner's full rights — refuse instead."""
|
|
if scope is not None:
|
|
raise HTTPException(400, f"a scoped run can't use the {harness} harness here")
|
|
|
|
|
|
class OpencodeDriver(SidecarHarness):
|
|
harness_id = "opencode"
|
|
catch_all_accounts = False
|
|
|
|
def __init__(self, ctx=None):
|
|
self.ctx = ctx
|
|
self.mirror = None
|
|
self._mcp = None
|
|
if ctx is not None:
|
|
cli.set_context_providers(getattr(ctx, "providers", None))
|
|
|
|
# ── helpers ──
|
|
def _config(self):
|
|
if self.ctx is not None:
|
|
return self.ctx.config
|
|
import config
|
|
return config
|
|
|
|
# ── life: the transcript mirror (each account's database → v1 JSONL) ──
|
|
def _account_mirror(self, a: str):
|
|
cfg = self._config()
|
|
return oc_mirror.AccountMirror(
|
|
a, cli.db_path(a), cfg.OPENCODE_RUNNER_DIR / "transcripts" / a,
|
|
cfg.OPENCODE_RUNNER_DIR / "state", cli.FORKS_PATH)
|
|
|
|
def mirror_accounts(self, accounts) -> None:
|
|
"""Accounts the hub's opencode proxy just gave this worker: mirrored
|
|
like the declared ones (opencode_proxy.py)."""
|
|
if not self._config().OPENCODE_MIRROR:
|
|
return
|
|
if self.mirror is None:
|
|
self.mirror = oc_mirror.MirrorThread([])
|
|
for a in accounts:
|
|
self.mirror.add(self._account_mirror(a))
|
|
|
|
def startup(self, ctx) -> None:
|
|
import opencode_proxy
|
|
self.ctx = ctx
|
|
cli.set_context_providers(getattr(ctx, "providers", None))
|
|
self.mirror_accounts(opencode_proxy.accounts())
|
|
cfg = self._config()
|
|
if cfg.OPENCODE_ACCOUNTS:
|
|
self.mirror_accounts(list(cfg.OPENCODE_ACCOUNTS))
|
|
|
|
def shutdown(self) -> None:
|
|
if self.mirror is not None:
|
|
self.mirror.stop()
|
|
self.mirror = None
|
|
|
|
def kick(self) -> None:
|
|
"""Mirror now rather than at the next poll."""
|
|
if self.mirror is not None:
|
|
self.mirror.kick()
|
|
|
|
# ── runs ──
|
|
def valid_model(self, model):
|
|
return cli.valid_model(model)
|
|
|
|
def prepare(self, body, sid: str, cwd: str, ctx, *, append: bool = False) -> dict:
|
|
"""Everything a run needs, checked before anything is stopped (a forced
|
|
resume must not kill the live turn, then fail validation): the account
|
|
and its login, the session (``ses_<sid>``, a fork's or a terminal
|
|
session's own id), the model + effort — a continue with none picked
|
|
keeps the session's own, as ``claude --resume`` does."""
|
|
from claude_env import _run_env
|
|
cfg = ctx.config
|
|
account = cli.valid_account(body.account)
|
|
session = cli.session_id(sid, account)
|
|
own_model, own_effort = (cli.session_model(account, session)
|
|
if append else (None, None))
|
|
keyless = cli.keyless(account)
|
|
model = (cli.valid_model(body.model) or own_model
|
|
or (cfg.OPENCODE_LOCAL_MODEL if keyless else cfg.OPENCODE_DEFAULT_MODEL))
|
|
# The ChatGPT login is what a bare (or `openai/`) model runs on; a model
|
|
# on another provider brings its own credentials. A keyless account has
|
|
# no login to fail: a GPT model there is the wrong pick, not a sign-out.
|
|
if cli.uses_login(model):
|
|
if keyless:
|
|
raise HTTPException(400, f"opencode account {account!r} has no ChatGPT login: "
|
|
f"pick one of its local models, not {model!r}")
|
|
if not cli.credential(account):
|
|
import run_errors
|
|
raise HTTPException(409, run_errors.error_detail(
|
|
f"opencode account {account!r} is not logged in", kind="auth",
|
|
account=account))
|
|
# The default effort is a GPT reasoning level; a local model's default
|
|
# (no variant) is thinking off, its `think` variant thinking on.
|
|
effort = (cli.valid_effort(body.effort)
|
|
or (own_effort if not body.model else None)
|
|
or (cli.valid_effort(cfg.OPENCODE_DEFAULT_EFFORT)
|
|
if cli.uses_login(model) else None))
|
|
return {"args": cli.run_args(sid, model, effort, session=session),
|
|
"env": cli.run_env(account, _run_env(sid, None), cwd, model,
|
|
# a machine with an agent limit: no native
|
|
# subagents (cli.run_config)
|
|
no_subagents=bool(getattr(body, "agentLimit", None))),
|
|
"model": model, "account": account, "append": append}
|
|
|
|
def launch(self, body, sid: str, cwd: str, ctx, *, append: bool = False,
|
|
prepared: dict | None = None) -> dict:
|
|
"""``opencode run --standalone`` on the account's database, the prompt
|
|
on stdin, the session created as ``ses_<sid>`` on first use (``-s``
|
|
creates an unknown id) — so spawn and resume are the same call."""
|
|
p = prepared or self.prepare(body, sid, cwd, ctx, append=append)
|
|
return ctx.launch._launch(p["args"], sid, cwd, model=p["model"], append=p["append"],
|
|
account=p["account"], harness="opencode", env=p["env"],
|
|
stdin_text=body.prompt.strip(), failure=cli.run_failure)
|
|
|
|
def spawn(self, body, sid, cwd, ctx):
|
|
_no_scope(body.scope)
|
|
return self.launch(body, sid, cwd, ctx)
|
|
|
|
def resume(self, body, sid, cwd, ctx):
|
|
_no_scope(body.scope) # before anything is stopped
|
|
prepared = self.prepare(body, sid, cwd, ctx, append=True)
|
|
reused = ctx.take_over(sid, body.force)
|
|
if reused:
|
|
return reused
|
|
return self.launch(body, sid, cwd, ctx, append=True, prepared=prepared)
|
|
|
|
def fork(self, body, sid, new_sid, cwd, ctx):
|
|
"""opencode forks natively (settled history strictly before a message)
|
|
under an id it mints; the map lets the mirror file the fork under the
|
|
UUID the hub chose, and lets later resumes find it."""
|
|
_no_scope(body.scope)
|
|
account = cli.valid_account(body.account)
|
|
new_ses = cli.fork_session(
|
|
account, dict(os.environ), sid, cli.session_id(sid, account),
|
|
body.cutUserOrd or 0, body.cutText, cwd, cut_key=body.cutKey)
|
|
cli.record_fork(new_sid, new_ses)
|
|
# the fork carries its source's model: a pick-less fork keeps it
|
|
prepared = self.prepare(body, new_sid, cwd, ctx, append=True)
|
|
return self.launch(body, new_sid, cwd, ctx, prepared=prepared)
|
|
|
|
def mcp_adapter(self):
|
|
"""The hub's MCP servers for opencode accounts (``mcp.py``: kept in a
|
|
file of ours, merged into each run's config) — None on a sidecar
|
|
without ``mcp_base``. Imported here: MCP never stops the driver loading."""
|
|
if self._mcp is None:
|
|
try:
|
|
from . import mcp
|
|
self._mcp = mcp.adapter() or False
|
|
except Exception: # noqa: BLE001
|
|
import logging
|
|
logging.getLogger("harness-opencode").exception("mcp adapter")
|
|
self._mcp = False
|
|
return self._mcp or None
|
|
|
|
def health_meta(self):
|
|
cfg = self._config()
|
|
return {"opencode": cfg.OPENCODE_BIN if cfg.OPENCODE_ACCOUNTS else None,
|
|
"opencodeAccounts": list(cfg.OPENCODE_ACCOUNTS)}
|
|
|
|
def setup_check(self, tc) -> dict:
|
|
"""The worker's Setup checklist row (sidecar tools_check, ``tc``):
|
|
the binary (``OPENCODE_BIN``, else ~/.opencode/bin), ``harness`` —
|
|
declared in this service (SIDECAR_OPENCODE_ACCOUNTS) — and that
|
|
account's credential (the hub's proxy counts)."""
|
|
import pathlib
|
|
cfg = self._config()
|
|
p = tc._which(cfg.OPENCODE_BIN) if cfg.OPENCODE_BIN else None
|
|
if not p:
|
|
alt = pathlib.Path.home() / ".opencode" / "bin" / "opencode"
|
|
p = str(alt) if os.access(alt, os.X_OK) else None
|
|
return tc.harness_row("opencode", p, cfg.OPENCODE_ACCOUNTS,
|
|
lambda a: tc._status("opencode", a))
|
|
|
|
def complete(self, system, prompt, model=None, account=None, timeout=30):
|
|
"""One short answer (the sidecar's ``/complete``): ``opencode run
|
|
--standalone --format json`` on a **throwaway database** in a temp dir
|
|
— no session in the account's store for the mirror to pick up. So only
|
|
a model that brings its own credentials (the local GPU machine's, a keyed
|
|
provider): a ChatGPT-login model would need the login's rotating
|
|
refresh token in that copy, which could sign the account out — 409."""
|
|
import json
|
|
import subprocess
|
|
import tempfile
|
|
cfg = self._config()
|
|
acct = cli.valid_account(account) if account else None
|
|
model = cli.valid_model(model) or (cfg.OPENCODE_LOCAL_MODEL if acct and cli.keyless(acct)
|
|
else None)
|
|
if not model or cli.uses_login(model):
|
|
raise HTTPException(409, {"message": "opencode one-shots run on a local or keyed "
|
|
"provider's model, not the ChatGPT login",
|
|
"kind": "login_model"})
|
|
run_cfg = {k: v for k, v in cli.run_config(model, None).items() if k != "instructions"}
|
|
text = f"<system>\n{system}\n</system>\n\n{prompt}" if system else prompt
|
|
with tempfile.TemporaryDirectory(prefix="sidecar-complete-") as d:
|
|
env = {**dict(os.environ), "OPENCODE_DISABLE_AUTOUPDATE": "1", "NO_COLOR": "1",
|
|
"OPENCODE_DB": f"{d}/opencode.db", "PWD": d,
|
|
"OPENCODE_CONFIG_CONTENT": json.dumps(run_cfg, separators=(",", ":"))}
|
|
env.pop("OPENAI_API_KEY", None)
|
|
try:
|
|
r = subprocess.run([cfg.OPENCODE_BIN, "run", "--standalone", "--format", "json",
|
|
"-m", cli.model_ref(model, None)],
|
|
input=text, cwd=d, env=env, capture_output=True, text=True,
|
|
timeout=timeout)
|
|
except subprocess.TimeoutExpired:
|
|
raise HTTPException(504, {"message": "opencode timed out", "kind": "timeout"})
|
|
parts, usage, cost = [], None, None
|
|
for ln in (r.stdout or "").splitlines():
|
|
try:
|
|
e = json.loads(ln)
|
|
except ValueError:
|
|
continue
|
|
part = e.get("part") if isinstance(e, dict) else None
|
|
if not isinstance(part, dict):
|
|
continue
|
|
if e.get("type") == "text" and part.get("text"):
|
|
parts.append(part["text"])
|
|
tok = part.get("tokens")
|
|
if isinstance(tok, dict):
|
|
c = tok.get("cache") or {}
|
|
usage = {"input_tokens": int(tok.get("input") or 0),
|
|
"output_tokens": int(tok.get("output") or 0)
|
|
+ int(tok.get("reasoning") or 0),
|
|
"cache_read_input_tokens": int(c.get("read") or 0),
|
|
"cache_creation_input_tokens": int(c.get("write") or 0)}
|
|
if isinstance(part.get("cost"), (int, float)):
|
|
cost = float(part["cost"])
|
|
text_out = "".join(parts).strip()
|
|
if not text_out:
|
|
msg, kind = cli.run_failure((r.stdout or "") + "\n" + (r.stderr or ""))
|
|
raise HTTPException(502, {"message": msg or "opencode failed", "kind": kind or "opencode"})
|
|
return {"text": text_out, "model": model, "account": acct or "opencode",
|
|
"usage": usage, "costUsd": cost}
|
|
|
|
# ── accounts ──
|
|
def owns_account(self, account):
|
|
return cli.known(account)
|
|
|
|
def _status(self, account):
|
|
"""An opencode account's login (read from its database) and the last
|
|
read of its ChatGPT usage."""
|
|
return {**cli.status(account), "usage": usage.last(account)}
|
|
|
|
def accounts_list(self):
|
|
return [self._status(a) for a in self._config().OPENCODE_ACCOUNTS]
|
|
|
|
def account_status(self, account, fresh=False):
|
|
return self._status(account)
|
|
|
|
def account_probe(self, account):
|
|
"""*Check again*: a fresh read of its ChatGPT usage — a real
|
|
authenticated call that costs nothing (no model turn), and that fails
|
|
with 401 once the login is dead. A keyless account has no login and no
|
|
plan: nothing to check."""
|
|
if cli.keyless(account):
|
|
return {"ok": True, **self._status(account)}
|
|
snap = usage.fetch(account)
|
|
if snap is not None and snap["rate_limits"]:
|
|
usage.write(account, snap)
|
|
last = usage._last.get(account) or {}
|
|
if snap is not None:
|
|
return {"ok": True, **self._status(account)}
|
|
err = last.get("error") or "usage read failed"
|
|
kind = "auth" if err in ("HTTP 401", "HTTP 403", "logged out") else "unknown"
|
|
return {"ok": False, "kind": kind, "message": err, **self._status(account)}
|
|
|
|
def account_login_start(self, account, body):
|
|
return cli.start_login(account, dict(os.environ))
|
|
|
|
def account_login_status(self, account):
|
|
out = cli.login_result(account)
|
|
if out["state"] == "complete":
|
|
return {**out, **self._status(account)}
|
|
return out
|
|
|
|
def account_login_cancel(self, account):
|
|
return {"cancelled": cli.cancel_login(account)}
|
|
|
|
def account_logout(self, account):
|
|
cli.cancel_login(account)
|
|
msg = cli.logout(account, dict(os.environ))
|
|
return {**self._status(account), "message": msg}
|
|
|
|
def access_token(self, account, refresh=False):
|
|
"""The ChatGPT access token and account id, for the hub's opencode
|
|
proxy. Host only, declared logged-in accounts only. A token about to
|
|
expire — or one upstream refused — is refreshed by opencode itself,
|
|
never here: the refresh token rotates."""
|
|
import run_errors
|
|
cfg = self._config()
|
|
if cfg.IS_WORKER:
|
|
raise HTTPException(409, "a worker's logins are not the hub's to use")
|
|
account = (account or "").strip().lower()
|
|
if account not in cfg.OPENCODE_ACCOUNTS or cli.keyless(account):
|
|
raise HTTPException(404, f"no ChatGPT login {account!r} on this host")
|
|
|
|
def read() -> dict:
|
|
v = (cli.credential(account) or {}).get("value") or {}
|
|
return {"accessToken": v.get("access"), "expiresAt": v.get("expires"),
|
|
"accountId": (v.get("metadata") or {}).get("accountID") or v.get("accountId")}
|
|
|
|
cur = read()
|
|
exp = cur["expiresAt"]
|
|
stale = not isinstance(exp, (int, float)) or exp / 1000 - time.time() < TOKEN_MARGIN_S
|
|
if cur["accessToken"] and (refresh or stale):
|
|
cli.refresh_token(account, dict(os.environ))
|
|
cur = read()
|
|
if not cur["accessToken"]:
|
|
raise HTTPException(409, run_errors.error_detail(
|
|
f"opencode account {account!r} is not logged in", kind="auth", account=account))
|
|
return cur
|
|
|
|
|
|
def create(ctx) -> OpencodeDriver:
|
|
return OpencodeDriver(ctx)
|