diff --git a/e2e/github_copilot_test.py b/e2e/github_copilot_test.py index 781d0be99..ff01523de 100644 --- a/e2e/github_copilot_test.py +++ b/e2e/github_copilot_test.py @@ -15,6 +15,7 @@ import time import unittest import urllib.parse +from acp_support import AcpClient from github_copilot_support import ACCESS_TOKEN, COPILOT_TOKEN, Github from harness import ( Albedo, @@ -30,6 +31,8 @@ from harness import ( ) CHAT_MODEL = "gemini-3.7-flash" +FRESH_MODEL = "mai-code-2" # models.dev has no row for it +OVERLAY_MODEL = "gemini-3.8-flash" # models.dev describes it differently # A name the families would send to /responses, which its list serves on # /chat/completions only. LISTED_CHAT_MODEL = "grok-code-chat" @@ -76,6 +79,35 @@ API_MODELS = { "supports": {"tool_calls": True, "streaming": True}, }, }, + { + "id": FRESH_MODEL, + "name": "MAI Code 2", + "model_picker_enabled": True, + "supported_endpoints": ["/chat/completions", "/responses"], + "capabilities": { + "family": "mai", + "limits": { + "max_context_window_tokens": 1050000, + "max_output_tokens": 128000, + }, + "supports": { + "tool_calls": True, + "reasoning_effort": ["low", "medium", "high", "xhigh", "max"], + }, + }, + }, + { + "id": OVERLAY_MODEL, + "model_picker_enabled": True, + "supported_endpoints": ["/chat/completions"], + "capabilities": { + "limits": { + "max_context_window_tokens": 1048576, + "max_output_tokens": 65536, + }, + "supports": {"tool_calls": True, "reasoning_effort": ["low", "high"]}, + }, + }, { "id": LISTED_CHAT_MODEL, "name": "Grok Code", @@ -114,9 +146,20 @@ MODELS_DEV = { "id": RESPONSES_MODEL, "limit": {"context": 400000, "output": 128000}, }, + OVERLAY_MODEL: { + "id": OVERLAY_MODEL, + "limit": {"context": 1000000, "output": 64000}, + "reasoning_options": [ + {"type": "effort", "values": ["low", "medium", "high"]} + ], + }, MESSAGES_MODEL: { "id": MESSAGES_MODEL, "limit": {"context": 200000, "output": 64000}, + # The profile's saved level must be valid on the starting model. + "reasoning_options": [ + {"type": "effort", "values": ["low", "medium", "high"]} + ], }, }, } @@ -168,20 +211,21 @@ class GithubCopilotTests(unittest.TestCase): self.github.seen.clear() self.github.authorized = False - def start(self, model, replies, *, token="github-fixture-seed"): + def start(self, model, replies, *, token="github-fixture-seed", effort=None): """A Copilot profile pinned at `model` over a scripted Copilot API.""" provider = Provider(scripting(list(replies)), catalog=API_MODELS) self.addCleanup(provider.close) + profile = { + "extension": "github-copilot", + "baseUrl": provider.url, + "model": model, + "protocol": "chat_completions", + } + if effort: + profile["effort"] = effort app = Albedo( provider, - providers={ - "copilot": { - "extension": "github-copilot", - "baseUrl": provider.url, - "model": model, - "protocol": "chat_completions", - } - }, + providers={"copilot": profile}, prepare=self.prepare, ) app.__enter__() @@ -472,6 +516,83 @@ class GithubCopilotTests(unittest.TestCase): self.assertEqual(usage["spent"]["basis"], "counted") self.assertAlmostEqual(usage["spent"]["usd"], 0.0042) + def test_a_model_only_the_accounts_list_describes_is_listed_and_selectable(self): + """The account's list describes a model models.dev lacks, overrules it + where they differ, and admits the model under a profile's saved level. + Without those facts the write answers -32602, which an editor reports as + "The agent did not accept the model". + """ + app, provider = self.start( + MESSAGES_MODEL, + [text("from mai")], + token="github-fixture-listed", + effort="high", + ) + endpoint = urllib.parse.quote(provider.url, safe="") + with app.api( + f"/models?provider=github-copilot&endpoint={endpoint}" + ) as response: + listed = {item["id"]: item for item in json.load(response)["items"]} + fresh = listed[FRESH_MODEL] + self.assertEqual(fresh["default_context_tokens"], 1050000) + self.assertEqual(fresh["max_output_tokens"], 128000) + self.assertEqual( + [effort["id"] for effort in fresh["efforts"]], + ["low", "medium", "high", "xhigh", "max"], + ) + self.assertIn("the account's model list", fresh["source"]) + # The list wins where both describe a model. + overlay = listed[OVERLAY_MODEL] + self.assertEqual(overlay["default_context_tokens"], 1048576) + self.assertEqual(overlay["max_output_tokens"], 65536) + self.assertEqual( + [effort["id"] for effort in overlay["efforts"]], ["low", "high"] + ) + + client = AcpClient(app.env) + self.addCleanup(client.kill) + self.acp(client, "initialize", {"protocolVersion": 1, "clientCapabilities": {}}) + created = self.acp( + client, "session/new", {"cwd": str(app.workspace), "mcpServers": []} + ) + offered = [ + choice["value"] + for option in created["configOptions"] + if option["id"] == "model" + for choice in option["options"] + ] + target = [value for value in offered if value.rsplit("/", 1)[-1] == FRESH_MODEL] + self.assertEqual(len(target), 1, offered) + # The switch a saved profile level used to be refused for. + self.acp( + client, + "session/set_config_option", + { + "sessionId": created["sessionId"], + "configId": "model", + "value": target[0], + }, + ) + turn = self.acp( + client, + "session/prompt", + { + "sessionId": created["sessionId"], + "prompt": [{"type": "text", "text": "hello"}], + }, + ) + self.assertEqual(turn["stopReason"], "end_turn") + [request] = provider.requests + # Its route, at the profile's level. + self.assertTrue(request["path"].endswith("/responses"), request["path"]) + self.assertEqual(request["request"]["reasoning"]["effort"], "high") + + def acp(self, client, method, params): + """An exchange the editor accepts; an error is the refusal it shows.""" + response = client.request(method, params).response + self.assertNotIn("error", response, response) + return response.get("result") or {} + def test_the_picker_lists_only_the_models_the_account_may_pick(self): app, provider = self.start(CHAT_MODEL, []) endpoint = urllib.parse.quote(provider.url, safe="") @@ -481,7 +602,16 @@ class GithubCopilotTests(unittest.TestCase): listed = json.load(response) self.assertEqual( sorted(item["id"] for item in listed["items"]), - sorted([CHAT_MODEL, RESPONSES_MODEL, MESSAGES_MODEL, LISTED_CHAT_MODEL]), + sorted( + [ + CHAT_MODEL, + RESPONSES_MODEL, + MESSAGES_MODEL, + FRESH_MODEL, + OVERLAY_MODEL, + LISTED_CHAT_MODEL, + ] + ), ) @exclusive diff --git a/extensions/github_copilot/README.md b/extensions/github_copilot/README.md index 87621789c..a57302d04 100644 --- a/extensions/github_copilot/README.md +++ b/extensions/github_copilot/README.md @@ -9,6 +9,9 @@ API. device login, the `github-copilot` model provider, and model catalogs. - [`accounts`](src/albedo_ext_github_copilot/accounts.gleam) exchanges GitHub credentials for short-lived Copilot tokens and selects profile accounts. +- [`catalog`](src/albedo_ext_github_copilot/catalog.gleam) answers a model's + limits and levels from models.dev and the account's own `/models` list, which + wins where it speaks. - [`wire`](src/albedo_ext_github_copilot/wire.gleam) chooses each model's request protocol and provider-specific headers. diff --git a/extensions/github_copilot/src/albedo_ext_github_copilot/catalog.gleam b/extensions/github_copilot/src/albedo_ext_github_copilot/catalog.gleam index 569985a6a..001f6419b 100644 --- a/extensions/github_copilot/src/albedo_ext_github_copilot/catalog.gleam +++ b/extensions/github_copilot/src/albedo_ext_github_copilot/catalog.gleam @@ -2,12 +2,16 @@ //// limits and efforts, and the account's own /models list for what it may pick. //// It answers only for the Copilot API, or a base url a Copilot profile names, //// so a shared model id elsewhere stays another catalog's to describe. +//// +//// The list's window, output limit and levels overrule models.dev's, and +//// stand alone for a model models.dev lacks. Routing reads it in `wire`. import albedo_bytes/digest import albedo_ext_github_copilot/accounts import albedo_ext_github_copilot/wire import albedo_file import albedo_http/buffered +import albedo_model as types import albedo_models_dev as models import albedo_sdk/credentials import albedo_sdk/extension @@ -27,17 +31,37 @@ import gleam/string pub const provider_name = "github-copilot" +/// What the account's list says about a model's limits, not its endpoints. +type Facts { + Facts( + context_tokens: Option(Int), + max_output_tokens: Option(Int), + /// Spelled as the API spells them. + efforts: List(String), + ) +} + pub fn catalog() -> extension.ModelCatalog { extension.ModelCatalog(lookup, list_models, None) } fn lookup(id: String, at: Option(String)) -> Option(extension.ModelInfo) { use url <- option.then(at) - use found <- option.then(models.lookup_provider(provider_name, id)) use <- bool.guard(!accounts.serves(settings.home(), url), None) + let listed = + dict.get(saved_facts(settings.home(), url), wire.served_key(id)) + |> option.from_result + use info <- option.then( + case models.lookup_provider(provider_name, id), listed { + Some(found), Some(facts) -> Some(with_listed_facts(found, facts)) + Some(found), None -> Some(found) + None, Some(facts) -> Some(listed_model(id, facts)) + None, None -> None + }, + ) Some( extension.ModelInfo( - ..found, + ..info, provider: provider_name, endpoint: Some(url), environment: ["GITHUB_TOKEN"], @@ -45,6 +69,45 @@ fn lookup(id: String, at: Option(String)) -> Option(extension.ModelInfo) { ) } +/// A model models.dev has no row for, from the account's list alone. +fn listed_model(id: String, facts: Facts) -> extension.ModelInfo { + extension.ModelInfo( + ..extension.blank_model(id, provider_name), + context_tokens: facts.context_tokens, + max_output_tokens: facts.max_output_tokens, + source: "the account's model list", + efforts: types.parse_efforts(facts.efforts), + ) +} + +/// `info` with the list's facts, which overrule the catalog's where stated. +fn with_listed_facts( + info: extension.ModelInfo, + facts: Facts, +) -> extension.ModelInfo { + let merged = + extension.ModelInfo( + ..info, + context_tokens: option.or(facts.context_tokens, info.context_tokens), + max_output_tokens: option.or( + facts.max_output_tokens, + info.max_output_tokens, + ), + efforts: case types.parse_efforts(facts.efforts) { + [] -> info.efforts + efforts -> efforts + }, + ) + case merged == info { + True -> info + False -> + extension.ModelInfo( + ..merged, + source: info.source <> "; the account's model list", + ) + } +} + /// The models the signed-in account may pick that can call tools, or /// models.dev's list until the API answers. fn list_models( @@ -83,6 +146,7 @@ fn models( case status { 200 -> { save_endpoints(home, access.session.endpoint, listed_endpoints(body)) + save_facts(home, access.session.endpoint, listed_facts(body)) chat_model_ids(body) } 401 -> Error("GitHub Copilot refused the credential") @@ -146,6 +210,56 @@ fn endpoints_file(api: String) -> String { <> ".json" } +/// The facts file for `api`, hashed like `endpoints_file`. +fn facts_file(api: String) -> String { + "github-copilot-facts-" + <> digest.hex(digest.sha256(<>)) + <> ".json" +} + +/// What each row states about its model, by `wire.served_key`. Rows that state +/// nothing, or cannot be read, are left out. +fn listed_facts(body: BitArray) -> Dict(String, Facts) { + json.parse_bits(body, decode.at(["data"], decode.list(decode.dynamic))) + |> result.unwrap([]) + |> list.filter_map(listed_facts_row) + |> dict.from_list +} + +fn listed_facts_row(item: Dynamic) -> Result(#(String, Facts), Nil) { + use id <- result.try( + decode.run(item, decode.at(["id"], decode.string)) + |> result.replace_error(Nil), + ) + use <- bool.guard(id == "", Error(Nil)) + let facts = + Facts( + context_tokens: positive(item, [ + "capabilities", "limits", "max_context_window_tokens", + ]), + max_output_tokens: positive(item, [ + "capabilities", "limits", "max_output_tokens", + ]), + efforts: texts(item, ["capabilities", "supports", "reasoning_effort"]), + ) + case facts == Facts(None, None, []) { + True -> Error(Nil) + False -> Ok(#(wire.served_key(id), facts)) + } +} + +fn positive(row: Dynamic, path: List(String)) -> Option(Int) { + case decode.run(row, decode.at(path, decode.int)) { + Ok(limit) if limit > 0 -> Some(limit) + _ -> None + } +} + +fn texts(row: Dynamic, path: List(String)) -> List(String) { + decode.run(row, decode.at(path, decode.list(decode.string))) + |> result.unwrap([]) +} + /// The usable ids, sorted and deduplicated. Invalid JSON and a body without a /// `data` list are both refused as the wrong shape. fn chat_model_ids(body: BitArray) -> Result(List(String), String) { @@ -191,3 +305,49 @@ fn usable_model(row: Dynamic) -> Bool { } } } + +/// What the last /models fetch from `api` said; empty until one ran. +fn saved_facts(home: String, api: String) -> Dict(String, Facts) { + albedo_file.read(albedo_file.join(home, facts_file(api))) + |> result.try(fn(bytes) { + json.parse_bits(bytes, decode.dict(decode.string, facts_decoder())) + |> result.replace_error(Nil) + }) + |> result.unwrap(dict.new()) +} + +fn save_facts(home: String, api: String, facts: Dict(String, Facts)) -> Nil { + let text = + json.dict(facts, fn(id) { id }, fn(facts) { + json.object([ + #("context", json.nullable(facts.context_tokens, json.int)), + #("output", json.nullable(facts.max_output_tokens, json.int)), + #("efforts", json.array(facts.efforts, json.string)), + ]) + }) + |> json.to_string + let _ = + albedo_file.write_private(albedo_file.join(home, facts_file(api)), << + text:utf8, + >>) + Nil +} + +fn facts_decoder() -> decode.Decoder(Facts) { + use context_tokens <- decode.optional_field( + "context", + None, + decode.optional(decode.int), + ) + use max_output_tokens <- decode.optional_field( + "output", + None, + decode.optional(decode.int), + ) + use efforts <- decode.optional_field( + "efforts", + [], + decode.list(decode.string), + ) + decode.success(Facts(context_tokens, max_output_tokens, efforts)) +} diff --git a/robot-docs/models.md b/robot-docs/models.md index 43a039548..bea285f9b 100644 --- a/robot-docs/models.md +++ b/robot-docs/models.md @@ -252,6 +252,12 @@ A model listed on several endpoints keeps the route its family usually takes when that is among them. Before a list has been fetched, or for a model it does not name, the family decides. +For the same endpoint it writes `github-copilot-facts-.json`: each row's +window, output limit and reasoning levels, which overrule models.dev's (the +shared catalog lags the seat) and describe a model models.dev has no row for. +Without them a model has no window to compact against, and a session inheriting +its profile's level is refused (clients report the model as not accepted). + Codex reads `codex-models.json` from the correctly encoded home path. If that file is absent, it checks the legacy path that treated UTF-8 bytes as Unicode codepoints and validates the cache before copying its bytes to the canonical