Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gateway: auto mode's classifier asks a model of unknown levels for no reasoning

yetonec8901d4723b6
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index b972d77f9..4a274bce3 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -184,6 +184,7 @@ recorded as a prediction failure (`noPrediction`).
- Levels the user kept of a model's own (`ModelEfforts`, `SetModelEfforts`; `magpie model efforts`, the editor's Names & levels, `magpie model spec --reasoning`) only narrow what is offered (#92): `provider.Efforts` returns the vendor's list's or models.dev's levels, and `fitEffort` fits a request to those, so an agent asking xhigh of a model kept to low–high still asks xhigh. A model no list knows levels of can be given them (`magpie model spec --reasoning`, Dani Ariyanto on Discord); those are then its levels, a request is fitted to them, and it counts as reasoning (`entryFor`). `AutoVision` honours the user's `ModelImages` over the model's own (`seesAt`). `TestModelSpecReachesTheGateway`, `TestNarrowedVendorLevelsAskAsBefore`, `TestAutoVisionTakesTheUsersVision`.
- A request to an Anthropic endpoint with `temperature`, `top_p` or `top_k` reaches a model that refuses them without them (`samplingAsTaken`, beside `thinkingOffAsTaken` in `forwardOnce`): Opus 4.7, 4.8, 5 and 5.5, Fable 5, Mythos 5, Sonnet 5 and 5.5, and Haiku 5.5, whose 400 is "`temperature` is deprecated for this model" (Claude Code's auto mode classifier and magpie's own classifiers ask at temperature 0). Older Claudes, Haiku 4.5 among them, other vendors' models and later lines go as they came (#1454). A Claude by a name these rules can't read, answering that a sampling parameter is deprecated (`samplingDeprecated`), is asked again without them, once — a Chat or Responses client's request translated to Messages (`forwardTranslated`) as much as a relayed one.
- Claude Code's auto mode asks the API to review each action ([`automode.go`](../../internal/gateway/automode.go), Anthropic's [auto-mode-classifier-billing](https://code.claude.com/docs/en/auto-mode-classifier-billing)): the `dangerous-tool-use-…` beta, a `safeguards` field, and `safeguard_results` in the reply (a stream's in its `message_delta`). Only Anthropic runs that classifier, so they reach only a route it answers on (`AutoModeReviewed`): the Claude subscription (the bridge hands them to Claude Code's own binary), a Claude model under any vendor's spelling on a provider with a key (Anthropic's API, a relay, Bedrock, Vertex), and anything on `api.anthropic.com`. Another subscription's or a plugin's Claude model (Copilot, Kiro, Cursor…) is that vendor's service and isn't reviewed by its name: Copilot turns `safeguards` away (#1756), the others translate the request, so neither the beta nor `safeguards` is sent there (`TestAutoModeReviewedRoutes`, `TestAutoModeReviewLeftOffOtherSubscriptions`). There the beta, `safeguards` and the results pass as sent, a whole reply's results moved into a stream's `message_delta` (`anthropicWholeEvents`), tool-use ids unchanged. To any other model they are taken off (`serverReview`; a translation never carries them), and magpie never answers a result on Anthropic's behalf. Claude Code then classifies locally and names the gateway in a notice; the wiring turns the review off in its settings while no model it can reach through magpie is reviewed (`claudeReviewEnv`, [agent wiring](agent-wiring.md)), which is the page's remedy for a gateway that can't run the checks (1EFLOPS on X: Codex's model behind magpie). Reviewed there means `AutoModeReviewable`: a reviewed model on a route that reaches the Messages API, since a Claude model asked on a relay's Chat or Responses URL is translated and never carries the review (nexnull on Discord, `TestAutoModeReviewableAsksOnMessages`).
+- Locally, Claude Code's classifier is a request of its own on the session's model: no tools, a system prompt asking for `<block>yes</block>` or `<block>no</block>`, the transcript in `<transcript>`, a small `max_tokens`, and no stream; Claude Code 2.1.310 waits 60 seconds an attempt for it. To a model that isn't Claude it goes with `classifierRoom` (2048) added to a limit below it and asked to reason least (`fitAutoModeClassifier`): none, or the lowest of the model's known levels. A model whose levels magpie doesn't know (a relay's own name, gpt6.1-sol) is asked for none too, as magpie's own ask (`Request.OwnEffort`): left to the vendor, a reasoning model reasoned at its default past the 60 seconds and every classifier request ended 499 (CyberCaius on Discord). Its 400 to that effort (`ownEffortRefused`) is asked again at low when it named the level, and without the effort when it named the field ("Unrecognized request argument supplied: reasoning_effort"), remembered in `unfit` until magpie restarts (`TestAutoModeClassifierReasonsLeastOnAnUnknownModel`, `TestAutoModeClassifierEffortRefusedGoesWithout`).
- Claude Code's billing line (`x-anthropic-billing-header: cc_version=…; cc_entrypoint=…; cch=…;`, its own first system block, `cch` changing every turn) goes on only to a Claude model asked on Anthropic's Messages API (`keepsBillingLine` in [`billing_line.go`](../../internal/gateway/billing_line.go): Anthropic's, a relay's, Bedrock's), as Claude Code sent it. Anywhere else it is left out, the rest of the system as sent (`withoutBillingLine`): a vendor's model relayed on Messages (`passthrough`), every translation to Chat, Responses or Gemini (`forwardTranslated`, Claude models too). Kept, a vendor read it as the prompt's first words and its prefix cache missed from byte 0 every turn (#1600, justrun1983: 4% read from DeepSeek's cache behind Command Code's plan). The Claude subscription's run sends its own (`withoutBillingHeader`), another magpie decides for the provider it picks, and Code Assist (Antigravity, Gemini CLI) is sent it as before, which `antigravityTurnsAway` reads (#666). Once Antigravity has turned such a request away, for `agForeseeing` (6 hours) after, a candidate loop with someone left after an Antigravity account skips it for a request that carries the line, without asking it (`antigravityForeseen`, #2156: each Claude Desktop turn waited about a second on the same refusal before the next member). The skip goes in `Fallback` with the hint, nothing rests, and the agent is told the refusal if nobody after it answers but with a quota. The last one left is still asked, and an old refusal foresees nothing, so a block Google lifts is noticed (`TestAntigravityTurnedAwayIsForeseen`).
- Claude Code's advisor (`/advisor`, `--advisor`) is Anthropic's server tool `advisor_20260301`, its `model` named as Claude Code names its own: on magpie, by magpie's id (the tier an alias like `opus` is on), which no vendor knows, so the request was turned away whole (JackChou on Discord). Relayed on Messages (`passthrough`), the advisor's model goes as the upstream's own name for it when it is the same provider's Claude model, or a Claude id naming no provider (`advisorTools` in [`advisor.go`](../../internal/gateway/advisor.go)); one it can't run there (another provider's, a group, not Claude's) is left out, as is every advisor when the request's own model isn't a Claude model (a vendor's Messages API knows no such tool), and the turn is answered without one. A translation drops it with every other server tool. Claude Code (2.1.300) also puts the advisor in the conversation: a `{role: "system"}` message whose text ends in its instructions ("# Advisor Tool … call advisor BEFORE substantive work") and a `tool_addition` naming it. Where the advisor is left out, that `tool_addition` goes too (and a message it leaves empty), and the instructions become Claude Code's own "The advisor tool is no longer available; disregard the earlier advisor instructions." (`withoutAdvisor` on Messages, `advisorGoneIn` in `parseAnthropic` for a translation): left there, the model called `advisor()` as one of the agent's tools and Claude Code answered "No such tool available: advisor" (JackChou on Discord). The Claude subscription's run declares only magpie's tools, so it never has one. `TestAdvisorModelAsTheUpstreamNamesIt`, `TestAdvisorLeftOutOnTranslation`.
- Kiro is told where to cache the prompt (plugins#110: a Kiro subscription read 0 from its cache). Its API takes Bedrock's `cachePoint: {"type":"default"}` on a `userInputMessage`, an `assistantResponseMessage` or as a tool entry. The built-in (`buildKiro` in [`kiro.go`](../../internal/gateway/kiro.go)) marks the first message when there is a system prompt, which it folds into that message, and the current message, as `buildAnthropic` marks Anthropic's. A moved Kiro's plugin (opencode-kiro-auth 0.1.10, the mover's `min`) turns each `cache_control` in the Anthropic body it is handed into one, at most 4, the last kept.
diff --git a/internal/gateway/automode.go b/internal/gateway/automode.go
index 81f06da93..e228d03f2 100644
--- a/internal/gateway/automode.go
+++ b/internal/gateway/automode.go
@@ -2,6 +2,7 @@ package gateway
import (
"bytes"
+ "regexp"
"slices"
"strings"
@@ -145,8 +146,15 @@ func hasReply(msgs []Message) bool {
// fitAutoModeClassifier asks a model that isn't Claude, for Claude Code's
// auto mode classifier, to reason least — none when it can go without, its
-// lowest level otherwise, left to the vendor when its levels aren't known —
-// with room for that reasoning and the verdict.
+// lowest level otherwise — with room for that reasoning and the verdict.
+// A model whose levels aren't known (one on a relay the user added, under
+// the relay's own name for it) is asked for none too, as magpie's own ask
+// (OwnEffort): left to the vendor, a model that reasons did so at its
+// default over the whole policy and transcript, and Claude Code, which
+// waits 60 seconds an attempt for the verdict (2.1.310), closed the
+// request first (CyberCaius on Discord: every classifier request 499 on
+// a new-api relay's gpt6.1-sol). One that turns none away is asked at
+// low, and one that takes no effort at all without it (forwardTranslated).
func fitAutoModeClassifier(p provider.Provider, model string, req *Request) {
if anthropicModel.MatchString(model) || !autoModeClassifier(req) {
return
@@ -157,10 +165,43 @@ func fitAutoModeClassifier(p provider.Provider, model string, req *Request) {
if req.Effort == "" {
if levels := p.Efforts(model); len(levels) > 0 {
req.Effort = fitEffort("none", levels)
+ } else {
+ req.Effort, req.OwnEffort = "none", true
}
}
}
+// ownEffortField is the effort magpie added (OwnEffort), remembered in
+// unfit for a model whose upstream turned the field away.
+func ownEffortField(model string) string { return "own effort\x00" + model }
+
+var (
+ // effortFieldUnknown is an upstream that doesn't know the effort's
+ // field: OpenAI's "Unrecognized request argument supplied:
+ // reasoning_effort", a validator's "Extra inputs are not permitted"
+ effortFieldUnknown = regexp.MustCompile(`(?i)(?:unrecogni[sz]ed|unknown|unsupported|unexpected|extra)\s+(?:request\s+)?(?:argument|parameter|field|property|name|key)s?(?:\s+supplied)?\W{0,4}reasoning(?:[._]effort)?\b|\breasoning(?:[._]effort)?['"\x60]?\W{0,4}(?:extra inputs are not permitted|is not (?:supported|allowed|permitted)|unsupported)`)
+)
+
+// ownEffortRefused reads a 400 to the effort magpie added (OwnEffort) as
+// turned away, and whether it was the level sent (value) rather than the
+// field. Anything else is the request's own fault and reaches the client.
+func ownEffortRefused(status int, body []byte, sent string) (refused, value bool) {
+ if !badRequest(status) || sent == "" {
+ return false, false
+ }
+ _, named := effortRefused(body, sent)
+ if !named && !effortFieldUnknown.Match(body) {
+ return false, false
+ }
+ low := strings.ToLower(string(body))
+ for _, q := range []string{"'", `"`, "`", `\"`} {
+ if strings.Contains(low, q+sent+q) {
+ return true, true
+ }
+ }
+ return true, false
+}
+
// autoModeClassifierBody is fitAutoModeClassifier for a request relayed to
// 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.
diff --git a/internal/gateway/automode_test.go b/internal/gateway/automode_test.go
index 34df3b1f7..ff38d73fe 100644
--- a/internal/gateway/automode_test.go
+++ b/internal/gateway/automode_test.go
@@ -106,8 +106,9 @@ func TestAutoModeClassifierOnAReasoningModel(t *testing.T) {
}
}
-// With its levels unknown, the reasoning is left to the vendor, but the
-// room is given all the same; a conversation's own turn is left alone.
+// With its levels unknown, the room is given all the same, and the model
+// asked for none (TestAutoModeClassifierReasonsLeastOnAnUnknownModel); a
+// 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}}}`)}
@@ -117,14 +118,15 @@ func TestAutoModeClassifierOnlyTheClassifier(t *testing.T) {
}
var asked map[string]any
json.Unmarshal(f.got, &asked)
- if asked["max_output_tokens"] != float64(64+classifierRoom) || asked["reasoning"] != nil {
+ if r, _ := asked["reasoning"].(map[string]any); asked["max_output_tokens"] != float64(64+classifierRoom) || r["effort"] != "none" {
t.Errorf("unknown levels: %s", f.got)
}
if code, body := post(t, "/v1/messages", `{"model":"m1","max_tokens":64,"thinking":{"type":"disabled"},"system":"be brief","messages":[{"role":"user","content":"a title for this"}]}`); code != 200 {
t.Fatalf("%d %s", code, body)
}
+ asked = nil
json.Unmarshal(f.got, &asked)
- if asked["max_output_tokens"] != float64(64) {
+ if asked["max_output_tokens"] != float64(64) || asked["reasoning"] != nil {
t.Errorf("a title ask was changed: %s", f.got)
}
}
@@ -823,3 +825,162 @@ func TestClaudeBridgeSafeguardConcurrentHandoff(t *testing.T) {
t.Fatal("claim not released at segment end")
}
}
+
+// classifierAsk is auto mode's first stage as Claude Code 2.1.310 sends
+// it to a model it doesn't know: no stream (a sideQuery), stopping at
+// </block>, thinking turned off and 64 tokens, or (thinking left out)
+// 64 and 2048 more for a model that can't turn it off.
+func classifierAsk(model string, off bool) string {
+ thinking, tokens := `"thinking":{"type":"disabled"},`, "64"
+ if !off {
+ thinking, tokens = "", "2112"
+ }
+ return `{"model":"` + model + `","max_tokens":` + tokens + `,"temperature":0,` + thinking + `
+ "system":[{"type":"text","text":"You are a security monitor for an autonomous coding agent.\n## Output Format\nAnswer <block>yes</block> to block the action, else <block>no</block>."}],
+ "stop_sequences":["</block>"],
+ "messages":[{"role":"user","content":[{"type":"text","text":"<transcript>\nUser: tidy up the build\nAction: Bash rm -rf build/\n</transcript>\n"}]}]}`
+}
+
+// classifierUpstream is a fake upstream for proto answering the
+// classifier's "no".
+func classifierUpstream(t *testing.T, proto provider.Protocol) *fake {
+ if proto == provider.Responses {
+ return &fake{t: t, reply: sse(
+ `event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","model":"gpt6.1-sol","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":"gpt6.1-sol","status":"completed","usage":{"input_tokens":4,"output_tokens":2}}}`)}
+ }
+ return &fake{t: t, reply: sse(
+ `data: {"id":"c1","model":"gpt6.1-sol","choices":[{"delta":{"role":"assistant","content":"<block>no"}}]}`,
+ `data: {"id":"c1","choices":[{"delta":{},"finish_reason":"stop"}]}`,
+ `data: [DONE]`)}
+}
+
+// askedEffort is the reasoning effort an upstream request for proto asked.
+func askedEffort(proto provider.Protocol, body []byte) any {
+ var up map[string]any
+ json.Unmarshal(body, &up)
+ if proto == provider.Responses {
+ r, _ := up["reasoning"].(map[string]any)
+ return r["effort"]
+ }
+ return up["reasoning_effort"]
+}
+
+// classifierProvider saves an OpenAI-compatible relay the user added by
+// its address, serving gpt6.1-sol, a model whose levels magpie doesn't
+// know, on proto (CyberCaius on Discord: a new-api relay).
+func classifierProvider(t *testing.T, proto provider.Protocol, f *fake) {
+ t.Helper()
+ noRests()
+ t.Cleanup(noRests)
+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+ t.Setenv("XDG_CACHE_HOME", t.TempDir())
+ up := httptest.NewServer(f)
+ t.Cleanup(up.Close)
+ p := provider.Provider{ID: "relay", Name: "Relay", Key: "k", Models: []string{"gpt6.1-sol"}}
+ if proto == provider.Responses {
+ p.Responses = up.URL + "/v1"
+ } else {
+ p.Chat = up.URL + "/v1"
+ }
+ if err := provider.Save(p); err != nil {
+ t.Fatal(err)
+ }
+ if levels := p.Efforts("gpt6.1-sol"); len(levels) > 0 {
+ t.Fatalf("levels known: %v", levels)
+ }
+}
+
+// askClassifier sends Claude Code's classifier ask to s, as Claude Code does:
+// waiting for the whole reply.
+func askClassifier(t *testing.T, s *Server, body string) (int, string) {
+ t.Helper()
+ rec := httptest.NewRecorder()
+ s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)))
+ return rec.Code, rec.Body.String()
+}
+
+// Auto mode's classifier waits 60 seconds for its verdict (Claude Code
+// 2.1.310, per attempt). A reasoning model whose levels magpie doesn't
+// know, asked with no effort, reasoned at its vendor's default over the
+// whole policy and transcript, past those 60 seconds, and Claude Code
+// closed the request (CyberCaius on Discord: every classifier request
+// ended 499 on a new-api relay's gpt6.1-sol). It is asked to reason
+// least, whether Claude Code turned thinking off or left it out.
+func TestAutoModeClassifierReasonsLeastOnAnUnknownModel(t *testing.T) {
+ for _, proto := range []provider.Protocol{provider.Chat, provider.Responses} {
+ for _, off := range []bool{true, false} {
+ t.Run(fmt.Sprintf("%s/off=%v", proto, off), func(t *testing.T) {
+ f := classifierUpstream(t, proto)
+ classifierProvider(t, proto, f)
+ code, body := askClassifier(t, New(), classifierAsk("relay/gpt6.1-sol", off))
+ if code != 200 || !saidNo(body) {
+ t.Fatalf("%d %s", code, body)
+ }
+ if got := askedEffort(proto, f.got); got != "none" {
+ t.Errorf("effort %v, want none: %s", got, f.got)
+ }
+ })
+ }
+ }
+}
+
+// The effort magpie adds is its own ask, not the client's: an upstream
+// that takes no none is asked at low, one that takes no reasoning effort
+// at all is asked without it, as it was before, and each is remembered,
+// so the next classifier ask goes once.
+func TestAutoModeClassifierEffortRefusedGoesWithout(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ proto provider.Protocol
+ refuse func(effort any) string
+ want any
+ }{{
+ name: "levels named",
+ proto: provider.Chat,
+ refuse: func(e any) string {
+ return map[bool]string{true: `{"error":{"message":"Invalid value: 'none'. Supported values are: 'low', 'medium', and 'high'.","param":"reasoning_effort"}}`}[e == "none"]
+ },
+ want: "low",
+ }, {
+ name: "chat field unknown",
+ proto: provider.Chat,
+ refuse: func(e any) string {
+ return map[bool]string{true: `{"error":{"message":"Unrecognized request argument supplied: reasoning_effort","type":"invalid_request_error"}}`}[e != nil]
+ },
+ want: nil,
+ }, {
+ name: "responses field unsupported",
+ proto: provider.Responses,
+ refuse: func(e any) string {
+ return map[bool]string{true: `{"error":{"message":"Unsupported parameter: 'reasoning.effort' is not supported with this model.","param":"reasoning.effort"}}`}[e != nil]
+ },
+ want: nil,
+ }} {
+ t.Run(tc.name, func(t *testing.T) {
+ f := classifierUpstream(t, tc.proto)
+ f.refuse = func(body []byte) (int, string) {
+ if msg := tc.refuse(askedEffort(tc.proto, body)); msg != "" {
+ return 400, msg
+ }
+ return 0, ""
+ }
+ classifierProvider(t, tc.proto, f)
+ s := New()
+ for i := range 2 {
+ f.calls = 0
+ code, body := askClassifier(t, s, classifierAsk("relay/gpt6.1-sol", true))
+ if code != 200 || !saidNo(body) {
+ t.Fatalf("ask %d: %d %s", i, code, body)
+ }
+ if got := askedEffort(tc.proto, f.got); got != tc.want {
+ t.Errorf("ask %d: effort %v, want %v: %s", i, got, tc.want, f.got)
+ }
+ if i == 1 && f.calls != 1 {
+ t.Errorf("the next ask took %d requests, want 1", f.calls)
+ }
+ }
+ })
+ }
+}
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index 9fb97de7c..a7c418aee 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -5123,6 +5123,10 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
r := *req
r.LoadedInPlace, req = want, &r
}
+ if req.OwnEffort && req.Effort != "" && !s.fits(p.ID, ownEffortField(model), to) {
+ r := *req
+ r.Effort, req = "", &r
+ }
if offEffort(req.Effort) && !s.fits(p.ID, offRefused(model), to) {
r := *req
r.Effort, req = onEffort(p, model), &r
@@ -5398,6 +5402,24 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
continue
}
}
+ if req.OwnEffort {
+ if refused, value := ownEffortRefused(res.StatusCode, b, req.Effort); refused {
+ // the effort magpie added for auto mode's classifier
+ // (fitAutoModeClassifier) turned away: none, by a model
+ // that reasons, is asked again at low; any other refusal,
+ // the field's, without it, as before. Remembered either way
+ r := *req
+ if value && offEffort(req.Effort) {
+ s.markUnfit(p.ID, offRefused(model), to)
+ r.Effort = onEffort(p, model)
+ } else {
+ s.markUnfit(p.ID, ownEffortField(model), to)
+ r.Effort = ""
+ }
+ req = &r
+ continue
+ }
+ }
if p.IsVertex() && res.StatusCode == http.StatusBadRequest && vertexSignatureRefused.Match(b) {
// a call's signature Vertex AI won't take (a client changed
// it, or another API gave it, the conversation having moved):
diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go
index 0cc785894..7359d837f 100644
--- a/internal/gateway/ir.go
+++ b/internal/gateway/ir.go
@@ -194,6 +194,12 @@ type Request struct {
// built); one that turns the field away is asked again without it
// (optionalFields)
OwnTier bool
+ // OwnEffort is set when Effort is magpie's own ask, not the client's:
+ // auto mode's classifier asked to reason least of a model whose levels
+ // aren't known (fitAutoModeClassifier). An upstream that turns it away
+ // is asked at low, or without it, as it would have been
+ // (ownEffortRefused)
+ OwnEffort bool
// CacheKey is the client's prompt_cache_key (Codex sends its thread's
// id), which OpenAI, and relays in front of it, route a conversation by
// to where its prompt is cached.