Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gateway: Claude Code's auto mode classifier follows a /model switch at once
yetone137187a401f7
diff --git a/internal/agent/claude.go b/internal/agent/claude.goindex 77fce66d3..f26e254b7 100644--- a/internal/agent/claude.go+++ b/internal/agent/claude.go@@ -2589,6 +2589,64 @@ func StandIn(agent, model string) string {return wslClaudeStandIn(model)}+// ClassifierStandIn is the model Claude Code's auto mode classifier goes+// to in place of the one it named, while the sonnet tier it named follows+// a main model that /model has moved since magpie last wrote the tiers.+// Claude Code 2.1.310 runs the classifier, with CLAUDE_CODE_AUTO_MODE_MODEL+// unset, on ANTHROPIC_DEFAULT_SONNET_MODEL ($Xe, BB in its bundle), not on+// the session's model. A pick in /model saves the main model alone, and+// the tiers following it move only when magpie next looks (Follow), so+// the first classifier request after a switch named the model before it+// (CyberCaius on Discord). "" leaves the model as asked. For+// gateway.ClassifierStandIn.+func ClassifierStandIn(agent, model string) string {+ if agent != "claude" {+ return ""+ }+ home, err := os.UserHomeDir()+ if err != nil {+ return ""+ }+ if m := claudeClassifierIn(here(home), model); m != "" || runtime.GOOS != "windows" {+ return m+ }+ return wslClaudeClassifier(model)+}++// claudeClassifierIn is ClassifierStandIn for the Claude Code at a place:+// the main model the sonnet tier follows, at the tier's effort, when the+// classifier named that tier as magpie last wrote it and the main model+// has moved on. A tier the user put on a model of its own, or an auto+// mode model set for the classifier, is left as it is.+func claudeClassifierIn(at place, model string) string {+ path := filepath.Join(at.claudeDir(), "settings.json")+ env := func(k string) string { v, _ := edit.GetJSON(path, "env."+k); return provider.ClaudeRead(v) }+ if u := env("ANTHROPIC_BASE_URL"); u != at.gw() && !surelyMagpie(u, at.gw()) {+ return ""+ }+ if env(claudeAutoModeEnv) != "" {+ return ""+ }+ st := stashLoad()+ if st[at.key("claude.tier_own.sonnet")] != "" {+ return ""+ }+ bare := func(v string) string { m, _ := tierAt(v); return strings.TrimSuffix(m, "[1m]") }+ tier, effort := tierAt(env(tierEnv("sonnet")))+ if tier == "" || bare(provider.ClaudeRead(model)) != bare(tier) {+ return ""+ }+ was := bare(cmp.Or(st[at.key("claude.main")], env("ANTHROPIC_MODEL")))+ if was == "" || bare(tier) != bare(follow("sonnet", was)) {+ return "" // the tier is on a model of its own+ }+ main := claudeMain(path)+ if main == "" || bare(main) == was || !isMagpie(bare(main)) {+ return ""+ }+ return followAt("sonnet", bare(main), effort)+}+func claudeStandIn(path, model string) string { return claudeStandInAt(path, model, gateway.URL()) }// claudeStandInAt is claudeStandIn for a Claude Code that reaches thediff --git a/internal/agent/claude_classifier_test.go b/internal/agent/claude_classifier_test.gonew file mode 100644index 000000000..02e9e9b26--- /dev/null+++ b/internal/agent/claude_classifier_test.go@@ -0,0 +1,100 @@+package agent++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/yetone/magpie/internal/edit"+ "github.com/yetone/magpie/internal/provider"+)++// CyberCaius on Discord: after a switch in /model, the first auto mode+// classifier request went to the model before it. Claude Code names its+// sonnet tier for the classifier, and magpie's sonnet tier follows the+// main model only once Follow has run. Until then the classifier's model+// is the tier the new main model would give it; a tier, or an auto mode+// model, of the user's own is theirs as it is.+func TestClaudeClassifierFollowsTheSwitchedModel(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))+ t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))+ if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro", "flash"}}); err != nil {+ t.Fatal(err)+ }+ path := filepath.Join(home, ".claude", "settings.json")+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(`{}`), 0o644); err != nil {+ t.Fatal(err)+ }+ a := claude(home)+ if err := a.Field("model").Set("deepseek/pro"); err != nil {+ t.Fatal(err)+ }+ env := func(k string) string { v, _ := edit.GetJSON(path, "env."+k); return v }+ tier := env(tierEnv("sonnet"))+ if tier != "deepseek/pro" {+ t.Fatalf("the sonnet tier doesn't follow the main model: %q", tier)+ }+ at := here(home)+ if got := claudeClassifierIn(at, tier); got != "" {+ t.Fatalf("main model unchanged, the classifier was moved to %q", got)+ }++ // /model saves the new main model; Follow hasn't run+ if err := edit.SetJSON(path, edit.KV{Path: "model", Value: "deepseek/flash"}); err != nil {+ t.Fatal(err)+ }+ if env(tierEnv("sonnet")) != tier {+ t.Fatal("the tier moved without Follow")+ }+ if got := claudeClassifierIn(at, tier); got != "deepseek/flash" {+ t.Fatalf("after /model the classifier goes to %q, want deepseek/flash", got)+ }+ if got := claudeClassifierIn(at, "deepseek/flash"); got != "" {+ t.Fatalf("a model that isn't the sonnet tier was moved to %q", got)+ }++ // an auto mode model of the user's own+ if err := edit.SetJSON(path, edit.KV{Path: "env." + claudeAutoModeEnv, Value: "deepseek/pro"}); err != nil {+ t.Fatal(err)+ }+ if got := claudeClassifierIn(at, tier); got != "" {+ t.Fatalf("the user's auto mode model was moved to %q", got)+ }+ if err := edit.SetJSON(path, edit.KV{Path: "env." + claudeAutoModeEnv, Value: nil}); err != nil {+ t.Fatal(err)+ }++ // a sonnet tier of the user's own+ if err := edit.SetJSON(path, edit.KV{Path: "model", Value: "deepseek/pro"}); err != nil {+ t.Fatal(err)+ }+ if err := a.Field("sonnet").Set("deepseek/pro"); err != nil {+ t.Fatal(err)+ }+ if err := edit.SetJSON(path, edit.KV{Path: "model", Value: "deepseek/flash"}); err != nil {+ t.Fatal(err)+ }+ if got := claudeClassifierIn(at, "deepseek/pro"); got != "" {+ t.Fatalf("the user's own sonnet tier was moved to %q", got)+ }++ // Follow has run: the tier is the new main model's, and nothing moves+ if err := a.Field("sonnet").Set(""); err != nil {+ t.Fatal(err)+ }+ if err := a.Follow(); err != nil {+ t.Fatal(err)+ }+ if got := env(tierEnv("sonnet")); got != "deepseek/flash" {+ t.Fatalf("Follow left the tier on %q", got)+ }+ if got := claudeClassifierIn(at, "deepseek/flash"); got != "" {+ t.Fatalf("after Follow the classifier was moved to %q", got)+ }+}diff --git a/internal/agent/wsl.go b/internal/agent/wsl.goindex 15ccee814..86ef535d3 100644--- a/internal/agent/wsl.go+++ b/internal/agent/wsl.go@@ -1150,6 +1150,28 @@ func wslClaudeStandIn(model string) string {return ""}+// wslClaudeClassifier is ClassifierStandIn for a Claude Code in a running+// distro, known by the same User-Agent.+func wslClaudeClassifier(model string) string {+ wsl.Lock()+ wslRunningLocked()+ var ds []distro+ for _, n := range wsl.names {+ if d := wsl.seen[n]; d != nil && wsl.running[n] && wslKindOf("claude").found(*d) {+ ds = append(ds, *d)+ }+ }+ wsl.Unlock()+ cfg := wslConfig()+ for _, d := range ds {+ d.mirror(cfg)+ if m := claudeClassifierIn(d.place("claude@wsl:"+d.Name), model); m != "" {+ return m+ }+ }+ return ""+}+// wslList is the names wsl.exe lists with args; ok is false when it// couldn't say (no WSL, or none installed).func wslList(args ...string) (names []string, ok bool) {diff --git a/internal/cli/main.go b/internal/cli/main.goindex 72ed5448f..1836268a1 100644--- a/internal/cli/main.go+++ b/internal/cli/main.go@@ -266,6 +266,9 @@ func run(args []string) error {// a model Claude Code names that magpie doesn't serve goes to the one// it is set to use for that tiergateway.StandIn = agent.StandIn+ // and its auto mode classifier, on a sonnet tier that follows a main+ // model /model has moved, to the model it moved to+ gateway.ClassifierStandIn = agent.ClassifierStandIn// a Codex that reaches magpie for account failover alone is handed// only its own models (#1385)gateway.CodexOwnOnly = agent.CodexOwnOnlydiff --git a/internal/gateway/automode.go b/internal/gateway/automode.goindex e228d03f2..ee66235ad 100644--- a/internal/gateway/automode.go+++ b/internal/gateway/automode.go@@ -206,11 +206,7 @@ func ownEffortRefused(status int, body []byte, sent string) (refused, value bool// an Anthropic endpoint as it was sent: a model that isn't Claude gets the// room to reason in. The rest of the body is left alone.func autoModeClassifierBody(model string, body []byte) []byte {- if anthropicModel.MatchString(model) || !bytes.Contains(body, []byte("<transcript>")) || !bytes.Contains(body, []byte("<block>")) && !bytes.Contains(body, []byte("<severity>")) {- return body- }- req, err := parseAnthropic(body)- if err != nil || !autoModeClassifier(req) {+ if anthropicModel.MatchString(model) || !autoModeClassifierAsk(body) {return body}asked := gjson.GetBytes(body, "max_tokens").Int()@@ -219,3 +215,34 @@ func autoModeClassifierBody(model string, body []byte) []byte {}return withFields(body, map[string]any{"max_tokens": asked + classifierRoom})}++// autoModeClassifierAsk reports whether body, a Messages API request, is+// Claude Code's auto mode classifier asking about an action. The bytes+// are looked at before the body is parsed: every request passes here.+func autoModeClassifierAsk(body []byte) bool {+ if !bytes.Contains(body, []byte("<transcript>")) || !bytes.Contains(body, []byte("<block>")) && !bytes.Contains(body, []byte("<severity>")) {+ return false+ }+ req, err := parseAnthropic(body)+ return err == nil && autoModeClassifier(req)+}++// ClassifierStandIn is the model Claude Code's auto mode classifier goes+// to in place of the tier's it named, while that tier follows a main model+// /model has moved since magpie wrote it; "" leaves it as asked. Set by+// main (agent.ClassifierStandIn).+var ClassifierStandIn func(agent, model string) string++// classifierStandIn is ClassifierStandIn for a request Claude Code sent,+// when it is the auto mode classifier: Claude Code names its sonnet tier+// for it, not the session's model, so the first one after a switch in+// /model went to the model before it until magpie moved the tier.+func classifierStandIn(agent string, from provider.Protocol, asked string, body []byte) string {+ if ClassifierStandIn == nil || agent != "claude" || from != provider.Anthropic || !autoModeClassifierAsk(body) {+ return ""+ }+ if m := ClassifierStandIn(agent, asked); m != asked {+ return m+ }+ return ""+}diff --git a/internal/gateway/automode_test.go b/internal/gateway/automode_test.goindex ff38d73fe..bd6e9f0df 100644--- a/internal/gateway/automode_test.go+++ b/internal/gateway/automode_test.go@@ -111,7 +111,9 @@ func TestAutoModeClassifierOnAReasoningModel(t *testing.T) {// conversation's own turn is left alone.func TestAutoModeClassifierOnlyTheClassifier(t *testing.T) {f := &fake{t: t, reply: sse(- `event: response.completed` + "\n" + `data: {"type":"response.completed","response":{"id":"r1","model":"m1","status":"completed","usage":{"input_tokens":4,"output_tokens":2}}}`)}+ `event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","model":"m1","usage":{"input_tokens":0,"output_tokens":0}}}`,+ `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"<block>no"}`,+ `event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"r1","model":"m1","status":"completed","usage":{"input_tokens":4,"output_tokens":2}}}`)}setup(t, provider.Responses, f)if code, body := post(t, "/v1/messages", autoModeAsk("m1")); code != 200 {t.Fatalf("%d %s", code, body)@@ -984,3 +986,52 @@ func TestAutoModeClassifierEffortRefusedGoesWithout(t *testing.T) {})}}++// CyberCaius on Discord: after a switch in /model, the first auto mode+// classifier request went to the model before it. Claude Code names its+// sonnet tier for the classifier, and that tier followed the old main+// model until magpie moved it. The classifier goes to the model the tier+// follows now (ClassifierStandIn); a turn of the conversation naming the+// same model, another session still on it, goes as asked.+func TestAutoModeClassifierFollowsTheSwitchedModel(t *testing.T) {+ setHome(t, t.TempDir())+ f := &fake{t: t, reply: sse(+ `event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","model":"m1","usage":{"input_tokens":0,"output_tokens":0}}}`,+ `event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"<block>no"}`,+ `event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"r1","model":"m1","status":"completed","usage":{"input_tokens":4,"output_tokens":2}}}`)}+ setup(t, provider.Responses, f)+ p, _ := provider.Find("fake")+ p.Models = []string{"m1", "m2"}+ if err := provider.Save(*p); err != nil {+ t.Fatal(err)+ }+ var asked []string+ ClassifierStandIn = func(agent, model string) string {+ asked = append(asked, agent+" "+model)+ if model == "fake/m1" {+ return "fake/m2"+ }+ return ""+ }+ t.Cleanup(func() { ClassifierStandIn = nil })+ send := func(body string) {+ t.Helper()+ f.got = nil+ rec := httptest.NewRecorder()+ req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))+ req.Header.Set("User-Agent", "claude-cli/2.1.310 (external, cli)")+ req.Header.Set("x-api-key", Token+"-claude")+ New().Handler().ServeHTTP(rec, req)+ if rec.Code != 200 {+ t.Fatalf("%d %s", rec.Code, rec.Body.String())+ }+ }+ send(autoModeAsk("fake/m1"))+ if got := modelOf(f.got); got != "m2" {+ t.Fatalf("the classifier went to %q, want the switched-to m2 (asked %v)", got, asked)+ }+ send(`{"model":"fake/m1","max_tokens":64,"messages":[{"role":"user","content":"hi"}],"tools":[{"name":"Bash","input_schema":{"type":"object"}}]}`)+ if got := modelOf(f.got); got != "m1" {+ t.Fatalf("a conversation's turn went to %q, want m1 as asked", got)+ }+}diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex e8f7860e4..43826a6e6 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -1733,7 +1733,11 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro}return m}- if m := claudeTierStandIn(r, agent, asked); m != "" {+ if m := classifierStandIn(agent, from, asked, body); m != "" {+ // Claude Code's auto mode classifier on its sonnet tier, which+ // follows a main model /model has moved: the model it moved to+ asked = grouped(at(m))+ } else if m := claudeTierStandIn(r, agent, asked); m != "" {// Claude Code (or a wrapper, T3 Code) naming one of Anthropic's// models by its full id: the model it is set to use for that tier,// whether or not magpie serves the id too