gateway: a relayed reply Anthropic reviewed for auto mode makes no call out of its text

xybio on Discord (#feedback): Claude Code through magpie (127.0.0.1:3425)
shows "We're changing auto mode to no longer charge for classifier
requests ... this session isn't eligible because your requests go through
127.0.0.1:3425". Anthropic's llm-gateway-protocol page asks a gateway to
forward request headers and body fields unchanged (safeguards among them)
and to return replies without dropping keys like safeguard_results or
rewriting tool-use ids.

Audit of the Anthropic-to-Anthropic path (passthrough, forwardOnce):
- Request: anthropic-beta and anthropic-version always go; safeguards and
  the dangerous-tool-use beta go as sent to a reviewed route
  (serverReview/AutoModeReviewed) and are taken off for any other model.
  No body field is dropped there.
- Reply: safeguard_results already pass, whole and streamed
  (TestAutoModeServerSideReviewRelayed). tool_use ids go as they came;
  toolUseIDs salts one only when the client already holds it (#4910),
  which Anthropic's unique ids never are.
- The one rewrite found: anthropicTextCalls (39bade71d, two days old)
  reads Claude's <invoke name=…> markup out of a relayed reply's text and
  makes it a tool_use with an id magpie invents (call_text_N), stop_reason
  tool_use. On a reviewed reply that call has an id Anthropic never
  judged, so Claude Code can match it to no verdict.

Fix (textcalls_anthropic.go): a stream whose message_delta carries
safeguard_results, or a whole reply that carries them, has no call read
out of its text; the text goes as text, stop_reason and results as they
came. Without results the written call is still made, so
packinggoodsllc_07668's case (a Claude group writing invokes) is kept.
docs/subsystems/gateway-routing.md says so.

Not changed, said here: masking (redact.MaskJSON, opt-in) masks values
inside safeguards.classifier_context (paths, user_identity) like any other
string the user sends; ids (tool_use_ids, *_id) are kept. Only
Content-Type and request ids are copied from a successful reply's
headers, so anthropic-ratelimit-unified-* don't reach Claude Code. The
wiring leaves the review on whenever a reviewed model is reachable
(claudeReviewEnv), so a session on a non-Claude model, or on a relay that
drops safeguard_results, still gets the notice; which route xybio uses is
not known.

Run (mote-run):
- TestAutoModeReviewedReplyMakesNoCall red with the stream check taken
  out (names [Bash], stop tool_use) and with the whole check taken out
  (call_text_1 tool_use), green with both.
- At e3f7d3194 (rebased on 2c214ce25): gofmt -l clean; GOOS=linux and
  GOOS=windows go vet ./internal/gateway ok; go test -count=1 -timeout
  45m ./internal/gateway: every test passed but
  TestCodexPoolSaysTheClientsVersion (734.7s), which is #4807.
- Rebased onto origin/main f3335dd1b, which fixes #4807 (17f2387e1) and
  changes thinking_bound.go: at the pushed head fe5d30d7c's tree, vet for
  linux and windows ok, and -run "TestAutoMode|TestInvokeReported|
  TestTextWritten|TestTextCall|TestClaudeBridgeSafeguard|TestCodexPool|
  Thinking|TestSafeguards|Passthrough" ok (36.6s). The full package was
  not rerun there.

Not tried: a real Claude Code auto-mode session through magpie and its
/status "Auto mode server" row; no real Anthropic reply carrying both
safeguard_results and written invoke text was seen.
This commit is contained in:
yetone
2026-11-03 13:23:49 +08:00
parent f3335dd1b4
commit d73f2254d7
3 changed files with 112 additions and 2 deletions
+1 -1
View File
@@ -302,7 +302,7 @@ recorded as a prediction failure (`noPrediction`).
- A model the user ticked no levels of (`ModelReasonless` in [settings](../../internal/settings/settings.go), `SetModelReasonless`; the provider editor's Names & levels, or `magpie model efforts <provider/model> off`) is sent no reasoning field on any route, whatever the agent asks: the candidate loop strips the body with `withoutAnyReasoning` ([`quiet.go`](../../internal/gateway/quiet.go): Chat's `reasoning_effort`, `reasoning`, `thinking`, `enable_thinking` and `include`'s `reasoning.encrypted_content`, Responses' `reasoning`, Anthropic's `thinking` of any type and `output_config.effort`, Gemini's `thinkingConfig`), the Anthropic relay doesn't add `thinking:{type:disabled}` for it, and `forwardTranslated` clears `Effort`, `ThinkOff` and `Thinking` for its other callers. It offers no levels (`Efforts`, `entryFor`), is `Quiet`, and as a routing-group member doesn't take the group's levels away. The learned refusals above cover only reasoning *off* and Gemini levels; a vendor that answers a plain `reasoning_effort` with 422 (yuexian7 on Discord) is not learned, so this is the user's switch. `TestReasonlessModelSentNoReasoning`, `TestReasonlessAnthropicRelay`, `TestGroupReasonlessMemberKeepsLevels`, `model-reasonless.test.cjs`.
- 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. A model whose own list refuses them (`RejectsTemperature`, from the catalog's `temperature`, or a plugin's `temperature: false` carried by [the plugin host](provider-plugins.md#a-plugin-models-sampling), #2492) is asked without `temperature` and `top_p` whatever the client speaks: a translation leaves them out (`build`), and a Chat or Responses request relayed as it came does too (`passthrough`).
- 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`).
- 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. A relayed reply carrying `safeguard_results` has no call read out of its text (`anthropicTextCalls`): a call made there would have an id Anthropic never judged, which Claude Code can't match to a verdict, so the text goes as text (xybio on Discord, `TestAutoModeReviewedReplyMakesNoCall`). 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`). Codex's own identity line for its GPT-5 models ("You are Codex, an agent based on GPT-5", "…a coding agent based on GPT-5", any case) is turned away the same way (`antigravityTurnsCodexAway`): Codex sends its model's prompt as the thread's first developer message, which goes in as the system instruction, and a thread begun on a GPT model keeps it after `/model`, `resume -m` or a fork as an agent's thread, so such a thread on an Antigravity model 429'd until Codex's retry limit while dsh on the same account answered (Jodiezzzzzz on X, 10-27). It gets its own hint (`antigravityCodexHint`: start a new chat on the model, which is sent magpie's own Codex prompt "You are Codex, based on GPT-5.", which Antigravity answers), chosen by `antigravityHint`. Codex sends its `web_search` tool every turn, so an Antigravity model's Codex turn goes through magpie's own search (`searchReply`); its rounds are wrapped in `antigravityRound`, which tells the 429 (or the reply's error event) the same way and marks the attempt, where before the search path returned the bare 429 that Codex retried to its limit.
- A request translated to a Chat or Responses upstream that carries no `prompt_cache_key` of the client's (every Anthropic client's) gets one for its conversation when the provider is OpenAI's API with a key or one the user added by its address (`ownCacheKey`, `cacheKeyOf` in [`gateway.go`](../../internal/gateway/gateway.go)): a hash, in a UUID's shape, of the session the client names, else of its first user message, so every turn of it has the same key and nothing in it names the client or magpie. A relay can turn a request away without one ("prompt_cache_key is required", CyberCaius's AnyRouter). A vendor's preset, a signed-in account, a plugin, Bedrock and Vertex get none, nor does a provider whose extraBody names `prompt_cache_key` (the user's value is sent). An upstream whose 400 names the field is asked again without it and not sent it again; another 400 is not asked again for it, so an unrelated refusal is tried as often as before.
@@ -0,0 +1,91 @@
package gateway
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// writtenBash is Claude's own call form, written as text in a reply whose
// review Anthropic answered.
const writtenBash = `<invoke name="Bash"><parameter name="command">echo hi</parameter></invoke>`
// reviewedTextReply is a streamed reply whose text holds writtenBash and
// whose message_delta carries the review's results, or none when review
// is "".
func reviewedTextReply(review string) string {
delta := `{"stop_reason":"end_turn","stop_sequence":null}`
if review != "" {
delta = `{"stop_reason":"end_turn","stop_sequence":null,"safeguard_results":` + review + `}`
}
text, _ := json.Marshal("I'd run it like this: " + writtenBash)
return sse(
`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-sonnet-5","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":7,"output_tokens":1}}}`,
`event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
`event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":`+string(text)+`}}`,
`event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`,
`event: message_delta`+"\n"+`data: {"type":"message_delta","delta":`+delta+`,"usage":{"output_tokens":20}}`,
`event: message_stop`+"\n"+`data: {"type":"message_stop"}`)
}
// A reply Anthropic reviewed for Claude Code's auto mode reaches it as it
// came: no call is made out of its text, whose id the review never
// judged and Claude Code could match to no verdict (xybio on Discord:
// "this session isn't eligible because your requests go through
// 127.0.0.1:3425"), and its stop_reason and safeguard_results are as they
// were. The same reply without results still has its written call made
// (packinggoodsllc_07668, textcalls_anthropic.go).
func TestAutoModeReviewedReplyMakesNoCall(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
f := &fake{t: t}
up := httptest.NewServer(f)
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "ant", Name: "Ant", Key: "k", Anthropic: up.URL, Models: []string{"claude-sonnet-5"}}); err != nil {
t.Fatal(err)
}
f.reply, f.ctype = reviewedTextReply(reviewed), ""
rec := askReview(t, New(), "/v1/messages?beta=true", reviewAsk("ant/claude-sonnet-5"))
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
raw := rec.Body.String()
text, names, _, stop := anthropicRead(t, raw)
if got := reviewIn(t, raw); !sameReview([]byte(got), []byte(reviewed)) || len(names) != 0 || stop != "end_turn" || text != "I'd run it like this: "+writtenBash {
t.Errorf("reviewed stream changed: results %s names %v stop %q text %q\n%s", got, names, stop, text, raw)
}
// whole
whole, _ := json.Marshal(map[string]any{"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-sonnet-5",
"content": []any{map[string]any{"type": "text", "text": "I'd run it like this: " + writtenBash}},
"stop_reason": "end_turn", "safeguard_results": json.RawMessage(reviewed), "usage": map[string]any{"input_tokens": 7, "output_tokens": 20}})
f.reply, f.ctype = string(whole), "application/json"
rec = askReview(t, New(), "/v1/messages?beta=true", strings.Replace(reviewAsk("ant/claude-sonnet-5"), `"stream":true`, `"stream":false`, 1))
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
var got struct {
Content []struct {
Type string `json:"type"`
} `json:"content"`
StopReason string `json:"stop_reason"`
Results json.RawMessage `json:"safeguard_results"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
t.Fatalf("%v: %s", err, rec.Body)
}
if len(got.Content) != 1 || got.Content[0].Type != "text" || got.StopReason != "end_turn" || !sameReview(got.Results, []byte(reviewed)) {
t.Errorf("reviewed whole reply changed: %s", rec.Body)
}
// no review: the written call is made, as for any relayed reply
f.reply, f.ctype = reviewedTextReply(""), ""
rec = askReview(t, New(), "/v1/messages?beta=true", reviewAsk("ant/claude-sonnet-5"))
if raw := rec.Body.String(); !strings.Contains(raw, `"tool_use"`) || !strings.Contains(raw, `"stop_reason":"tool_use"`) {
t.Errorf("unreviewed stream had no call made:\n%s", raw)
}
}
+20 -1
View File
@@ -18,6 +18,11 @@ import (
// reply stops for tool_use. Held text that isn't calls goes on as it came.
// A reply that came whole (no stream) is read as wholeTextCalls reads a
// Chat one.
//
// A reply carrying auto mode's review (safeguard_results, automode.go)
// goes as it came: Anthropic judged the calls it made by their ids, and a
// call made here would have an id it never judged, which Claude Code
// can't match to a verdict (xybio on Discord). Its text goes as text.
type anthropicTextCalls struct {
names map[string]bool
sse bool
@@ -166,7 +171,7 @@ func (t *anthropicTextCalls) event(ev []byte) []byte {
return append(out, ev...)
case "message_delta":
var pre []byte
if t.holding && !t.native {
if t.holding && !t.native && !hasReview(m["delta"]) {
if calls, rest, ok := parseTextCalls(t.held, t.names); ok {
t.held, t.holding = "", false
rest = t.pending + rest
@@ -248,6 +253,9 @@ func (t *anthropicTextCalls) whole(b []byte) []byte {
if decodeJSON(b, &reply) != nil || reply == nil {
return b
}
if _, ok := reply["safeguard_results"]; ok {
return b
}
var content []map[string]json.RawMessage
if decodeJSON(reply["content"], &content) != nil || len(content) == 0 {
return b
@@ -294,6 +302,17 @@ func (t *anthropicTextCalls) whole(b []byte) []byte {
return nb
}
// hasReview reports whether a stream's message_delta delta carries auto
// mode's review results.
func hasReview(delta json.RawMessage) bool {
var d map[string]json.RawMessage
if decodeJSON(delta, &d) != nil {
return false
}
_, ok := d["safeguard_results"]
return ok
}
func mustPlain(v any) json.RawMessage {
b, _ := marshalPlain(v)
return b