From 09c635cf037f902b033a174847f6fa671e7a0d10 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 25 Sep 2026 12:30:12 +0800 Subject: [PATCH] =?UTF-8?q?agents:=20a=20model=20through=20magpie=20tells?= =?UTF-8?q?=20Pi,=20Crush,=20omp=20and=20Codex=20how=20much=20it=20holds,?= =?UTF-8?q?=20and=20a=20provider=20added,=20edited=20or=20removed=20reache?= =?UTF-8?q?s=20the=20model=20lists=20agents=20keep=20in=20files=20of=20the?= =?UTF-8?q?ir=20own=20=E2=80=94=20the=20catalog=20carried=20no=20context?= =?UTF-8?q?=20window,=20so=20Pi=20took=20every=20model=20through=20magpie?= =?UTF-8?q?=20for=20a=20128K=20one=20(a=20CLIProxyAPI's=20gpt-5.5=20holds?= =?UTF-8?q?=20922K)=20and=20Crush=20for=20a=20200K=20one;=20each=20model?= =?UTF-8?q?=20now=20carries=20models.dev's=20input=20limit,=20else=20its?= =?UTF-8?q?=20context,=20looked=20up=20by=20bare=20id=20as=20most=20of=20t?= =?UTF-8?q?he=20providers=20serving=20it=20give=20it=20(a=20proxy's=20"ope?= =?UTF-8?q?nai/gpt-5.4",=20"gpt-5.4(high)",=20"glm-4.6:free"=20find=20it?= =?UTF-8?q?=20too;=20a=20group=20holds=20the=20least=20of=20its=20members'?= =?UTF-8?q?).=20And=20those=20lists=20were=20written=20only=20when=20a=20m?= =?UTF-8?q?odel=20was=20picked:=20Codex's=20magpie-models.json,=20Pi's=20m?= =?UTF-8?q?odels.json,=20OpenCode's,=20Crush's,=20Command=20Code's,=20omp'?= =?UTF-8?q?s=20and=20Hermes'=20provider=20blocks=20and=20dsh's=20llm-deeps?= =?UTF-8?q?eek=20entry=20kept=20the=20catalog=20as=20it=20was=20then,=20so?= =?UTF-8?q?=20a=20provider=20added=20later=20never=20showed.=20Saving=20a?= =?UTF-8?q?=20provider,=20a=20vendor's=20list=20fetched=20anew=20or=20mode?= =?UTF-8?q?ls.dev=20synced=20now=20rewrites=20each=20one=20magpie=20wrote,?= =?UTF-8?q?=20where=20it=20differs,=20and=20the=20app=20does=20once=20at?= =?UTF-8?q?=20start-up;=20a=20Codex=20signed=20in=20to=20ChatGPT,=20which?= =?UTF-8?q?=20asks=20the=20gateway,=20kept=20its=20cached=20list=20under?= =?UTF-8?q?=20the=20backend's=20ETag,=20which=20a=20change=20of=20magpie's?= =?UTF-8?q?=20never=20changed=20=E2=80=94=20the=20ETag=20(and=20a=20reply'?= =?UTF-8?q?s=20X-Models-Etag)=20now=20carries=20a=20tag=20of=20magpie's=20?= =?UTF-8?q?models,=20and=20a=20cache=20from=20before=20a=20change=20is=20a?= =?UTF-8?q?ged=20so=20the=20next=20Codex=20asks=20again?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/agent/agent.go | 4 + internal/agent/agents.go | 20 +++- internal/agent/codex.go | 44 +++++++ internal/agent/codex_route_test.go | 1 + internal/agent/commandcode.go | 3 + internal/agent/dsh.go | 37 ++++++ internal/agent/hermes.go | 3 + internal/agent/omp.go | 6 +- internal/agent/route.go | 2 +- internal/agent/sync.go | 111 ++++++++++++++++++ internal/agent/sync_test.go | 153 +++++++++++++++++++++++++ internal/catalog/catalog.go | 73 +++++++++++- internal/catalog/catalog_test.go | 36 ++++++ internal/catalog/live.go | 25 +++- internal/codexcat/codexcat.go | 38 ++++++ internal/codexcat/tag_test.go | 46 ++++++++ internal/gateway/codex_backend.go | 30 +++-- internal/gateway/codex_backend_test.go | 28 ++++- internal/gui/app.go | 4 + internal/provider/codex_models.go | 22 +++- internal/provider/group.go | 7 +- internal/provider/models.go | 11 +- internal/provider/provider.go | 9 +- main.go | 3 + 24 files changed, 685 insertions(+), 31 deletions(-) create mode 100644 internal/agent/sync.go create mode 100644 internal/agent/sync_test.go create mode 100644 internal/codexcat/tag_test.go diff --git a/internal/agent/agent.go b/internal/agent/agent.go index 637a7b06f..8cccd3cd0 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -55,6 +55,10 @@ type Agent struct { // UA is what the agent's User-Agent begins with, lower-case: how the // gateway tells its requests from others' UA []string + // Sync, for an agent that reads magpie's models from a file of its own + // rather than asking the gateway, rewrites that list as the catalog is + // now — where magpie wrote one; nothing else changes (see SyncCatalog). + Sync func() error } // Running reports whether a process whose command line matches any pattern diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 225baf7e2..61df2424d 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -193,7 +193,11 @@ func magpieProviderJSON(shape string) any { case "crush": var ms []map[string]any for _, m := range models { - ms = append(ms, map[string]any{"id": m.ID, "name": m.Name, "context_window": 200000, "default_max_tokens": 16384, + window := m.Context + if window == 0 { + window = 200000 + } + ms = append(ms, map[string]any{"id": m.ID, "name": m.Name, "context_window": window, "default_max_tokens": 16384, "can_reason": len(m.Efforts) > 0}) } if ms == nil { @@ -208,6 +212,11 @@ func magpieProviderJSON(shape string) any { if levels := piThinkingLevels(m.Efforts); levels != nil { e["thinkingLevelMap"] = levels } + // without it Pi takes every model for a 128K one, and compacts + // a 272K or 922K one long before it has to + if m.Context > 0 { + e["contextWindow"] = m.Context + } ms = append(ms, e) } if ms == nil { @@ -270,6 +279,9 @@ func opencode(home, cfg string) *Agent { ID: "opencode", Name: "OpenCode", Icon: "opencode", Aliases: []string{"oc"}, UA: []string{"opencode"}, Bin: "opencode", Dir: dir, Path: path, + Sync: func() error { + return syncJSON(path, "provider."+magpieID, func() any { return magpieProviderJSON("opencode") }) + }, Fields: []Field{ {Key: "model", Label: "model", Get: jsonGet(path, "model"), Set: set("model"), Options: opts("model")}, {Key: "small", Label: "small", Get: jsonGet(path, "small_model"), Set: set("small_model"), Options: opts("small")}, @@ -291,6 +303,9 @@ func pi(home string) *Agent { return &Agent{ ID: "pi", Name: "Pi", Icon: "pi", Bin: "pi", Dir: dir, Path: path, UA: []string{"pi-"}, + Sync: func() error { + return syncJSON(modelsPath, "providers."+magpieID, func() any { return magpieProviderJSON("pi") }) + }, Fields: []Field{ { Key: "model", Label: "model", @@ -470,6 +485,9 @@ func crush(home, cfg string) *Agent { return &Agent{ ID: "crush", Name: "Crush", Icon: "crush", Bin: "crush", Dir: filepath.Dir(path), Path: path, UA: []string{"crush"}, + Sync: func() error { + return syncJSON(path, "providers."+magpieID, func() any { return magpieProviderJSON("crush") }) + }, Fields: []Field{ {Key: "model", Label: "large", Get: pairGet(get, "models.large.provider", "models.large.model"), Set: setter("models.large.provider", "models.large.model"), Options: opts("model")}, {Key: "small", Label: "small", Get: pairGet(get, "models.small.provider", "models.small.model"), Set: setter("models.small.provider", "models.small.model"), Options: opts("small")}, diff --git a/internal/agent/codex.go b/internal/agent/codex.go index 5036ee4bc..326b54bac 100644 --- a/internal/agent/codex.go +++ b/internal/agent/codex.go @@ -199,6 +199,19 @@ func codex(home string) *Agent { return &Agent{ ID: "codex", Name: "Codex", Icon: "codex-color", Bin: "codex", Dir: dir, Path: path, UA: []string{"codex"}, + Sync: func() error { + switch { + case asProvider() && get("model_catalog_json") == catalogPath: + b := codexcat.Catalog(magpieModels()) + if cur, _ := edit.Read(catalogPath); string(cur) == string(b) { + return nil + } + return edit.WriteAtomic(catalogPath, b) + case viaBase(): + return codexStaleCache(filepath.Join(dir, "models_cache.json"), codexcat.Tag(provider.CodexListed())) + } + return nil + }, // the app-server behind the Codex app (and every codex TUI) builds // its model list once, at start-up. Notice: func() string { @@ -291,6 +304,37 @@ func isCodexGateway(u string) bool { return strings.HasPrefix(u, "http://127.0.0.1:") && strings.HasSuffix(strings.TrimSuffix(u, "/"), gateway.CodexPath) } +// codexStaleCache ages Codex's cached model list if it isn't the one magpie +// would hand out now (its ETag carries the list's tag), so the next Codex to +// start asks the gateway again rather than showing the old one until the +// cache ages on its own; the rest of the cache stays as Codex wrote it. +func codexStaleCache(path, tag string) error { + b, err := os.ReadFile(path) + if err != nil { + return nil + } + var c map[string]json.RawMessage + if json.Unmarshal(b, &c) != nil { + return nil + } + var etag string + json.Unmarshal(c["etag"], &etag) + if codexcat.Tagged(etag, tag) { + return nil + } + old := time.Unix(0, 0).UTC().Format(time.RFC3339) + var at string + if json.Unmarshal(c["fetched_at"], &at) == nil && at == old { + return nil + } + c["fetched_at"], _ = json.Marshal(old) + out, err := json.MarshalIndent(c, "", " ") + if err != nil { + return err + } + return edit.WriteAtomic(path, out) +} + // codexUsedUp reports whether the ChatGPT account Codex is signed in to // has used up its allowance. A var so tests can say. var codexUsedUp = func() bool { diff --git a/internal/agent/codex_route_test.go b/internal/agent/codex_route_test.go index 5eb153b81..c9ac325f0 100644 --- a/internal/agent/codex_route_test.go +++ b/internal/agent/codex_route_test.go @@ -16,6 +16,7 @@ func codexHome(t *testing.T, auth, config string) (home string, read func() stri t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) t.Setenv("CODEX_HOME", "") + noKeychain(t) usedUp := codexUsedUp codexUsedUp = func() bool { return false } t.Cleanup(func() { codexUsedUp = usedUp }) diff --git a/internal/agent/commandcode.go b/internal/agent/commandcode.go index 6a3223a8e..a54387717 100644 --- a/internal/agent/commandcode.go +++ b/internal/agent/commandcode.go @@ -34,6 +34,9 @@ func commandCode(home string) *Agent { ID: "commandcode", Name: "Command Code", Icon: "commandcode", Aliases: []string{"command-code", "cmd"}, UA: []string{"command-code", "commandcode"}, Bin: "command-code", Dir: dir, Path: path, + Sync: func() error { + return syncJSON(providers, "provider."+magpieID, func() any { return ccProviderJSON() }) + }, Notice: func() string { notes := []string{"Command Code wants its own sign-in (cmd login) even for models through magpie."} if Running(`(^|/)(cmd|cmdc|command-code|commandcode)( |$)`) { diff --git a/internal/agent/dsh.go b/internal/agent/dsh.go index 6c9de2f5b..829ade161 100644 --- a/internal/agent/dsh.go +++ b/internal/agent/dsh.go @@ -51,6 +51,7 @@ func dsh(home string) *Agent { ID: "dsh", Name: "DeepSeek Harness", Icon: "deepseek-color", Aliases: []string{"deepseek-harness"}, UA: []string{"deepseek-harness"}, Bin: "dsh", Dir: dir, Path: path, + Sync: func() error { return dshSync(dir) }, Notice: func() string { var notes []string if Running(`(^|/)dsh( |$)`) { @@ -381,6 +382,42 @@ func dshRouteLines(model string) []string { } } +// dshSync puts the catalog as it is now into each llm-deepseek entry magpie +// wrote, keyed as that entry is; nothing else in the patch lists changes. +func dshSync(dir string) error { + files := dshProfiles(dir) + if len(files) == 0 { + files = []string{filepath.Join(dir, "config.yaml")} + } + for _, f := range files { + head, items, err := dshRead(f) + if err != nil { + continue + } + i := dshFind(items, "llm-deepseek") + if i < 0 || !items[i].magpie { + continue + } + modern := false + for _, l := range items[i].lines { + modern = modern || strings.HasPrefix(strings.TrimSpace(l), "apiKeyEnv:") + } + lines := dshProviderLines(modern) + if strings.Join(lines, "\n") == strings.Join(items[i].lines, "\n") { + continue + } + items[i].lines = lines + out := append([]string{}, head...) + for _, it := range items { + out = append(out, it.lines...) + } + if err := edit.WriteAtomic(f, []byte(strings.Join(out, "\n")+"\n")); err != nil { + return err + } + } + return nil +} + // dshSettingsEndpoint reports whether dsh's own settings carry an // llm-deepseek section with an endpoint or key, which dsh puts over the // patch list. diff --git a/internal/agent/hermes.go b/internal/agent/hermes.go index abaa2de8e..1cf4c5411 100644 --- a/internal/agent/hermes.go +++ b/internal/agent/hermes.go @@ -50,6 +50,9 @@ func hermes(home string) *Agent { ID: "hermes", Name: "Hermes Agent", Icon: "hermes", Aliases: []string{"hermes-agent"}, UA: []string{"hermes-agent"}, Bin: "hermes", Dir: dir, Path: path, + Sync: func() error { + return syncYAML(path, "providers."+magpieID, func() any { return hermesProvider() }) + }, Notice: func() string { if Running(`(^|/)hermes( |$)`) { return "Hermes reads its settings at start-up — restart open Hermes sessions to use this." diff --git a/internal/agent/omp.go b/internal/agent/omp.go index c554aa58c..265a23b80 100644 --- a/internal/agent/omp.go +++ b/internal/agent/omp.go @@ -57,6 +57,9 @@ func omp(home string) *Agent { ID: "omp", Name: "omp", Icon: "omp", Aliases: []string{"oh-my-pi"}, UA: []string{"oh-my-pi"}, Bin: "omp", Dir: dir, Path: path, + Sync: func() error { + return syncYAML(pick("models"), "providers."+magpieID, func() any { return ompProvider() }) + }, Notice: func() string { if Running(`(^|/)omp( |$)`, `@oh-my-pi/pi-coding-agent`) { return "omp reads its settings at start-up — restart open omp sessions to use this." @@ -96,6 +99,7 @@ type ompModel struct { Name string `yaml:"name,omitempty"` Reasoning bool `yaml:"reasoning"` Thinking *ompThinking `yaml:"thinking,omitempty"` + Context int `yaml:"contextWindow,omitempty"` } type ompThinking struct { @@ -115,7 +119,7 @@ type ompProviderEntry struct { func ompProvider() ompProviderEntry { ms := []ompModel{} for _, m := range magpieModels() { - e := ompModel{ID: m.ID, Name: m.Name} + e := ompModel{ID: m.ID, Name: m.Name, Context: m.Context} var efforts []string for _, x := range ompEfforts { // in omp's order if slices.Contains(m.Efforts, x) { diff --git a/internal/agent/route.go b/internal/agent/route.go index 7d7fbecc4..c9699880f 100644 --- a/internal/agent/route.go +++ b/internal/agent/route.go @@ -74,7 +74,7 @@ func magpieModels() []catalog.Model { if e.Group != "" { by = "routing group" } - out = append(out, catalog.Model{ID: e.ID, Name: e.Name + " · " + by, Provider: firstOf(e.Provider.Catalogs()), Efforts: e.Efforts, Images: e.Images}) + out = append(out, catalog.Model{ID: e.ID, Name: e.Name + " · " + by, Provider: firstOf(e.Provider.Catalogs()), Efforts: e.Efforts, Images: e.Images, Context: e.Context}) } return out } diff --git a/internal/agent/sync.go b/internal/agent/sync.go new file mode 100644 index 000000000..e19b305b4 --- /dev/null +++ b/internal/agent/sync.go @@ -0,0 +1,111 @@ +package agent + +import ( + "encoding/json" + "reflect" + "strings" + "sync" + + "github.com/yetone/magpie/internal/edit" + "gopkg.in/yaml.v3" +) + +// Most agents can't ask the gateway which models it has: magpie writes the +// catalog into a file of the agent's own (Pi's models.json, OpenCode's +// provider block, Codex's model catalog …) when a model is picked through +// magpie. That list was the catalog as it was then, so a provider added +// later never reached the agent, and one removed stayed listed. SyncCatalog +// rewrites each such list whenever the catalog may have changed. + +var syncing struct { + sync.Mutex + running, again bool +} + +// SyncCatalog brings every model list magpie wrote into an agent's files up +// to the catalog as it is now. It is what catalog.Changed is set to, so a +// provider saved or removed, or a vendor's list fetched anew, reaches the +// agents; one already running asks for another round rather than waiting. +// Errors are left for the picker: a file magpie can't write now is one the +// next change, or a pick, writes. +func SyncCatalog() { + syncing.Lock() + if syncing.running { + syncing.again = true + syncing.Unlock() + return + } + syncing.running = true + syncing.Unlock() + for { + for _, a := range All() { + if a.Sync != nil { + _ = a.Sync() + } + } + syncing.Lock() + if !syncing.again { + syncing.running = false + syncing.Unlock() + return + } + syncing.again = false + syncing.Unlock() + } +} + +// syncJSON rewrites the value at key of a JSON file, if the file has one +// there and it differs: an agent that watches its files isn't told of a +// change that isn't one. +func syncJSON(path, key string, value func() any) error { + cur, ok := edit.GetJSON(path, key) + if !ok { + return nil + } + v := value() + if sameJSON(cur, v) { + return nil + } + return edit.SetJSON(path, edit.KV{Path: key, Value: v}) +} + +// sameJSON reports whether raw JSON says what v marshals to. +func sameJSON(raw string, v any) bool { + b, err := json.Marshal(v) + if err != nil { + return false + } + var x, y any + if json.Unmarshal([]byte(raw), &x) != nil || json.Unmarshal(b, &y) != nil { + return false + } + return reflect.DeepEqual(x, y) +} + +// syncYAML is syncJSON for a YAML file. +func syncYAML(path, key string, value func() any) error { + raw, err := edit.Read(path) + if err != nil || raw == nil { + return nil + } + var doc any + if yaml.Unmarshal(raw, &doc) != nil { + return nil + } + for _, k := range strings.Split(key, ".") { + m, _ := doc.(map[string]any) + if doc = m[k]; doc == nil { + return nil + } + } + v := value() + b, err := yaml.Marshal(v) + if err != nil { + return err + } + var want any + if yaml.Unmarshal(b, &want) == nil && reflect.DeepEqual(doc, want) { + return nil + } + return edit.SetYAML(path, edit.KV{Path: key, Value: v}) +} diff --git a/internal/agent/sync_test.go b/internal/agent/sync_test.go new file mode 100644 index 000000000..64270e6ab --- /dev/null +++ b/internal/agent/sync_test.go @@ -0,0 +1,153 @@ +package agent + +import ( + "encoding/json" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/codexcat" + "github.com/yetone/magpie/internal/provider" +) + +// syncHome is a sandbox home with a models.dev catalog that knows glm-4.6's +// window and a provider serving it. +func syncHome(t *testing.T) string { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + t.Setenv("CODEX_HOME", "") + t.Setenv("CLAUDE_CONFIG_DIR", filepath.Join(home, ".claude")) + t.Setenv("HERMES_HOME", "") + t.Setenv("DSH_HOME", "") + noKeychain(t) + os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755) + os.WriteFile(catalog.CachePath(), []byte(`{"zai":{"models":{"glm-4.6":{"id":"glm-4.6","name":"GLM-4.6","limit":{"context":204800}}}}}`), 0o644) + catalog.Reset() + t.Cleanup(catalog.Reset) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"glm-4.6"}}); err != nil { + t.Fatal(err) + } + return home +} + +// noKeychain puts a `security` that finds nothing first on PATH: the +// catalog looks for a Claude Code sign-in, on a Mac in the Keychain, which +// a test has no business reading. +func noKeychain(t *testing.T) { + t.Helper() + if runtime.GOOS == "windows" { + return + } + bin := t.TempDir() + if err := os.WriteFile(filepath.Join(bin, "security"), []byte("#!/bin/sh\nexit 44\n"), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) +} + +func writeFile(t *testing.T, path, body string) { + t.Helper() + os.MkdirAll(filepath.Dir(path), 0o755) + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +func readFile(path string) string { + b, _ := os.ReadFile(path) + return string(b) +} + +// Pi is handed each model's window: without one it takes every model for a +// 128K one. +func TestPiModelsCarryContextWindow(t *testing.T) { + syncHome(t) + b, _ := json.Marshal(magpieProviderJSON("pi")) + if !strings.Contains(string(b), `"id":"relay/glm-4.6"`) || !strings.Contains(string(b), `"contextWindow":204800`) { + t.Fatalf("%s", b) + } +} + +// A provider added after a magpie model was picked reaches the lists agents +// keep of magpie's models; a file magpie wrote nothing into stays as it is. +func TestSyncCatalogRewritesAgentLists(t *testing.T) { + home := syncHome(t) + piModels := filepath.Join(home, ".pi", "agent", "models.json") + writeFile(t, piModels, `{"providers":{"mine":{"baseUrl":"http://x"},"magpie":{"name":"magpie","models":[]}}}`) + crushCfg := filepath.Join(home, ".config", "crush", "crush.json") + crushBody := `{"providers":{"mine":{"base_url":"http://x"}}}` + writeFile(t, crushCfg, crushBody) + codexDir := filepath.Join(home, ".codex") + codexCat := filepath.Join(codexDir, "magpie-models.json") + writeFile(t, filepath.Join(codexDir, "config.toml"), "model = \"relay/glm-4.6\"\nmodel_provider = \"magpie\"\nmodel_catalog_json = \""+codexCat+"\"\n") + writeFile(t, codexCat, `{"models":[]}`) + + if err := provider.Save(provider.Provider{ID: "added", Name: "Added", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m2"}}); err != nil { + t.Fatal(err) + } + SyncCatalog() + + pi := strings.ReplaceAll(readFile(piModels), " ", "") + if !strings.Contains(pi, `"relay/glm-4.6"`) || !strings.Contains(pi, `"added/m2"`) || + !strings.Contains(pi, `"contextWindow":204800`) || !strings.Contains(pi, `"mine"`) { + t.Errorf("pi models.json:\n%s", pi) + } + if got := readFile(crushCfg); got != crushBody { + t.Errorf("crush config without magpie changed:\n%s", got) + } + cx := readFile(codexCat) + if !strings.Contains(cx, `"slug": "added/m2"`) || !strings.Contains(cx, `"context_window": 204800`) { + t.Errorf("codex catalog:\n%s", cx) + } + + // nothing changed since: nothing is written + st, _ := os.Stat(piModels) + os.Chtimes(piModels, st.ModTime().Add(-1e12), st.ModTime().Add(-1e12)) + was, _ := os.Stat(piModels) + SyncCatalog() + if now, _ := os.Stat(piModels); !now.ModTime().Equal(was.ModTime()) { + t.Error("pi models.json rewritten though nothing changed") + } +} + +// Signed in, Codex asks the gateway for its list and keeps it until it +// ages; a cache from before magpie's list changed is aged at once, one of +// the list as it is stays as it is. +func TestSyncCatalogAgesCodexCache(t *testing.T) { + home := syncHome(t) + dir := filepath.Join(home, ".codex") + writeFile(t, filepath.Join(dir, "config.toml"), "model = \"relay/glm-4.6\"\nopenai_base_url = \""+codexGatewayURL()+"\"\n") + cache := filepath.Join(dir, "models_cache.json") + writeFile(t, cache, `{"fetched_at":"2026-09-25T10:00:00Z","etag":"W/\"v1\"","client_version":"0.155.1","models":[{"slug":"gpt-5.5"}]}`) + SyncCatalog() + var c struct { + At string `json:"fetched_at"` + ETag string `json:"etag"` + Version string `json:"client_version"` + Models []map[string]any `json:"models"` + } + json.Unmarshal([]byte(readFile(cache)), &c) + if c.At != "1970-01-01T00:00:00Z" || c.ETag != `W/"v1"` || c.Version != "0.155.1" || len(c.Models) != 1 { + t.Errorf("stale cache: %+v", c) + } + + fresh := `{"fetched_at":"2026-09-25T10:00:00Z","etag":` + string(must(json.Marshal(codexcat.WithTag(`W/"v1"`, codexcat.Tag(provider.CodexListed()))))) + `,"models":[]}` + writeFile(t, cache, fresh) + SyncCatalog() + if got := readFile(cache); got != fresh { + t.Errorf("current cache changed:\n%s", got) + } +} + +func must(b []byte, err error) []byte { + if err != nil { + panic(err) + } + return b +} diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index dbd744e1d..33387882c 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -35,6 +35,9 @@ type Model struct { APIs []string `json:",omitempty"` // Images is set on a model that takes images as input. Images bool `json:",omitempty"` + // Context is how many tokens a prompt may hold, when known: models.dev's + // input limit, else its context window. + Context int `json:",omitempty"` } // Price is what a model costs, in USD per million tokens. @@ -72,7 +75,20 @@ type mdModel struct { Input []string `json:"input"` Output []string `json:"output"` } `json:"modalities"` - Cost *Price `json:"cost"` + Cost *Price `json:"cost"` + Limit struct { + Context int `json:"context"` + Input int `json:"input"` + } `json:"limit"` +} + +// window is the tokens a prompt to m may hold: the input limit where +// models.dev gives one (gpt-5's 272K of its 400K), else the whole context. +func (m mdModel) window() int { + if m.Limit.Input > 0 { + return m.Limit.Input + } + return m.Limit.Context } const modelsDevURL = "https://models.dev/api.json" @@ -83,6 +99,9 @@ var ( // images are the models, by bare id, most of the providers serving // them say take images (a few mislabel a text model) images map[string]bool + // windows are the models' context windows, by bare id, as most of the + // providers serving them give it + windows map[string]int syncMu sync.Mutex ) @@ -122,6 +141,7 @@ func load() map[string]mdProvider { if json.Unmarshal(b, &m) == nil && len(m) > 0 { mdev = m votes := map[string]int{} + sizes := map[string]map[int]int{} for _, p := range m { for id, x := range p.Models { if slices.Contains(x.Modalities.Input, "image") { @@ -129,8 +149,18 @@ func load() map[string]mdProvider { } else { votes[bareID(id)]-- } + if w := x.window(); w > 0 { + if sizes[bareID(id)] == nil { + sizes[bareID(id)] = map[int]int{} + } + sizes[bareID(id)][w]++ + } } } + windows = map[string]int{} + for id, by := range sizes { + windows[id] = mostGiven(by) + } images = map[string]bool{} for id, v := range votes { if v > 0 { @@ -147,7 +177,7 @@ func load() map[string]mdProvider { // Reset forgets the loaded catalog so the next call re-reads the cache. func Reset() { once = sync.Once{} - mdev, images = nil, nil + mdev, images, windows = nil, nil, nil } // Sync downloads the models.dev catalog into CachePath. It serializes with @@ -184,6 +214,7 @@ func Sync(ctx context.Context) error { return err } Reset() + Touched() // names, reasoning levels and context windows may be others return nil } @@ -240,7 +271,7 @@ func Provider(id string) []Model { continue } mm := Model{ID: m.ID, Name: m.Name, Provider: id, Released: m.ReleaseDate, Price: m.Cost, Temperature: m.Temperature, - Images: slices.Contains(m.Modalities.Input, "image")} + Images: slices.Contains(m.Modalities.Input, "image"), Context: m.window()} for _, r := range m.Reasoning { if r.Type == "effort" { mm.Efforts = r.Values @@ -272,6 +303,42 @@ func SeesImages(id string) bool { return images[bareID(id)] } +// ContextOf is the context window models.dev gives a model of this id, as +// most of the providers it lists serving it do, or 0 when it doesn't know +// the model. Like SeesImages it reaches a vendor models.dev doesn't list: a +// proxy serving "openai/gpt-5.4", or "gpt-5.4(high)" with the reasoning +// level CLIProxyAPI takes in the id, which a static model list would +// otherwise leave at the agent's default. +func ContextOf(id string) int { + load() + b := bareID(id) + if w, ok := windows[b]; ok { + return w + } + if i := strings.IndexByte(b, '('); i > 0 && strings.HasSuffix(b, ")") { + b = b[:i] + if w, ok := windows[b]; ok { + return w + } + } + if i := strings.IndexByte(b, ':'); i > 0 { // ":free", ":batch" + return windows[b[:i]] + } + return 0 +} + +// mostGiven is the size most providers give; a tie goes to the smaller, +// which a prompt fits either way. +func mostGiven(by map[int]int) int { + best, n := 0, 0 + for w, c := range by { + if c > n || c == n && w < best { + best, n = w, c + } + } + return best +} + // bareID is a model's id without the vendor's prefix, lowercase. func bareID(id string) string { id = strings.ToLower(id) diff --git a/internal/catalog/catalog_test.go b/internal/catalog/catalog_test.go index e953425ab..c80c0179f 100644 --- a/internal/catalog/catalog_test.go +++ b/internal/catalog/catalog_test.go @@ -89,3 +89,39 @@ func TestImages(t *testing.T) { t.Error("SeesImages") } } + +// A model's window is models.dev's input limit where it gives one (what a +// prompt may hold), else its context; looked up by bare id, it is the size +// most providers give, so a relay's model finds it too. +func TestContextOf(t *testing.T) { + writeCatalog(t, `{ + "openai": {"models": { + "gpt-5.5": {"id":"gpt-5.5","limit":{"context":1050000,"input":922000,"output":128000}}, + "gpt-4.1": {"id":"gpt-4.1","limit":{"context":1047576,"output":32768}} + }}, + "zai": {"models": {"glm-4.6": {"id":"glm-4.6","limit":{"context":204800}}}}, + "a": {"models": {"zai/glm-4.6": {"id":"zai/glm-4.6","limit":{"context":204800}}}}, + "b": {"models": {"glm-4.6": {"id":"glm-4.6","limit":{"context":128000}}}} + }`) + for id, want := range map[string]int{ + "gpt-5.5": 922000, + "openai/gpt-5.5": 922000, + "gpt-5.5(high)": 922000, + "gpt-4.1": 1047576, + "GLM-4.6": 204800, + "glm-4.6:free": 204800, + "unknown-model": 0, + } { + if got := ContextOf(id); got != want { + t.Errorf("ContextOf(%q) = %d, want %d", id, got, want) + } + } + for _, m := range Provider("openai") { + if m.ID == "gpt-5.5" && m.Context != 922000 { + t.Errorf("Provider: %+v", m) + } + } + if out := Decorate([]Model{{ID: "gpt-5.5"}}, Provider("openai")); out[0].Context != 922000 { + t.Errorf("Decorate: %+v", out[0]) + } +} diff --git a/internal/catalog/live.go b/internal/catalog/live.go index 34d41b87b..576c0b923 100644 --- a/internal/catalog/live.go +++ b/internal/catalog/live.go @@ -50,13 +50,33 @@ func SaveLive(provider, base string, models []Model) error { if errors.Is(err, os.ErrNotExist) { return nil } + if err == nil { + Touched() + } return err } if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { return err } b, _ := json.MarshalIndent(liveFile{Fetched: time.Now(), Base: base, Models: models}, "", " ") - return os.WriteFile(p, b, 0o644) + if err := os.WriteFile(p, b, 0o644); err != nil { + return err + } + Touched() + return nil +} + +// Changed, when set, is told that the models magpie offers may be others +// now: a provider added, edited or removed, a vendor's list fetched anew. +// The agent package sets it, to bring the model lists agents keep in files +// of their own up to date. +var Changed func() + +// Touched tells Changed, if set. +func Touched() { + if Changed != nil { + Changed() + } } // Fetch asks an endpoint for its models. base is an API base URL of any @@ -193,6 +213,9 @@ func Decorate(live []Model, known []Model) []Model { } m.Efforts, m.Released, m.Provider = k.Efforts, k.Released, k.Provider m.Images = m.Images || k.Images + if m.Context == 0 { + m.Context = k.Context + } if k.Temperature != nil { m.Temperature = k.Temperature } diff --git a/internal/codexcat/codexcat.go b/internal/codexcat/codexcat.go index 7c3faffc9..ceb31cfe2 100644 --- a/internal/codexcat/codexcat.go +++ b/internal/codexcat/codexcat.go @@ -4,7 +4,9 @@ package codexcat import ( + "crypto/sha256" _ "embed" + "encoding/hex" "encoding/json" "os" "path/filepath" @@ -72,6 +74,7 @@ func Entries(ms []catalog.Model, after int) []any { } `json:"truncation_policy"` Tools []string `json:"experimental_supported_tools"` Modalities []string `json:"input_modalities"` + Context *int `json:"context_window,omitempty"` } own := CacheEntries() var entries []any @@ -89,6 +92,9 @@ func Entries(ms []catalog.Model, after int) []any { if m.Images { e.Modalities = append(e.Modalities, "image") } + if c := m.Context; c > 0 { + e.Context = &c + } e.Truncation.Mode, e.Truncation.Limit = "tokens", 10000 for _, ef := range m.Efforts { e.Efforts = append(e.Efforts, level{Effort: ef}) @@ -142,3 +148,35 @@ func ownEntry(raw map[string]any, id, name string, priority int) map[string]any } return e } + +// Codex keeps the model list it was handed in models_cache.json, with the +// list's ETag, and asks again only once the cache has aged (minutes) — or +// when a reply's X-Models-Etag differs from it; the same one only makes the +// cache young again. Passed on as the ChatGPT backend gave it, the ETag +// said nothing of magpie's models, so a provider added since stayed out of +// Codex's /model for as long as Codex kept getting replies. The ETag magpie +// hands on carries a tag of its models too. + +// Tag names a list of magpie's models: another list, another tag. +func Tag(ms []catalog.Model) string { + b, _ := json.Marshal(ms) + sum := sha256.Sum256(b) + return hex.EncodeToString(sum[:6]) +} + +// tagMark is where a tag starts in an ETag magpie made. +const tagMark = "+magpie-" + +// WithTag is an ETag of the backend's (or none) with magpie's tag in it: +// W/"abc" becomes W/"abc+magpie-". +func WithTag(etag, tag string) string { + if strings.HasSuffix(etag, `"`) && len(etag) > 1 { + return strings.TrimSuffix(etag, `"`) + tagMark + tag + `"` + } + return etag + tagMark + tag +} + +// Tagged reports whether an ETag carries this tag. +func Tagged(etag, tag string) bool { + return strings.Contains(etag, tagMark+tag) +} diff --git a/internal/codexcat/tag_test.go b/internal/codexcat/tag_test.go new file mode 100644 index 000000000..aa516e119 --- /dev/null +++ b/internal/codexcat/tag_test.go @@ -0,0 +1,46 @@ +package codexcat + +import ( + "encoding/json" + "testing" + + "github.com/yetone/magpie/internal/catalog" +) + +// A model whose window is known says so, rather than Codex taking it for +// the size it assumes of any; one not known leaves it to Codex. +func TestEntriesCarryContextWindow(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + var got struct { + Models []map[string]any `json:"models"` + } + json.Unmarshal(Catalog([]catalog.Model{{ID: "relay/glm-4.6", Context: 204800}, {ID: "relay/x"}}), &got) + if len(got.Models) != 2 || got.Models[0]["context_window"] != float64(204800) { + t.Fatalf("%+v", got.Models) + } + if _, ok := got.Models[1]["context_window"]; ok { + t.Errorf("unknown window: %+v", got.Models[1]) + } +} + +// The ETag handed to Codex carries a tag of magpie's list: another list, +// another ETag, which Codex refetches on. +func TestETagTag(t *testing.T) { + a := Tag([]catalog.Model{{ID: "p/m1"}}) + b := Tag([]catalog.Model{{ID: "p/m1"}, {ID: "q/m2"}}) + if a == b || a != Tag([]catalog.Model{{ID: "p/m1"}}) { + t.Fatalf("tags %q %q", a, b) + } + for etag, want := range map[string]string{ + `W/"abc"`: `W/"abc+magpie-` + a + `"`, + `"abc"`: `"abc+magpie-` + a + `"`, + "": "+magpie-" + a, + } { + if got := WithTag(etag, a); got != want || !Tagged(got, a) || Tagged(got, b) { + t.Errorf("WithTag(%q) = %q, want %q", etag, got, want) + } + } + if Tagged(`W/"abc"`, a) { + t.Error("the backend's own ETag is tagged") + } +} diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index b0217389c..cffe9cda8 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -12,7 +12,6 @@ import ( "time" "github.com/klauspost/compress/zstd" - "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/codexcat" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/usage" @@ -151,6 +150,7 @@ func (s *Server) codexUpstream(w http.ResponseWriter, r *http.Request, rest stri w.Header()[k] = vs } } + modelsEtag(w.Header()) w.WriteHeader(res.StatusCode) var sniff *usageSniffer if rest == "/responses" { @@ -254,25 +254,21 @@ func (s *Server) codexModels(w http.ResponseWriter, r *http.Request) { own = append(own, e) } } - var ms []catalog.Model - for _, e := range provider.Catalog() { - // a ChatGPT account in magpie offers the models listed already - if e.Provider.Account != nil && e.Provider.Account.Agent == "codex" { - continue - } - // a group answers for its first member but is not that provider's - by := e.Provider.Name - if e.Group != "" { - by = "routing group" - } - ms = append(ms, catalog.Model{ID: e.ID, Name: e.Name + " · " + by, Efforts: e.Efforts, Images: e.Images}) - } - if etag != "" { - w.Header().Set("ETag", etag) - } + ms := provider.CodexListed() + // the list is the backend's and magpie's, and so is its ETag + w.Header().Set("ETag", codexcat.WithTag(etag, codexcat.Tag(ms))) writeJSON(w, 200, map[string]any{"models": append(own, codexcat.Entries(ms, len(own)+100)...)}) } +// modelsEtag is the X-Models-Etag of a backend reply as Codex should read +// it: with magpie's models in it, as the list's own ETag has them, so a +// change to either has Codex ask for the list again. +func modelsEtag(h http.Header) { + if v := h.Get("X-Models-Etag"); v != "" { + h.Set("X-Models-Etag", codexcat.WithTag(v, codexcat.Tag(provider.CodexListed()))) + } +} + // codexInput readies Codex's input for whoever serves it: a summary magpie // made becomes the message it stands for, and the backend's own controls // go. compact reports a request to compact the conversation, whose trigger diff --git a/internal/gateway/codex_backend_test.go b/internal/gateway/codex_backend_test.go index 5b1174064..1179d7d96 100644 --- a/internal/gateway/codex_backend_test.go +++ b/internal/gateway/codex_backend_test.go @@ -12,6 +12,7 @@ import ( "time" "github.com/klauspost/compress/zstd" + "github.com/yetone/magpie/internal/codexcat" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/usage" ) @@ -175,9 +176,11 @@ func TestCodexModelList(t *testing.T) { fake = m } } - // Other sign-ins found on the machine (Cursor's, say) may follow. + // Other sign-ins found on the machine (Cursor's, say) may follow. The + // ETag is the backend's with magpie's list in it. + tag := codexcat.Tag(provider.CodexListed()) if rec.Code != 200 || len(slugs) < 2 || slugs[0] != "gpt-5.5" || fake == nil || fake["base_instructions"] == "" || - rec.Header().Get("ETag") != `"v1"` || auth != "Bearer chatgpt-token" { + rec.Header().Get("ETag") != `"v1+magpie-`+tag+`"` || auth != "Bearer chatgpt-token" { t.Errorf("%d %v %q %q", rec.Code, slugs, rec.Header().Get("ETag"), auth) } for _, s := range slugs { @@ -187,6 +190,27 @@ func TestCodexModelList(t *testing.T) { } } +// A reply's X-Models-Etag carries magpie's list too: Codex refetches its +// model list on a new one, and only on the backend's it never would when a +// provider was added. +func TestCodexModelsEtagTagged(t *testing.T) { + setup(t, provider.Chat, &fake{t: t}) + chatgpt(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Models-Etag", `W/"v1"`) + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r1"}}`, + `data: {"type":"response.completed","response":{"id":"r1"}}`)) + }) + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":[]}`)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + New().Handler().ServeHTTP(rec, req) + tag := codexcat.Tag(provider.CodexListed()) + if got := rec.Header().Get("X-Models-Etag"); got != `W/"v1+magpie-`+tag+`"` || !codexcat.Tagged(got, tag) { + t.Errorf("%d X-Models-Etag %q", rec.Code, got) + } +} + // Responses over a WebSocket are turned away so Codex uses HTTP at once. func TestCodexWebSocketUpgradeRequired(t *testing.T) { chatgpt(t, func(w http.ResponseWriter, r *http.Request) { t.Error("sent to ChatGPT") }) diff --git a/internal/gui/app.go b/internal/gui/app.go index 00cada6c1..8a43f9a91 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -16,6 +16,7 @@ import ( "github.com/wailsapp/wails/v3/pkg/application" "github.com/wailsapp/wails/v3/pkg/events" + "github.com/yetone/magpie/internal/agent" "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/provider" @@ -290,6 +291,9 @@ func startBackend() (gw *gateway.Server) { } cancel() } + // lists an older magpie wrote into agents' files, without what + // it has learnt since (context windows, providers added) + agent.SyncCatalog() }() return gw } diff --git a/internal/provider/codex_models.go b/internal/provider/codex_models.go index 092943632..ef7268250 100644 --- a/internal/provider/codex_models.go +++ b/internal/provider/codex_models.go @@ -123,6 +123,7 @@ func parseCodexModels(b []byte) []catalog.Model { Levels []struct { Effort string `json:"effort"` } `json:"supported_reasoning_levels"` + Context int `json:"context_window"` } `json:"models"` } if json.Unmarshal(b, &list) != nil { @@ -134,7 +135,7 @@ func parseCodexModels(b []byte) []catalog.Model { if m.Slug == "" || m.Visibility == "hide" { continue } - mm := catalog.Model{ID: m.Slug, Name: m.DisplayName, Provider: "openai"} + mm := catalog.Model{ID: m.Slug, Name: m.DisplayName, Provider: "openai", Context: m.Context} for _, l := range m.Levels { mm.Efforts = append(mm.Efforts, l.Effort) } @@ -177,3 +178,22 @@ func codexFetchSaved(ctx context.Context) { } } } + +// CodexListed is the catalog as a Codex signed in to ChatGPT is handed it, +// after the backend's own models: all but a ChatGPT account's in magpie, +// which the backend lists already. A group answers for its first member +// but is not that provider's. +func CodexListed() []catalog.Model { + var ms []catalog.Model + for _, e := range Catalog() { + if e.Provider.Account != nil && e.Provider.Account.Agent == "codex" { + continue + } + by := e.Provider.Name + if e.Group != "" { + by = "routing group" + } + ms = append(ms, catalog.Model{ID: e.ID, Name: e.Name + " · " + by, Efforts: e.Efforts, Images: e.Images, Context: e.Context}) + } + return ms +} diff --git a/internal/provider/group.go b/internal/provider/group.go index c73e3bb22..a550e0c8b 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -193,13 +193,16 @@ func groupEntries(entries []Entry) []Entry { e.Icons = append(e.Icons, m.Provider.Icon) // each provider once, "" for one without } var efforts []string - images := false + images, ctx := false, 0 for _, x := range entries { if x.Provider.ID == m.Provider.ID && x.Model == m.Model { - efforts, images = x.Efforts, x.Images + efforts, images, ctx = x.Efforts, x.Images, x.Context } } e.Images = e.Images && images + if ctx > 0 && (e.Context == 0 || ctx < e.Context) { + e.Context = ctx + } if i == 0 { e.Efforts = efforts continue diff --git a/internal/provider/models.go b/internal/provider/models.go index 95840b73e..5b3d70a9e 100644 --- a/internal/provider/models.go +++ b/internal/provider/models.go @@ -240,6 +240,9 @@ type Entry struct { Group string `json:"group,omitempty"` // set on a routing group (group.go) Icons []string `json:"-"` // a group's: its providers' icons, one per provider Images bool `json:"images,omitempty"` // takes images as input (a group's: every member does) + // Context is the tokens a prompt may hold, when known (a group's: the + // least of its members') + Context int `json:"context,omitempty"` } // Catalog lists every exposed model of every ready provider, then the @@ -257,8 +260,14 @@ func providerEntries() []Entry { continue } for _, m := range p.Exposed() { + // a vendor models.dev doesn't list (a custom provider, a proxy) + // serves models it knows from others + ctx := m.Context + if ctx == 0 { + ctx = catalog.ContextOf(m.ID) + } out = append(out, Entry{ID: p.ID + "/" + m.ID, Model: m.ID, Name: m.Name, Efforts: m.Efforts, Provider: p, - Images: m.Images || catalog.SeesImages(m.ID)}) + Images: m.Images || catalog.SeesImages(m.ID), Context: ctx}) } } return out diff --git a/internal/provider/provider.go b/internal/provider/provider.go index ed3ed73b8..674eb8ed6 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -16,6 +16,8 @@ import ( "regexp" "slices" "strings" + + "github.com/yetone/magpie/internal/catalog" ) // Protocol is a wire API magpie can speak to an upstream. @@ -147,7 +149,12 @@ func store(f file) error { return err } pruneIcons(f) - return os.Chmod(p, 0o600) + if err := os.Chmod(p, 0o600); err != nil { + return err + } + // what agents were handed of the catalog may be out of date now + catalog.Touched() + return nil } // All lists the configured providers in the order they were added, then diff --git a/main.go b/main.go index 43a164d2e..986bedb3a 100644 --- a/main.go +++ b/main.go @@ -89,6 +89,9 @@ func run(args []string) error { } settings.Migrate() agent.RenameLegacy() + // a provider added, edited or removed, or a list fetched anew, reaches + // the model lists agents keep in files of their own + catalog.Changed = agent.SyncCatalog if len(args) == 0 { if hasGUI { return runGUI(true, "")