agent, gateway: Claude Code on a model Anthropic doesn't review gets auto mode's server review turned off, so it no longer says magpie isn't eligible (1EFLOPS on X)

1EFLOPS runs Claude Code through magpie on Codex's gpt-6.1-sol. In auto
mode, Claude Code 2.1.296 says "this session isn't eligible because your
requests go through 127.0.0.1:3425 ... ask your gateway to implement
https://code.claude.com/docs/en/auto-mode-classifier-billing".

What the page asks of a gateway: pass the anthropic-beta header
(dangerous-tool-use-2026-09-03), the request's `safeguards` field, and
`safeguard_results` in the reply through unchanged, and leave tool-use ids
alone. The results are verdicts from Anthropic's own safety classifier.
For a gateway that can't provide them, the page's remedy is
CLAUDE_CODE_AUTO_MODE_SERVER=0. Pro, Max and Team plans never see the
notice. In the bundle, Claude Code falls back on server_unsupported,
server_unavailable_disabled or server_no_result, and the notice shows
whenever there's no real verdict. Only that variable removes it.

Per route:
- Claude subscription bridge, Anthropic API key, relays in front of
  Anthropic, Bedrock and Vertex: already pass the beta, `safeguards` and
  `safeguard_results` through (e8cd4bac8, 8c21a4184). This commit doesn't
  change them. serverReview now uses the shared AutoModeReviewed rule
  (adding the subscription account, which never reaches serverReview).
- Codex/OpenAI and every other non-Claude model: magpie can't answer
  honestly. A verdict would be made up, and "unsupported" still shows the
  notice. So magpie answers nothing on Anthropic's behalf. Instead the
  Claude Code wiring writes env.CLAUDE_CODE_AUTO_MODE_SERVER="0" to
  settings.json. It does this only while Claude Code is routed through
  magpie and no model it can reach there is reviewed. That means checking
  the models shown to Claude Code (and Claude Desktop's while Desktop is on
  magpie), a shown group's members, those providers' fallbacks, and the
  models it is set to (claudeReviewed). If any one is reviewed, the
  variable stays unset, because /model can move the session onto it (the
  reason 8c21a4184 didn't write it at all). The value is rewritten on every
  model set and Sync, so adding a Claude provider turns the review back on.
  It is stash-tracked (claude.auto_mode_server): a user's own value is left
  alone, and magpie's goes on Disconnect, reset or a move off magpie.
- T3 Code (sibling): its magpie instance runs Claude Code on the gateway
  through its own environment, so it gets the same "0" by the models it
  lists.
Not covered: Claude Desktop's Code tab while Claude Code itself isn't
routed through magpie. Desktop users are on Pro/Max/Team, which never see
the notice.

Tests (each fails with its part of the change broken by hand):
- TestClaudeAutoModeReview: off on a non-Claude model; on with a Claude
  model shown, in a group or as a fallback; the user's "1" and "0" kept;
  dropped on reset and on a move to Claude Code's own model.
  A group that keeps its models out of the lists (#1783, Unlists) still
  routes to them, so its Claude member counts: members come from what is
  served, not from the catalog.
- TestT3CodeAutoModeReview.
- TestAutoModeReviewedRoutes: subscription, api.anthropic.com, relay,
  Bedrock and Vertex spellings yes; Codex, DeepSeek's Anthropic API,
  openai/gpt-6 and claudette no.
Mutations that went red: skipping group members, skipping fallbacks,
skipping an unlisting group, overwriting the user's value, not dropping it off magpie, always writing
it, the T3 env always or never, and the subscription not counted.

Real Claude Code 2.1.296, sandbox HOME/CLAUDE_CONFIG_DIR, magpie serve on
127.0.0.1:3591 under a scratch HOME, fake upstreams on 3593 (OpenAI Chat)
and 3594 (Anthropic):
- Before, on fakeai/fake-gpt, -p --permission-mode auto: the notice is on
  stderr (2 of 2 fresh config dirs). With the env in settings: none.
- With this build, `magpie claude fakeai/fake-gpt` wrote the "0", and a
  fresh run shows no notice. The same settings without it show the notice.
- `magpie provider add fakeanth anthropic=... models=claude-sonnet-5`:
  Sync took the "0" out. `magpie claude fakeanth/claude-sonnet-5` and a run
  in auto mode: the upstream got the dangerous-tool-use beta and
  `safeguards` on both turns, answered not_flagged in message_delta, and
  there was no notice.
Not tried: the Claude subscription bridge with a real account (its plans
don't see the notice), and a real Codex account (a fake Chat upstream
stood in for it).

Run: gofmt -l; go vet -tags nogui ./... for darwin, linux and windows;
go test -tags nogui ./... in a scratch HOME with the Go caches pinned.
The only red was TestOTelWaterfallIncludesUnbilledFallback, whose first
export was cut before the root span under load. That is #1794, filed
earlier today; this run is noted there. This change doesn't touch OTel.
internal/agent was timed against the unchanged base under the same load
and ran at the same pace.

Re-run after rebasing on origin/main 94aa15397 (load ~100, so not the
whole suite): gofmt -l on the touched files; go vet -tags nogui
./internal/agent ./internal/gateway for darwin, linux and windows;
go test -tags nogui -count=1 ./internal/agent (1381s) and
./internal/gateway (939s), green. Breaking writeReview to never write the
"0" turned TestClaudeAutoModeReview red, and dropping the subscription from
AutoModeReviewed turned TestAutoModeReviewedRoutes red.
This commit is contained in:
yetone
2026-10-12 22:25:35 +08:00
parent 0db8112afe
commit 24350a3722
7 changed files with 371 additions and 10 deletions
+2 -1
View File
@@ -53,6 +53,7 @@ something else shows up as drift.
- A Claude Code tier or its subagents given a model of their own keep it when the main model moves onto that model and on again (`ownKey` in `claudeIn`), whether the main model is picked in magpie or in Claude Code's `/model`. Same as model, picked for them, has them follow again.
- Claude Code's tier and subagent models the user had set for their own endpoint (`claudeOwnEnv`) are stashed with that endpoint and token when magpie is wired in, and come back with them when magpie steps out, by Disconnect or by Claude Code's own model (#1050).
- Claude Code's sign-in (`login`) is magpie's key (`""`, the default) or claude.ai (`claudeai`). claude.ai writes `ANTHROPIC_AUTH_TOKEN` empty, which Claude Code reads as no key: it keeps its claude.ai login and sends that to magpie, which never passes it on (`claudeSignIn` in the gateway). Every later write keeps the token empty (`wiredKey`), and a key put there by hand is reported by Check, not taken for magpie's. It's offered only where the gateway takes any key (`gwKey() == gateway.Token`: loopback, a WSL distro mirrored), not from a distro under NAT while magpie is shared on the network, where only the sharing key gets in. The choice is stashed, so it survives Disconnect and a port move. An empty token counts as magpie's only beside the address magpie last wrote (`claude.wired_at` in the stash, which Rewire carries to the new port, `keyOurs`): an endpoint of the user's own with an empty token stays theirs when the model goes back to Claude Code's own.
- Claude Code's auto mode review (`CLAUDE_CODE_AUTO_MODE_SERVER`, `claudeReviewEnv` in [`claude.go`](../../internal/agent/claude.go)) is written `"0"` while Claude Code is routed through magpie and none of the models it can reach there is one Anthropic reviews (`claudeReviewed`, by `gateway.AutoModeReviewed`): those it is shown (and Claude Desktop's while Desktop is on magpie), a shown group's members, those providers' fallbacks, and the models it is set to. Off, it classifies locally from the start, as it does anyway behind a gateway that doesn't answer, without the "isn't eligible because your requests go through 127.0.0.1:3425" notice (1EFLOPS on X). Any reviewed model leaves it unset, since `/model` can take the session there; a model hidden from Claude Code doesn't count. It is rewritten on every model set and `Sync`, so adding a Claude provider turns the review back on. magpie's value is kept apart in the stash (`claude.auto_mode_server`), a user's own is left alone, and it goes when Claude Code is taken off magpie (`desktopOnly`, `unroute`). T3 Code's magpie instance, which runs Claude Code on the gateway through its own environment, carries the same `"0"` there by the models it lists (`t3InstanceJSON` in [`t3code.go`](../../internal/agent/t3code.go)); a value in the user's `~/.claude` settings comes after it.
- MiniMax Code takes a model ref with one slash in the whole (a SubAgent's `model` must match `^[^/\s]+\/[^/\s]+$`, #1387), and magpie's refs there are `custom_provider:magpie/<model>`. So a model under `custom_provider.magpie` is written with `~` for each slash of its catalog id (`bb-codex~gpt-6.1-sol`, `provider.FlatID`), only when that spelling stands for one served id (`provider.Flattened`); the gateway takes it back. A config an older magpie wrote moves over on the next sync: the user's keys on a model go to its new key, `defaultModel`, `defaultLightModel` and `memory.captureModel`/`consolidationModel` follow (`mcodeRefs`), and the slashed key stays, switched off (`enabled: false`), so a session begun on it still resumes. magpie never edits the user's own `agents/<name>/agent.md`. No other agent was found with this limit ([`minimax.go`](../../internal/agent/minimax.go)).
- Claude Code 2.1.296 reads a Claude model whose version has a dot (`relay/claude-opus-4.6-us`) as Claude Opus 4: a retired warning, budget thinking, 32000 output tokens, no effort. With dashes (`relay/claude-opus-4-6-us`) it knows the model (misteer_ti. on Discord). So every model magpie writes into its settings (`model`, the tier envs, `ANTHROPIC_SMALL_FAST_MODEL`, `CLAUDE_CODE_SUBAGENT_MODEL`, `modelPicker`), T3 Code's Claude slugs and Claude Desktop's Code-tab ids (`claudeLooking`) spell a dotted Claude version with dashes (`provider.ClaudeSpelled`), only when that spelling stands for one served id. Every read of those keys takes it back (`provider.ClaudeRead`: `claudeIn`'s `env`, `claudeMain`, `claudeStandInAt`), so magpie's fields, applied state and Drift keep the dotted id. The user's own values are stashed and given back as written. Values an older magpie wrote dotted are rewritten on the next Sync. Other vendors' ids are never respelled ([`claudedash.go`](../../internal/provider/claudedash.go)).
- Codex's "subagents" field is `[agents] default_subagent_model`: only the model a subagent starts on when its lead names none in `spawn_agent` (codex-rs `core/src/agent/child_config.rs`). Unset, it isn't "same as model": the lead may still name another, so the GUI calls it the lead's pick, else the model (`leadPicks` in app.js), and its title points at the "subagent model" field.
@@ -76,7 +77,7 @@ something else shows up as drift.
```sh
go test -tags nogui ./internal/agent -run '^TestStepCode'
go test -tags nogui ./internal/agent -run 'TestConnect|TestDisconnect|Drift|TestKeptAddress|TestWSLAgentAddress|TestReachProbe|TestDryRunKnowsTheAskersProviders|TestReseat|TestPort|TestWSL|TestClaudeKeepsItsClaudeAISignIn|TestClaudeSignIn|TestClaudeOwnEndpointWithAnEmptyKey|TestClaudeAtAnOlderGatewayAddress'
go test -tags nogui ./internal/agent -run 'TestClaudeAutoModeReview|TestT3CodeAutoModeReview|TestConnect|TestDisconnect|Drift|TestKeptAddress|TestWSLAgentAddress|TestReachProbe|TestDryRunKnowsTheAskersProviders|TestReseat|TestPort|TestWSL|TestClaudeKeepsItsClaudeAISignIn|TestClaudeSignIn|TestClaudeOwnEndpointWithAnEmptyKey|TestClaudeAtAnOlderGatewayAddress'
go test -tags nogui ./internal/agent
go test -tags nogui ./internal/agent -run '^TestAir'
go test -tags nogui ./internal/agent ./internal/edit -run 'TestSyncKeepsAnAddressOnAnotherMachine|TestKeptAwayOnlyWhatIsSure|TestKeyValuesFormats|TestFilteredWrites'
+2
View File
@@ -84,6 +84,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
- A request to an Anthropic endpoint that turns thinking off is sent as the model takes it (`thinkingOffAsTaken`, in `forwardOnce`, so relayed requests, count_tokens, magpie's own thinking-off and retries all get it; the model is read as the vendor names it, from the body, or from the path for Bedrock and Vertex). Claude Sonnet 5.5 refuses `thinking: {type: "disabled"}` and is sent `{type: "between_tools"}` alone, at effort `high` at most. Opus 5.5, Fable 5 and Mythos 5 refuse it at every effort and are sent no thinking, at effort `low` unless one was asked, with `classifierRoom` added to a reply limit below it, as Claude Code does. Opus 5 and Haiku 5.5 take it only up to `high`, so `xhigh` and `max` are asked as `high`. `between_tools` sent to any other Claude goes as `disabled`, or as none where that is refused too. Other vendors' models, older Claudes and later lines than these go as they came (#1454). A Sonnet 5.5 by a name these rules can't read, answering 400 that asks for `between_tools` (`asksBetweenTools`), is asked again with it, once; a refusal of `disabled` at any effort (`thinkingOffRefused`) is asked again with thinking left to the model, as `alwaysThinks` is.
- A Chat or Responses client's reasoning turned off (`none`, `ThinkOff`), translated to an Anthropic endpoint (`buildAnthropic`), goes as `thinking: {type: "disabled"}`; it went as thinking at a 4096-token budget before (#1636). A model that refuses it (`alwaysThinks`, `mandatoryReasoning`, `thinkingOffRefused`) is asked again at its least (`thinkingBackOn`), and `markUnfit(offRefused)` sends it so at once until magpie restarts. A translated request's level can differ from the one asked: `none` and `minimal` go as `low` where the model's levels don't say it stops (`effortOf`). The route keeps the level asked; the try, the usage log and Routing's "went" say the one built (`noteWireEffort`, `wireEffort` in [`wire_effort.go`](../../internal/gateway/wire_effort.go)). Gemini's builders say theirs their own way and are logged as asked.
- 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).
- 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 model's reply limit is published within the window beside it (#1438, `provider.OutputWithin`, `Entry.PublishedOutput`): `/v1/models`' `max_output_tokens` (`modelObject`), Cursor Private Inference's `capabilities.max_output_tokens` (`cursorLocalModel`), Muse Code's `limit.output` (`museModels`), the GUI's model and group rows (`providerInfo`, `providersState`), `magpie model output`, and every agent's file (`agent.maxTokens`, #338). The window and the output can come from different sources: Grok's backend lists grok-4.7's 256000 window, and models.dev fills its 500000 output (`catalog.Decorate` and `Provider.replyLimit` fill an output only where the vendor gives none). An unknown window or output is published as it is. The catalog keeps the unclamped `Entry.Output`, and a group's member is still asked for no more than that (`outputLimit`, `withMaxOutput`), so a request isn't lowered by the clamp. A limit the user set stays in their settings as they set it (`TestModelListsKeepOutputWithinTheWindow`).
@@ -261,6 +262,7 @@ Covered by `TestVisionMCPAnalyzesImage`, `TestVisionMCPWithNoSeer`,
```sh
go test -tags nogui ./internal/gateway -run 'TestGroupAsksOneRestingMemberNotEach|TestLoneRestingMemberStillAsked|TestRetrievalGroupAsksOneRestingMember|TestProbeOne|TestLoop|TestLongReplyThatDoesNotLoop|TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestModelNotInPlanRestsTheModelNotTheKey|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestWindowCapsHoldTheAccount|TestAccountCap|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestSearchFollowsTheSearchersProxy|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact|TestProtection|TestSearchedConversation|TestUnsearchedConversationUnchanged|TestNotAnAPIReply|TestAPIReplyUntouched|TestCodexBackendWebPage|TestSub2APIKeyLimitIsQuota|TestKeysWeighedByTheirWindows|TestGroupWeighsKeyWindows|TestKeyOutOfItsWindowRestsUntilReset|TestKeyPoolErrorDoesNotRestForWindow|TestKeyBackOnceItsWindowIsNotFull|TestRestingKeyReadAgainInAnOrderedGroup|TestClaudeAccountBackOnceItsWindowRenews|TestThinkingStreams|TestHeldThinkingKeepsTheAgentAlive|TestCodexHeardWithinItsIdleTimeout|TestRefusalAfterThinkingFailsOver|TestGeminiEmptyRepliesAskedAgain|TestLocalUnredacted|TestCORS|TestForeignPagesRefused|TestAIStudioThinking|TestGeminiThoughtsThroughLocalProxy|TestGeminiRefusedLevel|TestGeminiThinkingOffAtItsLowest|TestThinkingOff|TestTranslatedEffortLoggedAsSent|TestTranslatedThinkingOffRefused|TestClaudeFiveFiveThinkingOffOnTheWire|TestSamplingAsTheModelTakesIt|TestHaikuFiveFiveSamplingOnTheWire|TestGeminiThoughtsMarkedInExtraContent|TestGeminiThinkingLevelRefused|TestGeminiMinimalRefusedTwiceAtOnce|TestPassthroughGeminiMinimalRefused|TestPassthroughEffortNoneRefused|TestPassthroughMinimalRefusedNoneTaken|TestOtherOffNamed|TestClaudeSignInNotToldItsSignInFailed|TestSignInWriterReleasesA403|TestSignInBetaStaysWithMagpie|TestStructuredOutput|TestResponsesTextKeepsVerbosityBesideFormat|TestRefusedFormatToldInWords|RPM|TestQueued|TestCustomGeminiUpstream|TestWholeNums|TestGrokCalls|TestOnlyGrokCalls|TestGrokModel|TestGrokPluginCalls'
go test -tags nogui ./internal/gateway -run 'TestVertex'
go test -tags nogui ./internal/gateway -run 'TestAutoMode|TestClaudeBridgeSafeguard'
go test -tags nogui ./internal/gateway ./internal/usage -run 'TestRetriedRequestCountsOnce|TestRequestsCountedOnceWithTheirRetries'
go test -tags nogui ./internal/gateway -run 'TestRemoteMagpie|TestRedactedKinds|TestKeyLimitTellsOnlyTheCaller'
go test -tags nogui ./internal/gateway -run 'TestSearchMCP|TestVisionMCP'
+93
View File
@@ -202,6 +202,54 @@ const claudeUnknownOutput = 32000
// model is said to have only the levels magpie knows it has.
const claudeCapsEnv = "CLAUDE_CODE_MODEL_CAPABILITIES"
// claudeReviewEnv is whether Claude Code's auto mode asks the API to review
// its actions (the dangerous-tool-use beta and `safeguards`), "0" for no.
// Behind a gateway whose model doesn't answer, it classifies locally anyway
// and names the gateway in a notice, "this session isn't eligible because
// your requests go through 127.0.0.1:3425…" (1EFLOPS on X, Claude Code on
// Codex). Anthropic's page on it says to set it to 0 for a gateway that
// can't run the checks: magpie does while none of the models Claude Code
// can reach through it is reviewed (claudeReviewed), and leaves it unset
// while one is. One the user set is theirs.
const claudeReviewEnv = "CLAUDE_CODE_AUTO_MODE_SERVER"
// claudeReviewed reports whether a model Claude Code can reach through
// magpie has its actions reviewed by Anthropic (gateway.AutoModeReviewed):
// one shown to the agents in catalogs (Claude Code, Claude Desktop whose
// Code tab is Claude Code, T3 Code's instance of it), a routing group's
// member, a provider's fallback, or one of models (those it is set to).
// Any such keeps the review on, as /model can take a session there.
func claudeReviewed(catalogs []string, models ...string) bool {
var entries []provider.Entry
for _, c := range catalogs {
shown, _ := provider.CatalogFor(c)
entries = append(entries, shown...)
}
reviewed := func(p provider.Provider, model string) bool {
if gateway.AutoModeReviewed(p, model) {
return true
}
return slices.ContainsFunc(p.Fallback, func(id string) bool {
fp, fm, ok := provider.Resolve(id)
return ok && gateway.AutoModeReviewed(fp, fm)
})
}
find := provider.GroupFinder()
for _, e := range entries {
if e.Group == "" {
if reviewed(e.Provider, e.Model) {
return true
}
continue
}
_, ms, _ := find(e.ID)
if slices.ContainsFunc(ms, func(m provider.Member) bool { return reviewed(m.Provider, m.Model) }) {
return true
}
}
return slices.ContainsFunc(models, func(m string) bool { return gateway.AutoModeReviewed(provider.Provider{}, m) })
}
// claudeCapsMax bounds claudeCapsEnv: the models Claude Code is set to go
// first, and those that don't fit after them are left as Claude Code takes
// them.
@@ -716,6 +764,40 @@ func claudeIn(at place) *Agent {
return edit.SetJSON(path, edit.KV{Path: "env." + claudeCapsEnv, Value: v})
}
writeCaps := func(models ...string) error { return putCaps(true, models...) }
// the auto mode review magpie turned off (claudeReviewEnv), kept apart
// from the user's own in the same way
reviewKey := at.key("claude.auto_mode_server")
reviewOurs := func() bool {
cur := rawEnv(claudeReviewEnv)
return cur != "" && cur == stashLoad()[reviewKey]
}
dropReview := func() error {
defer forget(reviewKey)
if reviewOurs() {
return edit.DelJSON(path, "env."+claudeReviewEnv)
}
return nil
}
// writeReview turns the review off while no model Claude Code can reach
// through magpie runs it, and back on (unset) once one does
writeReview := func(models ...string) error {
if rawEnv(claudeReviewEnv) != "" && !reviewOurs() {
forget(reviewKey)
return nil
}
catalogs := []string{"claude"}
if desktopOn() {
catalogs = append(catalogs, "claude-desktop")
}
if claudeReviewed(catalogs, models...) {
return dropReview()
}
stash(map[string]string{reviewKey: "0"})
if rawEnv(claudeReviewEnv) == "0" {
return nil
}
return edit.SetJSON(path, edit.KV{Path: "env." + claudeReviewEnv, Value: "0"})
}
// writeWindow tells Claude Code the window of the models it runs on
// (claudeWindow), and while Claude Desktop runs on magpie, of those its
// Code tab runs it on too (claudeDesktopWindow): the least of them, as
@@ -748,6 +830,11 @@ func claudeIn(at place) *Agent {
// Claude Code's being wired in wrote them before, so a user who wired
// in Desktop alone had 200K for every Desktop model (#1458).
desktopOnly := func() error {
// the review is turned off only for Claude Code's own requests to
// magpie
if err := dropReview(); err != nil {
return err
}
if !desktopOn() {
if err := dropWindow(); err != nil {
return err
@@ -1035,6 +1122,9 @@ func claudeIn(at place) *Agent {
if err := writePicker(); err != nil {
return err
}
if err := writeReview(models...); err != nil {
return err
}
return writeCaps(models...)
}
@@ -1426,6 +1516,9 @@ func claudeIn(at place) *Agent {
if err := writePicker(); err != nil {
return err
}
if err := writeReview(models...); err != nil {
return err
}
return writeCaps(models...)
},
// a model picked in Claude Code's /model is its main model: the tiers
+207
View File
@@ -0,0 +1,207 @@
package agent
import (
"encoding/json"
"path/filepath"
"testing"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/provider"
)
// TestClaudeAutoModeReview: Claude Code in auto mode behind magpie on a
// model Anthropic doesn't review (1EFLOPS on X, on Codex's gpt-6.1-sol)
// said "this session isn't eligible because your requests go through
// 127.0.0.1:3425…". Anthropic's page says to turn the review off
// (CLAUDE_CODE_AUTO_MODE_SERVER=0) for a gateway that can't run it: magpie
// does while no model Claude Code can reach through it is reviewed, and
// leaves it on while one is, shown or behind a group or a fallback. A
// value of the user's is theirs, and magpie's goes when Claude Code is
// taken off magpie.
func TestClaudeAutoModeReview(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("APPDATA", filepath.Join(home, "AppData", "Roaming"))
t.Setenv("LOCALAPPDATA", filepath.Join(home, "AppData", "Local"))
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
if err := provider.Save(provider.Provider{ID: "v", Name: "V", Chat: "http://127.0.0.1:1/v1", Key: "k", Models: []string{"gpt-x"}}); err != nil {
t.Fatal(err)
}
path := filepath.Join(home, ".claude", "settings.json")
writeFile(t, path, `{"theme":"dark"}`)
a := claude(home)
review := func() string { v, _ := edit.GetJSON(path, "env."+claudeReviewEnv); return v }
set := func(key, v string) {
t.Helper()
if err := a.Field(key).Set(v); err != nil {
t.Fatal(err)
}
}
sync := func() {
t.Helper()
if err := a.Sync(); err != nil {
t.Fatal(err)
}
}
// only a model no one reviews: off
set("model", "v/gpt-x")
if review() != "0" {
t.Fatalf("on v/gpt-x alone: %q, want 0", review())
}
sync()
if review() != "0" {
t.Fatalf("Sync: %q", review())
}
// a Claude model on an Anthropic endpoint joins: on, as /model can take
// the session there
if err := provider.Save(provider.Provider{ID: "a", Name: "A", Anthropic: "http://127.0.0.1:1", Key: "k", Models: []string{"claude-sonnet-5"}}); err != nil {
t.Fatal(err)
}
sync()
if review() != "" {
t.Fatalf("with a/claude-sonnet-5 shown: %q, want unset", review())
}
// hidden from Claude Code: off again; reachable through a group shown
// to it, or a provider's fallback, on
if err := provider.SetHiddenModels("claude", []string{"a/claude-sonnet-5"}); err != nil {
t.Fatal(err)
}
sync()
if review() != "0" {
t.Fatalf("Claude hidden: %q, want 0", review())
}
if err := provider.SaveGroup(provider.Group{Name: "mix", Members: []string{"v/gpt-x", "a/claude-sonnet-5"}}); err != nil {
t.Fatal(err)
}
sync()
if review() != "" {
t.Fatalf("a group with a Claude member: %q, want unset", review())
}
// a group that keeps its models out of the lists (#1783) still routes
// to them, so its Claude member counts
if err := provider.SetHiddenModels("claude", nil); err != nil {
t.Fatal(err)
}
if err := provider.SaveGroup(provider.Group{Name: "mix", Members: []string{"v/gpt-x", "a/claude-sonnet-5"}, Unlists: true}); err != nil {
t.Fatal(err)
}
sync()
if review() != "" {
t.Fatalf("a group unlisting its Claude member: %q, want unset", review())
}
if err := provider.SetHiddenModels("claude", []string{"a/claude-sonnet-5"}); err != nil {
t.Fatal(err)
}
if err := provider.DeleteGroup("mix"); err != nil {
t.Fatal(err)
}
sync()
if review() != "0" {
t.Fatalf("group deleted: %q, want 0", review())
}
if err := provider.Save(provider.Provider{ID: "v", Name: "V", Chat: "http://127.0.0.1:1/v1", Key: "k", Models: []string{"gpt-x"}, Fallback: []string{"a/claude-sonnet-5"}}); err != nil {
t.Fatal(err)
}
sync()
if review() != "" {
t.Fatalf("falling back to Claude: %q, want unset", review())
}
if err := provider.Save(provider.Provider{ID: "v", Name: "V", Chat: "http://127.0.0.1:1/v1", Key: "k", Models: []string{"gpt-x"}}); err != nil {
t.Fatal(err)
}
sync()
if review() != "0" {
t.Fatalf("fallback gone: %q, want 0", review())
}
// off magpie, onto Claude Code's own model, and reset: magpie's goes
set("model", "claude-opus-4-8")
if review() != "" {
t.Fatalf("Claude's own model kept magpie's value: %q", review())
}
set("model", "v/gpt-x")
if review() != "0" {
t.Fatalf("back on v/gpt-x: %q", review())
}
set("model", "")
if review() != "" {
t.Fatalf("reset kept magpie's value: %q", review())
}
// the user's own value is theirs, through a switch, Sync and reset
for _, mine := range []string{"1", "0"} {
if err := edit.SetJSON(path, edit.KV{Path: "env." + claudeReviewEnv, Value: mine}); err != nil {
t.Fatal(err)
}
set("model", "v/gpt-x")
sync()
if err := provider.Save(provider.Provider{ID: "a", Name: "A", Anthropic: "http://127.0.0.1:1", Key: "k", Models: []string{"claude-sonnet-5"}}); err != nil {
t.Fatal(err)
}
if err := provider.SetHiddenModels("claude", nil); err != nil {
t.Fatal(err)
}
sync()
if review() != mine {
t.Fatalf("the user's %q became %q", mine, review())
}
set("model", "")
if review() != mine {
t.Fatalf("reset took the user's %q away: %q", mine, review())
}
if err := edit.DelJSON(path, "env."+claudeReviewEnv); err != nil {
t.Fatal(err)
}
if err := provider.SetHiddenModels("claude", []string{"a/claude-sonnet-5"}); err != nil {
t.Fatal(err)
}
}
if v, _ := edit.GetJSON(path, "theme"); v != "dark" {
t.Fatal("theme lost")
}
}
// TestT3CodeAutoModeReview: T3 Code's magpie instance runs Claude Code on
// the gateway through its own environment, so it is told the same: the
// review off while none of the models it lists is reviewed, and on (not
// set) once one is.
func TestT3CodeAutoModeReview(t *testing.T) {
home := syncHome(t)
t.Setenv("T3CODE_HOME", "")
path := filepath.Join(home, ".t3", "userdata", "settings.json")
writeFile(t, path, `{}`)
a := t3code(home)
if err := a.Field("provider").Set(magpieID); err != nil {
t.Fatal(err)
}
review := func() (string, bool) {
t.Helper()
var file map[string]map[string]json.RawMessage
if err := json.Unmarshal([]byte(readFile(path)), &file); err != nil {
t.Fatal(err)
}
for _, v := range t3Format(t, file["providerInstances"][magpieID]).Environment {
if v.Name == claudeReviewEnv {
return v.Value, true
}
}
return "", false
}
if v, ok := review(); v != "0" || !ok {
t.Fatalf("relay/glm-4.6 alone: %q %v, want 0", v, ok)
}
if err := provider.Save(provider.Provider{ID: "a", Name: "A", Anthropic: "http://127.0.0.1:1", Key: "k", Models: []string{"claude-sonnet-5"}}); err != nil {
t.Fatal(err)
}
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if v, ok := review(); ok {
t.Fatalf("with a/claude-sonnet-5 listed: %q, want none", v)
}
}
+12 -5
View File
@@ -134,13 +134,20 @@ func t3InstanceJSON(path, gw string) map[string]any {
config[k] = v
}
}
environment := []map[string]any{
{"name": "ANTHROPIC_BASE_URL", "value": gw, "sensitive": false},
{"name": "ANTHROPIC_AUTH_TOKEN", "value": keyAt(gw), "sensitive": false},
}
// auto mode's review off while no model it lists is one Anthropic
// reviews, as for Claude Code itself (claudeReviewEnv); a value in the
// user's ~/.claude settings comes after it
if !claudeReviewed([]string{"t3code"}) {
environment = append(environment, map[string]any{"name": claudeReviewEnv, "value": "0", "sensitive": false})
}
return map[string]any{
"driver": "claudeAgent", "displayName": "magpie", "enabled": true,
"environment": []map[string]any{
{"name": "ANTHROPIC_BASE_URL", "value": gw, "sensitive": false},
{"name": "ANTHROPIC_AUTH_TOKEN", "value": keyAt(gw), "sensitive": false},
},
"config": config,
"environment": environment,
"config": config,
}
}
+20 -4
View File
@@ -20,9 +20,14 @@ import (
// (anthropicWholeEvents). Any other model neither sees them nor answers
// them (serverReview), and Claude Code, finding no result, classifies
// locally for the rest of the session, naming the gateway in a notice.
// magpie says nothing on the API's behalf, and doesn't turn the review off
// in Claude Code's settings: /model can take the same session to a Claude
// model behind the gateway, which reviews it.
// magpie says nothing on the API's behalf. Where no model Claude Code can
// reach through magpie is reviewed (AutoModeReviewed), the agent's wiring
// turns the review off in Claude Code's settings instead
// (CLAUDE_CODE_AUTO_MODE_SERVER=0, as Anthropic's page on the notice says to
// for a gateway that can't run the checks), so it classifies locally from
// the start and says nothing about the gateway (1EFLOPS on X). Where one
// is, it is left on: /model can take the same session to that model,
// which reviews it.
//
// Locally, the classifier is a request of its own on the session's model:
// the transcript in <transcript> blocks, a system prompt asking for
@@ -49,7 +54,7 @@ func isServerReviewBeta(b string) bool { return strings.HasPrefix(b, serverRevie
// is Claude's.
func (s *Server) serverReview(p provider.Provider, asked []string, body []byte) ([]string, []byte) {
model := gjson.GetBytes(body, "model").String()
claude := model == "" || anthropicModel.MatchString(model) || provider.HostOf(p.Base(provider.Anthropic)) == "api.anthropic.com"
claude := model == "" || AutoModeReviewed(p, model)
if !claude {
asked = slices.DeleteFunc(slices.Clone(asked), isServerReviewBeta)
}
@@ -62,6 +67,17 @@ func (s *Server) serverReview(p provider.Provider, asked []string, body []byte)
return betas, body
}
// AutoModeReviewed reports whether a request for model on p can have its
// actions reviewed by Anthropic for Claude Code's auto mode: the Claude
// subscription (the bridge hands the review to Claude Code's own binary),
// a Claude model (Anthropic's API, a relay in front of it, Bedrock's or
// Vertex's names for it), or anything on Anthropic's own API. No other
// vendor runs Anthropic's classifier, and magpie answers none on its
// behalf.
func AutoModeReviewed(p provider.Provider, model string) bool {
return p.Account != nil && p.Account.Agent == "claude" || anthropicModel.MatchString(model) || provider.HostOf(p.Base(provider.Anthropic)) == "api.anthropic.com"
}
// classifierRoom is what a model that reasons is given on top of the
// classifier's own budget, as Claude Code gives a Claude model that can't
// turn its thinking off.
+35
View File
@@ -296,6 +296,41 @@ func TestAutoModeReviewOnlyForClaude(t *testing.T) {
}
}
// TestAutoModeReviewedRoutes: the models whose requests can carry auto
// mode's review to Anthropic, the rule Claude Code's wiring turns the
// review off by while none of them is behind magpie (1EFLOPS on X): the
// Claude subscription, a Claude model under any vendor's spelling of it,
// and Anthropic's own API. Codex, DeepSeek's Anthropic API and an
// OpenAI-compatible relay's GPT are not.
func TestAutoModeReviewedRoutes(t *testing.T) {
sub := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}}
codex := provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "u"}}
anthropic := provider.Provider{ID: "anthropic", Anthropic: "https://api.anthropic.com", Key: "k"}
relay := provider.Provider{ID: "or", Chat: "https://openrouter.ai/api/v1", Anthropic: "https://openrouter.ai/api", Key: "k"}
deepseek := provider.Provider{ID: "ds", Anthropic: "https://api.deepseek.com/anthropic", Key: "k"}
for _, c := range []struct {
p provider.Provider
model string
want bool
}{
{sub, "claude-opus-4-8", true},
{sub, "", true},
{anthropic, "claude-sonnet-5", true},
{anthropic, "some-new-name", true},
{relay, "anthropic/claude-sonnet-5", true},
{relay, "us.anthropic.claude-opus-4-8-v1:0", true},
{relay, "claude-opus-4-8@20260101", true},
{codex, "gpt-6.1-sol", false},
{deepseek, "deepseek-v4", false},
{relay, "openai/gpt-6", false},
{relay, "claudette-7", false},
} {
if got := AutoModeReviewed(c.p, c.model); got != c.want {
t.Errorf("%s/%s: %v, want %v", c.p.ID, c.model, got, c.want)
}
}
}
// A provider that turned the beta away (Bedrock's runtime: Unexpected
// value(s) for the anthropic-beta header) is asked again without it, and
// without the safeguards it turns on, which it would turn away next.