From 8060650048839d2a4e49f6c27836e5ec0dbc0ffc Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 29 Sep 2026 00:02:01 +0800 Subject: [PATCH] agent: Pi starts on the model magpie picks, and asks a Messages-only provider's models on Messages (#160 Aimer779; Cleary on Discord) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While Pi's ~/.pi/agent/settings.json has a non-empty enabledModels (its Ctrl+P / /scoped-models list), a new session starts on defaultProvider/defaultModel only when that list takes the model in, else on the list's first entry, so a model picked in magpie outside the list was written and never used. Setting Pi's model now adds it to enabledModels as provider/model, as Pi's own picker does, when nothing in the list takes it in already: the same reference with or without a :level after it, or a glob (*, ?, [..], without case) that the reference or its model id fits. The user's entries, their order and comments stay; no list is made where there is none, and an empty one is left as it is. Turning the model back to Pi's own takes magpie/… entries out with magpie's provider, removing the key rather than leaving it empty. The model field shows what a new session starts on: the list's first model when the saved default isn't in the list and that entry names one model outright. The list itself isn't editable in magpie yet; Field is single-valued, and an editor needs a multi-value field kind in the API, GUI (a multi-select, reorderable picker), TUI and CLI. Pi's models.json now gives each magpie model the API its provider speaks natively, so the gateway passes the request through instead of translating Chat: Responses-native models keep openai-responses; a Messages-only provider's (a custom Anthropic-compatible endpoint, as Cleary's) get api anthropic-messages with baseUrl the gateway's root (Anthropic's SDK adds /v1/messages). A Claude from 4.6 on also gets compat.forceAdaptiveThinking, so Pi asks for adaptive thinking and an effort, not the budget such a Claude refuses (why these stayed on Chat before). Magpie's models stay under providers.magpie; other providers are untouched. Why Chat→Messages could 400 where Pi's direct Messages didn't: with reasoning on, buildAnthropic raised max_tokens to budget+4096 (28096 for high) past the client's own max_completion_tokens, which Pi sets to the model's output limit, so an upstream capped below that refused it. The budget now fits under a cap the client gives (at most the cap less 1024; no thinking when the cap is 2048 or less); with no cap it still raises max_tokens as before. Tested: go test -tags nogui ./... (new: TestPiTakes, TestPiModelJoinsEnabledModels, TestPiModelOffLeavesEnabledModels, TestThinkingBudgetFitsTheClientsCap; TestPiModelsAskedOnTheirNativeAPI extended), nogui builds for darwin, linux and windows. In a sandbox HOME: settings.json with enabledModels [xai/grok-4.6, openai-codex/gpt-5.6-sol, deepseek/deepseek-flash], magpie pi magpie/cleary/kimi-k3 appended the model and kept the rest, magpie pi default took it out again; models.json listed cleary's models on anthropic-messages, a Chat relay's on the provider's openai-completions, a Responses vendor's on openai-responses. Pi 0.87.1 loaded that models.json (--list-models) and, against a fake Messages endpoint standing in for the gateway (MAGPIE_ADDR on a spare port), posted to /v1/messages with the gateway key: kimi-k3 with a 15360-token budget under max_tokens 16384, claude-sonnet-5 with adaptive thinking and effort high. --- internal/agent/agents.go | 37 +++++--- internal/agent/pi.go | 109 +++++++++++++++++++++++ internal/agent/pi_api_test.go | 30 +++++-- internal/agent/pi_scope_test.go | 141 ++++++++++++++++++++++++++++++ internal/gateway/adaptive_test.go | 42 +++++++++ internal/gateway/anthropic.go | 15 +++- 6 files changed, 354 insertions(+), 20 deletions(-) create mode 100644 internal/agent/pi.go create mode 100644 internal/agent/pi_scope_test.go diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 20124252c..61d6deef4 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -248,16 +248,23 @@ func magpieProviderJSONFor(shape, catalog string) any { for _, m := range models { // reasoning lets Pi offer its thinking levels for the model e := map[string]any{"id": m.ID, "name": m.Name, "reasoning": len(m.Efforts) > 0} - // a model its provider serves on OpenAI's Responses API alone, + // each model is asked on the API its provider speaks natively, + // so the gateway relays what Pi sent as it is instead of + // translating Chat. One served on OpenAI's Responses API alone, // or best there (a ChatGPT sign-in, GPT on OpenAI's API or - // Copilot's), is asked there — Pi posts it to baseUrl/responses - // — so the gateway relays it as Pi sent it instead of - // translating Chat. One served on Anthropic's API stays on - // Chat: Pi's anthropic-messages picks thinking by the Claude - // ids it knows and asks a newer Claude for a thinking budget, - // which it turns away; magpie's translation knows its levels. - if slices.Contains(m.APIs, string(provider.Responses)) { + // Copilot's), goes to baseUrl/responses; one on Anthropic's + // Messages API alone to the gateway's /v1/messages (Anthropic's + // SDK adds the /v1). A Claude that thinks only adaptively is + // told so: Pi would otherwise ask it for a thinking budget, + // which it turns away. + switch { + case slices.Contains(m.APIs, string(provider.Responses)): e["api"] = "openai-responses" + case slices.Contains(m.APIs, string(provider.Anthropic)): + e["api"], e["baseUrl"] = "anthropic-messages", gateway.URL() + if gateway.AdaptiveThinking(m.ID) { + e["compat"] = map[string]any{"forceAdaptiveThinking": true} + } } if m.Images { e["input"] = []string{"text", "image"} @@ -466,20 +473,28 @@ func pi(home string) *Agent { Fields: []Field{ { Key: "model", Label: "model", - Get: pairGet(get, "defaultProvider", "defaultModel"), + // what a new session starts on, which enabledModels decides + Get: func() string { return piStartup(path, pairGet(get, "defaultProvider", "defaultModel")()) }, Set: func(v string) error { if v == "" { if err := edit.DelJSON(path, "defaultProvider", "defaultModel"); err != nil { return err } - return edit.DelJSON(modelsPath, "providers."+magpieID) + if err := edit.DelJSON(modelsPath, "providers."+magpieID); err != nil { + return err + } + return piScopeWithout(path) } if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) { if err := writeMagpie(); err != nil { return err } } - return pair(v) + if err := pair(v); err != nil { + return err + } + // a model outside the user's Ctrl+P list would never start + return piScopeWith(path, v) }, Options: func(cur map[string]string) []Option { return append(ownOptions(auth, cur["model"]), viaMagpie("pi", magpieID+"/")...) diff --git a/internal/agent/pi.go b/internal/agent/pi.go new file mode 100644 index 000000000..068caee26 --- /dev/null +++ b/internal/agent/pi.go @@ -0,0 +1,109 @@ +package agent + +import ( + "encoding/json" + "path" + "slices" + "strings" + + "github.com/yetone/magpie/internal/edit" +) + +// Pi's enabledModels (settings.json) is its Ctrl+P cycle and /scoped-models +// list. While it names anything, a new session starts on defaultModel only +// when the list takes that model in, and on the list's first model when it +// doesn't — so a model magpie picks outside it would never be used. The list +// is the user's: magpie adds the model it picks to it, as Pi's own model +// picker does, and never makes one where there is none. + +// piLevels are the thinking levels a pattern may end in (provider/model:high). +var piLevels = []string{"off", "minimal", "low", "medium", "high", "xhigh", "max"} + +// piScope is settings.json's enabledModels; nil when it is missing, empty +// or not a list of strings. +func piScope(settings string) []string { + raw, ok := edit.GetJSON(settings, "enabledModels") + if !ok { + return nil + } + var pats []string + if json.Unmarshal([]byte(raw), &pats) != nil || len(pats) == 0 { + return nil + } + return pats +} + +// piTakes reports whether Pi's scope pattern surely takes in ref, a +// provider/model: the same reference, a :level after it or not, or a glob +// (Pi's *, ? and [..], matched without case) that ref or its model id fits. +// A bare model id or part of one, which Pi resolves against every model it +// knows, is not counted: adding ref beside it costs nothing, since Pi drops +// a model listed twice. +func piTakes(pattern, ref string) bool { + glob := strings.ContainsAny(pattern, "*?[") + if i := strings.LastIndex(pattern, ":"); i >= 0 && slices.Contains(piLevels, pattern[i+1:]) { + pattern = pattern[:i] + } + pattern, ref = strings.ToLower(strings.TrimSpace(pattern)), strings.ToLower(ref) + if pattern == ref { + return true + } + if !glob { + return false + } + _, id, _ := strings.Cut(ref, "/") + for _, s := range []string{ref, id} { + if ok, _ := path.Match(pattern, s); ok { + return true + } + } + return false +} + +// piScopeWith adds ref to Pi's enabledModels, when there is such a list and +// nothing in it takes ref in; the user's entries stay as they are. +func piScopeWith(settings, ref string) error { + pats := piScope(settings) + if pats == nil || slices.ContainsFunc(pats, func(p string) bool { return piTakes(p, ref) }) { + return nil + } + return edit.SetJSON(settings, edit.KV{Path: "enabledModels", Value: append(pats, ref)}) +} + +// piScopeWithout takes magpie's models out of Pi's enabledModels once +// magpie's provider is gone from models.json, where they would name nothing. +// A list left with nothing is removed, never written empty. +func piScopeWithout(settings string) error { + pats := piScope(settings) + if pats == nil { + return nil + } + kept := slices.DeleteFunc(slices.Clone(pats), func(p string) bool { + return !strings.ContainsAny(p, "*?[") && strings.HasPrefix(strings.ToLower(p), magpieID+"/") + }) + switch { + case len(kept) == len(pats): + return nil + case len(kept) == 0: + return edit.DelJSON(settings, "enabledModels") + } + return edit.SetJSON(settings, edit.KV{Path: "enabledModels", Value: kept}) +} + +// piStartup is the model a new Pi session starts on, as the model field +// shows it: the default when enabledModels takes it in (or there is no such +// list), else the list's first entry when that names one model outright. +func piStartup(settings, def string) string { + pats := piScope(settings) + if def == "" || pats == nil || slices.ContainsFunc(pats, func(p string) bool { return piTakes(p, def) }) { + return def + } + first := strings.TrimSpace(pats[0]) + if i := strings.LastIndex(first, ":"); i >= 0 && slices.Contains(piLevels, first[i+1:]) { + first = first[:i] + } + if strings.ContainsAny(first, "*?[") || !strings.Contains(first, "/") { + return def + } + return first +} diff --git a/internal/agent/pi_api_test.go b/internal/agent/pi_api_test.go index dec27bc1a..22bf66c67 100644 --- a/internal/agent/pi_api_test.go +++ b/internal/agent/pi_api_test.go @@ -5,19 +5,21 @@ import ( "path/filepath" "testing" + "github.com/yetone/magpie/internal/gateway" "github.com/yetone/magpie/internal/provider" ) // Pi asks each model on the API its provider serves it on, so the gateway // relays the request as it is: a Responses-only provider's models and GPT -// on OpenAI's API go on openai-responses; a Chat provider's, an Anthropic -// one's and a group's stay on the provider's openai-completions. +// on OpenAI's API go on openai-responses; a Messages-only provider's on +// anthropic-messages at the gateway; a Chat provider's and a group's stay +// on the provider's openai-completions. func TestPiModelsAskedOnTheirNativeAPI(t *testing.T) { home := syncHome(t) for _, p := range []provider.Provider{ {ID: "resp", Name: "Resp", Key: "k", Responses: "http://127.0.0.1:1/v1", Models: []string{"grok-5", "gpt-5.5"}}, {ID: "openai", Name: "OpenAI", Key: "k", Chat: "https://api.openai.com/v1", Responses: "https://api.openai.com/v1", Models: []string{"gpt-5.5", "whisper-x"}}, - {ID: "anth", Name: "Anth", Key: "k", Anthropic: "http://127.0.0.1:1", Models: []string{"claude-sonnet-5"}}, + {ID: "anth", Name: "Anth", Key: "k", Anthropic: "http://127.0.0.1:1", Models: []string{"claude-sonnet-5", "kimi-k3"}}, } { if err := provider.Save(p); err != nil { t.Fatal(err) @@ -34,10 +36,10 @@ func TestPiModelsAskedOnTheirNativeAPI(t *testing.T) { if pm["api"] != "openai-completions" || pm["baseUrl"] != gatewayV1() { t.Fatalf("provider: %v", pm) } - apis := map[string]any{} + apis, entries := map[string]any{}, map[string]map[string]any{} for _, raw := range pm["models"].([]any) { m := raw.(map[string]any) - apis[m["id"].(string)] = m["api"] + apis[m["id"].(string)], entries[m["id"].(string)] = m["api"], m } for id, want := range map[string]any{ "resp/grok-5": "openai-responses", @@ -45,7 +47,8 @@ func TestPiModelsAskedOnTheirNativeAPI(t *testing.T) { "openai/gpt-5.5": "openai-responses", "openai/whisper-x": nil, "relay/glm-4.6": nil, - "anth/claude-sonnet-5": nil, + "anth/claude-sonnet-5": "anthropic-messages", + "anth/kimi-k3": "anthropic-messages", "group/auto-gpt-5-5": nil, } { got, ok := apis[id] @@ -55,4 +58,19 @@ func TestPiModelsAskedOnTheirNativeAPI(t *testing.T) { t.Errorf("%s: api %v, want %v", id, got, want) } } + // Anthropic's SDK posts to baseUrl + /v1/messages; only the Claude + // that refuses a thinking budget is told to think adaptively + for id, adaptive := range map[string]bool{"anth/claude-sonnet-5": true, "anth/kimi-k3": false} { + e := entries[id] + if e["baseUrl"] != gateway.URL() { + t.Errorf("%s: baseUrl %v, want %s", id, e["baseUrl"], gateway.URL()) + } + c, _ := e["compat"].(map[string]any) + if got := c["forceAdaptiveThinking"] == true; got != adaptive { + t.Errorf("%s: compat %v", id, e["compat"]) + } + } + if _, ok := entries["resp/grok-5"]["baseUrl"]; ok { + t.Errorf("a Responses model keeps the provider's baseUrl: %v", entries["resp/grok-5"]) + } } diff --git a/internal/agent/pi_scope_test.go b/internal/agent/pi_scope_test.go new file mode 100644 index 000000000..cb469d315 --- /dev/null +++ b/internal/agent/pi_scope_test.go @@ -0,0 +1,141 @@ +package agent + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/edit" +) + +func TestPiTakes(t *testing.T) { + for _, c := range []struct { + pattern, ref string + want bool + }{ + {"xai/grok-4.6", "xai/grok-4.6", true}, + {"XAI/Grok-4.6", "xai/grok-4.6", true}, + {"xai/grok-4.6:high", "xai/grok-4.6", true}, + {"xai/*", "xai/grok-4.6", true}, + {"*grok*", "xai/grok-4.6", true}, + {"magpie/*", "magpie/deepseek/deepseek-v4", false}, // Pi's * stops at a / + {"magpie/*/*", "magpie/deepseek/deepseek-v4", true}, + {"deepseek/*:low", "magpie/deepseek/deepseek-v4", true}, // the model id fits + {"grok-4.6", "xai/grok-4.6", false}, // a bare id: added beside + {"xai/grok-4.6", "xai/grok-4.7", false}, + {"openai-codex/gpt-5.6-sol", "opencode-go/deepseek-v4-flash", false}, + } { + if got := piTakes(c.pattern, c.ref); got != c.want { + t.Errorf("piTakes(%q, %q) = %v", c.pattern, c.ref, got) + } + } +} + +// Pi starts a new session on defaultModel only when enabledModels takes it +// in: the model magpie picks is added to the list, the user's entries +// kept; there is no list made where there was none, and none left empty +// (#160) +func TestPiModelJoinsEnabledModels(t *testing.T) { + home := syncHome(t) + settings := filepath.Join(home, ".pi", "agent", "settings.json") + os.MkdirAll(filepath.Dir(settings), 0o755) + os.WriteFile(settings, []byte(`{ + // the user's own + "enabledModels": ["xai/grok-4.6:high", "openai-codex/gpt-5.6-sol", "deepseek/*"], + "defaultProvider": "xai", + "defaultModel": "grok-4.6" +} +`), 0o644) + f := pi(home).Field("model") + if got := f.Get(); got != "xai/grok-4.6" { + t.Fatalf("Get = %q", got) + } + if err := f.Set("opencode-go/deepseek-v4-flash-vision-exp"); err != nil { + t.Fatal(err) + } + want := `["xai/grok-4.6:high","openai-codex/gpt-5.6-sol","deepseek/*","opencode-go/deepseek-v4-flash-vision-exp"]` + if got := strings.Join(strings.Fields(mustGet(t, settings, "enabledModels")), ""); got != want { + t.Errorf("enabledModels = %s, want %s", got, want) + } + if !strings.Contains(readFile(settings), "// the user's own") { + t.Errorf("comment lost: %s", readFile(settings)) + } + if got := f.Get(); got != "opencode-go/deepseek-v4-flash-vision-exp" { + t.Errorf("Get = %q", got) + } + // a model the list takes in already isn't added again + before := mustGet(t, settings, "enabledModels") + for _, v := range []string{"openai-codex/gpt-5.6-sol", "deepseek/deepseek-v4-pro", "xai/grok-4.6"} { + if err := f.Set(v); err != nil { + t.Fatal(err) + } + } + if got := mustGet(t, settings, "enabledModels"); got != before { + t.Errorf("enabledModels grew: %s", got) + } + + // set outside magpie: the model shown is the one Pi starts on + edit.SetJSON(settings, edit.KV{Path: "defaultModel", Value: "grok-3"}) + if got := f.Get(); got != "xai/grok-4.6" { + t.Errorf("Get with a default outside the list = %q, want the list's first", got) + } + + // no list: none is made + os.WriteFile(settings, []byte(`{"defaultProvider":"xai","defaultModel":"grok-4.6"}`), 0o644) + if err := f.Set("opencode-go/deepseek-v4-flash"); err != nil { + t.Fatal(err) + } + if _, ok := edit.GetJSON(settings, "enabledModels"); ok { + t.Errorf("enabledModels made: %s", readFile(settings)) + } + // an empty one means no list to Pi, and stays as it is + os.WriteFile(settings, []byte(`{"enabledModels":[]}`), 0o644) + if err := f.Set("opencode-go/deepseek-v4-flash"); err != nil { + t.Fatal(err) + } + if got := mustGet(t, settings, "enabledModels"); got != "[]" { + t.Errorf("empty enabledModels = %s", got) + } +} + +// Turning Pi's model back to its own takes magpie's models out of the list +// with magpie's provider; a list left with nothing goes, not left empty +func TestPiModelOffLeavesEnabledModels(t *testing.T) { + home := syncHome(t) + settings := filepath.Join(home, ".pi", "agent", "settings.json") + os.MkdirAll(filepath.Dir(settings), 0o755) + f := pi(home).Field("model") + + os.WriteFile(settings, []byte(`{"enabledModels":["xai/grok-4.6","magpie/*/*"]}`), 0o644) + if err := f.Set("magpie/relay/glm-4.6"); err != nil { + t.Fatal(err) + } + if err := f.Set("magpie/deepseek/deepseek-v4"); err != nil { + t.Fatal(err) + } + if err := f.Set(""); err != nil { + t.Fatal(err) + } + // the user's glob is theirs + if got := strings.Join(strings.Fields(mustGet(t, settings, "enabledModels")), ""); got != `["xai/grok-4.6","magpie/*/*"]` { + t.Errorf("enabledModels = %s", got) + } + + os.WriteFile(settings, []byte(`{"enabledModels":["magpie/relay/glm-4.6"],"defaultProvider":"magpie","defaultModel":"relay/glm-4.6"}`), 0o644) + if err := f.Set(""); err != nil { + t.Fatal(err) + } + if _, ok := edit.GetJSON(settings, "enabledModels"); ok { + t.Errorf("enabledModels left: %s", readFile(settings)) + } +} + +func mustGet(t *testing.T, path, key string) string { + t.Helper() + v, ok := edit.GetJSON(path, key) + if !ok { + t.Fatalf("%s: no %s in %s", path, key, readFile(path)) + } + return v +} diff --git a/internal/gateway/adaptive_test.go b/internal/gateway/adaptive_test.go index 66fb2e9d5..38b293a92 100644 --- a/internal/gateway/adaptive_test.go +++ b/internal/gateway/adaptive_test.go @@ -5,6 +5,48 @@ import ( "testing" ) +// A Chat client's max tokens is what the model can write — Pi sends the +// model's own output limit — so the thinking budget fits under it rather +// than max_tokens raised past it, which the upstream refuses with a 400. +// With no cap asked, max_tokens still makes room for the budget. +func TestThinkingBudgetFitsTheClientsCap(t *testing.T) { + for _, c := range []struct { + max int + effort string + wantMax float64 + wantBudget float64 + wantNoThink bool + }{ + {16384, "high", 16384, 15360, false}, + {32000, "high", 32000, 24000, false}, + {8192, "xhigh", 8192, 7168, false}, + {0, "high", 28096, 24000, false}, + {2048, "high", 2048, 0, true}, + } { + body, _ := json.Marshal(map[string]any{"model": "k", "max_completion_tokens": c.max, "reasoning_effort": c.effort, + "messages": []map[string]any{{"role": "user", "content": "hi"}}}) + r, err := parseChat(body) + if err != nil { + t.Fatal(err) + } + var out map[string]any + json.Unmarshal(buildAnthropic(r, "kimi-k3"), &out) + if out["max_tokens"] != c.wantMax { + t.Errorf("%d %s: max_tokens %v, want %v", c.max, c.effort, out["max_tokens"], c.wantMax) + } + th, _ := out["thinking"].(map[string]any) + if c.wantNoThink { + if th != nil { + t.Errorf("%d %s: thinking %v with no room for it", c.max, c.effort, th) + } + continue + } + if th["budget_tokens"] != c.wantBudget { + t.Errorf("%d %s: budget %v, want %v", c.max, c.effort, th["budget_tokens"], c.wantBudget) + } + } +} + func TestAdaptiveThinking(t *testing.T) { for model, want := range map[string]bool{ "claude-opus-5-5": true, "claude-opus-5": true, "claude-sonnet-4-6": true, diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go index 47dfa94f7..5269fe512 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.go @@ -207,6 +207,10 @@ func adaptiveOnly(model string) bool { return major > 4 || major == 4 && minor >= 6 } +// AdaptiveThinking is adaptiveOnly for agents told how to ask a model: a +// Claude that takes thinking.type=adaptive and an effort, never a budget. +func AdaptiveThinking(model string) bool { return adaptiveOnly(model) } + // effortInOutputConfig is a model that takes how hard it thinks from // output_config.effort, beside thinking turned on, as ZCode asks it: Z.ai's // GLM-5.2 and GLM-5.3 on their Anthropic endpoints. A budget alone leaves @@ -323,9 +327,14 @@ func buildAnthropic(r *Request, model string) []byte { } out["output_config"] = map[string]any{"effort": e} } - } else if r.Thinking || r.Effort != "" { - budget := budgetOf(r.Effort) - if maxTokens < budget+4096 { + } else if think, budget := r.Thinking || r.Effort != "", budgetOf(r.Effort); think && (r.MaxTokens <= 0 || r.MaxTokens > 2048) { + if r.MaxTokens > 0 { + // the client's cap is what the model can write (Pi sends the + // model's own output limit): the budget fits under it, leaving + // room for the answer, as a raised max_tokens past what the + // model takes is refused with a 400 + budget = min(budget, maxTokens-1024) + } else if maxTokens < budget+4096 { maxTokens = budget + 4096 } out["thinking"] = map[string]any{"type": "enabled", "budget_tokens": budget}