Skip to content

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

gateway: a client's reasoning effort "off" is magpie's none (plugins#334)

yetone56418ac5cb86
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index 4b9f72473..11d2ebaf0 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -89,6 +89,7 @@ recorded as a prediction failure (`noPrediction`).
- A model set for Claude Desktop's subagents (`settings.DesktopSubagentModel`, the Agents page's Claude Desktop "subagent model") is put on a subagent's turn in Desktop's Code tab or Cowork after `desktopTurn`, the tiers and the groups, whatever model its lead or its tier asked for (`desktopSubagentPick` in [`desktop_subagent.go`](../../internal/gateway/desktop_subagent.go)). Desktop runs its Claude Code with `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST=1`, under which Claude Code ignores the `CLAUDE_CODE_SUBAGENT_MODEL` magpie writes into its settings (see [agent wiring](agent-wiring.md)). A subagent's request is one with `x-claude-code-agent-id` (`subagentOf`) from `claude-desktop`, and only one that offers tools is its turn: Claude Code's tool-less helper calls inside a subagent, on the haiku tier's model, stay where they are, and so do the lead's turns, terminal Claude Code's and every other agent's. The model set must be served by its exact id (`provider.DesktopSubagentUnserved`: `Resolve` takes any model name under a provider that is on), enabled, and allowed to a gateway key held to some models (`groupAllowed` for a group); otherwise the subagent goes on the model asked for and the route trace says why (`Route.Subagent`, said on the Routing page by `subagentWhy`, its `Kind` staying empty). `Route.Model` and the ledger's `Requested` keep the model the subagent asked for. `count_tokens` counts on the model set the same way (`countTokens`). The setting is read on each request, so a change needs no restart of Desktop, and a provider renamed since it was set is read by its new id (`RenamedRef`). A Desktop on another computer that reaches magpie with a named gateway key is read as Claude Code (`agentOf`), so none of Desktop's routing, this included, applies to it. A subagent's turn, moved or not, is never kept as the session's model in `claude-desktop.model` (`desktopTurn`'s `bySubagent`): a subagent on the opus tier's model took the session's place until the lead's next turn, and Desktop's titles asked for meanwhile went to it.
- Desktop's subagent effort (`settings.DesktopSubagentEffort`, `desktopSubagentEffort` in [`desktop_subagent.go`](../../internal/gateway/desktop_subagent.go)) applies to the same subagent tool turns, independently of model replacement. Empty leaves requests unchanged. Set, it takes the place of a request model's effort suffix before the existing attempt-level effort fitting: a member fixed at an effort wins, then this pick fitted within group/model levels, then the turn's or request's effort. `withFixedEffort` can enable reasoning when it was disabled, or disable it with `none` on a model that supports that level; a reasonless model is still sent no reasoning fields. `countTokens` applies the pick after restoring any unmasked body. `Route.Effort` keeps the incoming effort, `Route.SubagentEffort` the configured pick, and each try and usage record the level actually sent; the Routing story explains the configured pick even when no model was replaced. A nonempty model pick already classifies the turn, so the effort check reuses it; empty effort costs only a held-settings read. The next request takes a changed or cleared effort without a Desktop restart.
- Every Claude Code subagent's turn, Desktop's or a terminal's, moved or not, keeps its `x-claude-code-agent-id` in `Route.SubagentID` (`subagentTurnOf` in [`desktop_subagent.go`](../../internal/gateway/desktop_subagent.go)): a request with the id that offers tools and names no kind, the turn the two settings above take. Claude Code 2.1.295 sends the id from any agent context but the main one; its `x-claude-code-request-class` and `x-claude-code-agent-type` hints go only to a first-party base URL or with `CLAUDE_CODE_GATEWAY_HINT_HEADERS`, so magpie doesn't get them. A Desktop pick or effort that found the turn is trusted, so the body isn't decoded again, and a request without the id isn't decoded at all. The Routing page tags it as Codex's subagents are (`tagKind` in [`routing.js`](../../internal/gui/assets/routing.js)): in the request list, the story, the replay and the tray panel, with the reason `kindWhy` gives Codex's. `Kind` stays empty, so its purpose stays unmarked in the Purpose filter, as in the ledger and on the Usage page. The ledger's `Subagent` keeps the same id, and also marks a subagent's tool-less helper calls, which aren't tagged. A route recorded before this has no id and no tag.
+ - A Chat or Responses client's effort spelled `off` (`reasoning_effort`, or `reasoning.effort`, any case) is read at the top of `serve` as magpie's own off level, `none` (`offAsNone`, plugins#334), and a model asked `<model>:off` as `<model>:none` (`askedAt`): every check and route below reads `none`, a model with an off level is sent its own spelling of it, and one without goes at its least level as `none` asked does (`fitEffort`). `off` itself is never sent on. `saysOff` looks for it without parsing the body, which only a body naming it pays for.
- Rules and image inputs are handled here too.
- A rule is decided as a user's turn begins and held for the rest of it (`ruleFor`, [`rules.go`](../../internal/gateway/rules.go)). What counts as the user's own words is one helper, `userWords`/`userSaid` in [`prompt.go`](../../internal/gateway/prompt.go), which the turn count (`turnIn`), the classifier's question (`userText`), the conversation's key (`firstWords`, in `ruleKey` and the affinity scope), Copilot's Auto (`lastUserText`) and the prompt breakdown's turns (`userSays`) all go by. It drops `<system-reminder …>` blocks (a `source=` attribute too) and any text that begins as an agent writes for the model alone: Codex's `<environment_context>`, `<user_instructions>`, `<turn_aborted>`, `<user_shell_command>`, `<subagent_notification>` and `# AGENTS.md instructions for …`; Claude Code's and ZCode's `<task-notification>`, `<subagent-notification>`, agent lists ("Available agent types …", "New agent types are now available …"), TodoWrite and task-tool nudges and rewind notices; ZCode's `<plugin_reference>`; the Codex app's `<in-app-browser-context …>`. The Codex app's context before `## My request (for Codex):` is dropped and what follows it kept (the `injected` list beside `agentsFor`). A user message with nothing of the user's in it (and no image or file) begins no turn: after an answer or a tool round it carries the turn on (`within`), so the turn's rule and stick hold and the classifier isn't asked; right after the user's words it leaves their turn as it began. The classifier is asked about the last user message that has words of the user's, only those words (`userText`: past 4000 runes, its first 3000 and last 1000). It is told what came before it too (`turnBefore`, @HirotaNagai on X: a short follow-up said alone, 继续 or fix that, came out the hardest kind): the user's message before it, the same way and cut to 1000 runes (`priorCap`: the first 750 and the last 250), and the assistant's last reply between the two, its text parts alone and their last 1000 runes. A tool call's arguments, a tool's result, thinking, a search's hits and the system prompt are never in either, and a reply of only tool calls is none. Jev gets them in its `state` as `previous_user_message` and `previous_assistant_reply` beside `message`, `previous_message_kind` and `previous_message_reasoning`, each only when there is one, and its intent, level and effort instructions name the ones there are (`jevState`, `priorAsk` in [`decide.go`](../../internal/gateway/decide.go)); a classifier asked in words gets them in `<previous_user_message>` and `<previous_assistant_reply>` before `<message>` (`writePrior`). Both come from the request the rules parsed, so Privacy masks them as it masks the message, and the answer kept for a message is kept for it with what came before (`classify`'s key). `TestTurnBeforeEachProtocol`, `TestTurnBeforeCuts`, `TestJevIsToldWhatCameBefore`, `TestChatClassifierIsToldWhatCameBefore`, `TestClassifyKeepsAnAnswerPerTurnBefore`, `TestJevSeesTheTurnBefore`. `firstWords` hashes the words of the first user message that has any, so an instruction file or notice the agent changes beside them doesn't move the conversation to a new key and lose its stick mid-turn (#1826: ZCode's TodoWrite nudge classified as a new, harder turn, and three keys for one ZCode session). `TestTurnInSkipsWhatTheAgentPutIn`, `TestUserTextSkipsWhatTheAgentPutIn`, `TestFirstWordsAreWhatTheUserSaid`, `TestIntentHoldsPastWhatTheAgentPutIn`.
- A rule's members go first (`ruleOver`, `applyRule`): the member it names, then those the matching rules after it name (`ruleOrder`), each not resting, then the group's others to fail over to. A member that is a group in the group is one member here: its models keep the order the group's own routing planned them, where ranking each by the group's listed order pinned a rotate group's first member on every request the rule put it first (#2407, `TestRuleNamingARotateGroupKeepsItsTurns`). That holds within the turn too, at the group's rule and at each nested group's (`nestedRules`): the one the turn stays on (affinity) stays first while it is of the rule's member that goes first, and the member's others follow it ahead of the group's others, so a failure fails over within the member the rule chose before going outside it. One the turn was kept on outside that member, which took over when the member failed, isn't held there: once one of the member is out of its rest, the turn's next request goes back to it (`Affinity.Why` `rule`). Before #1946 (XcodeFish) a held rule's order wasn't applied to a kept turn at all: a coding-quality member failing mid-turn failed over to coding-fast, the parent's first, and the turn stayed there. `TestHeldRuleFailsOverWithinItsMember`. Two groups in the group may share a model (the same provider, model and effort): it is asked once a request, where the walk met it first, and `provider.Member.Also` keeps its later places, each with its own path, `At` (its place in the walk) and Fast. A rule naming the later group has the model as that group does (`Member.In`, `membersNamed`), in that group's own order, and the nested rules below it, Fast and the first token's wait go by that group's way down (`homed`, `homeCands`). Before #2361 (davisjiahao) such a rule found none of the shared models, read unready, and the group ahead of it answered. A pause rule naming the later group still leaves a shared model to the group ahead of it. `rule_shared_test.go`.
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index 87b90e910..34d80eb43 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -1242,9 +1242,15 @@ func unprefixed(id string) string {
// on (#536) — into the model and the level, "" for none. As a routing
// group's member is read (#189), only a level's name after the last colon is
// one, and a model a provider has by the whole id ("x:high") is taken whole.
+//
+// A level spelled "off" (":off") is none, as a body's effort "off" is
+// (offAsNone).
func askedAt(id string) (string, string) {
bare, marked := strings.CutSuffix(id, "[1m]")
m, e := provider.MemberEffort(bare)
+ if i := strings.LastIndex(bare, ":"); e == "" && i > 0 && strings.EqualFold(bare[i+1:], "off") {
+ m, e = provider.MemberEffort(bare[:i] + ":none")
+ }
if e == "" {
return id, ""
}
@@ -1597,6 +1603,9 @@ func estimate(req *Request) int {
// serve routes one parsed-enough request to its provider.
func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Protocol, body []byte) {
start := time.Now()
+ // a client's "off" is magpie's none, for every route and check below
+ // that reads the body's effort (plugins#334)
+ body = offAsNone(from, body)
// the upstream names in force for this request, read once here rather
// than once per place a name is looked up below
r = withWires(r)
@@ -6553,6 +6562,67 @@ func conversationID(in http.Header, body []byte) string {
return "magpie-" + hex.EncodeToString(sum[:12])
}
+// offSpelled is a client's effort spelled "off", which no OpenAI API
+// takes: a client asking reasoning off by that word (plugins#334, raw
+// reasoning_effort "off" to a Command Code DeepSeek fell back to its lowest
+// level and still thought).
+func offSpelled(e string) bool { return strings.EqualFold(strings.TrimSpace(e), "off") }
+
+// offAsNone is a Chat or Responses body asking reasoning "off"
+// (reasoning_effort, or reasoning.effort) asking for magpie's own off
+// level, none, instead: what every check and route reads the effort by,
+// and what fitEffort fits to the model's own off level, or its least
+// where it has none, as "none" asked is. A body with no such field goes
+// as it came.
+func offAsNone(from provider.Protocol, body []byte) []byte {
+ if from != provider.Chat && from != provider.Responses || !saysOff(body) {
+ return body
+ }
+ var v struct {
+ ReasoningEffort *string `json:"reasoning_effort"`
+ Reasoning map[string]json.RawMessage `json:"reasoning"`
+ }
+ if decodeJSON(body, &v) != nil {
+ return body
+ }
+ fields := map[string]any{}
+ var e string
+ if v.ReasoningEffort != nil && offSpelled(*v.ReasoningEffort) {
+ fields["reasoning_effort"] = "none"
+ }
+ if decodeJSON(v.Reasoning["effort"], &e) == nil && offSpelled(e) {
+ v.Reasoning["effort"] = json.RawMessage(`"none"`)
+ fields["reasoning"] = v.Reasoning
+ }
+ if len(fields) == 0 {
+ return body
+ }
+ return withFields(body, fields)
+}
+
+// saysOff is whether body has an effort field valued "off" anywhere,
+// looked for without parsing it: serve looks at every request's body,
+// however large, and only one naming off is parsed (offAsNone).
+func saysOff(body []byte) bool {
+ key := []byte(`effort"`)
+ for rest := body; ; {
+ i := bytes.Index(rest, key)
+ if i < 0 {
+ return false
+ }
+ rest = rest[i+len(key):]
+ v := bytes.TrimLeft(rest, " \t\r\n")
+ if v, ok := bytes.CutPrefix(v, []byte(":")); ok {
+ v = bytes.TrimLeft(v, " \t\r\n")
+ if s, ok := bytes.CutPrefix(v, []byte(`"`)); ok {
+ if j := bytes.IndexByte(s, '"'); j >= 0 && offSpelled(string(s[:j])) {
+ return true
+ }
+ }
+ }
+ }
+}
+
// offEffort is an effort turning reasoning off, or as near off as asked.
func offEffort(e string) bool { return e == "none" || e == "minimal" }
diff --git a/internal/gateway/plugin_think_off_test.go b/internal/gateway/plugin_think_off_test.go
index 73e18d38f..f5f3da0f5 100644
--- a/internal/gateway/plugin_think_off_test.go
+++ b/internal/gateway/plugin_think_off_test.go
@@ -4,8 +4,11 @@ import (
"encoding/json"
"io"
"net/http"
+ "strings"
"sync"
"testing"
+
+ "github.com/yetone/magpie/internal/provider"
)
// Factory's plugin, as the built-in (TestFactoryThinkingOff): a model whose
@@ -33,6 +36,13 @@ func TestPluginThinkingOff(t *testing.T) {
{"responses none", "/v1/responses", `{"model":"` + pid + `/fake-off","reasoning":{"effort":"none"},"input":[{"role":"user","content":"hi"}]}`, "none"},
{"messages disabled", "/v1/messages", `{"model":"` + pid + `/fake-off","thinking":{"type":"disabled"},"messages":[{"role":"user","content":"hi"}],"max_tokens":8}`, "none"},
{"chat low", "/v1/chat/completions", `{"model":"` + pid + `/fake-off","reasoning_effort":"low","messages":[{"role":"user","content":"hi"}]}`, "low"},
+ // a client's "off" is none (plugins#334), in either API and as a
+ // model's suffix, never sent on as "off" nor as the least level on
+ {"chat off", "/v1/chat/completions", `{"model":"` + pid + `/fake-off","reasoning_effort":"off","messages":[{"role":"user","content":"hi"}]}`, "none"},
+ {"chat OFF spaced", "/v1/chat/completions", `{"model":"` + pid + `/fake-off","reasoning_effort" : " OFF ","messages":[{"role":"user","content":"hi"}]}`, "none"},
+ {"responses off", "/v1/responses", `{"model":"` + pid + `/fake-off","reasoning":{"effort":"off","summary":"auto"},"input":[{"role":"user","content":"hi"}]}`, "none"},
+ {"suffix off", "/v1/chat/completions", `{"model":"` + pid + `/fake-off:off","messages":[{"role":"user","content":"hi"}]}`, "none"},
+ {"no off, off", "/v1/chat/completions", `{"model":"` + pid + `/fake-on","reasoning_effort":"off","messages":[{"role":"user","content":"hi"}]}`, "low"},
{"no off", "/v1/responses", `{"model":"` + pid + `/fake-on","reasoning":{"effort":"none"},"input":[{"role":"user","content":"hi"}]}`, "low"},
} {
t.Run(tt.name, func(t *testing.T) {
@@ -48,3 +58,41 @@ func TestPluginThinkingOff(t *testing.T) {
})
}
}
+
+// TestOffAsNone: only an effort spelled "off" changes, to none; the rest
+// of the body, numbers included, goes as it came, and another level or
+// an "off" that isn't an effort is left alone (plugins#334).
+func TestOffAsNone(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ from provider.Protocol
+ in, want string
+ }{
+ {"chat", provider.Chat, `{"model":"m","reasoning_effort":"off","max_tokens":12345678901}`, `{"max_tokens":12345678901,"model":"m","reasoning_effort":"none"}`},
+ {"responses", provider.Responses, `{"model":"m","reasoning":{"effort":"Off","summary":"auto","max_tokens":4096}}`, `{"model":"m","reasoning":{"effort":"none","max_tokens":4096,"summary":"auto"}}`},
+ {"chat reasoning object", provider.Chat, `{"model":"m","reasoning":{"effort":"off"}}`, `{"model":"m","reasoning":{"effort":"none"}}`},
+ {"low", provider.Chat, `{"model":"m","reasoning_effort":"low"}`, `{"model":"m","reasoning_effort":"low"}`},
+ {"offline", provider.Chat, `{"model":"m","reasoning_effort":"offline"}`, `{"model":"m","reasoning_effort":"offline"}`},
+ {"off in text", provider.Chat, `{"model":"m","messages":[{"role":"user","content":"effort\": \"off\""}]}`, `{"model":"m","messages":[{"role":"user","content":"effort\": \"off\""}]}`},
+ {"anthropic", provider.Anthropic, `{"model":"m","output_config":{"effort":"off"}}`, `{"model":"m","output_config":{"effort":"off"}}`},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ got := strings.TrimSpace(string(offAsNone(tt.from, []byte(tt.in))))
+ if got != tt.want {
+ t.Errorf("offAsNone(%s) = %s, want %s", tt.in, got, tt.want)
+ }
+ })
+ }
+}
+
+// TestAskedAtOff: a model asked ":off" is asked at none, as ":none" is.
+func TestAskedAtOff(t *testing.T) {
+ for _, id := range []string{"group/g:off", "group/g:OFF"} {
+ if m, e := askedAt(id); m != "group/g" || e != "none" {
+ t.Errorf("askedAt(%q) = %q, %q; want group/g, none", id, m, e)
+ }
+ }
+ if m, e := askedAt("group/g:offline"); m != "group/g:offline" || e != "" {
+ t.Errorf("askedAt(group/g:offline) = %q, %q", m, e)
+ }
+}