gateway: an advisor magpie leaves out takes its instructions and tool_addition with it, so the model no longer calls a tool it hasn't got (JackChou on Discord)

JackChou: "claude code 使用 advisor 返回找不到对应工具". Claude Code 2.1.300
(its request read from a fake ANTHROPIC_BASE_URL in a sandbox HOME, with
--advisor and a fake key) declares the advisor as the server tool
{"type":"advisor_20260301","name":"advisor","model":…,"defer_loading":true}
and also puts it in the conversation: a {role:"system"} message whose text
ends in "# Advisor Tool … call advisor BEFORE substantive work", and a
{"type":"tool_addition","tool":{"type":"tool_reference","name":"advisor"}}
block.

79f64f028 left the server tool out where the upstream can't run it (a
vendor's model, another provider's advisor) and every translation drops
server tools, but both left the instructions and the tool_addition in place.
The model was told to call advisor() and given no such tool, so it called it
as one of the agent's tools and Claude Code answered "No such tool
available: advisor"; on Messages the tool_addition also named a tool the
request no longer declared.

Where magpie leaves the advisor out, withoutAdvisor (passthrough) drops the
tool_addition/tool_removal/tool_reference naming it, and a message left
empty, and replaces the instructions (up to the end of their reminder or
text) with Claude Code's own "The advisor tool is no longer available;
disregard the earlier advisor instructions." parseAnthropic does the same to
the text on a translation. An advisor that is kept goes as before.

Run: TestAdvisorModelAsTheUpstreamNamesIt (now on the literal 2.1.300 turn
in testdata/claude-code-advisor-turn.json, environment text cut short) and
the new TestAdvisorLeftOutOnTranslation (chat, responses, gemini). Broken by
hand (withoutAdvisor given no names, parseAnthropic not rewriting): both
red, the two left-out passthrough cases and all three translations; green
restored. go test -tags nogui -p 1 -run
'Advisor|Deferred|BillingLine|Shape|Anthropic|ToolSearch|TurnSystem|Passthrough'
./internal/gateway ok. gofmt -l clean; go vet -tags nogui ./internal/gateway
for GOOS darwin, linux, windows.

Not tried: a running magpie with real Claude Code end to end, and a real
vendor upstream; the reporter's provider and model aren't known, so whether
theirs was the passthrough or a translated route is inferred.

Full suite: SUITE_LINE
This commit is contained in:
yetone
2026-10-15 23:08:05 +08:00
parent 8f55c27ad0
commit b6fae8efd8
5 changed files with 217 additions and 9 deletions
+1 -1
View File
@@ -161,7 +161,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). 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. The Claude subscription's run declares only magpie's tools, so it never has one. `TestAdvisorModelAsTheUpstreamNamesIt`.
- 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.
- 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`.
+126 -1
View File
@@ -24,7 +24,8 @@ import (
// 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.
// that isn't on magpie would be. What Claude Code put in the conversation
// for an advisor left out goes with it (withoutAdvisor).
func advisorTools(body []byte, p provider.Provider, upstream string, wires map[string]string) []byte {
if !bytes.Contains(body, []byte(`"advisor_`)) {
return body
@@ -40,6 +41,7 @@ func advisorTools(body []byte, p provider.Provider, upstream string, wires map[s
}
claude := anthropicModel.MatchString(upstream)
changed := false
gone := map[string]bool{}
kept := list[:0]
for _, t := range list {
var typ, model string
@@ -51,6 +53,9 @@ func advisorTools(body []byte, p provider.Provider, upstream string, wires map[s
json.Unmarshal(t["model"], &model)
name, ok := advisorModel(p, model, wires)
if !claude || !ok {
var n string
json.Unmarshal(t["name"], &n)
gone[n] = true
changed = true
continue
}
@@ -69,6 +74,9 @@ func advisorTools(body []byte, p provider.Provider, upstream string, wires map[s
} else {
top["tools"], _ = json.Marshal(kept)
}
if m, ok := withoutAdvisor(top["messages"], gone); ok {
top["messages"] = m
}
out, err := json.Marshal(top)
if err != nil {
return body
@@ -96,3 +104,120 @@ func advisorModel(p provider.Provider, model string, wires map[string]string) (s
}
return model, anthropicModel.MatchString(model)
}
// advisorNote opens the instructions Claude Code puts in the conversation
// when its advisor is on ("# Advisor Tool\n\nYou have access to an
// `advisor` tool … Call advisor BEFORE substantive work"), at the end of a
// {role: "system"} message's text (2.1.300), and advisorGone is what Claude
// Code itself says there once the advisor is turned off.
const (
advisorNote = "# Advisor Tool\n"
advisorGone = "The advisor tool is no longer available; disregard the earlier advisor instructions."
)
// advisorGoneIn is text with the advisor's instructions, up to the end of
// the reminder they are in or of the text, said to be void as Claude Code
// says it, and whether it held them.
func advisorGoneIn(text string) (string, bool) {
i := strings.Index(text, advisorNote)
if i < 0 {
return text, false
}
end := len(text)
if j := strings.Index(text[i:], "</system-reminder>"); j >= 0 {
end = i + j
}
note := text[i:end]
trail := note[len(strings.TrimRight(note, " \t\r\n")):]
return text[:i] + advisorGone + trail + text[end:], true
}
// withoutAdvisor is a Messages request's messages without what Claude Code
// put there for an advisor tool that is left out, named in gone: the
// tool_addition (or tool_removal, tool_reference) naming it, and a message
// that leaves empty; and its instructions, said to be void (advisorGoneIn).
// Left there, the reference named a tool the request no longer has, and
// the instructions had the model call advisor() as one of the agent's own
// tools, which Claude Code answers "No such tool available: advisor"
// (JackChou on Discord).
func withoutAdvisor(raw json.RawMessage, gone map[string]bool) (json.RawMessage, bool) {
if len(gone) == 0 || !bytes.Contains(raw, []byte("dvisor")) {
return raw, false
}
var msgs []map[string]json.RawMessage
if json.Unmarshal(raw, &msgs) != nil {
return raw, false
}
changed := false
out := msgs[:0]
for _, m := range msgs {
var s string
if json.Unmarshal(m["content"], &s) == nil {
if t, ok := advisorGoneIn(s); ok {
m["content"], _ = marshalPlain(t)
changed = true
}
out = append(out, m)
continue
}
var blocks []map[string]json.RawMessage
if json.Unmarshal(m["content"], &blocks) != nil {
out = append(out, m)
continue
}
moved := false
kept := blocks[:0]
for _, b := range blocks {
var typ string
json.Unmarshal(b["type"], &typ)
if deferredBlock(typ) && gone[advisorRefName(b)] {
moved = true
continue
}
var text string
if typ == "text" && json.Unmarshal(b["text"], &text) == nil {
if t, ok := advisorGoneIn(text); ok {
b["text"], _ = marshalPlain(t)
moved = true
}
}
kept = append(kept, b)
}
if !moved {
out = append(out, m)
continue
}
changed = true
if len(kept) == 0 {
continue // it said only that the advisor came or went
}
m["content"], _ = marshalPlain(kept)
out = append(out, m)
}
if !changed {
return raw, false
}
b, err := marshalPlain(out)
if err != nil {
return raw, false
}
return b, true
}
// advisorRefName is the tool a deferred-tool block names: a tool_addition's
// or tool_removal's tool, or a tool_reference's own name.
func advisorRefName(b map[string]json.RawMessage) string {
var n string
if t, ok := b["tool"]; ok {
var tool map[string]json.RawMessage
if json.Unmarshal(t, &tool) == nil {
json.Unmarshal(tool["name"], &n)
}
return n
}
if json.Unmarshal(b["name"], &n) == nil && n != "" {
return n
}
json.Unmarshal(b["tool_name"], &n)
return n
}
+78 -7
View File
@@ -1,6 +1,7 @@
package gateway
import (
"os"
"strings"
"testing"
@@ -9,14 +10,17 @@ import (
"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).
// advisorTurn is a Claude Code turn with its advisor on, as Claude Code
// 2.1.300 sends it (read from its request to a fake ANTHROPIC_BASE_URL in
// a sandbox HOME, --advisor; the environment text cut short, the agent's
// tools but Read left out): the server tool, and a {role: "system"} message
// holding the advisor's instructions and a tool_addition naming it.
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}]}`
b, err := os.ReadFile("testdata/claude-code-advisor-turn.json")
if err != nil {
panic(err)
}
return strings.NewReplacer(`"MODEL"`, `"`+model+`"`, `"ADVISOR"`, `"`+advisor+`"`).Replace(string(b))
}
// Claude Code's advisor names its model as Claude Code names its own: on
@@ -67,5 +71,72 @@ func TestAdvisorModelAsTheUpstreamNamesIt(t *testing.T) {
if !strings.Contains(b, `"name":"Read"`) {
t.Errorf("%s: the agent's own tool lost: %s", c.name, b)
}
advisorSaid(t, c.name, b, c.want != "")
}
}
// advisorSaid checks what an upstream body b tells the model of the
// advisor: with it on (on), Claude Code's instructions and the
// tool_addition naming it as Claude Code sent them; with it left out,
// neither, and Claude Code's own word that it is gone. The rest of the
// message holding them stays.
func advisorSaid(t *testing.T, name, b string, on bool) {
t.Helper()
instructions := strings.Contains(b, "You have access to an `advisor` tool")
ref := false
gjson.Get(b, "messages").ForEach(func(_, m gjson.Result) bool {
m.Get("content").ForEach(func(_, blk gjson.Result) bool {
if blk.Get("type").String() == "tool_addition" && blk.Get("tool.name").String() == "advisor" {
ref = true
}
return true
})
return true
})
switch {
case on && (!instructions || !ref):
t.Errorf("%s: advisor on, but its instructions (%v) or tool_addition (%v) lost: %s", name, instructions, ref, b)
case !on && (instructions || ref):
// the model called advisor() as the agent's tool: "No such tool
// available: advisor" (JackChou on Discord)
t.Errorf("%s: advisor left out, but its instructions (%v) or tool_addition (%v) still sent: %s", name, instructions, ref, b)
case !on && !strings.Contains(b, advisorGone):
t.Errorf("%s: advisor left out without saying so: %s", name, b)
}
if !strings.Contains(b, "Today's date is 2026-10-15.") {
t.Errorf("%s: the system message's own text lost: %s", name, b)
}
}
// A translation has no advisor to offer: the tool goes with every other
// server tool, and Claude Code's instructions to call it are said to be
// void, so the model doesn't call advisor() as one of the agent's tools
// (JackChou on Discord: "找不到对应工具").
func TestAdvisorLeftOutOnTranslation(t *testing.T) {
for _, c := range []struct {
name string
api func(p *provider.Provider, url string)
model string
}{
{"chat", func(p *provider.Provider, url string) { p.Chat = url + "/v1" }, "glm-5.1"},
{"responses", func(p *provider.Provider, url string) { p.Responses = url + "/v1" }, "gpt-5.5"},
{"gemini", func(p *provider.Provider, url string) { p.Gemini = url + "/v1beta" }, "gemini-3.5-pro"},
} {
t.Run(c.name, func(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
u, url := newBillingUpstream(t)
p := provider.Provider{ID: "v", Name: "V", Key: "k", Models: []string{c.model}}
c.api(&p, url)
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
claudeCodeSends(t, advisorTurn("v/"+c.model, "claude-opus-5-5"))
b := u.last(t)
if strings.Contains(b, "advisor_") {
t.Errorf("the advisor server tool sent: %s", b)
}
advisorSaid(t, c.name, b, false)
})
}
}
+11
View File
@@ -177,6 +177,17 @@ func parseAnthropic(body []byte) (*Request, error) {
if strings.HasPrefix(t.Type, "web_search") {
r.WebSearch = true
}
if strings.HasPrefix(t.Type, "advisor_") {
// Claude Code's advisor: its instructions, which would
// have the model call a tool it hasn't got (advisor.go)
for i := range r.Messages {
for j, pt := range r.Messages[i].Parts {
if pt.Kind == Text {
r.Messages[i].Parts[j].Text, _ = advisorGoneIn(pt.Text)
}
}
}
}
continue
}
if t.Name == "DeferredToolPlaceholder" {
@@ -0,0 +1 @@
{"model":"MODEL","max_tokens":64,"stream":true,"messages":[{"role":"user","content":[{"type":"text","text":"hi"}]},{"role":"system","content":[{"type":"text","text":"# Environment\nYou have been invoked in the following environment: \n - Platform: darwin\n\nToday's date is 2026-10-15.\n\n# Advisor Tool\n\nYou have access to an `advisor` tool backed by a stronger reviewer model. It takes NO parameters -- when you call advisor(), your entire conversation history is automatically forwarded. They see the task, every tool call you've made, every result you've seen.\n\nCall advisor BEFORE substantive work -- before writing, before committing to an interpretation, before building on an assumption. If the task requires orientation first (finding files, fetching a source, seeing what's there), do that, then call advisor. Orientation is not substantive work. Writing, editing, and declaring an answer are.\n\nAlso call advisor:\n- When you believe the task is complete. BEFORE this call, make your deliverable durable: write the file, save the result, commit the change. The advisor call takes time; if the session ends during it, a durable result persists and an unwritten one doesn't.\n- When stuck -- errors recurring, approach not converging, results that don't fit.\n- When considering a change of approach.\n\nOn tasks longer than a few steps, call advisor at least once before committing to an approach and once before declaring done. On short reactive tasks where the next action is dictated by tool output you just read, you don't need to keep calling -- the advisor adds most of its value on the first call, before the approach crystallizes.\n\nGive the advice serious weight. If you follow a step and it fails empirically, or you have primary-source evidence that contradicts a specific claim (the file says X, the paper states Y), adapt. A passing self-test is not evidence the advice is wrong -- it's evidence your test doesn't check what the advice is checking.\n\nIf you've already retrieved data pointing one way and the advisor points another: don't silently switch. Surface the conflict in one more advisor call -- \"I found X, you suggest Y, which constraint breaks the tie?\" The advisor saw your evidence but may have underweighted it; a reconcile call is cheaper than committing to the wrong branch."},{"type":"tool_addition","tool":{"type":"tool_reference","name":"advisor"},"cache_control":{"type":"ephemeral"}}],"output_config":{"effort":"medium"}}],"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}]}