diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 0032d28dd..e05118ec0 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -74,7 +74,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | A plugin's own price | A model no catalog prices (models.dev has no vendor's own model: Devin's SWE-2 and SWE-1.7 Lightning, Cursor's auto, Qoder's efficient) is priced at what its plugin lists it at (`ListPrice` → `pluginListPrice`, `plugin.Model.Cost`, read by `pluginPrice`: an input or output above 0, OpenCode's 0 being none), else at $0 when the plugin says the plan serves it free (`pluginFree`, `plugin.Model.Free`: Devin's Free cost tier, Qoder's and WorkBuddy's x0). Both come after every catalog, so a price a catalog gives is kept over the plugin's. Devin's plugin (0.1.18) lists each paid model at the price Devin's GetCliModelConfigs gives it (input, cached input and output per 1M tokens); a moved Devin user's calls on Devin's own models had no cost on Usage before (太陽と向日葵 on Discord, `TestPluginFreeModelCostsNothing`). A plugin that gives no price and doesn't say free leaves the model unpriced. | [`models.go`](../../internal/provider/models.go), [`plugins.go`](../../internal/provider/plugins.go), [`providers.go`](../../internal/plugin/providers.go) | | Codex's free auto-review | OpenAI made Codex's Auto-review free for users signed in through a ChatGPT account (silverzhou on Discord), so a `codex-auto-review` call through the Codex subscription is priced at nothing (`ListPrice` → `codexReviewFree`, `provider.ChatGPTReviewFree`), not at GPT-5.6 Luna's price (`pricedNames`), and the Requests list names no model it is priced as (`PricedNameFor`). Not on a Free plan, where it spends the allowance (cybercaius), read from the plan Codex is signed in to now; a Codex signed out since counts as a paid plan, as the gateway's caps take it (`freeOnChatGPT`). The same model through an API key, the ChatGPT API subscription or a relay, and a review that followed the session to another model, keep their price; a price the user set wins. Every call is priced as it is read, so rows logged before are free too; the price views' cache keys on each account's plan (`usagePriceCacheKey`). Guarded by `TestAutoReviewFreeOnChatGPTSignIn` and `usage.TestAutoReviewFreeOnChatGPT`. | | A lab's models | models.dev keeps two catalogs: `api.json`, each provider's models with that host's prices, and `models.json`, each lab's models with only what is the model's on every host (name, window, reply limit, thinking, inputs, release), no price. `Sync` keeps the second beside the first as `labs.json` (`LabsPath`, `syncLabs`: best effort, through a rename, a failed fetch keeping the last; a catalog with none beside it is `Stale` once a process, so it comes at the next look). A model only a lab lists, no provider (models.dev took the gated Claude Mythos 5.1 out of anthropic's list in #11327 and kept its lab file), is voted into the same tables as a listed one (`loadGen`, `labs`), so `ContextOf`, `OutputOf`, `NameOf`, `Thinks`, `SeesImages` and every entry built on them know it wherever a vendor's or an account's list has it; a thinking one with no levels takes the levels of the newest of its family a provider gives them (`labKinEfforts`: Mythos 5.1 takes Mythos 5's). A model a provider lists keeps what providers say of it. `catalog.Describe` builds a model from these for a list that names an id alone. `TestLabOnlyModelIsKnown`, `TestLabsLeaveListedModels`, `TestSyncKeepsLabs`, `TestAnthropicKeyGatedModelDescribed` (iebb on Discord). | [`labs.go`](../../internal/catalog/labs.go), [`catalog.go`](../../internal/catalog/catalog.go) | -| A Claude account's models | magpie never asks Anthropic with a Claude sign-in, so a Claude account's list is models.dev's anthropic list and what Anthropic told the account's Claude Code beyond it. Claude Code keeps that in its `.claude.json` from its own bootstrap: `additionalModelOptionsCache` (models its /model picker offers beyond its own; a `null` value or a `disabled` one is not a model), `modelAccessCache` (`entitled` per API id) and `additionalModelCostsCache` (Anthropic's prices). `claudeModels` reads the file of Claude Code's own sign-in (`claudeProfilePath`) and of each saved account's directory (`claudeAccountDir`), through `filememo`, and adds each model none of them lists, described by `catalog.Describe` and priced as Anthropic told it. `Account.Lists` for a Claude account goes by its own file (`claudeLists`: the saved directory's, or Claude Code's own when its `oauthAccount` is that account, the one Anthropic answered last): a model it isn't entitled to is out, so routing tries the accounts entitled to a gated model first; with no file, every model is taken to be in, as before. `ListPrice` of a provider whose catalogs include anthropic falls back to that price after every catalog (`claudeCodePrice`). The agent's own Claude Code model picker (`claudeOwn`) offers what `ClaudeCodeModels` gives for the account signed in here; a WSL distro's keeps the catalog's. Not done: a Claude Code that never started on a saved account has no file, so its gated models show only once it has run there. `TestClaudeAccountListsGatedModels`. | [`claude_code_models.go`](../../internal/provider/claude_code_models.go), [`account.go`](../../internal/provider/account.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`claude.go`](../../internal/agent/claude.go) | +| A Claude account's models | magpie never asks Anthropic with a Claude sign-in, so a Claude account's list is models.dev's anthropic list and what Anthropic told the account's Claude Code beyond it. Claude Code keeps that in its `.claude.json` from its own bootstrap: `additionalModelOptionsCache` (models its /model picker offers beyond its own; a `null` value or a `disabled` one is not a model), `modelAccessCache` (`entitled` per API id) and `additionalModelCostsCache` (Anthropic's prices). `claudeModels` reads the file of Claude Code's own sign-in (`claudeProfilePath`) and of each saved account's directory (`claudeAccountDir`), through `filememo`, and adds each model none of them lists, described by `catalog.Describe` and priced as Anthropic told it. `Account.Lists` for a Claude account goes by its own file (`claudeLists`: the saved directory's, or Claude Code's own when its `oauthAccount` is that account, the one Anthropic answered last): a model it isn't entitled to is out, so routing tries the accounts entitled to a gated model first; with no file, every model is taken to be in, as before. `ListPrice` of a provider whose catalogs include anthropic falls back to that price after every catalog (`claudeCodePrice`). The agent's own Claude Code model picker (`claudeOwn`) offers what `ClaudeCodeModels` gives for the account signed in here; a WSL distro's keeps the catalog's. A fetch of the list in the app or `magpie serve` (Fetch models, the accounts' relist) fetches models.dev's catalog first when it is older than `askedAfter` (10 minutes) and wasn't tried in that time (`catalog.Asked`), only in a process that keeps the catalog fresh: the daily sync alone left a model launched since off the list the user had just fetched, while Claude Code's own /model, built from the catalog baked into its binary (`latest_per_family`), had it (hhdaxia on X: Fable 5.2, `TestClaudeFetchAsksModelsDevForANewModel`). Not done: a Claude Code that never started on a saved account has no file, so its gated models show only once it has run there. `TestClaudeAccountListsGatedModels`. | [`claude_code_models.go`](../../internal/provider/claude_code_models.go), [`account.go`](../../internal/provider/account.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`claude.go`](../../internal/agent/claude.go), [`fresh.go`](../../internal/catalog/fresh.go) | | A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its `/v1/usage` with `rate_limits` and no `remaining` (`readSub2APIKeyLimits`). With the Balance URL set to it, the key's card shows them as the windows *5 hours*, *1 day*, *7 days*, in USD, beside a balance field the user wrote; *Check balance* and `magpie provider show` give what its fullest window has left (`Balance`). A Balance URL at an account query left without its token (a sub2api panel's `/api/v1/user/profile`, new-api's `/api/user/self`, after the token was removed) asks the same panel's query for the key instead, the saved URL untouched (`keyQueryOf`, `BalanceQuery`), unless the user's Headers carry an Authorization or Cookie of their own. A Balance URL of the user's own is asked with GET, or with POST and no body when the provider's `BalanceMethod` says so (#2368: an endpoint that answers only a POST; the editor's GET/POST beside the URL, `balance.method=` on the command line); any other method is refused before anything is sent (`balanceMethodOf`). `KeyAllowance` gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (`quotas.json`) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code, Ollama Cloud, Mistral: `planQuotaSourceOf`) gives routing its card's windows the same way (`planKeyWindows`, Zhipu's team quota behind a key with none of its own); the Usage page's read of its card is taken at once (`noteKeyAllowance`), and a key there that turns out pay-as-you-go, with no windows, is asked again only every 30 minutes (`keyNoWindowsAge`). Kimi Code's `/usages` (`readKimiCode`) is read as kimi-cli and kimi-code read it: the week's `usage` and each `limits[]` window as counts, and the shares in `usages` (`limit_5h`, `limit_7d`, and `limit_month_total` as a *Month* window renewing at its `reset_time`, lidazi2016 on Discord); a window told both ways is the share's, and `limit_month_code`, the part of the month code used, is no window. `TestReadKimiCode`, `TestReadKimiCodeMonth`. A Command Code plan's key has its month of credits as a *Credits* window beside the 5-hour and weekly ones, as the signed-in subscription's card has (`cmdKeyWindows`, #2451): billing/credits leaves the plan out, so it is the key's billing/subscriptions plan, asked at most every ten minutes and the last one kept while it can't be read; the same reply's period end is the Credits window's reset, left off once it has passed (#2454); a key whose plan was never read has its two windows alone. On Go, GOAT and Pro the month is counted in Command Code's usage-value credits, not dollars (GOAT's 70 are $100 of a model like DeepSeek V4.1 Flash, $70 of GLM-5.2), so the window says "28.80 / 70.00 credits" with bought credits as "+ $5.00 extra" beside it; Max, Ultra and Teams Pro keep the CLI's dollar pool, and Provider, pay as you go, has no month (`cmdPlans`, as the plugin since 0.1.20, plugins #556). Ollama Cloud's `ollama.com/api/balance` (#1888, `readOllamaPlan`) tells the plan's included allowance as one window in USD, *Month* when its period is a month long, renewing at `period.until`, and Aside while credits bought on top are left; those credits are the key's balance card (`readOllamaCredits`), and a reply that names none has no balance card rather than $0. A Mistral key is told its organization's month at `api.mistral.ai/v1/billing/budget`, as Mistral's Vibe CLI reads it (`mistral_plan.go`, dhanyqaz on Discord). The budget is the organization's, so every key of it gets the same `vibe_budget` and `api_budget`; which one a key spends is its kind, asked once a key of `console.mistral.ai/api/vibe/whoami` (`plan_type`). A Vibe key (`chat`) has `vibe_budget` as one *Month* window, a Studio key made in the console (`api`) has `api_budget` as *API · Month*, so the accounts' strip never adds the two; each is in the currency billing names (none when it names none), Aside while pay-as-you-go is on (the budget's own, else the subscription's `vibe_payg_enabled` for Vibe and `payg_enabled` for Studio), with the plan's name from `billing/subscription` (EDU is Student). A key whoami can't place (a failed read, no `plan_type`, Mistral Code's key) or whose budget is 0 has no card, and Le Chat's own message limits are told nowhere. ModelScope's API-Inference token is told its 魔粒 at the OpenAPI's `modelscope.cn/openapi/v1/magicubes/balance` (`readModelScope`, jiabubu on Discord): `available_balance`, which leaves out what running tasks have frozen, as the balance card; the page's daily list (`/magicubes/transactions`) isn't in the OpenAPI, so what is spent a day is the card's own trend. StepFun's Step Plan is read through a platform sign-in, not the key, and isn't one of them: the sign-in is the provider's own, kept by provider id in `stepfun-auth.json` (two StepFun providers on one site can be two accounts, #2384), one card per signed-in provider; a file from before that, kept by site, is given on read to the StepFun providers on that site (`stepfunBySite`), and copies of one sign-in are renewed together. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (`AccessKeyID`, `SecretAccessKey`), asked of `open.volcengineapi.com` (`GetCodingPlanUsage`, `GetAFPUsage`) and signed as Volcengine's own SDK signs (`volcSign`), so they are cards on the Usage page (`volcPlanQuotas` in `PlanQuotas`), never routing's windows. Nor is Tencent Cloud's Token Plan 企业版 (#1574): what a team plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐) is told only to the account's SecretId and SecretKey (kept as `AccessKeyID`, `SecretAccessKey`), asked of `tokenhub.tencentcloudapi.com` (`DescribeTokenPlanList`, `DescribeTokenPlan`, version 2026-03-22) and signed TC3-HMAC-SHA256 (`tc3Sign`), one card per team plan (`tencentPlanQuotas`). | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go), [`tencent_usage.go`](../../internal/provider/tencent_usage.go) | | A relay's balance found | A provider added by hand, or from a relay's preset, with a key and no Balance URL, at no host magpie knows a query for, is asked where relays tell a key its balance: the base's origin's `/v1/usage` (sub2api, `$remaining`), then `/api/usage/token` (new-api, `$data.total_available / 500000`), with the key's own auth and headers (`probesBalance`, `probeBalance`). A 200 whose field reads is the query; it is kept in memory for the origins and key for 24 hours and then looked for again, so a relay that moved to other software is not read at a query that now means something else. When the look finds nothing, the old query stays while it turns the key away (401/403, so the card says so) or the relay is down. Finding none is kept for 6 hours (5 minutes when the relay couldn't be reached). Nothing is written to the provider: the card reads the found URL, `BalanceQuery` names it, and the editor shows it under the Balance URL (`BalanceFound`, `balanceFound` in /api/providers and the check's reply; `balfound.js`), with Use to copy it into the fields so a wrong amount can be put right. None found means no card (`errNoBalance`) and, from the editor's check, *No balance at /v1/usage or /api/usage/token*. Never asked: a model vendor's or local server's preset host, this computer, OpenCode and the Cline API (`noProbeHosts`), a plan's windows (`planQuotaSourceOf`). A hand-added yylx.io relay showed no balance until its operator had the user import it again (11-05). | [`balance_probe.go`](../../internal/provider/balance_probe.go) | | Account names and seats | `AccountNames` (by the account, in lower case, like `AccountCaps`) are names the user gives accounts, set by `SetAccountName` (GUI `provider/accountname`, `magpie accounts alias`); they live in providers.json only, never in a vendor's or plugin's sign-in. A name picks its account wherever the account's own name does (`AccountByName`): the CLI's `accountNamed` (switch, forget, alias), the pool's `--accounts`, and `accountRef` (caps, models, weights, concurrency) after an exact name. It is refused when two accounts have it or it is another account's email or name, so it never picks by guess; `accountRef` then finds no account, as the GUI passes exact names (StringKe in #4532, `TestAccountsAliasPicksTheAccount`). A GLM Coding Plan read with a key (`glmPlan`) and a ZCode account (built-in or `zcode-plugin`) whose windows' resets agree are one seat (`seatMatch`, #90/#953), shown once, on the account's card (`seatCards`, used by `quotas`, `Allotted` and `CachedCards`). A match is remembered in `seats.json` beside `quotas.json`: a failed read or a window with no reset yet is unknown and keeps the key's card off while the account is signed in; windows that disagree forget it (#1515). Cards carry `Seat` (the key provider's name, and the key's when it has several) and `Alias` (the user's name, else the plugin's, else `Seat`) with `Named` when it is the user's own, which Hide accounts leaves in sight (#3656), as `/v1/magpie/quotas`, `magpie quota` and `magpie accounts` do. Records (a trace's `who`, usage's `ProviderAccount`) keep the vendor's name, the key the user's name is kept by, and every list of them looks the name up as it is shown (`AccountShown`, `AccountShownOf`, `AccountRef.Shown`), so a request from before a rename reads by the new name too: the Routing page's accounts and requests (`userShown` in `plugins/routing/client.js`, from `/api/providers`' `accountNames`), its Several accounts pools (`onOf`), the Usage page's Accounts and the request log's Account filter (`usageapi`), `magpie usage`, and a gateway key's accounts (`AccountNames`, `/api/caller-keys`). Before plugins#310 (a renamed Kiro account read by its old name on every request after) those showed the vendor's name. An account with no name of the user's own goes by the name its plugin's `usage()` gives it (`PluginUserOf`, the `user` of its last read: `loginUsageCache`, else `quotas.json`), else by its id: a Huawei Cloud CodeArts account kept by its IAM id `iam:::user:` reads as the masked phone its card shows (#4416). `AccountShown`, `AccountShownOf` and `AccountLabelOf` (cards' `Alias`, `magpie accounts`, usageapi's Account filter, the quota alert) apply it, and the GUI has it as `/api/providers`' `accountUsers` (`accountShownOf` in app.js: the editor's rows, the per-account proxy lines, Routing's `userShown`, Hide accounts). The id stays the key everything is kept by; nothing stored changes. A read that fails keeps the last good `user`; nothing read yet, or a plugin whose windows are all model pools (not kept in `quotas.json`) after a restart, is its id until the next read. | [`account_names.go`](../../internal/provider/account_names.go), [`account_seats.go`](../../internal/provider/account_seats.go) | diff --git a/internal/catalog/fresh.go b/internal/catalog/fresh.go index 6aa9ac312..a098d2976 100644 --- a/internal/catalog/fresh.go +++ b/internal/catalog/fresh.go @@ -60,6 +60,48 @@ func Missing() { go fetch() } +// askedAfter is how old the catalog may be when a list made of it alone +// is asked for again (Asked). +var askedAfter = 10 * time.Minute + +// Asked says a model list made of the catalog alone is being fetched: a +// Claude subscription's, which is models.dev's anthropic list, as magpie +// asks Anthropic nothing in Claude Code's name. The catalog is fetched +// now, as long as ctx allows, when it is older than askedAfter and wasn't +// tried in that time, so a model launched since the day's fetch is on the +// list the user asked for (hhdaxia on X: Fable 5.2, on models.dev and in +// Claude Code's /model, not after Fetch models again). Only in a process +// that keeps the catalog fresh (KeepFresh), one fetch at a time, and a +// failed one leaves the catalog as it was. +func Asked(ctx context.Context) { + if !keeping.Load() || time.Since(time.Unix(0, lastFetch.Load())) < askedAfter { + return + } + if src := Source(); src != "" { + if st, err := os.Stat(src); err == nil && time.Since(st.ModTime()) < askedAfter { + return + } + } + if !fetching.CompareAndSwap(false, true) { + return + } + defer fetching.Store(false) + lastFetch.Store(time.Now().UnixNano()) + if err := Sync(ctx); err != nil { + log.Println("catalog:", err) + } +} + +// KeepFreshForTest has the catalog kept fresh from url, as the app's +// backend keeps it from models.dev, for a test of what asks for it. +func KeepFreshForTest(url string) (restore func()) { + was := modelsDevURL + modelsDevURL = url + keeping.Store(true) + lastFetch.Store(0) + return func() { modelsDevURL = was; keeping.Store(false); lastFetch.Store(0) } +} + // fetch is Sync with a bound, one at a time. func fetch() { if !fetching.CompareAndSwap(false, true) { diff --git a/internal/provider/account.go b/internal/provider/account.go index f6639d452..310ba2f83 100644 --- a/internal/provider/account.go +++ b/internal/provider/account.go @@ -879,7 +879,10 @@ func claudeProvider(acct *Account) Provider { // Claude's models are the ones magpie knows and the ones Claude Code // was told an account has (claude_models.go): listing them would ask // Anthropic with the account's sign-in, which magpie never does - acct.fetch = func(context.Context) ([]catalog.Model, error) { + acct.fetch = func(ctx context.Context) ([]catalog.Model, error) { + // models.dev's list, fetched again first when it is older than + // a few minutes: a model launched since the day's sync is listed + catalog.Asked(ctx) ms := claudeModels() return ms, catalog.SaveLive("claude", claudeBase, ms) } diff --git a/internal/provider/claude_models_test.go b/internal/provider/claude_models_test.go index d02ec60c7..e72cc242a 100644 --- a/internal/provider/claude_models_test.go +++ b/internal/provider/claude_models_test.go @@ -2,9 +2,12 @@ package provider import ( "context" + "net/http" + "net/http/httptest" "os" "path/filepath" "slices" + "sync/atomic" "testing" "time" @@ -208,3 +211,65 @@ func TestClaudeAccountListsFable52(t *testing.T) { t.Fatalf("not served beside picks of every model listed before: %v", got) } } + +// Fetch models again on a Claude subscription fetches models.dev's list +// first when the catalog magpie keeps is older than a few minutes: a +// model launched since the day's sync is on the list the user asked for +// (hhdaxia on X: Fable 5.2 in Claude Code's /model, on models.dev, and +// not in the vendor's list "just now" fetched). Outside a process that +// keeps the catalog fresh (a CLI command, a test) nothing is fetched. +func TestClaudeFetchAsksModelsDevForANewModel(t *testing.T) { + home := claudeHome(t) + claudeSignIn(t, home, time.Now().Add(time.Hour)) + t.Cleanup(catalog.Reset) + var hits atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + w.Write([]byte(`{"anthropic":{"id":"anthropic","name":"Anthropic","models":{` + mdOpus55 + "," + mdHaiku55 + "," + mdFable52 + `}}}`)) + })) + defer srv.Close() + + // the day's sync, two hours before Fable 5.2 reached models.dev + writeAnthropicCatalog(t, mdOpus55, mdHaiku55) + old := time.Now().Add(-2 * time.Hour) + if err := os.Chtimes(catalog.CachePath(), old, old); err != nil { + t.Fatal(err) + } + fetch := func() []string { + t.Helper() + p, ok := find(All(), "claude") + if !ok || p.Account == nil { + t.Fatalf("claude: %+v %v", p, ok) + } + ms, err := p.Fetch(context.Background()) + if err != nil { + t.Fatal(err) + } + return modelIDs(ms) + } + + t.Cleanup(catalog.KeepFreshForTest(srv.URL)) + if got := fetch(); len(got) == 0 || got[0] != "claude-fable-5-2" { + t.Fatalf("Fable 5.2 not first after a fetch: %v (%d asks of models.dev)", got, hits.Load()) + } + p, _ := find(All(), "claude") + if !slices.ContainsFunc(p.Available(), func(m catalog.Model) bool { return m.ID == "claude-fable-5-2" }) { + t.Fatalf("Fable 5.2 not served: %v", modelIDs(p.Available())) + } + // fetched again at once: models.dev is asked nothing more + fetch() + if n := hits.Load(); n != 1 { + t.Fatalf("%d asks of models.dev, want 1", n) + } + + // a process that doesn't keep the catalog fresh asks nothing + catalog.KeepFreshForTest(srv.URL)() + writeAnthropicCatalog(t, mdOpus55) + os.Chtimes(catalog.CachePath(), old, old) + if got := fetch(); slices.Contains(got, "claude-fable-5-2") { + t.Fatalf("models.dev asked outside KeepFresh: %v", got) + } + if n := hits.Load(); n != 1 { + t.Fatalf("%d asks of models.dev, want 1", n) + } +}