diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 743628e07..bf5446008 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -137,6 +137,7 @@ recorded as a prediction failure (`noPrediction`). - 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 (Anthropic's API, a relay, Bedrock, Vertex), and anything on `api.anthropic.com`. 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). - 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), and the subscriptions asked through their own clients' APIs (Cursor, Devin, Kiro, Qoder, Zed, Command Code's Go plan, in `attempt`). 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). +- 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. The Claude subscription's run declares only magpie's tools, so it never has one. `TestAdvisorModelAsTheUpstreamNamesIt`. - 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. - A model that refuses a conversation ending with the assistant's message (`refusesPrefill`: OpenCode Go's Claude models over Messages, "This model does not support assistant message prefill"; Volcengine's Agent Plan, "…for a model that does not support prefill"; Gemini's, "Requests ending with a model turn are not supported") is marked for that provider, model and API (`prefillRefused`, #1447); the provider's other models keep their prefill ([`prefill.go`](../../internal/gateway/prefill.go)). A Chat or Responses client's conversation ending with the assistant's message, which those APIs read as a turn already said (`Request.LastIsTurn`), is asked again with a user turn after it (`continueText`), translated (`forwardTranslated`) or relayed (`passthrough`, `userLastBody`), and so from then on. An Anthropic client's prefill is its own ask and gets the refusal as sent. magpie's own continuation of a cut reply (`continuation.go`) isn't asked of that model again; the try the model refused ends the reply with what cut it, not with the refusal. A request magpie builds in Gemini's own shape (`buildCodeAssistSent`: Vertex AI, Gemini CLI's and Antigravity's Code Assist, Factory) never ends with the model's turn, which all of them turn away: a user turn goes after it, `continueText`, or `compactLastText` when an agent is compacting with its ask in the system prompt (`modelLastAsk`), as one goes before a history that opens with the model's. Nor does it send a user turn that mixes a tool's `functionResponse` with text, which Vertex AI answers with the same "ending with a model turn" (#1533: Codex's compaction prompt after a tool's output): what the user said goes in a user turn of its own after the tools' responses (`hasResponse`), except for a Claude model on Antigravity, whose tool_result turn holds both. - A tool's `strict` that an upstream turns away (`toolStrictRefusal` in [`strict_refused.go`](../../internal/gateway/strict_refused.go): "Unsupported Chat Completions API field: tools[0].function.strict", OpenAI-style unknown_parameter, "Extra inputs are not permitted" and pydantic's extra_forbidden on it) is asked once more without it, in Chat's `tools[].function` and Responses' `tools[]` alike, and marked for that provider and API (`toolStrictRefused`): its next requests go without it at once. OpenCode 2 sends `"strict": false` on every tool through `@ai-sdk/openai-compatible`, and a custom provider that refused it ended the session (#1980). An upstream that hasn't refused it still gets it, as the ChatGPT backend needs it (#383). `TestToolStrictLeftOutWhereRefused` (real OpenCode 2.0.25 requests), `TestToolStrictRefusalWordings`. diff --git a/internal/gateway/advisor.go b/internal/gateway/advisor.go new file mode 100644 index 000000000..0352cbee1 --- /dev/null +++ b/internal/gateway/advisor.go @@ -0,0 +1,98 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "strings" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +// advisorTools fits Claude Code's advisor (/advisor, --advisor) to the +// upstream a Messages request goes to as it is (passthrough). Claude Code +// declares it as Anthropic's server tool, {"type": "advisor_20260301", +// "name": "advisor", "model": …}, and names the advisor's model as it +// names its own: on magpie, by magpie's id ("anthropic/claude-opus-5-5", +// or the tier an alias like opus is on), which no vendor knows, so the +// whole request was turned away (JackChou on Discord). +// +// The advisor runs at the vendor, on the same account: its model goes as +// that upstream's own name for it when it is p's, as the request's own +// model does (wires). An advisor magpie can't give that upstream (another +// provider's model, or not a Claude model) is left out, and so is every +// advisor when the request's model is not Claude's (a vendor's Messages +// API knows no such tool): the turn is answered without one, as a model +// that isn't on magpie would be. +func advisorTools(body []byte, p provider.Provider, upstream string, wires map[string]string) []byte { + if !bytes.Contains(body, []byte(`"advisor_`)) { + return body + } + tools := gjson.GetBytes(body, "tools") + if !tools.IsArray() { + return body + } + var top map[string]json.RawMessage + var list []map[string]json.RawMessage + if json.Unmarshal(body, &top) != nil || json.Unmarshal([]byte(tools.Raw), &list) != nil { + return body + } + claude := anthropicModel.MatchString(upstream) + changed := false + kept := list[:0] + for _, t := range list { + var typ, model string + json.Unmarshal(t["type"], &typ) + if !strings.HasPrefix(typ, "advisor_") { + kept = append(kept, t) + continue + } + json.Unmarshal(t["model"], &model) + name, ok := advisorModel(p, model, wires) + if !claude || !ok { + changed = true + continue + } + if name != model { + t["model"], _ = json.Marshal(name) + changed = true + } + kept = append(kept, t) + } + if !changed { + return body + } + if len(kept) == 0 { + delete(top, "tools") + delete(top, "tool_choice") + } else { + top["tools"], _ = json.Marshal(kept) + } + out, err := json.Marshal(top) + if err != nil { + return body + } + return out +} + +// advisorModel is the name p's upstream knows the advisor model by, and +// whether p can run it: one of p's models, by magpie's id, or a Claude +// model's own id that names no provider. +func advisorModel(p provider.Provider, model string, wires map[string]string) (string, bool) { + model = strings.TrimSuffix(strings.TrimSpace(model), "[1m]") + if model == "" { + return "", false + } + if q, m, ok := provider.Resolve(model); ok && !strings.HasPrefix(model, provider.GroupPrefix) { + if q.ID != p.ID { + return "", false + } + name := provider.UpstreamNameIn(wires, p.ID, m) + return name, anthropicModel.MatchString(name) + } + if strings.Contains(model, "/") { + return "", false + } + return model, anthropicModel.MatchString(model) +} diff --git a/internal/gateway/advisor_test.go b/internal/gateway/advisor_test.go new file mode 100644 index 000000000..af8c03269 --- /dev/null +++ b/internal/gateway/advisor_test.go @@ -0,0 +1,71 @@ +package gateway + +import ( + "strings" + "testing" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +// advisorTurn is a Claude Code turn with its advisor on, the tool as +// Claude Code 2.1.299 declares it (read from its request to a fake +// ANTHROPIC_BASE_URL, --advisor opus with the opus tier on magpie's id). +func advisorTurn(model, advisor string) string { + return `{"model":"` + model + `","max_tokens":64,"stream":true,` + + `"messages":[{"role":"user","content":"hi"}],` + + `"tools":[{"name":"Read","description":"read a file","input_schema":{"type":"object","properties":{"path":{"type":"string"}}}},` + + `{"type":"advisor_20260301","name":"advisor","model":"` + advisor + `","defer_loading":true}]}` +} + +// Claude Code's advisor names its model as Claude Code names its own: on +// magpie, by magpie's id, which the vendor doesn't know, so the request was +// turned away whole and the advisor never ran (JackChou on Discord). The +// advisor's model now goes as the upstream's own name for it when it is +// the same provider's Claude model; one the upstream can't run (another +// provider's, a vendor's model asked) is left out and the turn still +// answered. +func TestAdvisorModelAsTheUpstreamNamesIt(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + u, url := newBillingUpstream(t) + for _, p := range []provider.Provider{ + {ID: "relay", Name: "Relay", Key: "k", Anthropic: url, Models: []string{"claude-opus-5-5", "claude-sonnet-5-5"}}, + {ID: "other", Name: "Other", Key: "k", Anthropic: url, Models: []string{"claude-opus-5-5"}}, + {ID: "ds", Name: "DeepSeek", Key: "k", Anthropic: url, Models: []string{"deepseek-v4.1-flash"}}, + } { + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + } + advisors := func(b string) []string { + var out []string + for _, t := range gjson.Get(b, "tools").Array() { + if strings.HasPrefix(t.Get("type").String(), "advisor_") { + out = append(out, t.Get("model").String()) + } + } + return out + } + for _, c := range []struct { + name, model, advisor, want string // want "" = left out + }{ + {"same provider", "relay/claude-sonnet-5-5", "relay/claude-opus-5-5", "claude-opus-5-5"}, + {"1M mark", "relay/claude-sonnet-5-5", "relay/claude-opus-5-5[1m]", "claude-opus-5-5"}, + {"Claude's own id", "relay/claude-sonnet-5-5", "claude-opus-5-5", "claude-opus-5-5"}, + {"another provider", "relay/claude-sonnet-5-5", "other/claude-opus-5-5", ""}, + {"a vendor's model", "ds/deepseek-v4.1-flash", "relay/claude-opus-5-5", ""}, + } { + claudeCodeSends(t, advisorTurn(c.model, c.advisor)) + b := u.last(t) + got := advisors(b) + switch { + case c.want == "" && len(got) != 0, c.want != "" && (len(got) != 1 || got[0] != c.want): + t.Errorf("%s: advisor sent as %q, want %q: %s", c.name, got, c.want, b) + } + if !strings.Contains(b, `"name":"Read"`) { + t.Errorf("%s: the agent's own tool lost: %s", c.name, b) + } + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index c8c8fcd0e..e6bb2de67 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3675,6 +3675,8 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. geminiWhole = !streamOf(body) body = withoutFields(body, "stream") case provider.Anthropic: + // Claude Code's advisor, named by magpie's id (advisor.go) + body = advisorTools(body, p, upstream, wiresOf(r.Context())) if p.IsBedrock() { // Claude Code's metadata.user_id, a JSON string these days, is // not the plain id Bedrock checks it against (#176)