Files
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

474 lines
24 KiB
Python

"""The opencode harness: tool mapping (patch split per file), the database →
v1 mirror (append-only, restart-proof, a step written whole once it ends,
subagents linked to their call, an old-format file continued in v1), the
usage snapshot and the run argv/env."""
import json
import pathlib
import sqlite3
import uuid
import opencode_cli
import opencode_mirror as mirror
import opencode_tools as tools
import opencode_usage
SID = "11111111-2222-3333-4444-555555555555"
CWD = "/home/u/projects/demo"
# ── tools ───────────────────────────────────────────────────────────────────
PATCH = """*** Begin Patch
*** Add File: docs/new.md
+# New
+hello
*** Update File: src/calc.py
@@ def add(a, b):
def add(a, b):
- return a+b
+ return a + b
@@
-x = 1
+x = 2
*** Delete File: old.txt
*** End Patch"""
def test_a_patch_splits_into_one_claude_call_per_file():
calls = tools.map_call("patch", {"patchText": PATCH}, CWD, "call_1")
assert [(c[0], c[1]) for c in calls] == [
("call_1", "Write"), ("call_1.1", "MultiEdit"), ("call_1.2", "DeleteFile")]
assert calls[0][2] == {"file_path": f"{CWD}/docs/new.md", "content": "# New\nhello"}
edits = calls[1][2]["edits"]
assert calls[1][2]["file_path"] == f"{CWD}/src/calc.py"
assert edits[0] == {"old_string": "def add(a, b):\n return a+b",
"new_string": "def add(a, b):\n return a + b"}
assert edits[1] == {"old_string": "x = 1", "new_string": "x = 2"}
def test_a_one_chunk_update_is_an_edit():
calls = tools.map_call("patch", {"patchText": "*** Begin Patch\n*** Update File: a.py\n"
"@@\n-a\n+b\n*** End Patch"}, CWD, "c")
assert calls == [("c", "Edit", {"file_path": f"{CWD}/a.py", "old_string": "a",
"new_string": "b"})]
def test_tool_shapes():
assert tools.map_call("read", {"path": "x.py", "offset": 3}, CWD, "1") == [
("1", "Read", {"file_path": f"{CWD}/x.py", "offset": 3})]
assert tools.map_call("edit", {"path": "/a", "oldString": "o", "newString": "n",
"replaceAll": True}, CWD, "2")[0][2] == {
"file_path": "/a", "old_string": "o", "new_string": "n", "replace_all": True}
assert tools.map_call("shell", {"command": "ls", "timeout": 5000, "background": True},
CWD, "3")[0][1:] == (
"Bash", {"command": "ls", "timeout": 5000, "run_in_background": True})
assert tools.map_call("grep", {"pattern": "x", "include": "*.py", "caseSensitive": False},
CWD, "4")[0][2] == {"pattern": "x", "output_mode": "content",
"glob": "*.py", "-i": True}
assert tools.map_call("subagent", {"agent": "explore", "description": "d", "prompt": "p"},
CWD, "5")[0][1:] == (
"Agent", {"description": "d", "prompt": "p", "subagent_type": "explore"})
assert tools.map_call("skill", {"id": "greet"}, CWD, "6")[0][1:] == ("Skill", {"skill": "greet"})
# 1.x names still map
assert tools.map_call("bash", {"command": "pwd"}, CWD, "7")[0][1] == "Bash"
assert tools.map_call("read", {"filePath": "/f"}, CWD, "8")[0][2] == {"file_path": "/f"}
# unknown (MCP/plugin) tools pass through
assert tools.map_call("linear_get_issue", {"id": "X-1"}, CWD, "9") == [
("9", "linear_get_issue", {"id": "X-1"})]
def test_results_skill_body_and_subagent_report():
text, err = tools.result_text({"status": "error", "error": {"message": "boom"},
"content": [{"type": "text", "text": "partial"}]})
assert err and text == "partial\n\nError: boom"
assert tools.skill_body('<skill_content name="g">\n# Skill: g\n\nSay hi.\n\n'
'Base directory for this skill: /s/g\nRelative…') == "Say hi."
assert tools.subagent_report('<subagent sessionID="ses_x" state="completed">\nDone.\n'
'</subagent>') == "Done."
# ── mirror ──────────────────────────────────────────────────────────────────
SCHEMA = """
CREATE TABLE session_v2 (id TEXT PRIMARY KEY, parent_id TEXT, fork_session_id TEXT,
directory TEXT, title TEXT, agent TEXT, version TEXT, time_created INTEGER);
CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT, type TEXT, seq INTEGER,
time_created INTEGER, data TEXT);
CREATE TABLE event_sequence (aggregate_id TEXT PRIMARY KEY, seq INTEGER);
"""
class FakeDB:
def __init__(self, path: pathlib.Path):
self.path = path
self.db = sqlite3.connect(path, isolation_level=None)
self.db.executescript(SCHEMA)
self.seq: dict[str, int] = {}
def session(self, sid, parent=None, title=None, agent=None, t=1000, fork_of=None):
self.db.execute("INSERT INTO session_v2 VALUES (?,?,?,?,?,?,?,?)",
(sid, parent, fork_of, CWD, title, agent, "2.0.32", t))
self._bump(sid)
def _bump(self, sid):
self.seq[sid] = self.seq.get(sid, 0) + 1
self.db.execute("INSERT OR REPLACE INTO event_sequence VALUES (?,?)",
(sid, self.seq[sid]))
def put(self, sid, mid, typ, data):
"""Insert or update a message row (a new row gets the next seq)."""
self._bump(sid)
row = self.db.execute("SELECT seq FROM session_message WHERE id=?", (mid,)).fetchone()
if row:
self.db.execute("UPDATE session_message SET data=? WHERE id=?",
(json.dumps(data), mid))
else:
self.db.execute("INSERT INTO session_message VALUES (?,?,?,?,?,?)",
(mid, sid, typ, self.seq[sid], 1000, json.dumps(data)))
def _records(path: pathlib.Path) -> list[dict]:
return [json.loads(ln) for ln in path.read_text().splitlines() if ln.strip()]
def _mirror(tmp, db):
return mirror.AccountMirror("chatgpt-work", db.path, tmp / "out", tmp / "state",
tmp / "ids.json")
def _step(content, *, streamed=True, completed=False, tokens=None):
t = {"created": 2000}
if streamed:
t["streamed"] = 3000
if completed:
t["completed"] = 4000
d = {"agent": "build", "model": {"id": "gpt-5.5", "providerID": "openai",
"variant": "high"},
"content": content, "time": t, "cost": 0}
if tokens:
d["tokens"] = tokens
d["finish"] = "tool-calls"
return d
TOOL_RUNNING = {"type": "tool", "id": "call_a", "name": "shell",
"state": {"status": "running", "input": {"command": "ls"}, "metadata": {}},
"time": {"created": 2500, "ran": 3100}}
TOOL_DONE = {**TOOL_RUNNING, "state": {"status": "completed", "input": {"command": "ls"},
"content": [{"type": "text", "text": "a.py"}],
"metadata": {"exit": 0}},
"time": {"created": 2500, "ran": 3100, "completed": 3500}}
TOKENS = {"input": 1000, "output": 50, "reasoning": 20, "cache": {"read": 9000, "write": 0}}
def _kinds(evs: list[dict]) -> list[str]:
return [e["t"] + (f":{e['kind']}" if e.get("kind") and e["t"] in ("inject", "meta") else "")
+ (f":{e['reason']}" if e["t"] == "turn_end" else "") for e in evs]
def test_a_step_goes_out_whole_once_it_has_ended(tmp_path):
db = FakeDB(tmp_path / "opencode.db")
ses = f"ses_{SID}"
db.session(ses, title="List files")
db.put(ses, "msg_u1", "user", {"text": "list the files\n", "time": {"created": 1500}})
db.put(ses, "msg_a1", "assistant", _step([{"type": "reasoning", "text": "Let me look."},
TOOL_RUNNING]))
m = _mirror(tmp_path, db)
m.tick()
f = next((tmp_path / "out").glob(f"*/{SID}.jsonl"))
evs = _records(f)
# the step is still running: nothing of it yet (opencode has no tokens before its end)
assert _kinds(evs) == ["session", "meta:title", "prompt"]
head = evs[0]
assert head["v"] == 1 and head["id"] == SID and head["harness"] == "opencode"
assert head["cwd"] == CWD and head["harnessVersion"] == "2.0.32"
assert evs[2]["text"] == "list the files" and evs[2]["ocKey"] == "user:msg_u1"
# the tool settles, the step ends: call, blocks, usage — then the result
db.put(ses, "msg_a1", "assistant", _step([{"type": "reasoning", "text": "Let me look."},
TOOL_DONE], completed=True, tokens=TOKENS))
db.put(ses, "msg_i1", "idle", {"outcome": "succeeded", "time": {"created": 4100}})
m.tick()
evs = _records(f)
assert _kinds(evs[3:]) == ["call", "thinking", "tool_call", "usage", "tool_result",
"turn_end:done"]
call, _th, tc, usage, res = evs[3:8]
assert call["ocKey"] == "step:msg_a1" and call["ocKeys"] == ["usage:msg_a1"]
assert call["effort"] == "high" and call["model"] == "gpt-5.5" and call["id"] == "msg_a1"
assert tc["tool"] == "shell" and tc["native"] == "shell" and tc["call"] == "msg_a1"
assert usage == {"t": "usage", "at": call["at"], "input": 1000, "output": 70,
"cacheRead": 9000, "reasoning": 20, "call": "msg_a1"}
assert "cost" not in usage # $0 on a subscription: priced by the hub
assert res["toolCall"] == "call_a" and res["text"] == "a.py" and res["ok"] is True
# a restart (fresh mirror, no state) writes nothing twice
(tmp_path / "state" / "chatgpt-work.json").unlink()
assert _mirror(tmp_path, db).tick(force=True) == 0
assert len(_records(f)) == len(evs)
def test_a_step_still_running_when_its_turn_ends_goes_out_as_it_stands(tmp_path):
db = FakeDB(tmp_path / "opencode.db")
ses = f"ses_{SID}"
db.session(ses)
db.put(ses, "msg_u", "user", {"text": "go", "time": {"created": 1}})
db.put(ses, "msg_a", "assistant", _step([{"type": "text", "text": "Working."}, TOOL_RUNNING]))
m = _mirror(tmp_path, db)
m.tick()
f = next((tmp_path / "out").glob(f"*/{SID}.jsonl"))
assert _kinds(_records(f)) == ["session", "prompt"]
db.put(ses, "msg_i", "idle", {"outcome": "interrupted", "time": {"created": 9}})
m.tick()
assert _kinds(_records(f)) == ["session", "prompt", "call", "text", "tool_call",
"turn_end:interrupted"]
# its usage, if it ever comes, prices it on its own
db.put(ses, "msg_a", "assistant", _step([{"type": "text", "text": "Working."}, TOOL_DONE],
completed=True, tokens=TOKENS))
m.tick()
evs = _records(f)
assert _kinds(evs[-3:]) == ["tool_result", "call", "usage"]
assert evs[-2]["ocKey"] == "usage:msg_a" and evs[-2]["empty"] is True
def test_a_step_already_over_goes_out_as_one_record(tmp_path):
db = FakeDB(tmp_path / "opencode.db")
ses = "ses_eaf48e623ffegDXcxmVQI64kR8" # a terminal session's own id
db.session(ses)
db.put(ses, "msg_u", "user", {"text": "hi", "time": {"created": 1}})
db.put(ses, "msg_a", "assistant", _step([{"type": "text", "text": "Hello!"}],
completed=True, tokens=TOKENS))
_mirror(tmp_path, db).tick()
u = str(uuid.uuid5(mirror.NAMESPACE, ses))
evs = _records(next((tmp_path / "out").glob(f"*/{u}.jsonl")))
assert _kinds(evs[-3:]) == ["call", "text", "usage"]
assert evs[-2]["text"] == "Hello!" and evs[-1]["output"] == 70
assert evs[-3]["ocKeys"] == ["usage:msg_a"]
def test_errors_and_interrupts(tmp_path):
db = FakeDB(tmp_path / "opencode.db")
ses = f"ses_{SID}"
db.session(ses)
db.put(ses, "msg_u", "user", {"text": "go", "time": {"created": 1}})
err = {"type": "provider.rate-limit", "message": "ChatGPT usage limit reached.",
"status": 429, "response": {"body": json.dumps(
{"error": {"type": "usage_limit_reached", "resets_at": 1792400000}})}}
db.put(ses, "msg_a", "assistant", {**_step([], completed=True), "error": err,
"finish": "error"})
db.put(ses, "msg_i", "idle", {"outcome": "failed", "error": err, "time": {"created": 5}})
_mirror(tmp_path, db).tick()
evs = _records(next((tmp_path / "out").glob(f"*/{SID}.jsonl")))
# the failed step left nothing: one API-error call (the idle row doesn't repeat it)
assert _kinds(evs) == ["session", "prompt", "call", "error", "usage", "turn_end:error",
"turn_end:done"]
assert evs[2]["failed"] is True and evs[2]["model"] == "<synthetic>"
assert evs[3]["kind"] == "rate_limit" and "resets 2026-" in evs[3]["text"]
db.put(ses, "msg_u2", "user", {"text": "again", "time": {"created": 6}})
db.put(ses, "msg_i2", "idle", {"outcome": "interrupted", "time": {"created": 7}})
_mirror(tmp_path, db).tick(force=True)
evs = _records(next((tmp_path / "out").glob(f"*/{SID}.jsonl")))
assert evs[-1] == {**evs[-1], "t": "turn_end", "reason": "interrupted"}
def test_a_subagent_is_a_sidechain_linked_to_its_call(tmp_path):
db = FakeDB(tmp_path / "opencode.db")
ses, child = f"ses_{SID}", "ses_child0000000000000000"
db.session(ses)
db.put(ses, "msg_u", "user", {"text": "count files", "time": {"created": 1}})
call = {"type": "tool", "id": "call_sub", "name": "subagent",
"state": {"status": "running", "input": {"agent": "explore",
"description": "Count files",
"prompt": "count"}, "metadata": {}},
"time": {"created": 900, "ran": 950}}
db.put(ses, "msg_a", "assistant", _step([call]))
db.session(child, parent=ses, title="Count files", agent="explore", t=1000)
db.put(child, "msg_cu", "user", {"text": tools.SUBAGENT_PREFIX + "count",
"time": {"created": 1001}})
_mirror(tmp_path, db).tick()
sub = next((tmp_path / "out").glob(f"*/{SID}/subagents/agent-child*.jsonl"))
meta = json.loads(sub.with_name(sub.stem + ".meta.json").read_text())
assert meta["toolUseId"] == "call_sub" and meta["agentType"] == "explore"
head, prompt = _records(sub)[:2]
assert head["sidechain"] is True and head["id"] == SID and head["agent"] == "child0000000000000000"
assert prompt["text"] == "count" # opencode's subagent preamble dropped
def test_an_old_format_file_is_continued_in_v1_behind_a_header(tmp_path):
db = FakeDB(tmp_path / "opencode.db")
ses = f"ses_{SID}"
db.session(ses)
db.put(ses, "msg_u", "user", {"text": "first", "time": {"created": 1}})
f = tmp_path / "out" / mirror.cwd_slug(CWD) / f"{SID}.jsonl"
f.parent.mkdir(parents=True)
old = {"type": "user", "ocKey": "user:msg_u", "sessionId": SID, "cwd": CWD,
"entrypoint": "opencode", "uuid": "x", "timestamp": "2026-11-01T10:00:00.000Z",
"message": {"role": "user", "content": "first"}}
f.write_text(json.dumps(old) + "\n")
db.put(ses, "msg_u2", "user", {"text": "second", "time": {"created": 2}})
_mirror(tmp_path, db).tick()
evs = _records(f)
assert evs[0] == old # never rewritten, never repeated
assert _kinds(evs[1:]) == ["session", "prompt"]
assert evs[1]["v"] == 1 and evs[2]["text"] == "second"
def test_a_fork_is_filed_under_the_uuid_the_hub_chose(tmp_path):
db = FakeDB(tmp_path / "opencode.db")
(tmp_path / "ids.json").write_text(json.dumps({SID: "ses_forkedbyopencode00000"}))
db.session("ses_forkedbyopencode00000")
db.put("ses_forkedbyopencode00000", "msg_u", "user", {"text": "hi", "time": {"created": 1}})
_mirror(tmp_path, db).tick()
assert next((tmp_path / "out").glob(f"*/{SID}.jsonl"))
def test_session_uuid():
assert mirror.session_uuid(f"ses_{SID}", {}) == SID
assert mirror.session_uuid("ses_x", {"ses_x": SID}) == SID
assert mirror.session_uuid("ses_y", {}) == str(uuid.uuid5(mirror.NAMESPACE, "ses_y"))
# ── usage + run ─────────────────────────────────────────────────────────────
def test_usage_windows_are_named_by_duration():
snap = opencode_usage.parse({
"plan_type": "enterprise",
"rate_limit": {"limit_reached": False,
"primary_window": {"used_percent": 42, "limit_window_seconds": 604800,
"reset_at": 1792400000},
"secondary_window": None}}, now=1)
assert snap == {"plan_type": "enterprise", "limit_reached": False, "rate_limits": {
"seven_day": {"used_percentage": 42.0, "resets_at": 1792400000,
"window_seconds": 604800}}}
five = opencode_usage.parse({"rate_limit": {"primary_window": {
"used_percent": 7, "limit_window_seconds": 18000, "reset_after_seconds": 60}}}, now=100)
assert five["rate_limits"]["five_hour"]["resets_at"] == 160
def test_run_argv_and_env(monkeypatch, tmp_path):
monkeypatch.setattr(opencode_cli, "OPENCODE_ACCOUNTS",
{"chatgpt-work": None, "other": tmp_path / "other"})
monkeypatch.setattr(opencode_cli, "FORKS_PATH", tmp_path / "ids.json")
args = opencode_cli.run_args(SID, "gpt-6.1-sol", "high")
assert args[1:] == ["run", "--standalone", "--format", "json", "--auto",
"-s", f"ses_{SID}", "-m", "openai/gpt-6.1-sol#high"]
assert opencode_cli.model_ref("openrouter/qwen/qwen3.8-27b", None) == \
"openrouter/qwen/qwen3.8-27b"
env = opencode_cli.run_env("other", {"PATH": "/bin", "OPENAI_API_KEY": "sk", "PWD": "/x"},
CWD)
assert env["PWD"] == CWD and "OPENAI_API_KEY" not in env
assert env["OPENCODE_DB"] == str(tmp_path / "other" / "opencode.db")
cfg = json.loads(env["OPENCODE_CONFIG_CONTENT"])
assert {"action": "question", "resource": "*", "effect": "deny"} in cfg["permissions"]
assert "OPENCODE_DB" not in opencode_cli.run_env("chatgpt-work", {"OPENCODE_DB": "x"}, CWD)
# a fork runs under the id opencode minted
opencode_cli.record_fork(SID, "ses_minted")
assert opencode_cli.run_args(SID, "gpt-5.5", None)[7] == "ses_minted"
def test_run_failure_reads_the_json_error_event():
log = ('{"type":"step_start"}\n{"type":"error","error":{"type":"provider.auth",'
'"message":"Token expired","status":401}}\n')
assert opencode_cli.run_failure(log) == ("Token expired", "auth")
# ── review regressions ──────────────────────────────────────────────────────
def test_a_fresh_unmapped_fork_waits_for_its_id(tmp_path):
import time as _t
db = FakeDB(tmp_path / "opencode.db")
now = int(_t.time() * 1000)
db.session("ses_forkmintedbyopencode0", t=now, fork_of=f"ses_{SID}")
db.put("ses_forkmintedbyopencode0", "msg_u", "user", {"text": "hi", "time": {"created": now}})
m = _mirror(tmp_path, db)
m.tick()
assert not list((tmp_path / "out").glob("*/*.jsonl")) # not under a derived id
(tmp_path / "ids.json").write_text(json.dumps({SID: "ses_forkmintedbyopencode0"}))
db.put("ses_forkmintedbyopencode0", "msg_u2", "user", {"text": "go", "time": {"created": now}})
m.tick()
assert [p.name for p in (tmp_path / "out").glob("*/*.jsonl")] == [f"{SID}.jsonl"]
def test_a_row_of_an_unknown_shape_skips_itself_only(tmp_path):
db = FakeDB(tmp_path / "opencode.db")
bad, good = f"ses_{SID}", "ses_22222222-3333-4444-5555-666666666666"
db.session(bad, t=1)
db.put(bad, "msg_e", "assistant", {**_step([], completed=True), "finish": "error",
"error": {"type": "provider.x", "message": "x",
"response": {"body": '{"error": "model not found"}'}}})
db.put(bad, "msg_w", "shell", {"command": "ls", "status": "exited", "output": "plain string",
"time": {"created": 2}})
db.session(good, t=2)
db.put(good, "msg_u", "user", {"text": "still mirrored", "time": {"created": 3}})
_mirror(tmp_path, db).tick()
assert next((tmp_path / "out").glob("*/22222222-3333-4444-5555-666666666666.jsonl"))
evs = _records(next((tmp_path / "out").glob(f"*/{SID}.jsonl")))
assert any(e["t"] == "error" for e in evs)
assert any("plain string" in (e.get("text") or "") for e in evs if e["t"] == "prompt")
def test_a_restart_never_repeats_a_turns_error(tmp_path):
db = FakeDB(tmp_path / "opencode.db")
ses = f"ses_{SID}"
err = {"type": "provider.auth", "message": "expired", "status": 401}
db.session(ses)
db.put(ses, "m_u1", "user", {"text": "go", "time": {"created": 1}})
db.put(ses, "m_a1", "assistant", {**_step([], completed=True), "error": err, "finish": "error"})
db.put(ses, "m_i1", "idle", {"outcome": "failed", "error": err, "time": {"created": 3}})
_mirror(tmp_path, db).tick()
db.put(ses, "m_u2", "user", {"text": "again", "time": {"created": 4}})
(tmp_path / "state" / "chatgpt-work.json").unlink()
_mirror(tmp_path, db).tick(force=True) # a fresh process
evs = _records(next((tmp_path / "out").glob(f"*/{SID}.jsonl")))
assert sum(1 for e in evs if e["t"] == "call" and e.get("failed")) == 1
assert evs[-1]["t"] == "prompt" and evs[-1]["text"] == "again"
def test_a_terminal_session_runs_under_its_own_id(monkeypatch, tmp_path):
d = tmp_path / "acct"
d.mkdir()
db = FakeDB(d / "opencode.db")
db.session("ses_terminalsession000000")
db.db.execute("ALTER TABLE session_v2 ADD COLUMN model TEXT")
db.db.execute("UPDATE session_v2 SET model=? WHERE id=?",
(json.dumps({"id": "gpt-5.5", "providerID": "openai", "variant": "xhigh"}),
"ses_terminalsession000000"))
monkeypatch.setattr(opencode_cli, "OPENCODE_ACCOUNTS", {"acct": d})
monkeypatch.setattr(opencode_cli, "FORKS_PATH", tmp_path / "ids.json")
derived = str(uuid.uuid5(mirror.NAMESPACE, "ses_terminalsession000000"))
assert opencode_cli.session_id(derived, "acct") == "ses_terminalsession000000"
assert opencode_cli.session_id(SID, "acct") == f"ses_{SID}" # a new one
assert opencode_cli.session_model("acct", "ses_terminalsession000000") == ("gpt-5.5", "xhigh")
def test_pi_local_providers_reach_every_runs_config(monkeypatch, tmp_path):
reg = tmp_path / "models.json"
reg.write_text(json.dumps({"providers": {
"evox2": {"baseUrl": "http://box:8090/v1", "apiKey": "k", "models": [
{"id": "ggml-org/qwen3.8-27b", "name": "Qwen", "reasoning": True,
"contextWindow": 131072, "maxTokens": 16384},
{"id": "plain", "contextWindow": 8192}]},
"openrouter": {"baseUrl": "https://or", "models": [{"id": "x"}]}}}))
monkeypatch.setattr(opencode_cli, "PI_MODELS_FILE", reg)
# no provider-evox2 plugin here: models.json alone
monkeypatch.setattr(opencode_cli, "evox2_manifest", lambda: None)
prov = opencode_cli.run_config()["provider"]
assert list(prov) == ["evox2"] # only pi's local providers
p = prov["evox2"]
assert p["npm"] == "@ai-sdk/openai-compatible"
assert p["options"] == {"baseURL": "http://box:8090/v1", "apiKey": "k"}
q = p["models"]["ggml-org/qwen3.8-27b"]
# thinking off unless the `think` variant asks for it
assert q["options"]["chat_template_kwargs"] == {"enable_thinking": False}
assert q["variants"]["think"]["chat_template_kwargs"] == {"enable_thinking": True}
assert q["limit"] == {"context": 131072, "output": 16384}
assert "variants" not in p["models"]["plain"]
monkeypatch.setattr(opencode_cli, "PI_MODELS_FILE", tmp_path / "missing.json")
assert "provider" not in opencode_cli.run_config()
def test_a_keyless_account_is_signed_in_without_a_credential(monkeypatch, tmp_path):
monkeypatch.setattr(opencode_cli, "OPENCODE_ACCOUNTS", {"opencode-lab": tmp_path / "lab"})
monkeypatch.setattr(opencode_cli, "OPENCODE_KEYLESS", {"opencode-lab"})
s = opencode_cli.status("opencode-lab")
assert s["loggedIn"] and s["keyless"] and s["provider"] == "local"
assert opencode_cli.keyless("opencode-lab") and not opencode_cli.keyless("chatgpt-work")
assert not opencode_cli.uses_login("evox2/qwen3.6-35b-a3b")