Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188"""A profile's turns go to its own base url unless it names a key saved elsewhere.
A key account owns its routing, so a key in the wrong profile's list sends thatprofile's conversation to another host. Catches the two ways one got therewithout anyone choosing it: startup folded every OpenCode Go and Alibaba key intoeach such hand-written profile's rotation, and a plain Mistral profile took thefirst saved key whatever endpoint it was saved for.
Accounts and startup migrations are global, so every test gets its own daemon."""
import jsonimport timeimport unittestfrom contextlib import ExitStack, closing
from harness import Albedo, Provider, Reply, exclusive, operation_id, text
# A rotation spreads sessions over its members, so each profile runs a few.SESSIONS = 4
@exclusiveclass KeyEndpointTests(unittest.TestCase): def start(self, extension, model, *, keyed=True): """Two fake providers and one `extension` profile at each.""" stack = ExitStack() self.addCleanup(stack.close) providers = { name: stack.enter_context(closing(Provider(lambda _request: text("ok")))) for name in ("a", "b") } profiles = { name: { "extension": extension, "baseUrl": provider.url, "model": model, "protocol": "chat_completions", **({"apiKey": f"{name}-key"} if keyed else {}), } for name, provider in providers.items() } app = stack.enter_context(Albedo(providers["a"], providers=profiles)) return app, providers
def turns(self, app, profile): """Runs one turn in each of SESSIONS new sessions on `profile`.""" app.profile = profile for _ in range(SESSIONS): session = app.session() app.prompt(session, "say ok").close() app.idle(session)
def assert_own_endpoint(self, app, providers): config = json.loads((app.home / "config.json").read_text())["providers"] for name in providers: self.assertEqual(len(config[name].get("accountIds") or [None]), 1) for name in providers: self.turns(app, name) for name, provider in providers.items(): with self.subTest(profile=name): self.assertEqual( {sent["authorization"] for sent in provider.requests}, {f"Bearer {name}-key"}, ) self.assertEqual(len(provider.requests), SESSIONS)
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])
def test_opencode_go_profiles_keep_their_own_endpoint_and_key(self): self.assert_own_endpoint(*self.start("opencode-go", "qwen-fixture"))
def test_alibaba_profiles_keep_their_own_endpoint_and_key(self): self.assert_own_endpoint(*self.start("alibaba", "fixture-model"))
def test_a_plain_mistral_profile_skips_a_key_saved_for_another_endpoint(self): app, providers = self.start("mistral", "mistral-fixture", keyed=False) body = { "provider": "mistral", "endpoint": providers["b"].url, "api_key": "b-key", } with app.api(f"/auth/keys/{operation_id()}", body, method="PUT") as response: response.read() app.profile = "a" session = app.session() app.prompt(session, "say ok").close() deadline = time.monotonic() + 10 while time.monotonic() < deadline: with app.api(f"/sessions/{session}?tail=0") as response: blocked = json.load(response)["status"]["blocking_reason"] if blocked: break time.sleep(0.03) self.assertIn("Mistral is not authenticated", blocked["detail"]) self.assertEqual(providers["a"].requests, []) self.assertEqual(providers["b"].requests, []) self.turns(app, "b") self.assertEqual( {sent["authorization"] for sent in providers["b"].requests}, {"Bearer b-key"}, )
if __name__ == "__main__": unittest.main()