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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261"""Each wire format a provider adapter can pick carries a whole tool turn.
Catches a shared codec that encodes a request, reduces a stream or replays atool call wrongly. Several providers share the Anthropic Messages and Geminicodecs, and before this file no turn through the real daemon reached Gemini's.OpenCode Go is the adapter because an API key and a base URL are all it needs,and it picks one of four formats from the model's name. The format is what ischecked, not OpenCode Go: its sign-in is in opencode_go_login_test.py. Theproviders that reach fixed or signed hosts (Claude, Vertex, Bedrock, Codex,Antigravity) are not reached here, and Antigravity's wire is its own.
The catalogue is daemon-wide, so the class is exclusive."""
from collections.abc import Callableimport jsonfrom typing import Anyimport unittest
from harness import Albedo, Provider, Reply, cell_output, exclusive_class, python, text
MESSAGES_MODEL = "claude-go-fixture"GEMINI_MODEL = "gemini-go-fixture"RESPONSES_MODEL = "gpt-go-fixture"CHAT_MODEL = "glm-go-fixture"MODELS = [MESSAGES_MODEL, GEMINI_MODEL, RESPONSES_MODEL, CHAT_MODEL, "minimax-m2.7"]
# A ceiling no wire would pick by itself.CEILING = 12345MODELS_DEV = { "fixture": { "id": "fixture", "name": "Fixture", "api": "http://127.0.0.1", "models": { model: {"limit": {"context": 200000, "output": CEILING}} for model in MODELS }, }}CODE = "print(6 * 7)"
def tool_turn(_request: dict[str, Any]) -> list[Reply]: """The model thinks, runs a cell, then answers.""" return [ python(CODE, reasoning="multiply first"), text("the answer is 42", usage={"input_tokens": 1200, "output_tokens": 34}), ]
@exclusive_classclass ProviderProtocolTests(unittest.TestCase): def start( self, model: str, script: Callable[[dict[str, Any]], list[Reply]] = tool_turn, ) -> tuple[Albedo, Provider]: provider = Provider( script, catalog={"data": [{"id": model_id} for model_id in MODELS]} ) self.addCleanup(provider.close)
def offline(app: Albedo) -> None: (app.home / "models.json").write_text(json.dumps(MODELS_DEV)) (app.home / "models.json.index").unlink(missing_ok=True) app.write_extensions({"models": {"refreshHours": 0}})
app = Albedo( provider, providers={ "go": { "extension": "opencode-go", "baseUrl": provider.url, "apiKey": "go-key", "model": model, "protocol": "chat_completions", } }, prepare=offline, ) app.__enter__() self.addCleanup(app.__exit__, None, None, None) return app, provider
def turn(self, app: Albedo, session: str, prompt: str) -> list[tuple[str, str]]: """Runs one turn, which must end without an error, and returns what it showed as `(kind, text)` lines.""" app.prompt(session, prompt).close() lines = app.idle(session)["activity"]["lines"] self.assertEqual([line for line in lines if line["kind"] == "error"], []) return [(line["kind"], line["text"]) for line in lines]
def use(self, app: Albedo, session: str, model: str) -> None: with app.api(f"/sessions/{session}?view=configuration") as response: response.read() etag = response.headers["ETag"] with app.api( f"/sessions/{session}?view=configuration", {"model": model}, method="PATCH", headers={"If-Match": etag}, ) as response: response.read()
def assert_stream_reduced( self, app: Albedo, session: str, shown: list[tuple[str, str]] ) -> None: """The thinking and the answer were shown, and the usage the last stream reported was counted.""" self.assertIn(("thinking", "multiply first"), shown) self.assertIn(("assistant", "the answer is 42"), shown) self.assertFalse( any( kind == "assistant" and "multiply first" in value for kind, value in shown ) ) with app.api(f"/sessions/{session}?tail=0") as response: usage = json.load(response)["usage"] self.assertEqual( (usage["prompt_tokens"], usage["completion_tokens"]), (1200, 34) )
def test_anthropic_messages_carries_a_tool_turn(self) -> None: app, provider = self.start(MESSAGES_MODEL) session = app.session() shown = self.turn(app, session, "what is six times seven") self.assert_stream_reduced(app, session, shown)
# A misclassified title consumes a list reply and breaks this tool turn. asked, resumed = provider.requests self.assertTrue(asked["path"].endswith("/messages"), asked["path"]) self.assertEqual(asked["model"], MESSAGES_MODEL) body = asked["request"] self.assertEqual(body["max_tokens"], CEILING) self.assertEqual([tool["name"] for tool in body["tools"]], ["python"]) self.assertIn("input_schema", body["tools"][0]) self.assertEqual(body["messages"][-1]["role"], "user")
# Anthropic pairs a result with its call by id. call, result = [ block for message in resumed["request"]["messages"] for block in message["content"] if block["type"] in ("tool_use", "tool_result") ] self.assertEqual((call["name"], call["input"]["code"]), ("python", CODE)) self.assertTrue(call["id"]) self.assertEqual(result["tool_use_id"], call["id"]) self.assertEqual(cell_output(result["content"][0]["text"]), "42\n")
def test_gemini_carries_a_tool_turn(self) -> None: app, provider = self.start(GEMINI_MODEL) session = app.session() shown = self.turn(app, session, "what is six times seven") self.assert_stream_reduced(app, session, shown)
# A misclassified title consumes a list reply and breaks this tool turn. asked, resumed = provider.requests self.assertTrue( asked["path"].endswith( f"/models/{GEMINI_MODEL}:streamGenerateContent?alt=sse" ), asked["path"], ) self.assertEqual(asked["model"], GEMINI_MODEL) body = asked["request"] self.assertEqual(body["generationConfig"]["maxOutputTokens"], CEILING) [declared] = body["tools"] self.assertEqual( [tool["name"] for tool in declared["functionDeclarations"]], ["python"] ) self.assertEqual(body["contents"][-1]["role"], "user") self.assert_gemini_replays_the_call(resumed)
def test_a_tool_turn_is_replayed_in_each_format_a_session_moves_to(self) -> None: """A session that changes model keeps its history, whatever format the next model is served in.""" replies = [ python(CODE), text("the answer is 42"), text("still 42"), text("still 42"), ] app, provider = self.start(MESSAGES_MODEL, lambda _request: replies) session = app.session() self.turn(app, session, "what is six times seven") for model in (GEMINI_MODEL, RESPONSES_MODEL): self.use(app, session, model) self.turn(app, session, "and again")
gemini, responses = provider.requests[2:] self.assert_gemini_replays_the_call(gemini) self.assertTrue(responses["path"].endswith("/responses"), responses["path"]) items = responses["request"]["input"] [call] = [item for item in items if item.get("type") == "function_call"] [result] = [ item for item in items if item.get("type") == "function_call_output" ] self.assertEqual( (call["name"], json.loads(call["arguments"])["code"]), ("python", CODE) ) self.assertTrue(call["call_id"]) self.assertEqual(result["call_id"], call["call_id"]) self.assertEqual(cell_output(result["output"]), "42\n")
def test_request_ledger_marks_only_explicit_messages_cache_breakpoints( self, ) -> None: app, provider = self.start(MESSAGES_MODEL, lambda _request: [text("ok")]) session = app.session(name="cache accounting") for model in MODELS: with self.subTest(model=model): self.use(app, session, model) self.turn(app, session, "say ok") sent = provider.requests[-1] with app.api(f"/sessions/{session}/context?view=requests") as response: rows = json.load(response)["items"] row = [item for item in rows if item["kind"] == "turn"][-1] self.assertEqual(row["model"], model) if sent["path"].endswith("/messages"): self.assertTrue(row["cache_marks"], row) self.assertTrue( all(mark["ttl_seconds"] == 300 for mark in row["cache_marks"]) ) self.assertIn("cache_control", sent["request"]["system"][-1]) else: self.assertEqual(row["cache_marks"], [], row)
def assert_gemini_replays_the_call(self, sent: dict[str, Any]) -> None: """Gemini pairs a result with its call by name and order, not by id.""" self.assertTrue( sent["path"].endswith( f"/models/{GEMINI_MODEL}:streamGenerateContent?alt=sse" ), sent["path"], ) parts = [ part for content in sent["request"]["contents"] for part in content["parts"] ] self.assertEqual( [ key for part in parts for key in part if key in ("functionCall", "functionResponse") ], ["functionCall", "functionResponse"], ) [call] = [part["functionCall"] for part in parts if "functionCall" in part] [result] = [ part["functionResponse"] for part in parts if "functionResponse" in part ] self.assertEqual((call["name"], call["args"]["code"]), ("python", CODE)) self.assertEqual(result["name"], "python") self.assertEqual(cell_output(result["response"]["output"]), "42\n")
if __name__ == "__main__": unittest.main()