Files

824 lines
34 KiB
Python

"""
harness-opencode's account plumbing (ported from the sidecar's
``opencode_cli.py``, Wave 2D — the plugin owns it now): which opencode data a run uses, the
argv / env a run launches with, the headless ChatGPT login, the login status
read straight from opencode's database, and the fork.
**Accounts.** opencode V2 keeps its logins *and* its sessions in one SQLite
file, so an opencode account is a database: ``SIDECAR_OPENCODE_ACCOUNTS``
maps an id to ``default`` (opencode's own ``~/.local/share/opencode`` — a
plain ``opencode`` in a terminal shares it) or to a dir whose ``opencode.db``
the run gets through ``OPENCODE_DB``. A run is ``opencode run --standalone``:
a private server per run, so the per-run env (the account's database, the
session id the notify CLI reads, the cwd in ``PWD``) reaches its tools.
**Login** is OpenAI's Codex device-code flow, the one that works on a box with
no browser: ``opencode auth login openai --method chatgpt-headless`` prints a
code and ``auth.openai.com/codex/device``; the user enters the code on any
device and the CLI exits 0 once the credential is stored. Its token is also
the one ChatGPT's usage endpoint accepts (opencode_usage.py).
"""
from __future__ import annotations
import base64
import json
import os
import pathlib
import re
import sqlite3
import subprocess
import threading
import time
import uuid as uuidlib
from fastapi import HTTPException
import run_errors
import opencode_proxy
from config import (LOCAL_MODEL_GUIDE, OPENCODE_ACCOUNTS, OPENCODE_BIN, OPENCODE_EFFORTS,
OPENCODE_INSTRUCTIONS, OPENCODE_KEYLESS, OPENCODE_MODEL_RE,
OPENCODE_PROVIDER, OPENCODE_RUNNER_DIR, PI_MODELS_FILE)
LOGIN_TTL_S = float(os.environ.get("SIDECAR_OPENCODE_LOGIN_TTL_S", "900"))
_ANSI = re.compile(r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?]*[A-Za-z]")
_CODE = re.compile(r"Enter code:\s*([A-Z0-9]{3,6}-[A-Z0-9]{3,8})")
_URL = re.compile(r"https://auth\.openai\.com/\S+")
_OAUTH_METHODS = ("chatgpt-headless", "chatgpt-browser")
def known(account: str | None) -> bool:
"""A declared account, or one a worker runs through the hub's opencode
proxy (opencode_proxy.py)."""
return (account or "") in OPENCODE_ACCOUNTS or opencode_proxy.proxied(account)
def keyless(account: str | None) -> bool:
"""An account with no ChatGPT login: it runs local models only."""
return (account or "") in OPENCODE_KEYLESS
def valid_account(account: str | None) -> str:
a = (account or "").strip().lower() or next(iter(OPENCODE_ACCOUNTS), "")
if not known(a):
raise HTTPException(400, f"unknown opencode account: {account!r} "
f"(known: {', '.join(OPENCODE_ACCOUNTS) or 'none'})")
return a
def db_path(account: str) -> pathlib.Path:
"""The account's ``opencode.db`` (opencode's own path for ``default``; a
proxied account's own dir — it never shares the machine's login)."""
d = opencode_proxy.data_dir(account) if opencode_proxy.proxied(account) \
else OPENCODE_ACCOUNTS.get(account)
if d is not None:
return d / "opencode.db"
data = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share")
return pathlib.Path(data) / "opencode" / "opencode.db"
def account_env(account: str, base: dict[str, str]) -> dict[str, str]:
"""``base`` with the account's database, and no API key that could win
over the subscription login."""
env = {**base, "OPENCODE_DISABLE_AUTOUPDATE": "1", "NO_COLOR": "1"}
env.pop("OPENAI_API_KEY", None)
d = opencode_proxy.data_dir(account) if opencode_proxy.proxied(account) \
else OPENCODE_ACCOUNTS.get(account)
if d is not None:
d.mkdir(parents=True, exist_ok=True)
env["OPENCODE_DB"] = str(d / "opencode.db")
else:
env.pop("OPENCODE_DB", None)
return env
def _thinking(on: bool) -> dict:
return {"chat_template_kwargs": {"enable_thinking": on}}
# The levels an effort-scaled local model's twin offers (catalog `twinEfforts`).
EFFORT_LEVELS = ("none", "low", "medium", "high")
def _effort(level: str) -> dict:
return {"chat_template_kwargs": {"reasoning_effort": level}}
def _reasoning(m: dict) -> tuple[dict, dict]:
"""A pi model's default opencode ``options`` and its ``variants``.
A Qwen (``enable_thinking``) thinks only when asked: off by default, the
``think`` variant turns it on (``none`` is the explicit off) — pi's local
default. Not ``high``: a GPT pick left sticky in the composer would switch
it on. A model whose template takes a ``reasoning_effort`` (Inkling: pi's
``chatTemplateKwargs.reasoning_effort``) gets one variant per level and
its pi ``defaultThinking`` as the default (``off`` → its map's off value)."""
kwargs = (m.get("compat") or {}).get("chatTemplateKwargs") or {}
if "reasoning_effort" in kwargs:
level = m.get("defaultThinking") or "off"
if level == "off":
level = (m.get("thinkingLevelMap") or {}).get("off") or "none"
return _effort(level), {lv: _effort(lv) for lv in EFFORT_LEVELS}
return _thinking(False), {"none": _thinking(False), "think": _thinking(True)}
def _models_json() -> dict:
"""pi's ``models.json`` (``{}`` when unreadable)."""
try:
reg = json.loads(PI_MODELS_FILE.read_text())
return reg if isinstance(reg, dict) else {}
except (OSError, ValueError):
return {}
def _models_json_providers(reg: dict) -> dict:
"""pi's local providers (``evox2*`` in its models.json) as opencode
providers under the same names, so ``<provider>/<pi id>`` runs on the
same server with the same key; thinking per :func:`_reasoning`."""
out: dict = {}
for name, p in (reg.get("providers") or {}).items():
if not name.startswith("evox2") or not p.get("baseUrl"):
continue
models = {}
for m in p.get("models") or []:
entry: dict = {"name": m.get("name") or m["id"],
"limit": {"context": m.get("contextWindow") or 131072,
"output": m.get("maxTokens") or 16384}}
if m.get("reasoning"):
entry["options"], entry["variants"] = _reasoning(m)
models[m["id"]] = entry
if models:
opts = {"baseURL": p["baseUrl"]}
if p.get("apiKey"):
opts["apiKey"] = p["apiKey"]
out[name] = {"npm": "@ai-sdk/openai-compatible", "name": p.get("name") or name,
"options": opts, "models": models}
return out
# ── the local-model provider plugin (provider-evox2) ─────────────────────────
# Its plugin.json names the local servers (``provider.servers``) and the models
# each one serves (``provider.models[].server``, default ``evox2``). Where the
# sidecar has it — the usage-reader registry's provider configs, the
# SidecarContext's, or the live-providers dir the hub materializes — that is
# what an opencode run's local providers come from; pi's models.json only
# lends what a manifest doesn't hold (a server's key, a model's chat-template
# switches, its max output). No plugin ⇒ models.json alone, as before.
LOCAL_VENDOR = "evox2"
_ctx_providers: dict = {}
def set_context_providers(providers: dict | None) -> None:
"""The driver's ``SidecarContext.providers`` (``{vendorId: {pluginId, dir,
config}}``), kept for :func:`evox2_manifest`."""
_ctx_providers.clear()
_ctx_providers.update(providers or {})
def _provider_configs() -> dict:
try:
import usage_loader # core: the live provider plugins' readers
out = usage_loader.provider_configs()
if isinstance(out, dict) and out:
return out
except Exception: # noqa: BLE001 — no registry here: the context's copy
pass
return dict(_ctx_providers)
def _read_manifest(d: pathlib.Path) -> dict | None:
for p in (d / "plugin.json", d.parent / "plugin.json"):
try:
m = json.loads(p.read_text())
except (OSError, ValueError):
continue
pv = m.get("provider") if isinstance(m, dict) else None
if isinstance(pv, dict) and pv.get("vendorId") == LOCAL_VENDOR:
return pv
return None
def _live_providers_root() -> pathlib.Path | None:
try:
import usage_loader
root = usage_loader.LOADER.root()
return usage_loader.LOADER.base_of(root)
except Exception: # noqa: BLE001
v = os.environ.get("SIDECAR_LIVE_PROVIDERS_DIR")
return pathlib.Path(os.path.expanduser(v)) if v else None
def evox2_manifest() -> dict | None:
"""The ``provider`` object of the live provider-evox2 plugin, or None."""
spec = _provider_configs().get(LOCAL_VENDOR)
if isinstance(spec, dict) and spec.get("dir"):
pv = _read_manifest(pathlib.Path(spec["dir"]))
if pv:
return pv
base = _live_providers_root()
if base is not None and base.is_dir():
try:
idx = json.loads((base / "index.json").read_text())
ent = (idx.get("providers") or {}).get(LOCAL_VENDOR) or {}
if isinstance(ent, dict) and ent.get("dir"):
d = pathlib.Path(ent["dir"])
pv = _read_manifest(d if d.is_absolute() else base / d)
if pv:
return pv
except (OSError, ValueError, AttributeError):
pass
try:
for d in sorted(p for p in base.iterdir() if p.is_dir()):
pv = _read_manifest(d)
if pv:
return pv
except OSError:
pass
return None
def _manifest_reasoning(m: dict, pi_model: dict | None) -> tuple[dict, dict] | None:
"""A provider-evox2 model's ``options`` / ``variants``: pi's own entry's
when models.json has the model (its exact chat-template switches), else
from the manifest's ``efforts`` — levels of a ``reasoning_effort`` model
(Inkling: none…high), none = a Qwen-style think on/off."""
if pi_model is not None:
return _reasoning(pi_model) if pi_model.get("reasoning") else None
efforts = [e for e in (m.get("efforts") or []) if e in EFFORT_LEVELS]
if efforts:
level = m.get("defaultEffort") or "none"
return _effort(level), {lv: _effort(lv) for lv in EFFORT_LEVELS}
return _thinking(False), {"none": _thinking(False), "think": _thinking(True)}
def _manifest_providers(pv: dict, reg: dict) -> dict:
servers = pv.get("servers") if isinstance(pv.get("servers"), dict) else {}
pi = reg.get("providers") or {}
out: dict = {}
for name, srv in servers.items():
if not name.startswith("evox2") or not isinstance(srv, dict) or not srv.get("url"):
continue
pi_p = pi.get(name) if isinstance(pi.get(name), dict) else {}
pi_models = {m.get("id"): m for m in pi_p.get("models") or [] if isinstance(m, dict)}
models = {}
for m in pv.get("models") or []:
if not isinstance(m, dict) or not m.get("id"):
continue
if (m.get("server") or LOCAL_VENDOR) != name:
continue
pm = pi_models.get(m["id"])
entry: dict = {"name": m.get("displayName") or (pm or {}).get("name") or m["id"],
"limit": {"context": m.get("contextWindow")
or (pm or {}).get("contextWindow") or 131072,
"output": (pm or {}).get("maxTokens") or 16384}}
r = _manifest_reasoning(m, pm)
if r is not None:
entry["options"], entry["variants"] = r
models[m["id"]] = entry
if models:
opts = {"baseURL": srv["url"]}
key = srv.get("apiKey") or pi_p.get("apiKey")
if key:
opts["apiKey"] = key
out[name] = {"npm": "@ai-sdk/openai-compatible", "name": pi_p.get("name") or name,
"options": opts, "models": models}
return out
def local_providers() -> dict:
"""The local GPU machine's local providers as opencode providers (``evox2*``, the
names pi uses), so ``<provider>/<id>`` runs on the same server with the
same key: from the provider-evox2 plugin when the sidecar has it, else
pi's models.json (``_models_json_providers``)."""
reg = _models_json()
pv = evox2_manifest()
if pv:
out = _manifest_providers(pv, reg)
if out:
return out
return _models_json_providers(reg)
# opencode's subagent tool, under both names it has had (tools.py maps both).
SUBAGENT_TOOLS = ("task", "subagent")
def is_local(model: str | None) -> bool:
"""Whether a model ref runs on one of pi's local providers."""
return (model or "").split("/", 1)[0].startswith("evox2")
def run_config(model: str | None = None, account: str | None = None,
no_subagents: bool = False,
extra_instructions: list[str] | None = None) -> dict:
"""The config every run gets (``OPENCODE_CONFIG_CONTENT``, read when its
private server starts): no ``question`` tool — a headless run has nobody
to answer it (the ask-form skill is the way) — the CLAUDE.md files
opencode V2 doesn't read on its own, and pi's local providers. A run on a
local model also gets ``LOCAL_MODEL_GUIDE`` (small tool calls, big files in
sections — its stream is slow and invisible until a call completes). A
proxied account's ChatGPT provider points at the hub (opencode_proxy.py).
The MCP servers the hub gave the account go in as ``mcp`` (``mcp.py``).
``no_subagents`` (the machine has an agent limit — the hub's ``agentLimit``
on the launch, the agent-limits plugin): the subagent tool is denied too.
opencode has no hook to count a subagent against the machine's budget
before it starts, so on a limited machine a run does its work itself."""
cfg: dict = {"permissions": [{"action": "question", "resource": "*", "effect": "deny"}]}
if no_subagents:
cfg["permissions"] += [{"action": a, "resource": "*", "effect": "deny"}
for a in SUBAGENT_TOOLS]
instructions = list(OPENCODE_INSTRUCTIONS)
if is_local(model) and LOCAL_MODEL_GUIDE.is_file():
instructions.append(str(LOCAL_MODEL_GUIDE))
if extra_instructions:
instructions.extend(extra_instructions)
if instructions:
cfg["instructions"] = instructions
providers = local_providers()
if opencode_proxy.proxied(account):
providers.update(opencode_proxy.run_provider(account))
if providers:
cfg["provider"] = providers
servers = _mcp_servers(account)
if servers:
cfg["mcp"] = servers
return cfg
def _mcp_servers(account: str | None) -> dict:
"""The hub's MCP servers for a run on ``account`` — {} on any trouble:
a broken store never stops a run."""
if not account:
return {}
try:
from . import mcp
return mcp.run_servers(account)
except Exception: # noqa: BLE001
return {}
def run_env(account: str, base: dict[str, str], cwd: str,
model: str | None = None, no_subagents: bool = False,
extra_instructions: list[str] | None = None) -> dict[str, str]:
env = account_env(account, base)
# opencode takes its working directory from PWD before cwd().
env["PWD"] = cwd
env["OPENCODE_CONFIG_CONTENT"] = json.dumps(
run_config(model, account, no_subagents, extra_instructions=extra_instructions),
separators=(",", ":"))
return env
# A fork's session id is opencode's to mint: conversation UUID → that id
# (the mirror reads it back to file the fork under the UUID the hub chose).
FORKS_PATH = OPENCODE_RUNNER_DIR / "ids.json"
_forks_lock = threading.Lock()
def _forks() -> dict[str, str]:
try:
raw = json.loads(FORKS_PATH.read_text())
return raw if isinstance(raw, dict) else {}
except (OSError, ValueError):
return {}
def record_fork(sid: str, ses: str) -> None:
with _forks_lock:
m = _forks()
m[sid] = ses
FORKS_PATH.parent.mkdir(parents=True, exist_ok=True)
tmp = FORKS_PATH.with_suffix(".tmp")
tmp.write_text(json.dumps(m))
os.replace(tmp, FORKS_PATH)
def _ro(account: str) -> sqlite3.Connection | None:
p = db_path(account)
if not p.is_file():
return None
try:
return sqlite3.connect(f"file:{p}?mode=ro", uri=True, timeout=5)
except sqlite3.Error:
return None
def session_id(sid: str, account: str | None = None) -> str:
"""The opencode session a conversation UUID runs as: the id opencode
minted for a fork (``ids.json``), ``ses_<uuid>`` for one the hub started,
and — a session started in a terminal, mirrored under a UUID derived from
its own id — that own id. Unknown ⇒ ``ses_<uuid>`` (``run -s`` creates it)."""
mapped = _forks().get(sid)
if mapped or not account:
return mapped or f"ses_{sid}"
db = _ro(account)
if db is None:
return f"ses_{sid}"
try:
if db.execute("SELECT 1 FROM session_v2 WHERE id=?", (f"ses_{sid}",)).fetchone():
return f"ses_{sid}"
from .mirror import NAMESPACE # the mirror's derivation
for (ses,) in db.execute("SELECT id FROM session_v2 WHERE parent_id IS NULL"):
if str(uuidlib.uuid5(NAMESPACE, ses)) == sid:
return ses
except sqlite3.Error:
pass
finally:
db.close()
return f"ses_{sid}"
def session_model(account: str, ses: str) -> tuple[str | None, str | None]:
"""``(provider/model, variant)`` the session last ran on (its row), so a
continue with no model picked keeps it — a bare id for the ChatGPT
provider, like the composer sends."""
db = _ro(account)
if db is None:
return None, None
try:
row = db.execute("SELECT model FROM session_v2 WHERE id=?", (ses,)).fetchone()
except sqlite3.Error:
row = None
finally:
db.close()
try:
m = json.loads(row[0]) if row and row[0] else {}
except ValueError:
m = {}
if not isinstance(m, dict) or not m.get("id"):
return None, None
prov, mid = m.get("providerID"), m["id"]
model = mid if prov in (None, OPENCODE_PROVIDER) else f"{prov}/{mid}"
variant = m.get("variant")
return model, (variant if variant and variant != "default" else None)
def uses_login(model: str) -> bool:
"""Whether a model runs on the account's ChatGPT login (its provider)."""
return "/" not in model or model.startswith(f"{OPENCODE_PROVIDER}/")
def model_ref(model: str, effort: str | None) -> str:
"""``provider/model#variant`` — a bare id runs on the ChatGPT login."""
ref = model if "/" in model else f"{OPENCODE_PROVIDER}/{model}"
return f"{ref}#{effort}" if effort else ref
def valid_model(model: str | None) -> str | None:
m = (model or "").strip()
if not m:
return None
if not OPENCODE_MODEL_RE.match(m):
raise HTTPException(400, f"invalid opencode model: {m!r}")
return m
def valid_effort(effort: str | None) -> str | None:
e = (effort or "").strip().lower()
if not e or e == "default":
return None
if e not in OPENCODE_EFFORTS:
raise HTTPException(400, f"invalid opencode effort: {effort!r}")
return e
def run_args(sid: str, model: str, effort: str | None, *, session: str | None = None) -> list[str]:
return [OPENCODE_BIN, "run", "--standalone", "--format", "json", "--auto",
"-s", session or session_id(sid), "-m", model_ref(model, effort)]
def run_failure(text: str) -> tuple[str, str]:
"""(message, kind) out of what a dead run printed: its JSON ``error``
event (opencode's own type, e.g. ``provider.auth``), else the last line."""
for ln in reversed([x.strip() for x in (text or "").splitlines() if x.strip()]):
if not ln.startswith("{"):
continue
try:
o = json.loads(ln)
except ValueError:
continue
e = o.get("error") if isinstance(o, dict) else None
if isinstance(e, dict):
t = e.get("type") or ""
kind = ("auth" if t == "provider.auth" else
"rate_limit" if t in ("provider.rate-limit", "provider.quota") else
run_errors.classify(e.get("message")))
return str(e.get("message") or t or "opencode failed")[:400], kind
return run_errors.run_failure(text)
# ── login status, straight from the database ────────────────────────────────
def _jwt_claims(token: str | None) -> dict:
try:
payload = (token or "").split(".")[1]
return json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4)))
except (IndexError, ValueError):
return {}
def credential(account: str) -> dict | None:
"""The account's active ChatGPT credential row (``value`` decoded), or None.
Read-only: opencode refreshes its tokens itself, and a refresh token
rotates — refreshing it here would sign opencode out."""
p = db_path(account)
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 id, label, value, active, time_updated FROM credential"
" WHERE integration_id='openai' ORDER BY active DESC, time_updated DESC").fetchall()
finally:
db.close()
except sqlite3.Error:
return None
for cid, label, value, active, updated in rows:
try:
v = json.loads(value)
except ValueError:
continue
return {"id": cid, "label": label, "active": bool(active),
"updatedAt": (updated or 0) / 1000, "value": v if isinstance(v, dict) else {}}
return None
def _iso(t: float | None) -> str | None:
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(t)) if t else None
def status(account: str) -> dict:
"""What Settings shows for an opencode account — who, which plan, when the
credential last changed (a sign-in or a token refresh) — never a token.
Never raises: one odd credential row must not fail every account's read."""
try:
return _status(account)
except Exception as e:
return {"id": account, "harness": "opencode", "loggedIn": False,
"error": f"status unreadable: {e}"[:200], "pendingLogin": None}
def _status(account: str) -> dict:
if opencode_proxy.proxied(account):
# Its login is the Homelab's: the placeholder here is no JWT.
return {"id": account, "harness": "opencode", "provider": OPENCODE_PROVIDER,
"configDir": str(db_path(account).parent), "loggedIn": True,
"authMethod": "hub-proxy", "pendingLogin": None}
if keyless(account):
# Nothing to sign in to: its models bring their own credentials.
return {"id": account, "harness": "opencode", "provider": "local",
"configDir": str(db_path(account).parent), "loggedIn": True,
"keyless": True, "authMethod": "none", "pendingLogin": None}
cred = credential(account)
out: dict = {"id": account, "harness": "opencode", "provider": OPENCODE_PROVIDER,
"configDir": str(db_path(account).parent), "loggedIn": False,
"pendingLogin": pending_login(account)}
if not cred:
return out
v = cred["value"]
claims = _jwt_claims(v.get("access"))
auth = claims.get("https://api.openai.com/auth") or {}
prof = claims.get("https://api.openai.com/profile") or {}
orgs = auth.get("organizations") if isinstance(auth.get("organizations"), list) else []
org = auth.get("organization_name") or next(
(o.get("title") for o in orgs if isinstance(o, dict) and o.get("title")), None)
out.update({
"loggedIn": True, "authMethod": v.get("methodID") or v.get("type"),
"email": prof.get("email") or claims.get("email") or cred["label"],
"subscriptionType": auth.get("chatgpt_plan_type"),
"orgName": org,
"credentialsAt": _iso(cred["updatedAt"]),
"accessExpiresAt": _iso((v.get("expires") or 0) / 1000) if v.get("expires") else None,
"usageTracking": v.get("methodID") in _OAUTH_METHODS,
})
return out
# ── the device-code login ────────────────────────────────────────────────────
class _Login:
"""A device-code sign-in in flight: pumps the CLI's output, finds the code
and the address to enter it at (``code_re`` / ``url_re`` — opencode's by
default; tools_install.py's gh sign-in passes GitHub's)."""
def __init__(self, account: str, proc: subprocess.Popen,
code_re: re.Pattern | None = None, url_re: re.Pattern | None = None):
self.account = account
self.proc = proc
self._code_re = code_re or _CODE
self._url_re = url_re or _URL
self.started = time.time()
self.code: str | None = None
self.url: str | None = None
self._buf: list[str] = []
self._lock = threading.Lock()
threading.Thread(target=self._pump, daemon=True).start()
self._timer = threading.Timer(LOGIN_TTL_S, self.kill)
self._timer.daemon = True
self._timer.start()
def _pump(self) -> None:
fd = self.proc.stdout.fileno()
while True:
try:
chunk = os.read(fd, 4096)
except OSError:
break
if not chunk:
break
with self._lock:
self._buf.append(chunk.decode(errors="replace"))
def output(self) -> str:
with self._lock:
return _ANSI.sub("", "".join(self._buf))
def wait_code(self, timeout: float) -> bool:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
out = self.output()
c, u = self._code_re.search(out), self._url_re.search(out)
if c and u:
self.code, self.url = c.group(1), u.group(0).rstrip(".")
return True
if self.proc.poll() is not None:
return False
time.sleep(0.1)
return False
def kill(self) -> None:
self._timer.cancel()
if self.proc.poll() is None:
try:
self.proc.kill()
self.proc.wait(timeout=5)
except (OSError, subprocess.TimeoutExpired):
pass
def public(self) -> dict:
return {"account": self.account, "url": self.url, "userCode": self.code,
"flow": "device", "startedAt": int(self.started),
"expiresAt": int(self.started + LOGIN_TTL_S)}
_logins: dict[str, _Login] = {}
_logins_lock = threading.Lock()
def start_login(account: str, base_env: dict[str, str]) -> dict:
"""Start the device-code login: the code to enter and where to enter it.
The CLI keeps polling OpenAI and stores the credential by itself."""
with _logins_lock:
old = _logins.pop(account, None)
if old:
old.kill()
env = {**account_env(account, base_env), "BROWSER": "true"}
try:
proc = subprocess.Popen(
[OPENCODE_BIN, "auth", "login", OPENCODE_PROVIDER, "--method", "chatgpt-headless",
"--standalone"],
stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
env=env, cwd=str(pathlib.Path.home()))
except OSError as e:
raise HTTPException(500, run_errors.error_detail(
f"could not start `opencode auth login`: {e}", kind="login", account=account))
login = _Login(account, proc)
if not login.wait_code(30):
tail = login.output().strip().splitlines()
login.kill()
raise HTTPException(502, run_errors.error_detail(
"opencode printed no device code: " + (tail[-1][:300] if tail else "(no output)"),
kind="login", account=account))
with _logins_lock:
_logins[account] = login
return login.public()
def pending_login(account: str) -> dict | None:
with _logins_lock:
login = _logins.get(account)
if login and login.proc.poll() is None:
return login.public()
return None
def login_result(account: str) -> dict:
"""``{state: pending|complete|failed|none, message?}`` of the last login."""
with _logins_lock:
login = _logins.get(account)
if login is None:
return {"state": "none"}
rc = login.proc.poll()
if rc is None:
return {"state": "pending", **login.public()}
with _logins_lock:
_logins.pop(account, None)
tail = [ln.strip(" │└┌◇◆●○") for ln in login.output().splitlines() if ln.strip(" │└┌◇◆●○")]
if rc == 0 and credential(account):
return {"state": "complete"}
return {"state": "failed", "message": (tail[-1] if tail else f"exit {rc}")[:300]}
def cancel_login(account: str) -> bool:
with _logins_lock:
login = _logins.pop(account, None)
if not login:
return False
login.kill()
return True
def logout(account: str, base_env: dict[str, str]) -> str:
cred = credential(account)
if not cred:
return "not logged in"
try:
r = subprocess.run([OPENCODE_BIN, "auth", "logout", OPENCODE_PROVIDER, cred["id"],
"--standalone"], capture_output=True, text=True, timeout=60,
stdin=subprocess.DEVNULL, env=account_env(account, base_env),
cwd=str(pathlib.Path.home()))
except (OSError, subprocess.TimeoutExpired) as e:
raise HTTPException(502, run_errors.error_detail(f"opencode auth logout failed: {e}",
kind="login", account=account))
out = _ANSI.sub("", (r.stdout or "") + (r.stderr or "")).strip()
if r.returncode != 0:
raise HTTPException(502, run_errors.error_detail(
(out.splitlines() or [f"exit {r.returncode}"])[-1][:300], kind="login",
account=account))
return "logged out"
_refresh_locks: dict[str, threading.Lock] = {}
def refresh_token(account: str, base_env: dict[str, str]) -> bool:
"""Have opencode refresh the account's access token, without a model call:
booting a server loads the OpenAI plugin, which resolves (and, within 5 min
of expiry, refreshes) the active credential. True when it ran. One at a
time per account: two refreshes at once race the refresh-token rotation."""
lock = _refresh_locks.setdefault(account, threading.Lock())
with lock:
return _refresh(account, base_env)
def _refresh(account: str, base_env: dict[str, str]) -> bool:
try:
r = subprocess.run([OPENCODE_BIN, "auth", "list", "--format", "json", "--standalone"],
capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL,
env=account_env(account, base_env), cwd=str(pathlib.Path.home()))
return r.returncode == 0
except (OSError, subprocess.TimeoutExpired):
return False
def fork_session(account: str, base_env: dict[str, str], src_sid: str, src_ses: str,
cut_user_ord: int, cut_text: str | None, cwd: str,
cut_key: str | None = None) -> str:
"""Branch ``src_ses`` before one of its user messages (opencode's own fork:
settled history strictly before it) and answer the new session id opencode
minted. The message is the mirrored record's own (``cut_key`` =
``user:<message id>``) — the transcript also holds turns opencode doesn't
count as user messages (a compaction summary, a `!` command) — else the
``cut_user_ord``-th user message."""
p = db_path(account)
try:
db = sqlite3.connect(f"file:{p}?mode=ro", uri=True, timeout=5)
try:
users = db.execute("SELECT id, data FROM session_message WHERE session_id=?"
" AND type='user' ORDER BY seq", (src_ses,)).fetchall()
finally:
db.close()
except sqlite3.Error as e:
raise HTTPException(502, f"cannot read opencode session {src_ses}: {e}")
by_key = {f"user:{m}": (m, d) for m, d in users}
exact = bool(cut_key and cut_key in by_key)
if exact:
mid, data = by_key[cut_key]
elif 0 <= cut_user_ord < len(users):
mid, data = users[cut_user_ord]
else:
raise HTTPException(409, f"fork point not found: user message #{cut_user_ord} "
f"(session has {len(users)})")
# An ordinal can drift from what the viewer counted; the record's own key
# can't (and the mirror may have added to its text: an `@skill`, a file).
if cut_text and not exact:
try:
text = json.loads(data).get("text") or ""
except ValueError:
text = ""
want = " ".join(cut_text.split())
if want not in " ".join(text.split()):
raise HTTPException(409, "fork point mismatch — the session changed since the "
"viewer loaded it; reload the conversation and retry")
env = {**account_env(account, base_env), "PWD": cwd}
try:
r = subprocess.run([OPENCODE_BIN, "api", "POST", f"/api/session/{src_ses}/fork",
"-d", json.dumps({"before": mid}), "--standalone"],
capture_output=True, text=True, timeout=60,
stdin=subprocess.DEVNULL, env=env, cwd=cwd)
new = (json.loads(r.stdout or "{}").get("data") or {}).get("id")
except (OSError, subprocess.TimeoutExpired, ValueError) as e:
raise HTTPException(502, f"opencode fork failed: {e}")
if r.returncode != 0 or not new:
raise HTTPException(502, f"opencode fork failed: {(r.stderr or r.stdout or '')[-300:]}")
return new