From 990d7652d391ffc7e41b60a5855236e2139b7bce Mon Sep 17 00:00:00 2001 From: "bunny.fae.mom" Date: Mon, 16 Nov 2026 01:06:46 -0500 Subject: [PATCH] refactor(models): carry vision limits, output modes and route capabilities refactor(vision): carry provider image facts as typed limits ImageLimits now carries a VisionProfile: the vision geometry a provider's images are read with, whether they reach it as uploads rather than inline, and the frame cap that applies when the provider states no image count. Every provider extension declares it on its Upstream, and snapcompact's shape, provider_cap and known_cap no longer match provider or model names; shape takes the declared geometry and the cap and the inline byte budget come from the profile. Frames and caps are unchanged for Anthropic API, Claude (uploads, so no byte budget), Bedrock, Antigravity (by model family), Vertex, Mistral, Perplexity and the OpenAI API itself. Codex keeps the unmeasured floor cap of 5 that its catalog attribution gave it before. Behaviour change, because snapcompact can no longer see a model name: routes that serve any vendor's model (Copilot, OpenCode Go and Zen, OpenAI-compatible gateways including OpenRouter) now render the default frame geometry, where a gpt, o-series or gemini-named model there used the OpenAI or Gemini geometry before. Their frame caps follow the host (OpenRouter 90, other gateways the floor) rather than whichever catalog attributed the model. refactor(openai): filter models by the outputs the endpoint lists OpenAI-compatible /models lists that carry architecture.output_modalities (OpenRouter and llama.cpp style gateways) now decide chat eligibility: a model that produces text is kept. The id name filter judges only rows that list no outputs, so a plain OpenAI list is unchanged. Behaviour change, limited to rows that list outputs: a model whose id contains audio, image, or similar but that produces text now appears in the picker, and a model that produces no text is hidden whatever its id says. A new e2e scenario in model_catalogs_test covers both orderings and the id fallback. refactor(copilot): route a model by the endpoints its /models list names The Copilot catalog keeps each model's supported_endpoints when it fetches /models, in a per-endpoint file beside the other model lists, and every connection carries them to the wire. wire.route now takes that fact: a model goes to the Chat Completions, Responses or Messages route its list names, and the prefix guess is only the fallback for a model no fetched list names, documented as such. A model listed on several endpoints keeps the route its family usually takes when that is among them, so no model whose family guess was already served moves; only a model whose list excludes the guess changes route (the new e2e uses a grok id the list serves on chat only). Models and the picker are unchanged. fix(codex): give the ChatGPT backend OpenAI's frame cap Codex's vision profile held snapcompact to the unmeasured floor of 5 frames per request. The floor was never chosen for it: the old cap table spelled the provider openai-codex while its catalog attributes models to codex, so the lookup missed and fell through to the default. The profile is now openai_vision as written for the other OpenAI routes. Snapcompact's frame budget for a Codex session rises from 5 to 60 frames, the inline byte budget being the tighter bound under the 200-frame cap. Geometry and image edge limits are unchanged. --- robot-docs/compaction.md | 9 ++- robot-docs/models.md | 14 ++++ .../extensions/anthropic_api/extension.gleam | 1 + .../extensions/antigravity/extension.gleam | 5 +- .../extensions/bedrock/extension.gleam | 2 +- .../harness/extensions/claude/extension.gleam | 5 +- .../harness/extensions/codex/extension.gleam | 2 +- .../extensions/github_copilot/catalog.gleam | 62 +++++++++++++++- .../extensions/github_copilot/extension.gleam | 7 +- .../extensions/github_copilot/wire.gleam | 69 +++++++++++++++--- .../harness/extensions/openai/extension.gleam | 53 ++++++++++---- .../extensions/snapcompact/extension.gleam | 72 +++++-------------- .../harness/extensions/vertex/extension.gleam | 2 +- src/albedo/openai_api/catalog.gleam | 12 +++- src/albedo/openai_api/types.gleam | 34 ++++++++- test/e2e/github_copilot_test.py | 45 ++++++++++-- test/e2e/model_catalogs_test.py | 26 +++++++ test/harness/messages_cache_test.gleam | 8 ++- test/harness/snapcompact_test.gleam | 17 ++++- 19 files changed, 346 insertions(+), 99 deletions(-) diff --git a/robot-docs/compaction.md b/robot-docs/compaction.md index 5935e61b9..a26c5229f 100644 --- a/robot-docs/compaction.md +++ b/robot-docs/compaction.md @@ -43,9 +43,12 @@ can represent earlier conversation as rendered frames or serialized text, with a verbatim tail. Its memory extension exposes `transcript.grep` and `transcript.read` to retrieve transcript rows. Its defaults are an 80% trigger, 10% tail, and 20% archive budget. When `maxFrames` is unset, the frame budget -depends on capacity, image limits, and provider caps, with an upper bound of 80 -frames. Settings validation requires `0 < tailPercent < triggerPercent < 100` -and `0 < archivePercent < 100`. +depends on capacity and the provider's declared image limits, with an upper +bound of 80 frames. Each provider's `ImageLimits` carries a `VisionProfile` +(geometry family, whether images ride inline, and a frame cap for a provider +that states no image count); snapcompact reads only that, never a provider or +model name. Settings validation requires +`0 < tailPercent < triggerPercent < 100` and `0 < archivePercent < 100`. Snapcompact's Gleam extension owns archive normalization and pagination. It expands tabs to four spaces and folds adjacent CR/LF runs into full-block cells. diff --git a/robot-docs/models.md b/robot-docs/models.md index 241f26258..24f021a7c 100644 --- a/robot-docs/models.md +++ b/robot-docs/models.md @@ -213,10 +213,24 @@ by [`catalog.input_modalities`](../src/albedo/openai_api/catalog.gleam)) in with them, completed from models.dev. A model that reports only text input then gets its images projected out instead of sent to a server that would refuse them. A model whose list entry omits the field keeps the old behavior. The +extension's picker keeps a model that reports `architecture.output_modalities` +(read by `catalog.output_modalities`) when it lists `text`, and hides one that +does not; only a listed model without that field is judged by its ID's name. The [ordinary HTTP client](../src/albedo/harness/sdk/http.gleam) preserves response headers for conditional catalog requests. Mixed-credential catalog reads do not establish model-session affinity. +The +[GitHub Copilot catalog](../src/albedo/harness/extensions/github_copilot/catalog.gleam) +keeps the `supported_endpoints` of each model its `/models` fetch lists in +`github-copilot-endpoints-.json` per API endpoint. Each session's +connection carries them, and the +[wire](../src/albedo/harness/extensions/github_copilot/wire.gleam) sends a model +to Chat Completions, Responses or Messages by what the list names. 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. + 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 diff --git a/src/albedo/harness/extensions/anthropic_api/extension.gleam b/src/albedo/harness/extensions/anthropic_api/extension.gleam index 6b9fb8660..9fae9f042 100644 --- a/src/albedo/harness/extensions/anthropic_api/extension.gleam +++ b/src/albedo/harness/extensions/anthropic_api/extension.gleam @@ -119,6 +119,7 @@ fn resolve( images: types.ImageLimits( int.min(image_edge, types.anthropic_images.max_edge), types.anthropic_images.max_images, + types.anthropic_vision, ), output: extension.NoCeiling, cache_marks: messages.cache_marks(_, wire.cache_ttl_seconds), diff --git a/src/albedo/harness/extensions/antigravity/extension.gleam b/src/albedo/harness/extensions/antigravity/extension.gleam index fd6abcc83..522e1b22d 100644 --- a/src/albedo/harness/extensions/antigravity/extension.gleam +++ b/src/albedo/harness/extensions/antigravity/extension.gleam @@ -292,7 +292,10 @@ fn upstream( fn(access) { access.access.email }, case catalog.family(model) { family.Claude -> types.anthropic_images - family.Gemini | family.GptOss -> types.any_images + family.Gemini -> + types.ImageLimits(types.max_image_edge, None, types.gemini_vision) + family.GptOss -> + types.ImageLimits(types.max_image_edge, None, types.openai_vision) }, ) } diff --git a/src/albedo/harness/extensions/bedrock/extension.gleam b/src/albedo/harness/extensions/bedrock/extension.gleam index 5b0abf5af..b60eb37cb 100644 --- a/src/albedo/harness/extensions/bedrock/extension.gleam +++ b/src/albedo/harness/extensions/bedrock/extension.gleam @@ -217,7 +217,7 @@ fn resolve( fn() { None }, fn(_) { [] }, case config.api { - "converse" -> types.ImageLimits(8000, Some(20)) + "converse" -> types.ImageLimits(8000, Some(20), types.anthropic_vision) _ -> types.anthropic_images }, extension.NoCeiling, diff --git a/src/albedo/harness/extensions/claude/extension.gleam b/src/albedo/harness/extensions/claude/extension.gleam index 3c9af24ba..512fd7967 100644 --- a/src/albedo/harness/extensions/claude/extension.gleam +++ b/src/albedo/harness/extensions/claude/extension.gleam @@ -182,7 +182,10 @@ fn resolve( } }, fn(connection) { wire.owner(connection.auth) }, - types.anthropic_images, + types.ImageLimits( + ..types.anthropic_images, + vision: types.VisionProfile(..types.anthropic_vision, uploaded: True), + ), ) Ok( extension.Upstream(..upstream, cache_marks: wire.cache_marks(auth.auth, _)), diff --git a/src/albedo/harness/extensions/codex/extension.gleam b/src/albedo/harness/extensions/codex/extension.gleam index 1b419eb92..1fd60f53d 100644 --- a/src/albedo/harness/extensions/codex/extension.gleam +++ b/src/albedo/harness/extensions/codex/extension.gleam @@ -259,7 +259,7 @@ fn resolve( profile_failure(context.home, context.profile, client, error) }, account_label, - types.any_images, + types.ImageLimits(types.max_image_edge, None, types.openai_vision), ) // The ChatGPT backend answers `Unsupported parameter: max_output_tokens` // and applies its own ceiling. diff --git a/src/albedo/harness/extensions/github_copilot/catalog.gleam b/src/albedo/harness/extensions/github_copilot/catalog.gleam index cf64dc116..227c515d9 100644 --- a/src/albedo/harness/extensions/github_copilot/catalog.gleam +++ b/src/albedo/harness/extensions/github_copilot/catalog.gleam @@ -4,13 +4,17 @@ //// so a shared model id elsewhere stays another catalog's to describe. import albedo/harness/extensions/github_copilot/accounts +import albedo/harness/extensions/github_copilot/wire import albedo/harness/extensions/models/catalogue as models import albedo/harness/sdk/credentials +import albedo/harness/sdk/digest import albedo/harness/sdk/extension +import albedo/harness/sdk/file import albedo/harness/sdk/http import albedo/harness/sdk/key_environment.{type KeyEnvironment} import albedo/harness/sdk/settings import gleam/bool +import gleam/dict.{type Dict} import gleam/dynamic.{type Dynamic} import gleam/dynamic/decode import gleam/int @@ -76,12 +80,68 @@ fn models( http.Timeouts(10_000, 5000), )) case status { - 200 -> chat_model_ids(body) + 200 -> { + save_endpoints(home, access.session.endpoint, listed_endpoints(body)) + chat_model_ids(body) + } 401 -> Error("GitHub Copilot refused the credential") _ -> Error("endpoint returned HTTP " <> int.to_string(status)) } } +/// The endpoints each model is served on, by `wire.served_key`, as the list's +/// `supported_endpoints` give them. A model whose row names none is left out. +fn listed_endpoints(body: BitArray) -> Dict(String, List(String)) { + let row = { + use id <- decode.field("id", decode.string) + use endpoints <- decode.field( + "supported_endpoints", + decode.list(decode.string), + ) + decode.success(#(wire.served_key(id), endpoints)) + } + json.parse_bits(body, decode.at(["data"], decode.list(decode.dynamic))) + |> result.unwrap([]) + |> list.filter_map(fn(item) { decode.run(item, row) }) + |> dict.from_list +} + +fn save_endpoints( + home: String, + api: String, + endpoints: Dict(String, List(String)), +) -> Nil { + let text = + json.dict(endpoints, fn(id) { id }, json.array(_, json.string)) + |> json.to_string + let _ = file.home_write(home, endpoints_file(api), text) + Nil +} + +/// What the last /models fetch from the Copilot API at `api` said each model +/// is served on; empty until one was fetched. +pub fn served_endpoints( + home: String, + api: String, +) -> Dict(String, List(String)) { + file.home_read(home, endpoints_file(api)) + |> result.try(fn(bytes) { + json.parse_bits( + bytes, + decode.dict(decode.string, decode.list(decode.string)), + ) + |> result.replace_error(Nil) + }) + |> result.unwrap(dict.new()) +} + +/// One file per Copilot API endpoint, named by a hash of its url. +fn endpoints_file(api: String) -> String { + "github-copilot-endpoints-" + <> digest.hex(digest.sha256(<>)) + <> ".json" +} + /// 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) { diff --git a/src/albedo/harness/extensions/github_copilot/extension.gleam b/src/albedo/harness/extensions/github_copilot/extension.gleam index 8982457a6..18e7685ce 100644 --- a/src/albedo/harness/extensions/github_copilot/extension.gleam +++ b/src/albedo/harness/extensions/github_copilot/extension.gleam @@ -107,7 +107,12 @@ pub fn pool( _ -> Ok(Connection( access, - wire.client(access.session.endpoint, access.session.token, session), + wire.client( + access.session.endpoint, + access.session.token, + session, + catalog.served_endpoints(home, access.session.endpoint), + ), )) } }, diff --git a/src/albedo/harness/extensions/github_copilot/wire.gleam b/src/albedo/harness/extensions/github_copilot/wire.gleam index 4365e8c44..50e4cdbe0 100644 --- a/src/albedo/harness/extensions/github_copilot/wire.gleam +++ b/src/albedo/harness/extensions/github_copilot/wire.gleam @@ -1,10 +1,10 @@ //// GitHub Copilot's wire: Chat Completions for most models, OpenAI Responses //// for GPT-5 and later, Grok and MAI Code, and Anthropic Messages for Claude. //// -//// Copilot serves each model family on the endpoint its own model list names; -//// the routing here follows the published families, since a settlement that -//// cannot stream is worse than a route the live list would have chosen. Every -//// route converts from and reduces back to portable ChatCompletions replay +//// Copilot's own /models list names the endpoints each model is served on +//// (`supported_endpoints`); the catalog keeps that and `client` carries it, so +//// a model routes by what the list says. Until a list has been fetched, the +//// published model families stand in for it. Every route converts from and reduces back to portable ChatCompletions replay //// items (`openai_api/bridge`), so switching models keeps the conversation. import albedo/anthropic_api/request as messages_request @@ -16,6 +16,7 @@ import albedo/openai_api/refusal as openai_refusal import albedo/openai_api/request as openai_request import albedo/openai_api/stream as reducer import albedo/openai_api/types.{type Error, type Request, Responses} +import gleam/dict.{type Dict} import gleam/dynamic.{type Dynamic} import gleam/int import gleam/json @@ -26,12 +27,23 @@ import gleam/string import gleam/string_tree pub type Client { - Client(connection: types.Client, session_id: String) + Client( + connection: types.Client, + session_id: String, + /// The endpoints each model is served on, by lowercased id, as the + /// account's /models list gave them; empty before one was fetched. + served: Dict(String, List(String)), + ) } -pub fn client(base_url: String, token: String, session: String) -> Client { +pub fn client( + base_url: String, + token: String, + session: String, + served: Dict(String, List(String)), +) -> Client { let connection = openai_api.client(types.ChatCompletions, base_url, token) - Client(types.Client(..connection, timeout_ms: 120_000), session) + Client(types.Client(..connection, timeout_ms: 120_000), session, served) } pub const api_version = "2026-08-01" @@ -107,9 +119,44 @@ pub type Route { MessagesRoute } -/// Which Copilot endpoint serves `model`. -pub fn route(model: String) -> Route { - let id = string.lowercase(string.trim(model)) +/// The key `served` holds a model under. +pub fn served_key(model: String) -> String { + string.lowercase(string.trim(model)) +} + +/// Which Copilot endpoint serves `model`: the one its listed +/// `supported_endpoints` name. A model listed on several keeps the route its +/// family usually takes when it is among them, and otherwise takes the first +/// listed that albedo speaks, Messages before Responses before Chat. A model +/// the list does not name, or names only on endpoints albedo does not speak, +/// takes the family's route. +pub fn route(served: Dict(String, List(String)), model: String) -> Route { + let family = family_route(served_key(model)) + let listed = + dict.get(served, served_key(model)) + |> result.unwrap([]) + |> list.filter_map(endpoint_route) + case list.contains(listed, family) { + True -> family + False -> + [MessagesRoute, ResponsesRoute, ChatRoute] + |> list.find(list.contains(listed, _)) + |> result.unwrap(family) + } +} + +fn endpoint_route(endpoint: String) -> Result(Route, Nil) { + case endpoint { + "/chat/completions" -> Ok(ChatRoute) + "/responses" -> Ok(ResponsesRoute) + "/v1/messages" -> Ok(MessagesRoute) + _ -> Error(Nil) + } +} + +/// The route a model family is published on, for a model no fetched list +/// names. +fn family_route(id: String) -> Route { case string.starts_with(id, "claude-"), responses_model(id) { True, _ -> MessagesRoute _, True -> ResponsesRoute @@ -156,7 +203,7 @@ pub fn stream( on_event: fn(types.Event) -> types.Control, ) -> Result(types.Turn, types.Error) { use _ <- result.try(validate(client, request.model)) - case route(request.model) { + case route(client.served, request.model) { ChatRoute -> { use prepared <- result.try(openai_api.encode_request( client.connection, diff --git a/src/albedo/harness/extensions/openai/extension.gleam b/src/albedo/harness/extensions/openai/extension.gleam index 830ba03d6..f5affbe1c 100644 --- a/src/albedo/harness/extensions/openai/extension.gleam +++ b/src/albedo/harness/extensions/openai/extension.gleam @@ -148,6 +148,7 @@ fn resolve( images: types.ImageLimits( int.min(config.image_edge, types.max_image_edge), None, + vision_profile(connection.client.base_url), ), output: output_ceiling(connection.client.base_url), count: case connection.client.protocol { @@ -174,17 +175,35 @@ fn responses_count(client: types.Client) -> token_count.Endpoint { /// limit, so a catalogued ceiling it was not asked for narrows the route; it /// gets only a limit the caller names. pub fn output_ceiling(base_url: String) -> extension.OutputCeiling { - let host = - uri.parse(base_url) - |> result.map(fn(parsed) { option.unwrap(parsed.host, "") }) - |> result.unwrap("") - |> string.lowercase - case host == "openrouter.ai" || string.ends_with(host, ".openrouter.ai") { + case is_openrouter(host_of(base_url)) { True -> extension.ProviderCeiling False -> extension.NoCeiling } } +/// OpenAI's own endpoint is read by OpenAI's vision stack. OpenRouter fronts +/// any vendor's, so it states none but takes Anthropic's request budget; any +/// other host is unmeasured. +fn vision_profile(base_url: String) -> types.VisionProfile { + let host = host_of(base_url) + case host == "api.openai.com", is_openrouter(host) { + True, _ -> types.openai_vision + _, True -> types.VisionProfile(types.DefaultGeometry, False, 90) + False, False -> types.default_vision + } +} + +fn is_openrouter(host: String) -> Bool { + host == "openrouter.ai" || string.ends_with(host, ".openrouter.ai") +} + +fn host_of(base_url: String) -> String { + uri.parse(base_url) + |> result.map(fn(parsed) { option.unwrap(parsed.host, "") }) + |> result.unwrap("") + |> string.lowercase +} + fn fast_mode(context: extension.ModelContext) -> extension.FastMode { let pool = pool_mode( @@ -367,7 +386,8 @@ fn models( case status { 200 -> { save_modalities(home, endpoint, model_catalog.input_modalities(body)) - model_catalog.ids(body, is_chat_model) + let produces = model_catalog.output_modalities(body) + model_catalog.ids(body, fn(id) { is_chat_model(id, produces) }) } _ -> Error("endpoint returned HTTP " <> int.to_string(status)) } @@ -428,12 +448,17 @@ fn modalities_file(endpoint: String) -> String { "openai-modalities-" <> id <> ".json" } -// Keep non-chat entitlements out of every compatible endpoint's picker. -fn is_chat_model(id: String) -> Bool { - let lowered = string.lowercase(id) +// Keep non-chat entitlements out of every compatible endpoint's picker: a +// model that lists its outputs is a chat model when it produces text, and the +// id name filter judges only the models whose row lists none. +fn is_chat_model(id: String, produces: List(#(String, List(String)))) -> Bool { id != "auto" - && !list.any( - ["audio", "tts", "realtime", "image", "wan", "asr", "livetranslate"], - fn(marker) { string.contains(lowered, marker) }, - ) + && case list.key_find(produces, id) { + Ok(outputs) -> list.contains(outputs, "text") + Error(Nil) -> + !list.any( + ["audio", "tts", "realtime", "image", "wan", "asr", "livetranslate"], + fn(marker) { string.contains(string.lowercase(id), marker) }, + ) + } } diff --git a/src/albedo/harness/extensions/snapcompact/extension.gleam b/src/albedo/harness/extensions/snapcompact/extension.gleam index 78341ae87..9d39547ab 100644 --- a/src/albedo/harness/extensions/snapcompact/extension.gleam +++ b/src/albedo/harness/extensions/snapcompact/extension.gleam @@ -46,8 +46,8 @@ const default_archive_percent = 20 const max_frames = 80 /// Inline base64 frame data one request may carry: gateways fail opaquely -/// once a request carries a few MB. A frame is about 50 KB. The Claude -/// provider uploads images through the files API, so it is exempt. +/// once a request carries a few MB. A frame is about 50 KB. A provider whose +/// vision profile says it takes uploads is exempt. const frame_data_budget = 3_000_000 const frame_data_estimate = 50_000 @@ -556,14 +556,13 @@ fn survey( |> result.map(fn(split) { #(archive, split.0, split.1) }) |> option.from_result }) - let shape = fit(shape(context.model), context.images) + let shape = fit(shape(context.images.vision.geometry), context.images) let capacity = case context.session_window, context.capacity { Some(tokens), _ -> Some(tokens) None, Some(compaction.Capacity(tokens, _)) -> Some(tokens) None, None -> config.context_window_tokens } - let limit = - frame_budget(config, shape, context.reader, context.images, capacity) + let limit = frame_budget(config, shape, context.images, capacity) let #(previous, evicted, rest, current, status) = case resumed { None -> #(None, [], folded, folded, "not_needed") Some(#(archive, evicted, tail)) -> { @@ -718,12 +717,10 @@ fn view( fn frame_budget( config: Config, shape: Shape, - reader: Option(compaction.Reader), images: types.ImageLimits, capacity: Option(Int), ) -> Int { - let cap = - option.lazy_unwrap(config.max_frames, fn() { provider_cap(reader, images) }) + let cap = option.lazy_unwrap(config.max_frames, fn() { provider_cap(images) }) let cost = compaction.image_tokens(shape.width, shape.rows * shape.pitch) case capacity { Some(tokens) -> @@ -734,42 +731,20 @@ fn frame_budget( /// The frames a provider's requests may carry. A provider that states how /// many images a request takes keeps a tenth of them for the conversation's -/// own; otherwise oh-my-pi's per-request image budgets apply: policy caps -/// under the vendor limits (Anthropic 100, OpenAI 500, Gemini ~2500), with -/// `antigravity` taking Anthropic's, since it also serves Claude models. -fn provider_cap( - reader: Option(compaction.Reader), - limits: types.ImageLimits, -) -> Int { - let provider = option.map(reader, fn(reader) { reader.provider }) - let images = case limits.max_images, provider { - Some(images), _ -> images - images / 10 - None, provider -> known_cap(provider) +/// own; otherwise its declared `frame_cap` applies. Inline frames also stay +/// within the byte budget, which a provider that takes uploads is exempt from. +fn provider_cap(limits: types.ImageLimits) -> Int { + let images = case limits.max_images { + Some(images) -> images - images / 10 + None -> limits.vision.frame_cap } - let bytes = case provider { - Some("claude") -> max_frames - _ -> frame_data_budget / frame_data_estimate + let bytes = case limits.vision.uploaded { + True -> max_frames + False -> frame_data_budget / frame_data_estimate } images |> int.min(bytes) |> int.min(max_frames) } -fn known_cap(provider: Option(String)) -> Int { - case provider { - Some("anthropic") - | Some("amazon-bedrock") - | Some("openrouter") - | Some("antigravity") -> 90 - Some("openai") - | Some("openai-codex") - | Some("google") - | Some("google-vertex") - | Some("google-gemini-cli") -> 200 - Some("umans") -> 10 - // oh-my-pi's floor for unmeasured providers; the strictest seen is ~5. - _ -> 5 - } -} - fn observation( status: String, config: Config, @@ -815,20 +790,11 @@ pub fn fit(shape: Shape, limits: types.ImageLimits) -> Shape { } /// Geometry per vision stack: billing mode and measured glyph legibility. -pub fn shape(model: String) -> Shape { - let name = string.lowercase(model) - case string.contains(name, "gemini") || string.contains(name, "google") { - True -> Shape(8, 22, 2048, 64) - False -> - case - string.contains(name, "gpt") - || string.contains(name, "codex") - || string.contains(name, "o3") - || string.contains(name, "o4") - { - True -> Shape(8, 22, 1568, 56) - False -> Shape(11, 16, 1568, 44) - } +pub fn shape(geometry: types.VisionGeometry) -> Shape { + case geometry { + types.GeminiGeometry -> Shape(8, 22, 2048, 64) + types.OpenaiGeometry -> Shape(8, 22, 1568, 56) + types.AnthropicGeometry | types.DefaultGeometry -> Shape(11, 16, 1568, 44) } } diff --git a/src/albedo/harness/extensions/vertex/extension.gleam b/src/albedo/harness/extensions/vertex/extension.gleam index 57bfc6aaa..49eeb01d1 100644 --- a/src/albedo/harness/extensions/vertex/extension.gleam +++ b/src/albedo/harness/extensions/vertex/extension.gleam @@ -79,7 +79,7 @@ fn resolve( explain, fn() { None }, fn(_) { [] }, - types.any_images, + types.ImageLimits(types.max_image_edge, None, types.gemini_vision), extension.NoCeiling, None, None, diff --git a/src/albedo/openai_api/catalog.gleam b/src/albedo/openai_api/catalog.gleam index 434c9f8d4..1e78c81b5 100644 --- a/src/albedo/openai_api/catalog.gleam +++ b/src/albedo/openai_api/catalog.gleam @@ -38,10 +38,20 @@ pub fn ids( /// OpenRouter and llama.cpp-style servers list them. Models without the field /// are left out, so an absent list never reads as text-only. pub fn input_modalities(body: BitArray) -> List(#(String, List(String))) { + modalities(body, "input_modalities") +} + +/// What each model reports it produces under `architecture`; a chat model +/// lists `text`. Models without the field are left out. +pub fn output_modalities(body: BitArray) -> List(#(String, List(String))) { + modalities(body, "output_modalities") +} + +fn modalities(body: BitArray, field: String) -> List(#(String, List(String))) { let row = { use id <- decode.field("id", decode.string) use modalities <- decode.subfield( - ["architecture", "input_modalities"], + ["architecture", field], decode.list(decode.string), ) decode.success(#(id, modalities)) diff --git a/src/albedo/openai_api/types.gleam b/src/albedo/openai_api/types.gleam index f5f213987..07145a32e 100644 --- a/src/albedo/openai_api/types.gleam +++ b/src/albedo/openai_api/types.gleam @@ -57,20 +57,48 @@ const max_image_pixels = 40_000_000 /// every request the session will send, so it is the strictest bound the /// provider applies as a conversation grows, not the one for a lone image. /// `max_images` is how many one request may carry, when the provider says. +/// `vision` is what a renderer needs to size images for the provider. pub type ImageLimits { - ImageLimits(max_edge: Int, max_images: Option(Int)) + ImageLimits(max_edge: Int, max_images: Option(Int), vision: VisionProfile) } +/// How a provider reads and carries images, beyond what it refuses: +/// `geometry` is the vision stack whose glyph legibility frames are sized for, +/// `uploaded` is whether images reach it through a files API rather than inline +/// in the request, and `frame_cap` is how many frames a request may carry when +/// `max_images` states no count. +pub type VisionProfile { + VisionProfile(geometry: VisionGeometry, uploaded: Bool, frame_cap: Int) +} + +pub type VisionGeometry { + AnthropicGeometry + OpenaiGeometry + GeminiGeometry + /// A provider that does not say which stack answers. + DefaultGeometry +} + +/// oh-my-pi's floor for a provider nobody measured; the strictest seen is 5. +pub const default_vision = VisionProfile(DefaultGeometry, False, 5) + +pub const anthropic_vision = VisionProfile(AnthropicGeometry, False, 90) + +pub const openai_vision = VisionProfile(OpenaiGeometry, False, 200) + +pub const gemini_vision = VisionProfile(GeminiGeometry, False, 200) + /// The bounds albedo itself validates images against, for a provider that /// states none of its own. -pub const any_images = ImageLimits(max_image_edge, None) +pub const any_images = ImageLimits(max_image_edge, None, default_vision) /// Anthropic takes an 8000px image alone, but once a request carries more /// than 20 images every one of them, old turns and tool results included, /// must fit in 2000px. A working session passes 20 quickly, so that is the /// bound an image is held to from the start. A request carries at most 100. /// It is Anthropic's rule, so it follows the model family to every route. -pub const anthropic_images = ImageLimits(max_edge: 2000, max_images: Some(100)) +pub const anthropic_images = + ImageLimits(max_edge: 2000, max_images: Some(100), vision: anthropic_vision) /// Why a provider held to `limits` refuses `image`, or `None` when it takes it. pub fn image_refusal(limits: ImageLimits, image: Image) -> Option(String) { diff --git a/test/e2e/github_copilot_test.py b/test/e2e/github_copilot_test.py index 148cd7626..ef4c414fa 100644 --- a/test/e2e/github_copilot_test.py +++ b/test/e2e/github_copilot_test.py @@ -1,9 +1,10 @@ """GitHub Copilot is a model provider over the Copilot API. GitHub's device sign-in stores an account, the daemon mints a short-lived -Copilot token from the GitHub token, and each model family is served on the -route Copilot publishes for it: Chat Completions, OpenAI Responses, or Anthropic -Messages. The request carries GitHub's client identity, and the picker lists +Copilot token from the GitHub token, and each model is served on the route the +account's own model list names for it: Chat Completions, OpenAI Responses, or +Anthropic Messages; its family's published route stands in before a list was +fetched. The request carries GitHub's client identity, and the picker lists only the models the account may actually pick. The sign-in writes the daemon's own creds, so the class is exclusive. @@ -29,6 +30,9 @@ from harness import ( ) CHAT_MODEL = "gemini-3.7-flash" +# A name the families would send to /responses, which its list serves on +# /chat/completions only. +LISTED_CHAT_MODEL = "grok-code-chat" RESPONSES_MODEL = "gpt-5.4-luna" MESSAGES_MODEL = "claude-haiku-5.5" @@ -72,6 +76,18 @@ API_MODELS = { "supports": {"tool_calls": True, "streaming": True}, }, }, + { + "id": LISTED_CHAT_MODEL, + "name": "Grok Code", + "version": "2026-07-15", + "model_picker_enabled": True, + "supported_endpoints": ["/chat/completions"], + "capabilities": { + "family": "grok", + "limits": {"max_context_window_tokens": 256000}, + "supports": {"tool_calls": True, "streaming": True}, + }, + }, { "id": "gpt-4o-mini", "name": "GPT-4o mini", @@ -299,6 +315,27 @@ class GithubCopilotTests(unittest.TestCase): answers[-1]["content"], [{"kind": "text", "text": "from responses"}] ) + def test_a_model_routes_by_the_endpoints_the_account_list_names(self): + app, provider = self.start( + LISTED_CHAT_MODEL, [text("from the list")], token="github-fixture-listed" + ) + # Until the list has been fetched the model's family decides; the + # picker's fetch keeps what the list says each model is served on. + with app.api( + "/models?" + + urllib.parse.urlencode( + {"provider": "github-copilot", "endpoint": provider.url} + ) + ) as response: + listed = [item["id"] for item in json.load(response)["items"]] + self.assertIn(LISTED_CHAT_MODEL, listed) + + session = app.session() + self.ask(app, session, "hello") + [request] = provider.requests + self.assertTrue(request["path"].endswith("/chat/completions"), request["path"]) + self.assertIn("messages", request["request"]) + def test_gemini_reasoning_text_with_usage_is_saved_and_replayed_to_compaction(self): thought = "compare the two routes" frame = { @@ -444,7 +481,7 @@ 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]), + sorted([CHAT_MODEL, RESPONSES_MODEL, MESSAGES_MODEL, LISTED_CHAT_MODEL]), ) @exclusive diff --git a/test/e2e/model_catalogs_test.py b/test/e2e/model_catalogs_test.py index 32b71619a..5b5319025 100644 --- a/test/e2e/model_catalogs_test.py +++ b/test/e2e/model_catalogs_test.py @@ -255,6 +255,32 @@ class ModelCatalogReloadTests(unittest.TestCase): ["local-a", "local-b"], ) + def test_generic_openai_endpoint_filters_by_the_outputs_it_lists(self): + def row(model, outputs=None): + if outputs is None: + return {"id": model} + return {"id": model, "architecture": {"output_modalities": outputs}} + + gateway = Provider( + lambda _request: text("ok"), + catalog={ + "data": [ + # Text out is a chat model whatever its id says. + row("audio-chat", ["text", "audio"]), + row("image-only", ["image"]), + row("plain-chat", ["text"]), + # No listed outputs: the id decides. + row("legacy-tts"), + row("legacy-chat"), + ] + }, + ) + self.addCleanup(gateway.close) + self.assertEqual( + [item["id"] for item in self.listed("openai", gateway.url)], + ["audio-chat", "legacy-chat", "plain-chat"], + ) + def test_generic_openai_endpoint_answers_from_its_saved_list(self): gateway = Provider(lambda _request: text("ok"), catalog=GATEWAY_MODELS) self.addCleanup(gateway.close) diff --git a/test/harness/messages_cache_test.gleam b/test/harness/messages_cache_test.gleam index 912e98d08..7fa164921 100644 --- a/test/harness/messages_cache_test.gleam +++ b/test/harness/messages_cache_test.gleam @@ -6,6 +6,7 @@ import albedo/harness/extensions/github_copilot/wire as copilot import albedo/harness/extensions/opencode_go/wire as opencode import albedo/openai_api import albedo/openai_api/types +import gleam/dict import gleam/dynamic/decode import gleam/json import gleam/list @@ -17,7 +18,12 @@ import gleam/string_tree.{type StringTree} fn materialize(body: StringTree) -> Result(String, String) fn copilot_client() -> copilot.Client { - copilot.client("https://api.githubcopilot.com", "token", "session") + copilot.client( + "https://api.githubcopilot.com", + "token", + "session", + dict.new(), + ) } fn opencode_client() -> opencode.Client { diff --git a/test/harness/snapcompact_test.gleam b/test/harness/snapcompact_test.gleam index 721cb05c4..28c84b0aa 100644 --- a/test/harness/snapcompact_test.gleam +++ b/test/harness/snapcompact_test.gleam @@ -35,9 +35,22 @@ pub fn bound_keeps_the_first_and_newest_frames_test() -> Nil { } pub fn a_full_frame_renders_inside_the_provider_edge_test() -> Nil { - let limits = types.ImageLimits(max_edge: 1000, max_images: None) + let limits = + types.ImageLimits( + max_edge: 1000, + max_images: None, + vision: types.default_vision, + ) use model <- list.each(["gemini-3-pro", "gpt-5", "claude-opus-5-5"]) - let shape = snapcompact.fit(snapcompact.shape(model), limits) + let shape = + snapcompact.fit( + snapcompact.shape(case model { + "gemini-3-pro" -> types.GeminiGeometry + "gpt-5" -> types.OpenaiGeometry + _ -> types.AnthropicGeometry + }), + limits, + ) let assert [page, ..] = snapcompact.paginate(shape, string.repeat("x\u{2588}", 100_000)) let assert Ok(#(width, height, _)) = -- knotmirror 0.0.1