provider: Claude Code's version-2 model catalog lists an account's models too (#6418)

Claude Code 2.1.323+ keeps an account's models in
<config dir>/cache/model-catalog/<organizationUuid>-<sha256(accountUuid)[:12]>-cc.json
(version 2, catalog.config.models), and magpie read only .claude.json's
additionalModelOptionsCache / modelAccessCache. A model only that catalog
has, and models.dev's anthropic list lacks, was missing from the Claude
provider, `magpie models` and Claude Code's own picker (pwn2ooown).

readClaudeCodeModels, which every reader of those caches goes through
(claudeModels, claudeModelsOf/claudeLists, ClaudeCodeModels,
claudeCodePrice), now adds the catalog of the account its .claude.json
names, from that config directory or Claude Code's own (~/.claude keeps
every account's that signed in there), the one fetched last. A model
models.dev doesn't describe takes the catalog's window, reply limit,
effort levels and mm_images. The legacy caches are read as before.
Another account's catalog is never read; a file of another version or
surface is unknown; a .claude.json or catalog that doesn't parse
(halfway through a write) is what it said last (readKeepingGood), a file
gone is gone.

The name and shape come from this Mac's Claude Code, read only: 7 files
in ~/.claude/cache/model-catalog and 2 in saved account dirs; the name's
first part is organizationUuid and its second sha256(accountUuid)[:12]
for every account whose .claude.json is here.

Run (mote):
- go test -tags nogui ./internal/provider ./internal/agent ./internal/cli
  ./internal/catalog ./internal/filememo ./internal/proc: all ok (provider 166s, agent 357s, cli 67s)
- go vet ./...; GOOS=linux go vet -tags nogui and GOOS=windows go vet of
  internal/provider and internal/agent; gofmt -l clean
- built magpie, `magpie models` in sandbox HOMEs (the issue's repro
  adapted): baseline, other account's catalog, half-written catalog: no
  Fable 5.2; the issue's catalog: listed; legacy cache: listed; a copy of
  a real Claude Code catalog's bytes under synthetic ids: all 13 models
  listed.
- after rebasing on 58629a0f8 (no change in these packages): provider
  and usage ok again at the pushed head.

Broken by hand (TestClaudeCodeCatalogV2Models red each time):
- catalog not read: "Fable 5.2 from the version-2 catalog not listed"
- last good dropped: "a half-written catalog dropped Fable 5.2"
- name keyed on org only: "another account's catalog listed"

Not tried: Claude Code on Linux/Windows (same path under the config dir
assumed); a real account whose catalog has a model models.dev lacks
(every model in this Mac's catalogs is in models.dev); the full ./...
suite. The issue's repro names its file <org>-<accountUuid>-cc.json,
which Claude Code doesn't write, so that literal name is not read.
This commit is contained in:
yetone
2026-11-14 03:17:11 +08:00
parent 58629a0f8e
commit 7b50e1f2c6
4 changed files with 355 additions and 8 deletions
File diff suppressed because one or more lines are too long
+170
View File
@@ -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: <config dir>/cache/model-catalog/
// <organizationUuid>-<first 12 hex of sha256(accountUuid)>-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
}
+42 -7
View File
@@ -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
}
@@ -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)
}
}