Files
ai-agent/backend/test_opencode.py

235 lines
11 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The opencode harness on the hub side: OpenAI list prices (long-context tier,
priority tiers), a mirrored transcript parsed like a Claude one (its step's
usage written after its content, still charged to the step's tool), the
opencode account and its week-only plan, the feed's opencode files, and the
usage alert. ``python3 -m unittest test_opencode``"""
import json
import os
import pathlib
import tempfile
import time
import unittest
TMP = pathlib.Path(tempfile.mkdtemp())
os.environ.setdefault("OPENCODE_TRANSCRIPTS_DIR", str(TMP / "oc"))
import accounts # noqa: E402
from conversations.parse import parse_conversation # noqa: E402
from conversations.pricing import (book_key, norm_usage, plan_units, # noqa: E402
rates_for, usage_cost)
from usage import calibrate # noqa: E402
from usage.poller import UsagePoller # noqa: E402
from workers.remotefeed import local_rel, opencode_account # noqa: E402
def openai_model(model):
"""(book key, mode) when provider-openai prices the id."""
hit = book_key(model)
return hit[1:] if hit and hit[0] == "openai" else None
SID = "11111111-2222-3333-4444-555555555555"
def _u(inp=0, out=0, cache=0, write=0):
return norm_usage({"input_tokens": inp, "output_tokens": out,
"cache_read_input_tokens": cache,
"cache_creation_input_tokens": write})
class Pricing(unittest.TestCase):
def test_openai_ids(self):
self.assertEqual(openai_model("gpt-5.5"), ("gpt-5.5", None))
self.assertEqual(openai_model("gpt-6.1-sol-ultrafast"), ("gpt-6.1-sol", "ultrafast"))
self.assertEqual(openai_model("gpt-6.2-sol"), ("gpt-6.1-sol", None)) # newer: its line
self.assertIsNone(openai_model("openai/gpt-5.5")) # an OpenRouter id
self.assertIsNone(openai_model("claude-opus-5-5"))
self.assertEqual(rates_for("gpt-5.5"), (5.0, 30.0, 0.5))
self.assertEqual(rates_for("gpt-5.5-fast"), (12.5, 75.0, 1.25))
def test_cost_tiers_and_plan_units(self):
short = _u(inp=10_000, out=2_000, cache=100_000)
self.assertAlmostEqual(usage_cost(short, "gpt-5.5"),
(10_000 * 5 + 2_000 * 30 + 100_000 * 0.5) / 1e6)
long = _u(inp=10_000, out=2_000, cache=300_000) # prompt > 272K
self.assertAlmostEqual(usage_cost(long, "gpt-5.5"),
(10_000 * 10 + 2_000 * 45 + 300_000 * 1.0) / 1e6)
# a cache write is 1.25× input on the models that bill one
self.assertAlmostEqual(usage_cost(_u(write=100_000), "gpt-6-sol"), 0.25)
# the ChatGPT seat's limits are fitted on plain list $
self.assertAlmostEqual(plan_units(short, "gpt-5.5"), usage_cost(short, "gpt-5.5"))
def _rec(**kw):
return {"sessionId": SID, "cwd": "/home/u/repo", "entrypoint": "opencode",
"timestamp": "2026-10-18T10:00:00.000Z", **kw}
class Parse(unittest.TestCase):
def _write(self, recs) -> pathlib.Path:
p = TMP / "proj" / f"{SID}.jsonl"
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("".join(json.dumps(r) + "\n" for r in recs))
return p
def test_usage_after_content_is_charged_to_the_steps_tool(self):
usage = {"input_tokens": 1000, "output_tokens": 70,
"cache_read_input_tokens": 9000, "cache_creation_input_tokens": 0}
msg = {"id": "msg_a", "role": "assistant", "model": "gpt-5.5"}
p = self._write([
_rec(type="user", message={"role": "user", "content": "list files"}),
_rec(type="assistant", requestId="msg_a", effort="high",
message={**msg, "content": [
{"type": "thinking", "thinking": "look"},
{"type": "tool_use", "id": "call_a", "name": "Bash",
"input": {"command": "ls"}}]}),
_rec(type="user", message={"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "call_a",
"content": [{"type": "text", "text": "a.py"}]}]}),
_rec(type="assistant", requestId="msg_a",
message={**msg, "content": [], "usage": usage}),
_rec(type="assistant", requestId="msg_b",
message={"id": "msg_b", "role": "assistant", "model": "gpt-5.5",
"content": [{"type": "text", "text": "a.py only. DONE"}],
"usage": usage}),
])
s = parse_conversation(p, full=False)
self.assertEqual(s["harness"], "opencode")
self.assertEqual(s["assistantTurns"], 2)
one = usage_cost(norm_usage(usage), "gpt-5.5")
self.assertAlmostEqual(s["cost"], 2 * one)
# the step's charge went to its tool, not to "msg" (the first call's
# prompt share is the injected context, as on any transcript)
self.assertAlmostEqual(s["byTool"]["shell"]["cost"] + s["byTool"]["context"]["cost"], one)
self.assertAlmostEqual(s["byTool"]["msg"]["cost"], one)
self.assertEqual(s["efforts"], ["high"])
t = parse_conversation(p, full=True)
card = next(i for i in t["thread"] if i.get("name") == "shell")
self.assertAlmostEqual(card["turnCost"], one)
self.assertEqual(card["result"], "a.py")
self.assertFalse([i for i in t["thread"] if i.get("kind") == "turn"])
class Accounts(unittest.TestCase):
def test_the_chatgpt_seat(self):
self.assertEqual(accounts.harness_of("chatgpt-work"), "opencode")
self.assertEqual(accounts.harness_of("work"), "claude")
# clean provider accounts: the EVOX2's keyless one is `evox2` (alias
# `opencode-lab`); pi bills its model's vendor, never a fake `personal`
self.assertEqual(accounts.for_harness("opencode"), ["chatgpt-work", "evox2"])
self.assertEqual(accounts.for_harness("pi"), ["openrouter", "evox2"])
self.assertEqual(accounts.valid("opencode-lab"), "evox2")
self.assertIsNone(accounts.valid_for("work", "opencode"))
self.assertEqual(accounts.plan_windows("chatgpt-work"), ["week"])
self.assertEqual(accounts.plan_windows("personal"), ["week", "h5"])
self.assertFalse(accounts.counts_in_totals("chatgpt-work"))
self.assertEqual(accounts.transcripts_dirs()["chatgpt-work"],
(TMP / "oc" / "chatgpt-work").resolve())
def test_the_keyless_lab_account(self):
import models
from models import catalog
self.assertEqual(accounts.harness_of("opencode-lab"), "opencode")
self.assertEqual(accounts.plan_windows("opencode-lab"), [])
pub = {a["id"]: a for a in accounts.public()}
self.assertTrue(pub["evox2"]["keyless"])
self.assertEqual(pub["evox2"]["aliases"], ["opencode-lab"])
self.assertFalse(pub["chatgpt-work"]["keyless"])
self.assertTrue(accounts.counts_in_totals("opencode-lab"))
# pi's EVOX2 chips, twinned for opencode under the provider prefix
local = {m["id"]: m for m in catalog.list_models()
if m["harness"] == "opencode" and m["provider"] == "evox2"}
self.assertIn("evox2/ggml-org/qwen3.8-27b", local)
self.assertTrue(all(m["harness"] == "opencode" for m in local.values()))
# a Qwen twin thinks only when asked; Inkling's (on its own server,
# llm-inkling = pi's `evox2-inkling`) takes reasoning levels
self.assertEqual(local["evox2/ggml-org/qwen3.8-27b"]["efforts"], ["think"])
self.assertEqual(local["evox2-inkling/inkling-2-mini"]["efforts"],
["none", "low", "medium", "high"])
self.assertTrue(models.is_local("evox2/qwen3.6-35b-a3b"))
self.assertTrue(models.is_local("ggml-org/qwen3.8-27b"))
self.assertTrue(models.is_local("inkling-2-mini"))
self.assertTrue(models.is_local("evox2-inkling/inkling-2-mini"))
self.assertFalse(models.is_local("gpt-6-sol"))
self.assertFalse(models.is_local("qwen/qwen3.8-27b"))
self.assertEqual(rates_for("evox2/ggml-org/qwen3.8-27b"), (0, 0, 0))
# an id with no family hint is still free, never priced as Opus
self.assertEqual(rates_for("inkling-2-mini"), (0, 0, 0))
self.assertEqual(rates_for("evox2-inkling/inkling-2-mini"), (0, 0, 0))
def test_context_window_reads_the_catalogue_entry_first(self):
import models
# the EVOX2 serves the 27B at 131k: its entry, not the qwen family's 262k
self.assertEqual(models.context_window("ggml-org/qwen3.8-27b"), 131_072)
self.assertEqual(models.context_window("inkling-2-mini"), 131_072)
# OpenRouter's twin of the same model is no catalogue entry: the family's
self.assertEqual(models.context_window("qwen/qwen3.8-27b-turbo"), 262_144)
self.assertEqual(models.context_window("claude-haiku-4-5"), 200_000)
self.assertEqual(models.context_window("something-new"), 200_000)
def test_local_twin_base(self):
from models import catalog
self.assertEqual(catalog.local_twin_base("evox2-inkling/inkling-2-mini"), "inkling-2-mini")
self.assertEqual(catalog.local_twin_base("evox2/ggml-org/qwen3.8-27b"), "ggml-org/qwen3.8-27b")
for mid in ("inkling-2-mini", "qwen/qwen3.8-27b", "openrouter/qwen/x", "evox2", None):
self.assertIsNone(catalog.local_twin_base(mid))
class Calibration(unittest.TestCase):
def test_a_week_only_plan(self):
cal = calibrate.default_calibration("chatgpt-work")
self.assertIn("week", cal)
self.assertNotIn("h5", cal)
self.assertTrue(calibrate._trusted({**cal, "source": "fit",
"week": {**cal["week"], "r2": 0.9, "n": 30}}))
class Feed(unittest.TestCase):
def test_opencode_files_land_in_claudes_layout(self):
rel = pathlib.PurePosixPath(f"@opencode/chatgpt-work/-Users-g-repo/{SID}.jsonl")
self.assertEqual(local_rel(rel).as_posix(), f"-Users-g-repo/{SID}.jsonl")
sub = pathlib.PurePosixPath(f"@opencode/chatgpt-work/-x/{SID}/subagents/agent-a.jsonl")
self.assertEqual(local_rel(sub).as_posix(), f"-x/{SID}/subagents/agent-a.jsonl")
self.assertEqual(opencode_account(rel.as_posix()), "chatgpt-work")
self.assertIsNone(opencode_account(f"-x/{SID}.jsonl"))
class FakeUsageStore:
def __init__(self):
self.rows = []
def last_point(self, account, window):
pts = [r for r in self.rows if r[0] == account and r[1] == window]
return (pts[-1][2], pts[-1][3], pts[-1][4]) if pts else None
def add_points(self, rows):
self.rows += rows
return len(rows)
class UsageAlerts(unittest.TestCase):
def test_a_worker_snapshot_and_one_push_past_95(self):
body = {"updated_at": time.time(), "rate_limits": {
"seven_day": {"used_percentage": 90.0, "resets_at": 1792400000}}}
pushes = []
store = FakeUsageStore()
poller = UsagePoller(store, dirs={}, remote=lambda: {"chatgpt-work": body},
alert=lambda *a: pushes.append(a))
poller.poll_once()
self.assertIn("chatgpt-work", poller.accounts())
self.assertEqual(poller.limits()["chatgpt-work"]["windows"]["seven_day"]["pct"], 90.0)
body["updated_at"] += 60
body["rate_limits"]["seven_day"]["used_percentage"] = 96.0
poller.poll_once()
body["updated_at"] += 60
body["rate_limits"]["seven_day"]["used_percentage"] = 97.0
poller.poll_once()
self.assertEqual(pushes, [("chatgpt-work", "seven_day", 96.0, 95, 1792400000)])
if __name__ == "__main__":
unittest.main()