"""OpenCode Zen keeps one session identity and its cost basis on both routes. Zen keys its cached prefix by the session headers, and bills by the cost fields in each route's own usage. The route a profile's model picks, the headers the client adds, and the usage the session records meet only in the running daemon. """ import json import unittest from contextlib import closing from harness import Albedo, Provider, Reply, text class OpencodeZenTests(unittest.TestCase): def test_zen_keeps_its_identity_on_chat_and_responses_routes(self): # OpenCode's cost fields, which both routes carry in their own usage. billing: dict[str, object] = {} def script(request: dict) -> Reply: if request["model"].startswith("muse-spark-"): return text( "ok", usage={"input_tokens": 10, "output_tokens": 20, **billing} ) usage = {"prompt_tokens": 10, "completion_tokens": 20, **billing} return Reply( "text", "ok", events=[ {"choices": [{"index": 0, "delta": {"content": "ok"}}]}, { "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}], "usage": usage, }, ], ) with closing(Provider(script)) as provider: profiles = { name: { "extension": "opencode-zen", "baseUrl": provider.url, "apiKey": "zen-key", "protocol": "chat_completions", "model": model, } for name, model in ( ("chat", "fixture-model"), ("responses", "muse-spark-fixture"), ) } with Albedo(provider, providers=profiles) as app: for profile, path in ( ("chat", "/chat/completions"), ("responses", "/responses"), ): app.profile = profile session = app.session() before = len(provider.requests) for charge, basis, usd in ( (0, "listed", 0.00412), (0.002, "charged", 0.002), ): billing["cost"] = charge billing["opencode"] = { "billing_source": "balance" if charge else "free", "list_cost": 0.00412, } app.prompt(session, "say ok").close() app.idle(session) with app.api(f"/sessions/{session}?tail=0") as response: spent = json.load(response)["usage"]["spent"] self.assertIsNotNone(spent) self.assertEqual(spent["basis"], basis) self.assertAlmostEqual(spent["usd"], usd) sent = provider.requests[before:] self.assertEqual(len(sent), 2) self.assertTrue( all(record["path"].endswith(path) for record in sent) ) identities = [] for record in sent: headers = record["headers"] self.assertEqual(headers["authorization"], "Bearer zen-key") self.assertEqual(headers["x-opencode-client"], "cli") self.assertTrue(headers["user-agent"].startswith("opencode/")) identity = headers["x-opencode-session"] self.assertTrue(identity.startswith("ses_")) for key in ( "x-opencode-session-id", "x-session-affinity", "x-session-id", ): self.assertEqual(headers[key], identity) self.assertTrue(headers["x-opencode-project"]) identities.append(identity) self.assertEqual(identities[0], identities[1]) if __name__ == "__main__": unittest.main()