From bb478f0e5066de8180e14ec1b8ec642c9fe77117 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 1 Nov 2026 06:09:56 +0800 Subject: [PATCH] agent: a look that only ranges over magpie's models reads the list kept magpieModels gives each caller its own copy of the list it keeps per agent. Most callers only range over it, or count it, and a range copies each model anyway, so the copy guarded nothing for them (the models' own lists were shared before too: the copy was shallow). sharedModels is the list kept, read only; every `range magpieModels(` and `len(magpieModels(` in internal/agent (39 files) takes it. Callers that keep the list, append to it or hand it on still get their copy. Real accounts (sandbox copy of the owner's HOME, network blocked), 40 polls of /api/state, /api/providers and drift, pprof alloc_space between two heap snapshots, 616405061 (mrows) vs this (mshare): stampedLists.get's slices.Clone 36.7 MB -> gone (under pprof's cut); most of it was piOffered (22.5 MB) and claudeViaMagpie (13.7 MB) total 637 MB -> 584 MB (runs vary +-25 MB) /api/state and drift bodies byte-identical, /api/providers equal but for `fetched` and `lapsed` (a refused refresh in the blocked sandbox) TestModelReadersShareTheList: sharedModels gives the kept array, not a copy, and no non-test file in internal/agent ranges over or counts magpieModels(. Broken by hand on mote: sharedModels through get fails "a shared look copies the kept list"; one `range magpieModels("kimi")` put back fails naming kimi.go. Run on mote at this tree (before rebase): gofmt; go vet for darwin, windows and linux; the new test with TestMagpieModelsKeptWhileCatalogStays, TestKeptListSharedWithoutACopy and TestViaMagpieKept 3/3 ok; go test ./internal/agent ok (201s); go test ./internal/gui: only the known reds TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and TestMainWindowCorners (#3949). Not run: the full ./... suite. --- internal/agent/agy.go | 2 +- internal/agent/alma.go | 2 +- internal/agent/ante.go | 2 +- internal/agent/astrbot.go | 2 +- internal/agent/atomcode.go | 6 ++-- internal/agent/claude.go | 16 +++++----- internal/agent/cline.go | 2 +- internal/agent/commandcode.go | 4 +-- internal/agent/copilotjetbrains.go | 2 +- internal/agent/droid.go | 2 +- internal/agent/dsh.go | 8 ++--- internal/agent/goose.go | 2 +- internal/agent/grok.go | 2 +- internal/agent/grokapp.go | 2 +- internal/agent/hanako.go | 2 +- internal/agent/hermes.go | 2 +- internal/agent/jcode.go | 2 +- internal/agent/kimi.go | 2 +- internal/agent/minimax.go | 2 +- internal/agent/morph.go | 2 +- internal/agent/mothx.go | 4 +-- internal/agent/newmax.go | 2 +- internal/agent/omp.go | 2 +- internal/agent/openclaw.go | 2 +- internal/agent/openpencil.go | 2 +- internal/agent/pencil.go | 2 +- internal/agent/pi.go | 2 +- internal/agent/plugged.go | 2 +- internal/agent/qoder.go | 2 +- internal/agent/qwen.go | 2 +- internal/agent/raycast.go | 2 +- internal/agent/route.go | 9 ++++++ internal/agent/shared_models_test.go | 46 ++++++++++++++++++++++++++++ internal/agent/snow.go | 4 +-- internal/agent/stepcode.go | 2 +- internal/agent/t3code.go | 2 +- internal/agent/vscode.go | 2 +- internal/agent/workbuddy.go | 2 +- internal/agent/zcode.go | 4 +-- internal/agent/zed.go | 2 +- internal/agent/zoocode.go | 2 +- 41 files changed, 110 insertions(+), 55 deletions(-) create mode 100644 internal/agent/shared_models_test.go diff --git a/internal/agent/agy.go b/internal/agent/agy.go index 716d67db1..8e1e11f1b 100644 --- a/internal/agent/agy.go +++ b/internal/agent/agy.go @@ -223,7 +223,7 @@ func agyIn(at place) *Agent { } } if with { - for _, m := range magpieModels("agy") { + for _, m := range sharedModels("agy") { ms[magpieID+"/"+m.ID] = map[string]string{"apiProvider": "API_PROVIDER_GOOGLE_GEMINI", "modelName": m.ID} } } diff --git a/internal/agent/alma.go b/internal/agent/alma.go index 2cd2fea8b..f7155bd21 100644 --- a/internal/agent/alma.go +++ b/internal/agent/alma.go @@ -238,7 +238,7 @@ func almaMagpie(ps []almaProvider) *almaProvider { // and each one's name and what magpie knows it can do (almaCaps). func almaModels() (ids []string, known []map[string]any) { ids, known = []string{}, []map[string]any{} - for _, m := range magpieModels("alma") { + for _, m := range sharedModels("alma") { ids = append(ids, m.ID) k := map[string]any{"id": m.ID, "name": m.Name} caps := almaCaps(m) diff --git a/internal/agent/ante.go b/internal/agent/ante.go index f2b8c313a..07658d56d 100644 --- a/internal/agent/ante.go +++ b/internal/agent/ante.go @@ -318,7 +318,7 @@ func anteAt(at place) *Agent { // (provider.Described). No other agent magpie wires declares this either. func anteProviderJSON(gw string) map[string]any { ms := []map[string]any{} - for _, m := range magpieModels("ante") { + for _, m := range sharedModels("ante") { ms = append(ms, anteModelJSON(m)) } p := map[string]any{ diff --git a/internal/agent/astrbot.go b/internal/agent/astrbot.go index 4e2464d37..2c13261b6 100644 --- a/internal/agent/astrbot.go +++ b/internal/agent/astrbot.go @@ -345,7 +345,7 @@ func astrbotWired(raw []byte, on bool, gw, key string) ([]byte, error) { var wantModels []map[string]any if on { wantSource = astrbotSourceJSON(gw, key) - for _, m := range magpieModels("astrbot") { + for _, m := range sharedModels("astrbot") { wantModels = append(wantModels, astrbotModelJSON(m)) } } diff --git a/internal/agent/atomcode.go b/internal/agent/atomcode.go index 06b2fa2e4..56740040d 100644 --- a/internal/agent/atomcode.go +++ b/internal/agent/atomcode.go @@ -262,7 +262,7 @@ func atomcodeIn(at place) *Agent { } ref := strings.TrimPrefix(k, magpieID+"/") var offered []string - for _, m := range magpieModels("atomcode") { + for _, m := range sharedModels("atomcode") { if m.ID == ref { offered = atomcodeSupportedEfforts(m.Efforts) break @@ -275,7 +275,7 @@ func atomcodeIn(at place) *Agent { }, Options: func(c map[string]string) []Option { if ref, ok := strings.CutPrefix(c["model"], magpieID+"/"); ok { - for _, m := range magpieModels("atomcode") { + for _, m := range sharedModels("atomcode") { if m.ID == ref { return static(atomcodeSupportedEfforts(m.Efforts)...) } @@ -307,7 +307,7 @@ func atomcodeTablesAt(path, v1, key string) []edit.Table { {Path: "base_url", Value: v1}, {Path: "api_key", Value: key}, }}} - for _, m := range magpieModels("atomcode") { + for _, m := range sharedModels("atomcode") { ctx := m.Context if ctx <= 0 { ctx = atomcodeContext diff --git a/internal/agent/claude.go b/internal/agent/claude.go index 0fec634e9..548f9efbc 100644 --- a/internal/agent/claude.go +++ b/internal/agent/claude.go @@ -510,7 +510,7 @@ func claudeLight(main string) string { return id } best := "" - for _, m := range magpieModels("claude") { + for _, m := range sharedModels("claude") { if !strings.HasPrefix(m.ID, prefix) { continue } @@ -581,7 +581,7 @@ func tierWith(model, effort string) string { // magpie knows the model has, else those Claude Code sends it. func tierEfforts(model string) []string { id := strings.TrimSuffix(model, "[1m]") - for _, m := range magpieModels("claude") { + for _, m := range sharedModels("claude") { if m.ID == id && len(m.Efforts) > 0 { return slices.DeleteFunc(slices.Clone(m.Efforts), func(l string) bool { return !contains(provider.MemberEfforts, l) }) } @@ -1186,7 +1186,7 @@ func claudeIn(at place) *Agent { } if main != "" { window := map[string]int{} - for _, m := range magpieModels("claude") { + for _, m := range sharedModels("claude") { window[m.ID] = m.Context } // a tier fixed at an effort is handed Claude Code with it, and @@ -1247,7 +1247,7 @@ func claudeIn(at place) *Agent { return false } window := map[string]int{} - for _, m := range magpieModels("claude") { + for _, m := range sharedModels("claude") { window[m.ID] = m.Context } for _, v := range pickerRefs() { @@ -2487,7 +2487,7 @@ func claudeAliasOption(v string, ms []catalog.Model, tier func(string) string) ( // picker that lists Claude Code's own models above them. func claudeViaMagpie(fold bool) []Option { big := map[string]bool{} - for _, m := range magpieModels("claude") { + for _, m := range sharedModels("claude") { big[m.ID] = m.Context >= 1_000_000 } opts := viaMagpie("claude", "") @@ -2513,7 +2513,7 @@ func claude1M() func(ref string) string { return claude1MFor("claude") } func claude1MFor(agent string) func(ref string) string { const mark = "[1m]" window := map[string]int{} - for _, m := range magpieModels(agent) { + for _, m := range sharedModels(agent) { window[m.ID] = m.Context } return func(ref string) string { @@ -2581,7 +2581,7 @@ func claudeLongMain(main string) bool { func claudeWindow(main string, tiers map[string]string) int { const mark = "[1m]" window := map[string]int{} - for _, m := range magpieModels("claude") { + for _, m := range sharedModels("claude") { window[m.ID] = m.Context } if !strings.HasSuffix(main, mark) { @@ -2635,7 +2635,7 @@ func claudeOutput(models ...string) int { return 0 } output := map[string]int{} - for _, m := range magpieModels("claude") { + for _, m := range sharedModels("claude") { output[m.ID] = m.Output } n := 0 diff --git a/internal/agent/cline.go b/internal/agent/cline.go index 9ff56bfa5..f69ae8599 100644 --- a/internal/agent/cline.go +++ b/internal/agent/cline.go @@ -375,7 +375,7 @@ func clineModels(model string) map[string]any { return clineModelsAt(model, gate // clineModelsAt is clineModels for a Cline reaching the gateway's /v1 at v1. func clineModelsAt(model, v1 string) map[string]any { ms := map[string]any{} - for _, m := range magpieModels("cline") { + for _, m := range sharedModels("cline") { caps := []string{"streaming", "tools"} if m.Images { caps = append(caps, "images") diff --git a/internal/agent/commandcode.go b/internal/agent/commandcode.go index 6b4721775..7caa3920d 100644 --- a/internal/agent/commandcode.go +++ b/internal/agent/commandcode.go @@ -124,7 +124,7 @@ func commandCodeIn(at place) *Agent { }, Options: func(cur map[string]string) []Option { if ref, ok := strings.CutPrefix(cur["model"], magpieID+"/"); ok { - for _, m := range magpieModels("commandcode") { + for _, m := range sharedModels("commandcode") { if m.ID != ref { continue } @@ -150,7 +150,7 @@ func commandCodeIn(at place) *Agent { // any, and Command Code refuses one written out. func ccProviderJSONAt(v1 string) any { ms := map[string]any{} - for _, m := range magpieModels("commandcode") { + for _, m := range sharedModels("commandcode") { e := map[string]any{"name": m.Name} var efforts []string for _, x := range m.Efforts { diff --git a/internal/agent/copilotjetbrains.go b/internal/agent/copilotjetbrains.go index e3b7db436..67c64fe99 100644 --- a/internal/agent/copilotjetbrains.go +++ b/internal/agent/copilotjetbrains.go @@ -222,7 +222,7 @@ func copilotJBWrite(path string) error { // (JetBrains) is shown it, keyed by model id. func copilotJBModelsJSON(hidden map[string]bool) map[string]any { out := map[string]any{} - for _, m := range magpieModels(copilotJBID) { + for _, m := range sharedModels(copilotJBID) { context := m.Context if context == 0 { context = 128000 // the server's own default for a custom endpoint diff --git a/internal/agent/droid.go b/internal/agent/droid.go index 55f55909d..e7ec24bfb 100644 --- a/internal/agent/droid.go +++ b/internal/agent/droid.go @@ -76,7 +76,7 @@ func droidEntries() []droidEntry { return droidEntriesAt(gateway.URL()) } // droidEntriesAt are droidEntries for a droid reaching the gateway at gw. func droidEntriesAt(gw string) []droidEntry { var out []droidEntry - for _, m := range magpieModels("droid") { + for _, m := range sharedModels("droid") { e := droidEntry{Model: m.ID, ID: droidID + m.ID, APIKey: keyAt(gw), Provider: "generic-chat-completion-api", MaxContextLimit: m.Context, MaxOutputTokens: maxTokens(m), NoImageSupport: !m.Images} switch want := droidWants(m.ID); { diff --git a/internal/agent/dsh.go b/internal/agent/dsh.go index 837004aa1..53063e6d7 100644 --- a/internal/agent/dsh.go +++ b/internal/agent/dsh.go @@ -758,7 +758,7 @@ func dshWired(items []dshItem) bool { return len(dshRoutesIn(items)) > 0 } // written again would list it, where one naming a model magpie no longer // gives dsh would not. func dshServes(id string) bool { - for _, m := range magpieModels("dsh") { + for _, m := range sharedModels("dsh") { if m.ID == id { return true } @@ -891,7 +891,7 @@ func dshCheck(dir, gw string) string { // for the round to write it from. A profile taken off magpie for real, // its start with it, is said as before, and so is one still on the old // wiring, which dshSync moves rather than this round writing beside. - canWriteBack := len(magpieModels("dsh")) > 0 + canWriteBack := len(sharedModels("dsh")) > 0 for _, f := range files[1:] { _, items, err := dshRead(f) if err != nil || dshWired(dshOver(dir, items)) { @@ -997,7 +997,7 @@ func dshCheck(dir, gw string) string { // nothing can (no catalog to write it from — the key check still runs, since // a route written without its key would fail the turn all the same). func dshCheckStripped(dir, gw string) string { - if len(magpieModels("dsh")) == 0 { + if len(sharedModels("dsh")) == 0 { return "DeepSeek Harness starts on one of magpie's models, but magpie's route is out of " + dshHomePatch(dir) + " and the profiles' and there is no model list to write it back from; pick a model of magpie's again once it has one" } env := filepath.Join(dir, ".env") @@ -1813,7 +1813,7 @@ func dshModelLevels(efforts []string) ([]string, *dshPiLevels) { // dshLevels are the thinking levels dsh offers for a catalog model. func dshLevels(ref string) []string { - for _, m := range magpieModels("dsh") { + for _, m := range sharedModels("dsh") { if m.ID == ref { levels, _ := dshModelLevels(m.Efforts) return levels diff --git a/internal/agent/goose.go b/internal/agent/goose.go index ded08ca31..58c7ecfe5 100644 --- a/internal/agent/goose.go +++ b/internal/agent/goose.go @@ -118,7 +118,7 @@ func gooseProviderPath(cfg string) string { // place, its models the catalog as Goose is shown it. func gooseProviderJSON(at place) map[string]any { models := []map[string]any{} - for _, m := range magpieModels("goose") { + for _, m := range sharedModels("goose") { e := map[string]any{"name": m.ID, "reasoning": gooseThinks.MatchString(m.ID)} if m.Context > 0 { e["context_limit"] = m.Context diff --git a/internal/agent/grok.go b/internal/agent/grok.go index 2dea8a227..de27120b2 100644 --- a/internal/agent/grok.go +++ b/internal/agent/grok.go @@ -50,7 +50,7 @@ var grokModelTable = `model."` + magpieID + "/" func grokModelTables(v1 string, had, wrote map[string]int) ([]edit.Table, map[string]int) { var out []edit.Table st, gave := settings.Load(), map[string]int{} - for _, m := range magpieModels("grok") { + for _, m := range sharedModels("grok") { kvs := []edit.KV{ {Path: "model", Value: m.ID}, {Path: "name", Value: m.Name}, diff --git a/internal/agent/grokapp.go b/internal/agent/grokapp.go index b974b07e7..20b201648 100644 --- a/internal/agent/grokapp.go +++ b/internal/agent/grokapp.go @@ -129,7 +129,7 @@ func grokAppWant(was string) []grokAppModel { } } var out []grokAppModel - for _, m := range magpieModels("grok-app") { + for _, m := range sharedModels("grok-app") { e := grokAppModel{ID: m.ID, Name: m.Name, ContextWindow: m.Context} if e.Name == "" { e.Name = m.ID diff --git a/internal/agent/hanako.go b/internal/agent/hanako.go index 4d70ff106..b6a7485ce 100644 --- a/internal/agent/hanako.go +++ b/internal/agent/hanako.go @@ -222,7 +222,7 @@ type hanakoProviderEntry struct { // over an older one keeps what the new one leaves out. func hanakoProvider() hanakoProviderEntry { ms := []hanakoModel{} - for _, m := range magpieModels("hanako") { + for _, m := range sharedModels("hanako") { ms = append(ms, hanakoModel{ID: m.ID, Name: m.Name, Context: m.Context, MaxOutput: maxTokens(m), Image: m.Images, Reasoning: len(m.Efforts) > 0, XHigh: slices.Contains(m.Efforts, "xhigh")}) } diff --git a/internal/agent/hermes.go b/internal/agent/hermes.go index 69c939461..a560b2d57 100644 --- a/internal/agent/hermes.go +++ b/internal/agent/hermes.go @@ -615,7 +615,7 @@ type hermesProviderEntry struct { // release on, so the header names it for the gateway's usage view. func hermesProviderAt(gw string) hermesProviderEntry { ms := []string{} - for _, m := range magpieModels("hermes") { + for _, m := range sharedModels("hermes") { ms = append(ms, m.ID) } return hermesProviderEntry{ diff --git a/internal/agent/jcode.go b/internal/agent/jcode.go index 899496228..90d05d8af 100644 --- a/internal/agent/jcode.go +++ b/internal/agent/jcode.go @@ -104,7 +104,7 @@ func jcodeWant(was []jcodeModel) []jcodeModel { kept[m.ID] = m.ReasoningEffort } var out []jcodeModel - for _, m := range magpieModels("jcode") { + for _, m := range sharedModels("jcode") { ctx := m.Context if ctx <= 0 { ctx = jcodeContext diff --git a/internal/agent/kimi.go b/internal/agent/kimi.go index 78d7b2aec..d441d9392 100644 --- a/internal/agent/kimi.go +++ b/internal/agent/kimi.go @@ -66,7 +66,7 @@ func kimiModelTables(path string, legacy bool, wrote map[string]map[string]strin var out []edit.Table now := map[string]map[string]string{} names, _ := edit.TOMLTables(path) - for _, m := range magpieModels("kimi") { + for _, m := range sharedModels("kimi") { name := "models." + strconv.Quote(magpieID+"/"+m.ID) ctx := m.Context if ctx <= 0 { diff --git a/internal/agent/minimax.go b/internal/agent/minimax.go index 76c5be032..ab2a7e68e 100644 --- a/internal/agent/minimax.go +++ b/internal/agent/minimax.go @@ -227,7 +227,7 @@ func writeMiniMaxEntryAt(path, gw string) error { models := &yaml.Node{Kind: yaml.MappingNode} // keys is each model's key, its flat one where it has one keys := map[string]string{} - for _, m := range magpieModels("minimax-code") { + for _, m := range sharedModels("minimax-code") { key := mcodeKey(flat, m.ID) keys[m.ID] = key mn := yamlGet(old, key) diff --git a/internal/agent/morph.go b/internal/agent/morph.go index 4c75b6f57..82a93137b 100644 --- a/internal/agent/morph.go +++ b/internal/agent/morph.go @@ -81,7 +81,7 @@ func morphIn(at place) *Agent { } // window is the context magpie knows ref to take, 0 when unknown window := func(ref string) int { - for _, m := range magpieModels("morph") { + for _, m := range sharedModels("morph") { if m.ID == ref { return m.Context } diff --git a/internal/agent/mothx.go b/internal/agent/mothx.go index c53633271..cf9da4fb2 100644 --- a/internal/agent/mothx.go +++ b/internal/agent/mothx.go @@ -188,7 +188,7 @@ func mothxBlockKept(path string, value func() any) func() any { // thinking:{type:enabled}, whatever served it. func mothxProvider(at place, key string) any { ms := []map[string]any{} - for _, m := range magpieModels("mothx") { + for _, m := range sharedModels("mothx") { ms = append(ms, mothxModelJSON(m)) } return map[string]any{"baseUrl": at.v1(), "api": "openai-chat", "apiKey": key, @@ -268,7 +268,7 @@ func mothxOffered(model string) []string { if !ok { return nil } - for _, m := range magpieModels("mothx") { + for _, m := range sharedModels("mothx") { if m.ID != ref || len(m.Efforts) == 0 { continue } diff --git a/internal/agent/newmax.go b/internal/agent/newmax.go index 1ff8f2f12..9bce00a60 100644 --- a/internal/agent/newmax.go +++ b/internal/agent/newmax.go @@ -173,7 +173,7 @@ func newMaxEntryFor(gw string) newMaxEntry { e := newMaxEntry{ID: newMaxID, Name: "magpie", BaseURL: gw, APIKey: key, APIKeys: []string{key}, APIKeyField: "ANTHROPIC_AUTH_TOKEN", APIFormat: "anthropic", Models: []string{}, Enabled: true, CanDelete: true} seen := map[string]bool{} - for _, m := range magpieModels("newmax") { + for _, m := range sharedModels("newmax") { if m.ID == "" || seen[m.ID] { continue } diff --git a/internal/agent/omp.go b/internal/agent/omp.go index 0d7195e2a..8969ad856 100644 --- a/internal/agent/omp.go +++ b/internal/agent/omp.go @@ -648,7 +648,7 @@ func ompProvider() ompProviderEntry { return ompProviderAt(gateway.URL(), ompVer func ompProviderAt(gw, version string) ompProviderEntry { takesMax := ompTakesMax(version) ms := []ompModel{} - for _, m := range magpieModels("omp") { + for _, m := range sharedModels("omp") { e := ompModel{ID: m.ID, Name: m.Name, Context: m.Context, MaxTokens: maxTokens(m)} if p := m.Price; p != nil { e.Cost = &ompCost{Input: p.Input, Output: p.Output, CacheRead: p.CacheRead, CacheWrite: p.CacheWrite} diff --git a/internal/agent/openclaw.go b/internal/agent/openclaw.go index c0c418031..e5b1075a9 100644 --- a/internal/agent/openclaw.go +++ b/internal/agent/openclaw.go @@ -159,7 +159,7 @@ func openClawWant(raw gjson.Result) []any { } } out := []any{} - for _, m := range magpieModels("openclaw") { + for _, m := range sharedModels("openclaw") { ctx := m.Context if ctx <= 0 { ctx = openClawContext diff --git a/internal/agent/openpencil.go b/internal/agent/openpencil.go index 752758e20..cdcb2e653 100644 --- a/internal/agent/openpencil.go +++ b/internal/agent/openpencil.go @@ -196,7 +196,7 @@ type openPencilAgent struct { func openPencilEntry(gw string) openPencilAgent { var ms []string seen := map[string]bool{} - for _, m := range magpieModels("openpencil") { + for _, m := range sharedModels("openpencil") { if m.ID == "" || seen[m.ID] || len([]rune(m.ID)) > 256 { continue } diff --git a/internal/agent/pencil.go b/internal/agent/pencil.go index 229bad4f9..fcb1183b4 100644 --- a/internal/agent/pencil.go +++ b/internal/agent/pencil.go @@ -99,7 +99,7 @@ func pencilApp(home string) bool { // spend being counted by magpie. func pencilProviderJSON(gw string) map[string]any { ms := []map[string]any{} - for _, m := range magpieModels("pencil") { + for _, m := range sharedModels("pencil") { e := piModelJSON(m, gw, false) if _, ok := e["input"]; !ok { e["input"] = []string{"text"} diff --git a/internal/agent/pi.go b/internal/agent/pi.go index adba77712..03a87ce56 100644 --- a/internal/agent/pi.go +++ b/internal/agent/pi.go @@ -117,7 +117,7 @@ func piOffered(agentID, model string) []string { if !ok { return nil } - for _, m := range magpieModels(agentID) { + for _, m := range sharedModels(agentID) { if m.ID == ref { return piSupported(piModelJSON(piAsked(agentID, m), "", true)) } diff --git a/internal/agent/plugged.go b/internal/agent/plugged.go index 1603210b6..b6b008c28 100644 --- a/internal/agent/plugged.go +++ b/internal/agent/plugged.go @@ -276,7 +276,7 @@ func plugged(home string, p *agentplug.Agent) *Agent { wire := func(ref string) error { var model map[string]any var models []map[string]any - for _, m := range magpieModels(id) { + for _, m := range sharedModels(id) { j := map[string]any{"id": m.ID, "name": m.Name, "context": m.Context, "output": m.Output, "images": m.Images, "efforts": m.Efforts} if j["efforts"] == nil { j["efforts"] = []string{} diff --git a/internal/agent/qoder.go b/internal/agent/qoder.go index 5a543fdea..a72e009c7 100644 --- a/internal/agent/qoder.go +++ b/internal/agent/qoder.go @@ -297,7 +297,7 @@ func qoderProvider(agent, model string) map[string]any { // at v1. func qoderProviderAt(agent, model, v1 string) map[string]any { var ms []map[string]any - for _, m := range magpieModels(agent) { + for _, m := range sharedModels(agent) { caps := map[string]any{"tools": true, "vision": m.Images} var levels []string for _, e := range m.Efforts { diff --git a/internal/agent/qwen.go b/internal/agent/qwen.go index ccddcb830..f132597d4 100644 --- a/internal/agent/qwen.go +++ b/internal/agent/qwen.go @@ -67,7 +67,7 @@ type qwenGen struct { // v1. func qwenEntriesAt(v1 string) []qwenEntry { var out []qwenEntry - for _, m := range magpieModels("qwen") { + for _, m := range sharedModels("qwen") { // name is what /model shows, the id beside it when they differ: // the model's name as every agent's list calls it, by the Provider // in model names setting (magpie/ before, which none of the diff --git a/internal/agent/raycast.go b/internal/agent/raycast.go index 345cee92b..f6a5304e9 100644 --- a/internal/agent/raycast.go +++ b/internal/agent/raycast.go @@ -127,7 +127,7 @@ type raycastProvider struct { // effort on a model with effort levels. func raycastProviderYAML(gw string) raycastProvider { ms := []raycastModel{} - for _, m := range magpieModels("raycast") { + for _, m := range sharedModels("raycast") { ms = append(ms, raycastModel{ID: m.ID, Name: cmp.Or(m.Name, m.ID), Context: m.Context, Abilities: raycastAbilities{ Temperature: raycastSupported{m.Temperature == nil || *m.Temperature}, Vision: raycastSupported{m.Images}, diff --git a/internal/agent/route.go b/internal/agent/route.go index 1c1e0193d..339e6cb73 100644 --- a/internal/agent/route.go +++ b/internal/agent/route.go @@ -210,6 +210,15 @@ func magpieModels(agent string) []catalog.Model { return builtModels.get(agent, func() []catalog.Model { return buildModels(agent) }) } +// sharedModels is magpieModels without the caller's own copy, for one +// that only reads it: a range over it copies each model, so it can't +// write into the list kept. A copy per call was 37 MB of what forty polls +// of the window allocated with real accounts, most of it Pi's and Claude +// Code's thinking levels, read per field. +func sharedModels(agent string) []catalog.Model { + return builtModels.shared(agent, func() []catalog.Model { return buildModels(agent) }) +} + // builtModels is what magpieModels built last, per agent. The window asks // /api/drift every 15s, and each agent's Drift asked for its list again // per field, each built whole with its prices and Vision's ranking of the diff --git a/internal/agent/shared_models_test.go b/internal/agent/shared_models_test.go new file mode 100644 index 000000000..2d4c6fc3a --- /dev/null +++ b/internal/agent/shared_models_test.go @@ -0,0 +1,46 @@ +package agent + +import ( + "os" + "path/filepath" + "regexp" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// A look that only ranges over magpie's models reads the list kept, not a +// copy: a copy per look was 37 MB of what forty window polls allocated +// with real accounts, most of it Pi's and Claude Code's thinking levels. +func TestModelReadersShareTheList(t *testing.T) { + syncHome(t) + if err := provider.Save(provider.Provider{ID: "oa", Name: "OA", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"gpt-5.5", "gpt-5.4"}}); err != nil { + t.Fatal(err) + } + for range 5 { + got := sharedModels("pi") + builtModels.Lock() + kept := builtModels.m["pi"].list + builtModels.Unlock() + if len(got) == 0 || &got[0] != &kept[0] { + t.Fatal("a shared look copies the kept list") + } + } + + // every look that ranges over the list, or counts it, takes it shared + reads := regexp.MustCompile(`(range|len\()\s*magpieModels\(`) + files, _ := filepath.Glob("*.go") + for _, f := range files { + if strings.HasSuffix(f, "_test.go") { + continue + } + b, err := os.ReadFile(f) + if err != nil { + t.Fatal(err) + } + if m := reads.Find(b); m != nil { + t.Errorf("%s reads magpieModels' copy only to range over it: %s", f, m) + } + } +} diff --git a/internal/agent/snow.go b/internal/agent/snow.go index 5cc9a1aff..97bb8d327 100644 --- a/internal/agent/snow.go +++ b/internal/agent/snow.go @@ -430,7 +430,7 @@ func snowIn(at place) *Agent { if !ok { return nil } - for _, m := range magpieModels("snow") { + for _, m := range sharedModels("snow") { if m.ID == ref && len(m.Efforts) > 0 { return append([]Option{{Value: "", Takes: "off"}}, static(m.Efforts...)...) } @@ -493,7 +493,7 @@ func snowProfileFor(from []byte, ours bool, v1, key, ref string, wrote map[strin } ctx, out := snowContext, snowOutput sees := false - for _, m := range magpieModels("snow") { + for _, m := range sharedModels("snow") { if m.ID == ref { if m.Context > 0 { ctx = m.Context diff --git a/internal/agent/stepcode.go b/internal/agent/stepcode.go index 81a45e576..a3b4d96e9 100644 --- a/internal/agent/stepcode.go +++ b/internal/agent/stepcode.go @@ -41,7 +41,7 @@ func stepcodeDir(at place) string { func stepcodeProvider(at place) any { ms := make([]map[string]any, 0) - for _, m := range magpieModels("stepcode") { + for _, m := range sharedModels("stepcode") { ms = append(ms, piModelJSON(piAsked("stepcode", m), at.gw(), true)) } return map[string]any{ diff --git a/internal/agent/t3code.go b/internal/agent/t3code.go index 0b656417f..f472a51ec 100644 --- a/internal/agent/t3code.go +++ b/internal/agent/t3code.go @@ -182,7 +182,7 @@ func t3App(home string) bool { func t3InstanceJSON(path, gw string) map[string]any { mark := claude1MFor("t3code") models := []map[string]any{} - for _, m := range magpieModels("t3code") { + for _, m := range sharedModels("t3code") { // Claude Code reads a dotted Claude version as Claude Opus 4 e := map[string]any{"slug": provider.ClaudeSpelled(mark(m.ID)), "name": m.Name} if c := t3Capabilities(m.ID, m.Efforts); c != nil { diff --git a/internal/agent/vscode.go b/internal/agent/vscode.go index b78f37746..f62ff8f71 100644 --- a/internal/agent/vscode.go +++ b/internal/agent/vscode.go @@ -487,7 +487,7 @@ func vscodeURL() string { return gatewayV1() + "/chat/completions" } // Code k is shown it. func vscodeGroupJSON(k vscodeKind, vendor string) map[string]any { list := []any{} - for _, m := range magpieModels(k.id) { + for _, m := range sharedModels(k.id) { context := m.Context if context == 0 { context = 128000 // what VS Code takes a model of unknown window for diff --git a/internal/agent/workbuddy.go b/internal/agent/workbuddy.go index 1b8262692..54664013d 100644 --- a/internal/agent/workbuddy.go +++ b/internal/agent/workbuddy.go @@ -284,7 +284,7 @@ func buddyWriteAt(path, agent string, on bool, where place) error { var add []json.RawMessage var ids []string if on { - for _, m := range magpieModels(agent) { + for _, m := range sharedModels(agent) { e := buddyModel(agent, m.ID, m.Name, m.Context, outputOr(m, zcodeOutput(maxTokens(m))), m.Images, m.Efforts) if off[m.ID] { e["disabled"] = true diff --git a/internal/agent/zcode.go b/internal/agent/zcode.go index 7403d3d21..a22d112ed 100644 --- a/internal/agent/zcode.go +++ b/internal/agent/zcode.go @@ -131,7 +131,7 @@ func zcode(home string) *Agent { func zcodeProviderJSON(path string, keep bool) any { was := zcodeVariants(path) ms := map[string]any{} - for _, m := range magpieModels("zcode") { + for _, m := range sharedModels("zcode") { window := m.Context if window == 0 { window = 200000 @@ -441,7 +441,7 @@ func zcodeRules(path string, on, keep bool) error { format := zcodeFormat(filepath.Dir(path)) searched, known := zcodeSearched() var ids []string - for _, m := range magpieModels("zcode") { + for _, m := range sharedModels("zcode") { ids = append(ids, m.ID) if byHand[m.ID] { // set by hand in ZCode: its own settings, and the default diff --git a/internal/agent/zed.go b/internal/agent/zed.go index 87de5344c..feb0b7fc9 100644 --- a/internal/agent/zed.go +++ b/internal/agent/zed.go @@ -204,7 +204,7 @@ func zedProviderJSON(path string) map[string]any { } } models := []any{} - for _, m := range magpieModels("zed") { + for _, m := range sharedModels("zed") { context := m.Context if context == 0 { context = 128000 // Zed requires a context window for every custom model. diff --git a/internal/agent/zoocode.go b/internal/agent/zoocode.go index 90e73db6e..f3de4f52f 100644 --- a/internal/agent/zoocode.go +++ b/internal/agent/zoocode.go @@ -232,7 +232,7 @@ func zooCodeProfiles(ref string) map[string]any { "openAiBaseUrl": gatewayV1(), "openAiApiKey": agentKey("zoo-code"), "openAiModelId": ref, "openAiStreamingEnabled": true, } - for _, m := range magpieModels("zoo-code") { + for _, m := range sharedModels("zoo-code") { if m.ID == ref { p["openAiCustomModelInfo"] = zooCodeModelInfo(m) break