diff --git a/src/albedo/harness/extensions/claude/albedo_claude_models.erl b/src/albedo/harness/extensions/claude/albedo_claude_models.erl new file mode 100644 index 000000000..0615e8aaa --- /dev/null +++ b/src/albedo/harness/extensions/claude/albedo_claude_models.erl @@ -0,0 +1,123 @@ +%% The Claude model list from the Anthropic Models API, newest first, cached in +%% $ALBEDO_HOME/claude-models.json with each model's limits, image input, and +%% effort levels. A model Anthropic releases reaches the picker without an +%% albedo update. +-module(albedo_claude_models). +-export([read/1, reload/2, refresh/2, api_key/1]). + +-define(CATALOG, "claude-models.json"). +-define(URL, "https://api.anthropic.com/v1/models?limit=1000"). +-define(MAX_AGE_MS, 21600000). +-define(TIMEOUT_MS, 20000). +%% A thousand models a page; more pages than this is a runaway cursor. +-define(MAX_PAGES, 10). +-define(REFRESH_PROCESS, albedo_claude_models_refresh). + +%% The cache as JSON text for the Gleam decoder. +read(Home) -> + case file:read_file(path(Home)) of + {ok, Bytes} -> {ok, Bytes}; + _ -> {error, nil} + end. + +%% Refetches the list with one credential header. A bearer token is a Claude +%% Code subscription, which the API accepts only with the OAuth beta. +reload(Home, {Name, Value}) -> + Headers = [{text(Name), text(Value)}, + {"anthropic-version", "2023-06-01"}, + {"accept", "application/json"}, + {"user-agent", "albedo"}] + ++ [{"anthropic-beta", "oauth-2025-04-20"} || Name =:= <<"authorization">>], + case pages(Headers, "", ?MAX_PAGES, []) of + {ok, Models} -> + case albedo_credentials:write(path(Home), json:encode(Models)) of + ok -> {ok, nil}; + _ -> {error, <<"could not save the Claude model list">>} + end; + Error -> Error + end. + +%% Refetches off the caller's process when the cache is missing or old, one +%% refresh at a time. `Reload' resolves a credential and calls reload/2. +refresh(Home, Reload) -> + case albedo_credentials:stale(path(Home), ?MAX_AGE_MS) of + false -> nil; + true -> + Pid = spawn(fun() -> receive go -> Reload() end end), + try register(?REFRESH_PROCESS, Pid) of + true -> Pid ! go, nil + catch _:_ -> exit(Pid, kill), nil + end + end. + +%% The Console key of the first claude profile that sets one. +api_key(Home) -> + case albedo_credentials:read_json(filename:join(text(Home), "config.json")) of + {ok, #{<<"providers">> := Providers}} when is_map(Providers) -> + case [Key || {_, #{<<"extension">> := <<"claude">>, <<"apiKey">> := <<_, _/binary>> = Key}} + <- lists:sort(maps:to_list(Providers))] of + [Key | _] -> {ok, Key}; + [] -> {error, nil} + end; + _ -> {error, nil} + end. + +pages(_, _, 0, Models) -> {ok, Models}; +pages(Headers, After, Left, Models) -> + Url = ?URL ++ [["&after_id=", After] || After =/= ""], + case albedo_http:get(lists:flatten(Url), Headers, ?TIMEOUT_MS, 10000) of + {ok, {200, _, Body}} -> + try json:decode(Body) of + #{<<"data">> := Data} = Page when is_list(Data) -> + Listed = Models ++ [M || Raw <- Data, M <- [trim(Raw)], M =/= skip], + case Page of + #{<<"has_more">> := true, <<"last_id">> := <<_, _/binary>> = Last} -> + pages(Headers, binary_to_list(Last), Left - 1, Listed); + _ -> {ok, Listed} + end; + _ -> {error, <<"Anthropic model list is not valid">>} + catch _:_ -> {error, <<"Anthropic model list is not valid">>} + end; + {ok, {Status, _, _}} -> + {error, iolist_to_binary(io_lib:format("Anthropic model list returned HTTP ~B", [Status]))}; + _ -> {error, <<"Anthropic model list request failed">>} + end. + +%% Only what lookup and listing read. +trim(#{<<"id">> := <<_, _/binary>> = Id} = Model) -> + Capabilities = case maps:get(<<"capabilities">>, Model, null) of + C when is_map(C) -> C; + _ -> #{} + end, + #{<<"id">> => Id, + <<"context">> => positive(maps:get(<<"max_input_tokens">>, Model, null)), + <<"output">> => positive(maps:get(<<"max_tokens">>, Model, null)), + <<"images">> => supported(maps:get(<<"image_input">>, Capabilities, null)), + <<"efforts">> => efforts(maps:get(<<"effort">>, Capabilities, null))}; +trim(_) -> skip. + +supported(#{<<"supported">> := true}) -> true; +supported(_) -> false. + +%% The supported levels, lowest first; a level albedo does not know sorts last. +efforts(#{<<"supported">> := true} = Levels) -> + Supported = [Level || {Level, Detail} <- maps:to_list(Levels), + Level =/= <<"supported">>, supported(Detail)], + lists:sort(fun(A, B) -> {rank(A), A} =< {rank(B), B} end, Supported); +efforts(_) -> []. + +rank(<<"minimal">>) -> 0; +rank(<<"low">>) -> 1; +rank(<<"medium">>) -> 2; +rank(<<"high">>) -> 3; +rank(<<"xhigh">>) -> 4; +rank(<<"max">>) -> 5; +rank(_) -> 6. + +positive(N) when is_integer(N), N > 0 -> N; +positive(_) -> null. + +path(Home) -> filename:join(text(Home), ?CATALOG). + +text(Value) when is_binary(Value) -> unicode:characters_to_list(Value); +text(Value) when is_list(Value) -> Value. diff --git a/src/albedo/harness/extensions/claude/catalog.gleam b/src/albedo/harness/extensions/claude/catalog.gleam new file mode 100644 index 000000000..92abfd30b --- /dev/null +++ b/src/albedo/harness/extensions/claude/catalog.gleam @@ -0,0 +1,82 @@ +//// Claude models as the Anthropic Models API lists them for the signed-in +//// account, newest first, with their limits, image input, and efforts. +//// Nothing here names a model, so a new one appears once Anthropic lists it. + +import gleam/dynamic/decode +import gleam/json +import gleam/option.{type Option, None} +import gleam/result + +pub type Model { + Model( + id: String, + context: Option(Int), + output: Option(Int), + images: Bool, + efforts: List(String), + ) +} + +/// Refetches the list now with the Claude subscription, or else with the +/// Console key of the first claude profile that sets one. +pub fn reload(home: String) -> Result(Nil, String) { + use header <- result.try(case native_access(home, "") { + Ok(access) -> Ok(#("authorization", "Bearer " <> access)) + Error(error) -> + native_api_key(home) + |> result.map(fn(key) { #("x-api-key", key) }) + |> result.replace_error(error) + }) + native_reload(home, header) +} + +/// Refetches in the background when the cached list is missing or old. +pub fn refresh_later(home: String) -> Nil { + native_refresh(home, fn() { reload(home) }) +} + +/// The cached list, empty before the first fetch lands. +pub fn models(home: String) -> List(Model) { + native_read(home) + |> result.try(fn(bytes) { + json.parse_bits(bytes, decode.list(model_decoder())) + |> result.replace_error(Nil) + }) + |> result.unwrap([]) +} + +fn model_decoder() -> decode.Decoder(Model) { + use id <- decode.field("id", decode.string) + use context <- decode.optional_field( + "context", + None, + decode.optional(decode.int), + ) + use output <- decode.optional_field( + "output", + None, + decode.optional(decode.int), + ) + use images <- decode.optional_field("images", False, decode.bool) + use efforts <- decode.optional_field( + "efforts", + [], + decode.list(decode.string), + ) + decode.success(Model(id, context, output, images, efforts)) +} + +@external(erlang, "albedo_claude_models", "read") +fn native_read(home: String) -> Result(BitArray, Nil) + +@external(erlang, "albedo_claude_models", "reload") +fn native_reload(home: String, header: #(String, String)) -> Result(Nil, String) + +@external(erlang, "albedo_claude_models", "refresh") +fn native_refresh(home: String, reload: fn() -> Result(Nil, String)) -> Nil + +@external(erlang, "albedo_claude_models", "api_key") +fn native_api_key(home: String) -> Result(String, Nil) + +@external(erlang, "albedo_claude_auth", "access") +fn native_access(home: String, session: String) -> Result(String, String) diff --git a/src/albedo/harness/extensions/claude/extension.gleam b/src/albedo/harness/extensions/claude/extension.gleam index a43d17038..4b2845c98 100644 --- a/src/albedo/harness/extensions/claude/extension.gleam +++ b/src/albedo/harness/extensions/claude/extension.gleam @@ -3,11 +3,13 @@ import albedo/daemon/configuration import albedo/harness/extension +import albedo/harness/extensions/claude/catalog import albedo/harness/extensions/claude/stream import albedo/harness/extensions/claude/wire import albedo/harness/extensions/models/extension as models import albedo/harness/oauth import albedo/harness/rotation +import albedo/harness/settings import albedo/openai_api import albedo/openai_api/types import gleam/bool @@ -24,13 +26,6 @@ const client_id = "9d1c250a-e61b-44d9-88ed-5944d1962f5e" const scope = "org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload" -/// Picker policy, not model metadata: only show requested current and fallback -/// tiers that models.dev actually lists for Anthropic. -const preferred = [ - "claude-opus-5-5", "claude-fable-5-1", "claude-sonnet-5", "claude-opus-5", - "claude-opus-4-8", "claude-haiku-4-5", -] - pub fn extension() -> extension.Extension { extension.Extension( "claude", @@ -38,8 +33,11 @@ pub fn extension() -> extension.Extension { ["models"], [ extension.LoginPlugin(login()), - // models.dev is the list: its own catalog reloads it. - extension.ModelsPlugin(extension.ModelCatalog(lookup, list_models, None)), + extension.ModelsPlugin(extension.ModelCatalog( + lookup, + list_models, + Some(fn() { catalog.reload(settings.home()) }), + )), extension.ModelProviderPlugin(extension.ModelProvider( "anthropic", resolve, @@ -152,36 +150,60 @@ fn authenticate(context: extension.ModelContext) -> Result(wire.Auth, String) { } } +/// Every model the Anthropic API lists for this account, newest first. The +/// first listing waits for the fetch; until one lands, models.dev's list. fn list_models(provider: String, _endpoint: String) -> List(String) { case provider { "anthropic" -> { - models.refresh() - available_models(models.path()) + let home = settings.home() + case catalog.models(home) { + [] -> catalog.reload(home) |> result.unwrap(Nil) + _ -> catalog.refresh_later(home) + } + case catalog.models(home) { + [] -> models.list("anthropic", "") + listed -> list.map(listed, fn(model) { model.id }) + } } _ -> [] } } -pub fn available_models(catalog: String) -> List(String) { - let listed = models.list_at(catalog, "anthropic", "") - list.filter(preferred, fn(id) { list.contains(listed, id) }) -} - fn lookup(id: String, at: String) -> Option(extension.ModelInfo) { - models.refresh() - model_at(models.path(), id, at) + use <- bool.guard(at != "" && at != endpoint, None) + let home = settings.home() + case list.find(catalog.models(home), fn(model) { model.id == id }) { + Ok(model) -> Some(listed_info(home, model)) + Error(_) -> unlisted_info(id) + } } -pub fn model_at( - catalog: String, - id: String, - at: String, -) -> Option(extension.ModelInfo) { - use <- bool.guard( - !list.contains(preferred, id) || at != "" && at != endpoint, - None, +/// The API's own facts; models.dev fills in only a limit it leaves out. Its +/// efforts stand as listed, since none means the model takes no effort. +fn listed_info(home: String, model: catalog.Model) -> extension.ModelInfo { + let info = + extension.ModelInfo( + ..extension.blank_model(model.id, "claude"), + context_tokens: model.context, + max_output_tokens: model.output, + input_modalities: case model.images { + True -> ["text", "image"] + False -> ["text"] + }, + endpoint: Some(endpoint), + source: "Anthropic models API cached in " <> home, + ) + extension.ModelInfo( + ..models.complete_model(info, endpoint), + environment: [], + efforts: model.efforts, ) - use found <- option.map(models.lookup_provider_at(catalog, "anthropic", id)) +} + +/// What models.dev knows of a model the API list does not name, such as an +/// alias a session picked before the list was fetched. +fn unlisted_info(id: String) -> Option(extension.ModelInfo) { + use found <- option.map(models.lookup_provider("anthropic", id)) extension.ModelInfo( ..found, provider: "claude", diff --git a/src/albedo/harness/extensions/claude/wire.gleam b/src/albedo/harness/extensions/claude/wire.gleam index 78cf2a71a..119b552cc 100644 --- a/src/albedo/harness/extensions/claude/wire.gleam +++ b/src/albedo/harness/extensions/claude/wire.gleam @@ -184,8 +184,13 @@ pub fn encode( ] _ -> fields } - let fields = case request.options.effort { - Some(effort) if request.model != "claude-haiku-4-5" -> [ + // Haiku 4.5 rejects effort under its alias and its dated id alike. + let effort = case string.starts_with(request.model, "claude-haiku-4-5") { + True -> None + False -> request.options.effort + } + let fields = case effort { + Some(effort) -> [ // Newer models omit thinking text unless asked for a summary. #( "thinking", @@ -242,9 +247,9 @@ pub fn encode( "mid-conversation-tool-changes-2026-07-01", ] }, - case request.options.effort { - Some(_) if request.model != "claude-haiku-4-5" -> ["effort-2025-11-24"] - _ -> [] + case effort { + Some(_) -> ["effort-2025-11-24"] + None -> [] }, ["extended-cache-ttl-2025-04-11"], ]) diff --git a/test/e2e/model_catalogs_test.py b/test/e2e/model_catalogs_test.py index 5280355d7..923fadf50 100644 --- a/test/e2e/model_catalogs_test.py +++ b/test/e2e/model_catalogs_test.py @@ -1,13 +1,16 @@ -"""`/reload models` refetches each provider's own model list, not only models.dev. +"""Provider model lists: each provider's own list reaches the picker and reloads. Alibaba caches its /models answer for a day, so a model it starts offering -stays out of the picker until that cache ages out; the reload must refetch it -at once through the configured profile's endpoint and key. A catalog that -cannot be fetched (Codex and Antigravity are never signed in here) keeps its -previous list: the reload still succeeds and names it rather than reporting it -refreshed. Every list is served on loopback, so no live network is reached. It -writes the shared home's Alibaba cache and models settings, so the class is -exclusive and removes the cache again. +stays out of the picker until that cache ages out; `/reload models` must +refetch it at once through the configured profile's endpoint and key. A +catalog that cannot be fetched (Codex, Antigravity, and Claude are never +signed in here) keeps its previous list: the reload still succeeds and names +it rather than reporting it refreshed. Claude's picker shows whatever the +Anthropic Models API listed, newest first, with the API's own limits and +efforts, so a model released after albedo shipped is offered without an +update. Every list is served on loopback or seeded on disk, so no live network +is reached. The class writes the shared home's list caches and models +settings, so it is exclusive and removes the caches again. """ import json import unittest @@ -15,14 +18,35 @@ import urllib.parse from harness import Albedo, Provider, exclusive, text -MODELS_CATALOG = {"fixture": { - "id": "fixture", "name": "Fixture", - "models": {"fixture-model": {"id": "fixture-model", - "limit": {"context": 8000}}}, -}} +MODELS_CATALOG = { + "fixture": { + "id": "fixture", "name": "Fixture", + "models": {"fixture-model": {"id": "fixture-model", + "limit": {"context": 8000}}}, + }, + # Claims efforts the Anthropic API says the model does not take. + "anthropic": { + "id": "anthropic", "name": "Anthropic", + "models": {"claude-fixture-small": { + "id": "claude-fixture-small", + "limit": {"context": 200000, "output": 8000}, + "reasoning_options": [{"type": "effort", + "values": ["low", "medium", "high"]}], + }}, + }, +} ALIBABA_MODELS = {"data": [{"id": "qwen-fresh"}, {"id": "qwen-tts-fresh"}]} +# As the Anthropic Models API answered, newest first; neither id is one +# albedo or models.dev knows. +CLAUDE_MODELS = [ + {"id": "claude-fixture-6", "context": 500000, "output": 32000, + "images": True, "efforts": ["low", "high"]}, + {"id": "claude-fixture-small", "context": 200000, "output": 8000, + "images": False, "efforts": []}, +] + @exclusive class ModelCatalogReloadTests(unittest.TestCase): @@ -35,8 +59,10 @@ class ModelCatalogReloadTests(unittest.TestCase): self.addCleanup(self.alibaba.close) def prepare(app): - # Fresh on disk, so nothing but an explicit reload refetches it. + # Fresh on disk, so nothing but an explicit reload refetches them. (app.home / "alibaba-models.json").write_text(json.dumps(["qwen-stale"])) + (app.home / "claude-models.json").write_text(json.dumps(CLAUDE_MODELS)) + (app.home / "models.json").unlink(missing_ok=True) (app.home / "extensions.json").write_text(json.dumps({ "models": {"url": self.catalog.url + "/models.json", "refreshHours": 0}, @@ -51,28 +77,46 @@ class ModelCatalogReloadTests(unittest.TestCase): "protocol": "chat_completions"}, }) self.app.__enter__() - self.addCleanup((self.app.home / "alibaba-models.json").unlink, missing_ok=True) + for name in ("alibaba-models.json", "claude-models.json"): + self.addCleanup((self.app.home / name).unlink, missing_ok=True) self.addCleanup(self.app.__exit__, None, None, None) - def listed(self): - endpoint = urllib.parse.quote(self.alibaba.url, safe="") - with self.app.api(f"/models/alibaba?endpoint={endpoint}") as response: + def listed(self, provider, query=""): + with self.app.api(f"/models/{provider}{query}") as response: return json.load(response) - def test_reload_models_refetches_provider_lists_and_names_failures(self): - self.assertEqual(self.listed(), ["qwen-stale"]) + def reload(self, target): session = self.app.session() with self.app.api(f"/sessions/{session}/commands", - {"name": "/reload", "args": {"target": "models"}}) as response: - outcome = json.load(response)["result"] + {"name": "/reload", "args": {"target": target}}) as response: + return json.load(response)["result"] + + def alibaba_listed(self): + endpoint = urllib.parse.quote(self.alibaba.url, safe="") + return self.listed("alibaba", f"?endpoint={endpoint}") + + def test_reload_models_refetches_provider_lists_and_names_failures(self): + self.assertEqual(self.alibaba_listed(), ["qwen-stale"]) + outcome = self.reload("models") catalogs = outcome["catalogs"] self.assertIn("alibaba", catalogs["reloaded"]) self.assertIn("models", catalogs["reloaded"]) - self.assertEqual({"codex", "antigravity"}, set(catalogs["failed"])) - self.assertIn("codex (", outcome["message"]) - self.assertNotIn("alibaba", catalogs["failed"]) + self.assertEqual({"codex", "antigravity", "claude"}, set(catalogs["failed"])) + self.assertIn("claude (", outcome["message"]) # The non-chat entitlement stays filtered, as on any other fetch. - self.assertEqual(self.listed(), ["qwen-fresh"]) + self.assertEqual(self.alibaba_listed(), ["qwen-fresh"]) + # A failed reload keeps the list it had. + self.assertEqual(self.listed("claude"), ["claude-fixture-6", "claude-fixture-small"]) + + def test_claude_picker_offers_the_api_list_with_its_facts(self): + self.reload("models") + newest, small = self.listed("claude", "?details=1") + self.assertEqual([newest["id"], small["id"]], + ["claude-fixture-6", "claude-fixture-small"]) + self.assertEqual((newest["context"], newest["output"], newest["efforts"]), + (500000, 32000, ["low", "high"])) + # No effort listed means the model takes none, not a guessed default. + self.assertEqual(small["efforts"], []) if __name__ == "__main__":