diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index aabc8b6d4..b8c8eeaf3 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -80,7 +80,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | 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) | | models.dev unreachable | The catalog (`CachePath`, `models.json`) is written whole through a rename (`writeWhole`), so a reader never sees it half written and a fetch that fails (refused, hanging past `fetchBound`, a page that isn't the catalog) keeps the last good copy. `loadGen` reads magpie's copy, then OpenCode's, then the copy the binary ships with (`bundled/api.json.gz`, `bundledAt`), passing over one it can't parse. `Seed` (the app's backend, `magpie serve`, the plugin host) writes the shipped copy into `CachePath` dated `bundledAt` when there is no catalog file or the one there is older, so the plugin host's `mdev` reads it too and `Stale` still has the real one fetched. The app's backend fetches beside the vendors' lists rather than before them, and `KeepFresh` tries a failed fetch again after `retryFirst` (2 minutes), doubling up to the hour (`nextRetry`). The fetch goes through `http.DefaultClient`, so through the proxy in Settings, `*_PROXY` or the system's (`netproxy.Install`). A test binary has the shipped copy off (`bundledOn`). Refresh it with `go generate ./internal/catalog` and set `bundledAt` (creeksuen on X). `TestFailedSyncKeepsLastGood`, `TestFirstRunOfflineAnswersFromShippedCopy`, `TestUnreadableCacheFallsBackToShippedCopy`, `TestSeed`, `TestSyncWritesThroughRename`, `TestFailedFetchRetriedSoon`. | [`bundled.go`](../../internal/catalog/bundled.go), [`fresh.go`](../../internal/catalog/fresh.go), [`catalog.go`](../../internal/catalog/catalog.go), [`backend.go`](../../internal/gui/backend.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 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). Claude Code 2.1.323 and later also keep a version-2 catalog per account, `/cache/model-catalog/--cc.json` (`catalog.config.models`: id, name, `runtime` window, reply limit, effort levels, `mm_images`); `readClaudeCodeModels` adds the models of the catalog of the account its `.claude.json` names, from that config directory or Claude Code's own (which keeps every account's that signed in there), the one fetched last, and fills a window, limit or levels models.dev doesn't have from it. Another account's catalog in the folder is never read, a file of another version or surface is unknown, and a `.claude.json` or catalog that doesn't parse (halfway through a write) is what it said last (`readKeepingGood`; #6418, `TestClaudeCodeCatalogV2Models`). `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), [`claude_code_catalog.go`](../../internal/provider/claude_code_catalog.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/provider/claude_code_catalog.go b/internal/provider/claude_code_catalog.go new file mode 100644 index 000000000..02f32ead3 --- /dev/null +++ b/internal/provider/claude_code_catalog.go @@ -0,0 +1,170 @@ +package provider + +// Claude Code 2.1.323 and later keep an account's models in a catalog of +// their own beside .claude.json: /cache/model-catalog/ +// --cc.json, a +// version-2 file whose catalog.config.models are what its /model picker +// offers that account (#6418, pwn2ooown). The name says whose it is, so +// ~/.claude's folder keeps the catalogs of every account that was signed in +// there, and only the one of the account a .claude.json names is read with +// it. The file's shape and name are read from Claude Code's own on a Mac +// (11-14): models with id, name and runtime (max_input_tokens, +// max_output_tokens, effort_levels, capabilities). + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io/fs" + "path/filepath" + "slices" + "strings" + "sync" + + "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/filememo" +) + +// claudeCatalog is what one model-catalog file says of an account's models. +type claudeCatalog struct { + // at is when Claude Code fetched it (fetchedAt), in ms + at float64 + models []claudeExtra +} + +func parseClaudeCatalog(b []byte) (claudeCatalog, error) { + var raw struct { + Version int `json:"version"` + FetchedAt float64 `json:"fetchedAt"` + Catalog *struct { + Surface string `json:"surface"` + Config *struct { + Models []struct { + ID string `json:"id"` + Name string `json:"name"` + Runtime struct { + MaxInput int `json:"max_input_tokens"` + MaxOutput int `json:"max_output_tokens"` + Efforts []string `json:"effort_levels"` + Capabilities []string `json:"capabilities"` + } `json:"runtime"` + } `json:"models"` + } `json:"config"` + } `json:"catalog"` + } + if err := json.Unmarshal(b, &raw); err != nil { + return claudeCatalog{}, err + } + // another version's or surface's file is a shape not known here: unknown, + // never "no models" + if raw.Version != 2 || raw.Catalog == nil || raw.Catalog.Surface != "cc" || raw.Catalog.Config == nil { + return claudeCatalog{}, errors.New("not a version-2 Claude Code model catalog") + } + out := claudeCatalog{at: raw.FetchedAt} + seen := map[string]bool{} + for _, m := range raw.Catalog.Config.Models { + id := claudeAPIID(m.ID) + if id == "" || seen[id] { + continue + } + seen[id] = true + r := m.Runtime + out.models = append(out.models, claudeExtra{ + id: id, name: strings.TrimSpace(m.Name), + context: max(r.MaxInput, 0), output: max(r.MaxOutput, 0), + efforts: slices.Clip(r.Efforts), images: slices.Contains(r.Capabilities, "mm_images"), + }) + } + return out, nil +} + +// claudeCatalogName is the file Claude Code keeps the account's catalog +// in; "" when the account isn't known. +func claudeCatalogName(org, account string) string { + if org == "" || account == "" { + return "" + } + sum := sha256.Sum256([]byte(account)) + return org + "-" + hex.EncodeToString(sum[:])[:12] + "-cc.json" +} + +// claudeCatalogDirs are the model-catalog folders an account's catalog may +// be in, for the .claude.json at profile: its own config directory's, and +// that of Claude Code as it runs here, which keeps every account's that +// was signed in to it. +func claudeCatalogDirs(profile string) []string { + own := appdir.ClaudeDir() + if profile != claudeProfilePath() { + own = filepath.Dir(profile) + } + dirs := []string{filepath.Join(own, "cache", "model-catalog")} + if here := filepath.Join(appdir.ClaudeDir(), "cache", "model-catalog"); here != dirs[0] { + dirs = append(dirs, here) + } + return dirs +} + +// claudeCatalogOf is the catalog Claude Code keeps for the account of the +// .claude.json at profile: of its copies, the one fetched last. +func claudeCatalogOf(profile, org, account string) (claudeCatalog, bool) { + name := claudeCatalogName(org, account) + if name == "" { + return claudeCatalog{}, false + } + var best claudeCatalog + found := false + for _, d := range claudeCatalogDirs(profile) { + if c, ok := readKeepingGood("claude catalog", filepath.Join(d, name), parseClaudeCatalog); ok && (!found || c.at > best.at) { + best, found = c, true + } + } + return best, found +} + +// goodReads are the last parse of each file read through readKeepingGood. +var goodReads sync.Map // goodKey → any + +type goodKey struct{ kind, path string } + +// readKeepingGood is filememo.Read of path, with a file that doesn't +// parse now (Claude Code halfway through writing it) taken as what it +// said last, never as one with nothing in it; a file gone is gone. +func readKeepingGood[T any](kind, path string, parse func([]byte) (T, error)) (T, bool) { + k := goodKey{kind, path} + v, err := filememo.Read(kind, path, parse) + if err == nil { + goodReads.Store(k, v) + return v, true + } + if errors.Is(err, fs.ErrNotExist) { + goodReads.Delete(k) + var zero T + return zero, false + } + if g, ok := goodReads.Load(k); ok { + return g.(T), true + } + var zero T + return zero, false +} + +// withCatalog is m with the models its account's catalog offers that its +// .claude.json doesn't name. m is filememo's shared value: it is copied, +// never changed. +func (m claudeCodeModels) withCatalog(c claudeCatalog) claudeCodeModels { + m.extra = slices.Clone(m.extra) + for _, x := range c.models { + if i := slices.IndexFunc(m.extra, func(e claudeExtra) bool { return e.id == x.id }); i >= 0 { + if m.extra[i].name == "" { + m.extra[i].name = x.name + } + e := &m.extra[i] + e.context, e.output, e.efforts, e.images = x.context, x.output, x.efforts, x.images + continue + } + m.extra = append(m.extra, x) + } + m.at = max(m.at, c.at) + return m +} diff --git a/internal/provider/claude_code_models.go b/internal/provider/claude_code_models.go index c621455fa..9ed2e803c 100644 --- a/internal/provider/claude_code_models.go +++ b/internal/provider/claude_code_models.go @@ -12,7 +12,9 @@ package provider // account is or isn't entitled to; additionalModelCostsCache, their // prices. magpie reads them back, as it reads the account's identity from // the same file: nothing is asked of Anthropic in Claude Code's name -// (iebb on Discord: "最好以 claude code 返回为准"). +// (iebb on Discord: "最好以 claude code 返回为准"). Claude Code 2.1.323 +// and later keep the models in a catalog file too (claude_code_catalog.go), +// read with the .claude.json of the account it names. import ( "encoding/json" @@ -22,7 +24,6 @@ import ( "strings" "github.com/yetone/magpie/internal/catalog" - "github.com/yetone/magpie/internal/filememo" "github.com/yetone/magpie/internal/settings" ) @@ -38,9 +39,20 @@ type claudeCodeModels struct { entitled map[string]bool // prices are Anthropic's, by API id, USD per million tokens prices map[string]catalog.Price + // org and account are the oauthAccount's organizationUuid and + // accountUuid: whose catalog file goes with this one + org, account string } -type claudeExtra struct{ id, name string } +// claudeExtra is a model Claude Code offers; context, output, efforts and +// images are its catalog's runtime, when the catalog has it, for a model +// models.dev doesn't describe. +type claudeExtra struct { + id, name string + context, output int + efforts []string + images bool +} func parseClaudeCodeModels(b []byte) (claudeCodeModels, error) { var raw struct { @@ -61,11 +73,15 @@ func parseClaudeCodeModels(b []byte) (claudeCodeModels, error) { Write1h *float64 `json:"promptCacheWrite1hTokens"` CacheRead float64 `json:"promptCacheReadTokens"` } `json:"additionalModelCostsCache"` + Account struct { + Org string `json:"organizationUuid"` + Account string `json:"accountUuid"` + } `json:"oauthAccount"` } if err := json.Unmarshal(b, &raw); err != nil { return claudeCodeModels{}, err } - out := claudeCodeModels{at: raw.At} + out := claudeCodeModels{at: raw.At, org: strings.TrimSpace(raw.Account.Org), account: strings.TrimSpace(raw.Account.Account)} seen := map[string]bool{} for _, o := range raw.Options { if o.Value == nil || o.Disabled { @@ -76,7 +92,7 @@ func parseClaudeCodeModels(b []byte) (claudeCodeModels, error) { continue } seen[id] = true - out.extra = append(out.extra, claudeExtra{id, strings.TrimSpace(o.Label)}) + out.extra = append(out.extra, claudeExtra{id: id, name: strings.TrimSpace(o.Label)}) } for _, a := range raw.Access { if id := claudeAPIID(a.APIName); id != "" && a.Entitled != nil { @@ -122,9 +138,18 @@ func claudeAPIID(v string) string { return v } +// readClaudeCodeModels is what the .claude.json at path and its +// account's model catalog say: a file that doesn't parse now is what it +// said last. func readClaudeCodeModels(path string) (claudeCodeModels, bool) { - m, err := filememo.Read("claude models", path, parseClaudeCodeModels) - return m, err == nil + m, ok := readKeepingGood("claude models", path, parseClaudeCodeModels) + if !ok { + return m, false + } + if c, ok := claudeCatalogOf(path, m.org, m.account); ok { + m = m.withCatalog(c) + } + return m, true } // claudeCodeFiles are the state files of every Claude Code magpie knows of @@ -197,6 +222,16 @@ func claudeModels() []catalog.Model { have[x.id] = true m := catalog.Describe(x.id, x.name) m.Provider = "anthropic" + if m.Context == 0 { + m.Context = x.context + } + if m.Output == 0 { + m.Output = x.output + } + if len(m.Efforts) == 0 && len(x.efforts) > 0 { + m.Efforts, m.Reasoning = slices.Clone(x.efforts), true + } + m.Images = m.Images || x.images if p, ok := cm.prices[x.id]; ok { m.Price = &p } diff --git a/internal/provider/claude_code_models_test.go b/internal/provider/claude_code_models_test.go index b8c3fe85e..af7b2d123 100644 --- a/internal/provider/claude_code_models_test.go +++ b/internal/provider/claude_code_models_test.go @@ -175,3 +175,145 @@ func TestAnthropicKeyGatedModelDescribed(t *testing.T) { t.Errorf("entry = id %s name %q default %q context %d output %d efforts %v", e.ID, e.Name, e.Default, e.Context, e.Output, e.Efforts) } } + +// #6418's fixture (pwn2ooown): models.dev's anthropic list with Sonnet 5.5 +// alone, a .claude.json whose legacy caches are empty, and Claude Code +// 2.1.323's version-2 catalog with Fable 5.2, in the shape the issue gives +// it and named as Claude Code names it on a Mac (organizationUuid, then the +// first 12 hex of sha256(accountUuid)). +const ( + fableOrg = "00000000-0000-4000-8000-000000000002" + fableAccount = "00000000-0000-4000-8000-000000000001" + fableCatalog = `{"version": 2, "fetchedAt": 1763100000000, "staleAt": 1763103600000, + "catalog": {"surface": "cc", "config": {"id": "cc", "models": [{ + "id": "claude-fable-5-2", "name": "Fable 5.2", "short_name": "Fable", "section": "main", + "runtime": {"max_input_tokens": 1000000, "max_output_tokens": 128000, + "effort_levels": ["low", "medium", "high"], "default_effort": "medium"} + }], "provider_alias_targets": {}, "settings_vocabulary": {}}, + "state": {"id": "cc", "model": "claude-fable-5-2", "thinking": {"type": "effort", "effort": "medium"}}}}` +) + +func fableCatalogs(t *testing.T, home string) { + t.Helper() + put := func(path, s string) { + os.MkdirAll(filepath.Dir(path), 0o755) + if err := os.WriteFile(path, []byte(s), 0o600); err != nil { + t.Fatal(err) + } + } + put(catalog.CachePath(), `{"anthropic": {"id": "anthropic", "name": "Anthropic", "npm": "@ai-sdk/anthropic", + "env": ["ANTHROPIC_API_KEY"], "models": {"claude-sonnet-5-5": {"id": "claude-sonnet-5-5", "name": "Claude Sonnet 5.5", + "release_date": "2026-09-28", "limit": {"context": 1000000, "output": 128000}, + "modalities": {"input": ["text"], "output": ["text"]}}}}}`) + put(catalog.LabsPath(), `{}`) + catalog.Reset() + t.Cleanup(catalog.Reset) + writeFile(t, filepath.Join(home, ".claude.json"), map[string]any{ + "oauthAccount": map[string]any{"emailAddress": "catalog-repro@example.com", "accountUuid": fableAccount, "organizationUuid": fableOrg}, + "additionalModelOptionsCache": []any{}, "additionalModelOptionsAnsweredAt": time.Now().UnixMilli(), + "modelAccessCache": []any{}, "additionalModelCostsCache": map[string]any{}, + }) + filememo.Forget() +} + +// A model Claude Code 2.1.323+ keeps only in its version-2 model catalog, +// not in .claude.json's legacy caches nor in models.dev's anthropic list, +// is on the account's list with the catalog's name, window and levels; a +// catalog of another account in the same folder adds nothing, and a +// catalog halfway through being written is what it said last (#6418). +func TestClaudeCodeCatalogV2Models(t *testing.T) { + home := claudeHome(t) + claudeSignIn(t, home, time.Now().Add(time.Hour)) + claudeBase = "http://127.0.0.1:1" // asked nothing + fableCatalogs(t, home) + dir := filepath.Join(home, ".claude", "cache", "model-catalog") + write := func(name, s string) { + os.MkdirAll(dir, 0o755) + if err := os.WriteFile(filepath.Join(dir, name), []byte(s), 0o600); err != nil { + t.Fatal(err) + } + filememo.Forget() + } + listed := func() []catalog.Model { + t.Helper() + ForgetAccounts() + p, ok := find(All(), "claude") + if !ok || p.Account == nil { + t.Fatal("no Claude account") + } + return p.Available() + } + if ids := modelIDs(listed()); slices.Contains(ids, "claude-fable-5-2") || !slices.Contains(ids, "claude-sonnet-5-5") { + t.Fatalf("baseline: %v", ids) + } + + // another account's catalog (same org, another accountUuid) is not this one's + other := claudeCatalogName(fableOrg, "00000000-0000-4000-8000-000000000009") + write(other, fableCatalog) + if ids := modelIDs(listed()); slices.Contains(ids, "claude-fable-5-2") { + t.Fatalf("another account's catalog listed: %v", ids) + } + os.Remove(filepath.Join(dir, other)) + + own := claudeCatalogName(fableOrg, fableAccount) + if want := fableOrg + "-" + "11e594f48195" + "-cc.json"; own != want { + // sha256("00000000-0000-4000-8000-000000000001")[:12] + t.Fatalf("catalog name %s, want %s", own, want) + } + write(own, fableCatalog) + ms := listed() + i := slices.IndexFunc(ms, func(m catalog.Model) bool { return m.ID == "claude-fable-5-2" }) + if i < 0 { + t.Fatalf("Fable 5.2 from the version-2 catalog not listed: %v", modelIDs(ms)) + } + if m := ms[i]; m.Name != "Fable 5.2" || m.Context != 1_000_000 || m.Output != 128_000 || !m.Reasoning || !slices.Equal(m.Efforts, []string{"low", "medium", "high"}) { + t.Errorf("Fable 5.2 = %+v", m) + } + if own := modelIDs(ClaudeCodeModels()); !slices.Contains(own, "claude-fable-5-2") { + t.Errorf("Claude Code's own picker lacks it: %v", own) + } + if has, ok := claudeLists("catalog-repro@example.com", "claude-fable-5-2"); !ok || !has { + t.Errorf("claudeLists = %v %v", has, ok) + } + + // halfway through a write: what it said last, not no models + write(own, fableCatalog[:120]) + if ids := modelIDs(listed()); !slices.Contains(ids, "claude-fable-5-2") { + t.Errorf("a half-written catalog dropped Fable 5.2: %v", ids) + } + os.Remove(filepath.Join(dir, own)) + filememo.Forget() + if ids := modelIDs(listed()); slices.Contains(ids, "claude-fable-5-2") { + t.Errorf("a catalog gone still lists Fable 5.2: %v", ids) + } + + // a saved account's own config directory keeps its catalog there + saved := "saved@example.com" + sdir := claudeAccountDir(saved) + writeFile(t, filepath.Join(sdir, ".claude.json"), map[string]any{ + "oauthAccount": map[string]any{"emailAddress": saved, "accountUuid": "acct-saved", "organizationUuid": "org-saved"}, + }) + os.MkdirAll(filepath.Join(sdir, "cache", "model-catalog"), 0o755) + os.WriteFile(filepath.Join(sdir, "cache", "model-catalog", claudeCatalogName("org-saved", "acct-saved")), []byte(fableCatalog), 0o600) + filememo.Forget() + if ids := modelIDs(claudeModels()); !slices.Contains(ids, "claude-fable-5-2") { + t.Errorf("a saved account's catalog not read: %v", ids) + } + if cm, ok := claudeModelsOf(saved); !ok || !slices.ContainsFunc(cm.extra, func(x claudeExtra) bool { return x.id == "claude-fable-5-2" }) { + t.Errorf("claudeModelsOf(saved) = %+v %v", cm, ok) + } +} + +// A model-catalog file of a version or surface not known here is not +// taken as a catalog with no models. +func TestClaudeCatalogUnknownShape(t *testing.T) { + for _, s := range []string{`{"version":3,"catalog":{"surface":"cc","config":{"models":[]}}}`, `{"version":2,"catalog":{"surface":"web","config":{"models":[]}}}`, `{"version":2}`, `{"version":2,"catalog":`} { + if _, err := parseClaudeCatalog([]byte(s)); err == nil { + t.Errorf("%s parsed", s) + } + } + c, err := parseClaudeCatalog([]byte(fableCatalog)) + if err != nil || len(c.models) != 1 || c.models[0].id != "claude-fable-5-2" { + t.Fatalf("%+v %v", c, err) + } +}