gateway: a Gemini CLI sign-in goes without Claude Code's billing line, so Gemini's cache reads its prefix

Reported on X by @niyezaimenglima: Claude Code on a Gemini model through
magpie showed a cache hit rate of 0.

Cause: Claude Code's first system line, x-anthropic-billing-header, carries
a cch= that changes every turn (#1600). On a Gemini CLI sign-in (Code
Assist, Account.Agent "gemini") magpie kept that line at the head of
systemInstruction, so no two turns shared a prefix and Gemini's implicit
cache never matched. dropsBillingLine now drops it there. forwardTranslated
also built the Code Assist body from req instead of sent, so a dropped line
went out anyway; it builds from sent now, as buildFor does.

Scoped to that one route:
- The built-in Antigravity account's cloak already removes the line, and
  its refusal check (#666) judges the system as written. Unchanged.
- The antigravity, agy-cli and zed plugin cloaks cut the line to its end,
  and Claude Code's identity sentence (joined onto the same line) goes with
  it. Cutting only the fields in magpie, as a first version of this did,
  left "You are Claude Code..." on line 1, and a real Antigravity plugin
  account answered its 429 refusal (400 to Claude Code). Plugins keep the
  line.
- Other vendors: unchanged (dropsBillingLine's non-Code-Assist branch is as
  before).

Measured on a real Antigravity plugin account (sandbox HOME, copied
credentials, antigravity/gemini-3.8-flash-low, three Claude Code-shaped
turns, ~8.3k tokens):
- old code: turn 1 cache_read 0, turns 2 and 3 read 6238/6278 (in ~2084).
- a per-turn changing line near the head of the system (what Gemini CLI's
  kept billing line is): cache_read 0/0/0, in 8297/8331/8381. This is the
  reporter's 0.
- new code on the plugin route, stream and non-stream: 6248/6242/6274, so
  the route is unchanged; usage.jsonl matches the response.
- history in the first user message instead of the system: 6246/6288, so
  conversation content is cached too. The last ~2k tokens are never cached
  (Gemini's chunking).

Tests (both red on the old billing_line.go):
- TestBillingLineLeftOutForCodeAssist: a Gemini CLI login end to end, two
  turns with different cch; neither GenerateContent body has the line and
  systemInstruction is the same in both.
- TestBillingLineCodeAssistOthers: Antigravity built-in and an Antigravity
  plugin keep the line; Gemini CLI drops it.

Run:
- Full suite, go test -timeout 45m ./..., on mote at 72e6f9542 (this change
  on 593ea437d): every package ok except internal/gateway, whose only red is
  TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes, #7117, red on
  origin/main too (3 of 3 alone). mica's disk was full (1.2G), so its run
  tested nothing and was discarded.
- Rebased onto 2926b7bef (one commit, usage-record Wire field, no overlap):
  go test ./internal/gateway -run 'BillingLine|CodeAssist|Antigravity|Gemini'
  ok on mote; GOOS=linux and GOOS=windows go vet ./internal/gateway ok;
  gofmt -l clean.

Not tried: a real Gemini CLI account (Google refuses personal Code Assist
sign-ins here), so the Gemini CLI numbers stand in through the per-turn
line above; an AI Studio API key (that route already drops the line,
whether Google reports cached_tokens there is unverified). Not changed: the
agy-cli plugin runs the local agy CLI with its own session and compaction,
and reports agy's cachedReadTokens; that is agy's or the plugin's.
This commit is contained in:
yetone
2026-11-19 14:52:25 +08:00
parent 2926b7beff
commit 7f11dfc77f
4 changed files with 116 additions and 7 deletions
+2 -2
View File
@@ -449,14 +449,14 @@ the key's leaves the call as asked, with a log line (`compactRefused`).
- 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. 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, or, where Anthropic's per-account flag has turned its local classifier off behind a gateway (`tengu_bright_dragonfly`, read in 2.1.312 to 2.1.316), has no check at all and asks for approval of each action the check would judge ("your requests go through 127.0.0.1:3425, which doesn't pass it through", chenxiang0010 on Discord): only a route above can make auto mode work there, and none of magpie's other routes can; the wiring turns the review off in its settings unless every model it can reach through magpie surely gets the results back (`AutoModeAnswered`: the subscription or `api.anthropic.com`, not a relay, which may drop them; `claudeReviewEnv`, [agent wiring](agent-wiring.md), JoyYoung2Lucky on X), 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.
- 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. On Code Assist only Gemini CLI's sign-in goes without it (`dropsBillingLine`, and `codeAssistBody` is built from the request that goes): kept, it was Gemini's first system words and the implicit cache read nothing on any turn (niyezaimenglima on X, `TestBillingLineLeftOutForCodeAssist`). The built-in Antigravity account is sent it as before, which its cloak leaves out and `antigravityTurnsAway` reads (#666), and so is a plugin on Code Assist: the antigravity, agy-cli and Zed plugins' cloaks take the line to its end, Claude Code's identity sentence with it, and cut here that sentence reached Antigravity's plugin alone and a real account answered the 429 (`TestBillingLineCodeAssistOthers`). 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.
- Claude Desktop's check that a gateway model answers (`{"max_tokens":1,"messages":[{"role":"user","content":"."}]}`, sent as it starts and by its settings' Test connection on the shortest id it is listed with haiku in it, else sonnet, else opus, else the first model listed; `desktopProbe` in [`desktop.go`](../../internal/gateway/desktop.go)) goes to the model the user chose in one of Desktop's own model menus that magpie still serves (`desktopChosen`: `__model_selector_state` in Claude-3p's `local-agent-mode-sessions/<account>/<org>/cowork_account_settings.json`, in the order Code, Cowork, Chat; cybercaius's DeepSeek in the Code tab, v0.1.2033), unless a session's turn was sent after that file was last written: then the model that turn was for (`desktopPicked`), while magpie serves it, the newer of the two being what the user is on now (before, the last session's model came first whenever any menu still held it, so the Code tab switched off DeepSeek with Cowork left on it kept the check on DeepSeek, cybercaius on Discord, v0.1.2212), else to Desktop's default model, the first one listed to it (`desktopDefault`; Desktop's own settings call the first listed model the default), never to the haiku it names, which is another provider's quota, nor, with no menu chosen, to the model the last session ran on (`desktopPicked`), which can be days old: v0.1.1821 sent it there, a relay's GPT model CyberCaius had left for his routing group, and the relay turned it away (Discord, v0.1.1838). It is asked for 16 tokens upstream (`desktopProbeTokens`): OpenAI's models refuse fewer, and a relay in front of one (AnyRouter's "bad response status code 400") passes on no floor for `tokenFloor` to ask again at. A relay that needs `prompt_cache_key` gets one (above). It is recorded with kind `connection_check` (`KindDesktopCheck`), which the Routing page tags "Connection check" with why its model is the id Desktop named and not the one chosen in the conversation: a list with no Claude-named id made the row read "requested deepseek-flash" while the menu's gpt-6.1-sol answered (cybercaius on Discord, v0.1.2212). `TestClaudeDesktopProbeToDefaultModel`, `TestClaudeDesktopProbeToChosenModel`. `TestClaudeDesktopProbeAsksNoClassifier` checks the kind.
- Claude Desktop's `/v1/models` tags a model with `anthropic_family_tier` only when the user picked it for that tier (`DesktopTiers`, the Agents page's opus, sonnet, haiku and fable). Before, a Claude model magpie served was tagged with its own tier unpicked, so Desktop's Code tab told Claude Code to run its haiku calls (its small, fast model) on whichever provider served a `claude-haiku-…`: a chat on AgentRouter's gpt-6.1-sol sent them to Leee's `claude-haiku-5-5` (cybercaius on Discord). Untagged, Claude Code asks for its own id of the tier. A background call (no tools) or a subagent's turn asking for a Claude model by Claude's own id that is no catalog id (`claudeOwnID`) stays on the chat's provider (`desktopPicked`), even when another provider serves a model of that name: `servedBeside` gives that provider's model of that name, else its newest model of the tier, beside the chat's model first, else the call goes to the chat's model. The provider's Claude models stand in only when the chat itself is on one of them: a chat on Leee's DeepSeek had Claude Code's sonnet calls sent to Leee's `claude-sonnet-5-5`, which its key may not use (403, CyberCaius on Discord), so Claude Code's own calls in a chat on another vendor's model go to the chat's model, and a tier the user picked takes Claude Code's own id of it even where a provider lists a model by that name (`TestClaudeDesktopNonClaudeChatKeepsTierCalls`). A lead's turn and an id the user picked for a tier (a catalog id) go as asked. `TestClaudeDesktopBackgroundStaysOnChatProvider`.
- While a model is picked for one of Claude Desktop's tiers, magpie's Desktop profile also lists Desktop's models in `inferenceModels` (`DesktopInferenceModels` in [`desktop_list.go`](../../internal/gateway/desktop_list.go)), so a pick that isn't a Claude model runs in the Code tab with the prompt of its tier's newest Claude model (`behavesAs`: `claude-opus-5-5`, `claude-sonnet-5-5`, `claude-haiku-5-5`, Desktop's catalog v3739; `claude-fable-5-2`, Claude Code 2.1.321's newest Fable, which Desktop's catalog v4371 doesn't list yet), not Claude Code's generic one (moer2831 on Discord). Desktop 4.29 and later hand Claude Code `behavesAs` only from that list (z3t in its app.asar, 4.4212: `modelPicker.options` with each entry's `behavesAs`); the gateway's `behaves_as` row field feeds Desktop's own effort profile only. A non-empty list replaces `/v1/models` in Desktop's menus (pzn: a discovered row gives only its name and description, by id), so the list is every row `/v1/models` gives Desktop, by its id and in its order, each with what Desktop would have read off the row: `supports1m` for a window of 1M and up, `prefer1m` (and the row's `display_name` as `labelOverride`, where Desktop names the row by display_name) for a model listed by its `[1m]` id, and a pick's `anthropicFamilyTier` with `isFamilyDefault`. Desktop keys the list by name and reads one tier off an entry (FPn in its app.asar, 4.23118: the entry tagged with a tier names its `ANTHROPIC_DEFAULT_<TIER>_MODEL`), so a model picked for two tiers is tagged with the first (`desktopTierOf`). Each later tier (`desktopSharedTiers`) gets the model's id form under a number of its own (`desktopTierAlias`: magpie-<number>.anthropic.<model>, mythos-magpie-<number> or anthropic/magpie-<number>), which `aliased` reads back to the model, so the gateway serves it as the pick (`desktopTierAsked`). That id is a row of Desktop's `/v1/models` only (`DesktopTierRows`, a copy of the model's row tagged `anthropic_family_tier` and `is_family_default`), never a list entry: the list is Desktop's model menu, and an entry there showed as a model of its own, "Gemini 4 Hydrogen · haiku" beside "Gemini 4 Hydrogen" (yanghonghang on X, v0.1.3997). Desktop's discovery pins a tier the list leaves out from a tagged row (`shortnameIdentityOverrides` in its app.asar, 4.23118, under the list's own pins), and with a list it reads `/v1/models` only when the profile says `modelDiscoveryEnabled`, which magpie's profile carries while a tier is shared (`DesktopDiscovers`). The later tier has no `behavesAs`, which Desktop takes only from the list, so a model that isn't Claude runs there on Claude Code's generic prompt. Before, the later tier had no model: copilot/claude-sonnet-5.5 picked for sonnet and haiku gave Claude Code an empty `ANTHROPIC_DEFAULT_HAIKU_MODEL`, and its small tasks, WebFetch's page summaries among them, ran on the session's model. A Claude model picked runs as itself where Claude Code knows it by the id it is listed by; a routing group led by one is listed by its mythos-magpie-<number> and runs as the group's model, as one listed by anthropic/magpie-<number> does (`desktopRunsAs`; `TestDesktopTierSharedPick`, `TestDesktopGroupPickRunsAsItsModel`). Nothing picked (or a pick of a model no longer listed): no list, and Desktop finds the models as before, unless two rows are named after one Claude model of Desktop's catalog, when the list is written for its `labelOverride`s alone (`desktopNamesClash`, onkashiko on X). Picks that can't be read are unknown, and what is written stays. Older builds take the entries' names and drop the rest (2.7032's entry is a zod object, which strips unknown keys). Desktop reads its profile only as it starts, so the tiers' menu says to restart it, and the Agents row's Restart shows (`AppBehind` reads the profile). `TestDesktopInferenceModels`.
- Claude Code's WebSearch subrequest in Desktop's gateway mode goes to `DesktopTiers()["haiku"]` when that pick is set and served (`desktopSearchCall`, `desktopSearchTier`, `movedSearch` in [`desktop.go`](../../internal/gateway/desktop.go): exactly one `web_search_*` server tool, forced by `tool_choice` to `web_search`); without a usable pick the existing routing stays as it was, since Desktop disables GrowthBook and Claude Code 2.1.321's small-model search flag defaults off. A moved search never changes `desktopPicked`, and a subagent's search is a helper call exempt from its model, effort and turn tag only when a served haiku pick takes it, even when it already asked for that model; without one its existing subagent routing stays as it was, and terminal Claude Code is unchanged (`desktopSearchHelper`; `TestDesktopWebSearchHaiku`, `TestDesktopWebSearchKeepsSessionPick`, `TestDesktopSubagentWebSearchIsHelper`, `TestDesktopWebSearchLeavesTerminalSubagent`).
- A request naming magpie's own id for a model it listed Claude Desktop (`claudeLooking`: `magpie-<n>.anthropic.<model>`, `mythos-magpie-<n>`, `anthropic/magpie-<n>`, or a later tier's `desktopTierAlias`) is served by the model whose id gives `<n>` (`aliased`): the catalog's first, then the models picked for Desktop's tiers (`DesktopTiers`, a routing group's id left out). A pick the catalog leaves out for now, its provider's list having come back without it, refused a while (`copilotRefuses`) or its picks waiting for it, is still the session's model and goes to its provider as asked. Before, the id was taken for a model magpie doesn't serve, and the session's turns went to the model the last turn of any Desktop session ran on (`desktop-gone`, `desktopPicked`): Copilot's `/models` answered without its Claude models for an hour, and a chat on Copilot's Opus 5.5 was answered by another provider's model, the one another chat ran on, with Desktop still saying Opus (mdwsk88). An id that names no model still, but names a Claude model (`magpie-<n>.anthropic.claude-opus-5-5`, `aliasClaude`), goes to the model picked for that model's tier (`desktopTierTurn`, `desktop-tier`), as Claude Code's own id of one does; any other, or one whose tier has no pick, goes as before (`TestDesktopAliasOfTierPickLeftOutOfCatalog`, `TestDesktopAliasSkipsGroupPick`, `TestDesktopClaudeAliasGoneTakesItsTier`, `TestDesktopAliasLeftOutRoute`).
- Antigravity answers a system instruction holding one of a few lines with a 429 "Resource has been exhausted" whatever quota is left, on every model (`agTurnedAway` in [`codeassist.go`](../../internal/gateway/codeassist.go)): Claude Code's billing line, the Claude Agent SDK's identity line, Codex's identity lines for its GPT-5 models (which a Codex thread begun on a GPT model keeps after a switch), Hermes Agent's earlier default persona, and oh-my-pi's RFC 2119 line; since the evening of 11-14 also "You are Hermes Agent" (Hermes' current persona), "You are OpenCode", Codex CLI's "You are a coding agent running in the Codex CLI" (its prompt for models it has none of its own for) and pi's "a coding assistant running inside pi". Codex's GPT-6 prompt, Claude Code's own line, Gemini CLI, Qwen Code, Cline, Kilo, goose, Amp, Droid, Kimi, Aider and Cursor pass as written (real account, 11-14). An Antigravity account's system instruction goes with each such line reworded with the same meaning (`antigravityCloak`, `agSaidAs`, in `codeAssistBody`): the billing line left out, "built on the Claude Agent SDK by Anthropic", Codex's "built on GPT-5", Hermes' "built by Nous Research", oh-my-pi's "RFC 2119 key words", "You're" for Hermes', OpenCode's and Codex CLI's "You are", and pi's "running within pi". The refusal's hint names the agent (`antigravityHint`: Codex, Codex CLI, Hermes, OpenCode, pi, RFC), word for word as the antigravity and agy-cli plugins and the Routing page's `HINTS` have it. Until 11-14 they went broken up by zero-width spaces; since then Google's check reads past invisible characters and turned every broken-up line away 5 of 5 on a real account, so a line is also matched with invisible characters inside it and a copy an older magpie or middleware broke up is reworded too. Every other provider, Gemini CLI's sign-in on the same envelope included, is sent the prompt as written. `magpie provider set antigravity prompt=as-written` (`Provider.PromptAsWritten`) turns it off. The refusal is still told against the system prompt as the agent wrote it (`antigravityTurnedAway`): a 400 with the hint for that prompt, the account not rested, and a group skipping Antigravity for that prompt for 6 hours after a refusal (`antigravityForeseen`).
- Antigravity answers a system instruction holding one of a few lines with a 429 "Resource has been exhausted" whatever quota is left, on every model (`agTurnedAway` in [`codeassist.go`](../../internal/gateway/codeassist.go)): Claude Code's billing line, the Claude Agent SDK's identity line, Codex's identity lines for its GPT-5 models (which a Codex thread begun on a GPT model keeps after a switch), Hermes Agent's earlier default persona, and oh-my-pi's RFC 2119 line; since the evening of 11-14 also "You are Hermes Agent" (Hermes' current persona), "You are OpenCode", Codex CLI's "You are a coding agent running in the Codex CLI" (its prompt for models it has none of its own for) and pi's "a coding assistant running inside pi". Codex's GPT-6 prompt, Claude Code's own line, Gemini CLI, Qwen Code, Cline, Kilo, goose, Amp, Droid, Kimi, Aider and Cursor pass as written (real account, 11-14). An Antigravity account's system instruction goes with each such line reworded with the same meaning (`antigravityCloak`, `agSaidAs`, in `codeAssistBody`): the billing line left out, "built on the Claude Agent SDK by Anthropic", Codex's "built on GPT-5", Hermes' "built by Nous Research", oh-my-pi's "RFC 2119 key words", "You're" for Hermes', OpenCode's and Codex CLI's "You are", and pi's "running within pi". The refusal's hint names the agent (`antigravityHint`: Codex, Codex CLI, Hermes, OpenCode, pi, RFC), word for word as the antigravity and agy-cli plugins and the Routing page's `HINTS` have it. Until 11-14 they went broken up by zero-width spaces; since then Google's check reads past invisible characters and turned every broken-up line away 5 of 5 on a real account, so a line is also matched with invisible characters inside it and a copy an older magpie or middleware broke up is reworded too. Every other provider, Gemini CLI's sign-in on the same envelope included, is sent the prompt as written (Gemini CLI's without the billing line, above). `magpie provider set antigravity prompt=as-written` (`Provider.PromptAsWritten`) turns it off. The refusal is still told against the system prompt as the agent wrote it (`antigravityTurnedAway`): a 400 with the hint for that prompt, the account not rested, and a group skipping Antigravity for that prompt for 6 hours after a refusal (`antigravityForeseen`).
- 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)). The model Claude Code names is first taken to the id magpie serves, as a request's own model is (`advisorID`): a dotted Claude id is given to Claude Code with dashes, and the advisor came back so, so `relay/claude-fable-5-2` on a provider listing `claude-fable-5.2` went upstream as `claude-fable-5-2`, a name the relay doesn't know (Refeccd on Discord); one it can't run there (another provider's, a group, not Claude's) is run by magpie when magpie serves it (below) and otherwise 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 bridge runs it as magpie does on a translation (below, and [claude-subscription-bridge.md](claude-subscription-bridge.md)). `TestAdvisorModelAsTheUpstreamNamesIt`, `TestAdvisorLeftOutOnTranslation`.
- magpie runs Claude Code's advisor itself where the upstream can't and the advisor's model is one magpie serves (`provider.Resolve` takes it; `advisedHere` in [`advisor_serve.go`](../../internal/gateway/advisor_serve.go), Awad_Yoo on X). Claude Code sends the advisor for any model only with `CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL` set (2.1.316), which the Claude Code advisor field writes (agent-wiring.md). Such a request is translated, a relay on Messages too (`ownAPI`): the server tool becomes `Request.Advisor`, and the model is offered a function tool `advisor` with no parameters (`advisorToolDef`, a neutral description naming neither magpie nor a vendor), Claude Code's instructions and `tool_addition` kept as written. A call of it is answered inside the reply's rounds, beside web search's (`searchRounds`, `adviceRound`): the advisor model is asked through the gateway (`advise`, User-Agent `magpie-advisor/1`, the executor's system prompt and conversation, what the model said before the call, its tools offered with `tool_choice` none, no reasoning, and a short ask appended to the last user message, `adviceFor`; Claude Code's advisor instructions are cut from its system prompt and messages, `advisorCut`, since with them, or `advisorGone` in their place, the advisor answered as the executor that it had no advisor, #6804), and the reply goes on with the advice as the call's result. Claude Code is told as Anthropic's server tells it: a `server_tool_use` (`srvtoolu_…`, empty input) and an `advisor_tool_result` with `{type: advisor_result, text}`, or `{type: advisor_tool_result_error, error_code}` (`unavailable`, `too_many_requests`, `overloaded`, `prompt_too_long`, `execution_time_exceeded`, or `max_uses_exceeded` past three calls a reply). Claude Code echoes both blocks in the next turn's assistant message; `readAdvised` reads them back as the model's call and its result, splitting the message around them (`adviceApart`). Not handled: a round that calls the advisor beside an agent tool keeps the agent's tool call only, as with web search. `TestAdvisorServedForAVendorModel`, `TestAdvisorHistoryGoesBackAsACall`, `TestAdvisorFailureIsAnErrorCode`, `TestAdvisedHere`.
- An advisor Anthropic's server runs (the request relayed on Messages, `advisorTools` above) bills apart from the request's model: the reply's top-level `usage` is the executor's alone, and each call is an `advisor_message` entry of `usage.iterations`, with its `model` and token counts, billed at the advisor model's rates and in no top-level total (Anthropic's advisor tool page, "Usage and billing"). The ledger had the executor's row only, so an Opus advisor beside a Sonnet executor was in no row (#6977, Refeccd on Discord). `aUsage.Iterations` is read (whole, and from a stream's `message_delta`, whose list holds every call so far and replaces the one before: `Usage.advised`), and each advisor call is a usage row of its own (`advisorRows` in [`advisor_usage.go`](../../internal/gateway/advisor_usage.go), written by `appendAdvised` beside every row of a try that reached a provider, and on the native route): under the advisor's model by magpie's id (`advisorKeyModel` of the request's advisor tool, `advisedAs` in `passthrough`; else the vendor's name), its `Served` the vendor's, `Kind` `advisor` (`usage.KindAdvisor`, named Advisor on Usage's Requests and filters), the request's route, agent, account and session, status 200, no timing. It counts as a request of its own, as an advisor call magpie runs itself does (below). The executor's row is as the reply said; nothing is taken from it. Routing prices the calls too, before the request's own usage (`advisorRouteUsage`), so the prompt is still read from the last. Not captured from a real reply: the fixture is Anthropic's documented example word for word. `TestAdvisorIterationsRead`, `TestAdvisorCallHasItsOwnRow`.
+18 -3
View File
@@ -18,8 +18,20 @@ import (
// without the line (#1600, justrun1983). It goes on only to a Claude model
// asked on Anthropic's Messages API (Anthropic's own, a relay's, Bedrock's),
// as Claude Code sent it. The Claude subscription's run sends its own
// (withoutBillingHeader), another magpie decides for the provider it picks,
// and Code Assist is sent it as before (antigravityTurnsAway, #666).
// (withoutBillingHeader), and another magpie decides for the provider it
// picks.
//
// A Gemini CLI sign-in goes without it too: Code Assist was sent it as
// Gemini's first system words, so Gemini's implicit cache, which needs the
// same prefix, read nothing on any turn in Claude Code (niyezaimenglima on
// X: "缓存命中是0"). Every other Code Assist route is handed it as before.
// The built-in Antigravity account's cloak leaves it out on the way
// (antigravityCloak), and its refusal is told against the system as
// written, line and all (antigravityTurnsAway, #666). A plugin's request is
// the plugin's: Antigravity's, agy-cli's and Zed's cloaks match the line to
// the end of its line, which takes Claude Code's identity sentence after
// it, so with the line cut here that sentence reached Antigravity, and it
// answered the 429 it gives Claude Code's prompt.
// billingLine is a system block that is the billing line and nothing else.
var billingLine = lazyre.New(`^x-anthropic-billing-header:(\s*[A-Za-z_]+=[^;\s]*;)*\s*$`)
@@ -34,7 +46,10 @@ func keepsBillingLine(to provider.Protocol, model, wire string) bool {
// dropsBillingLine says whether p's request for model asked on to goes
// without the billing line.
func dropsBillingLine(p provider.Provider, to provider.Protocol, model, wire string) bool {
return !p.IsRemoteMagpie() && to != provider.CodeAssist && !keepsBillingLine(to, model, wire)
if to == provider.CodeAssist {
return accountAgent(p) == "gemini"
}
return !p.IsRemoteMagpie() && !keepsBillingLine(to, model, wire)
}
// withoutBillingLine is an Anthropic Messages body without Claude Code's
+93
View File
@@ -1,12 +1,16 @@
package gateway
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
@@ -188,3 +192,92 @@ func TestBillingLineKeptForClaude(t *testing.T) {
}
}
}
// A Gemini CLI sign-in in Claude Code read nothing from Gemini's cache on
// any turn (niyezaimenglima on X: "缓存命中是0"): Code Assist was sent the
// billing line as the system instruction's first words, and its cch
// changes every turn, so the prefix Gemini's implicit cache needs was new
// each time. Two turns that differ only in cch now go the same, without
// the line.
func TestBillingLineLeftOutForCodeAssist(t *testing.T) {
fresh(t)
dir := filepath.Dir(provider.Path())
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
logins := []map[string]any{{"agent": "gemini", "user": "u@example.com", "on": true,
"auth": map[string]any{"access_token": "tok", "refresh_token": "ref", "project": "p1", "expiry_date": time.Now().Add(time.Hour).UnixMilli()}}}
if err := os.WriteFile(filepath.Join(dir, "logins.json"), mustJSON(logins), 0o600); err != nil {
t.Fatal(err)
}
old := http.DefaultClient
http.DefaultClient = &http.Client{Transport: countTransport(func(r *http.Request) (*http.Response, error) {
if strings.Contains(r.URL.Path, ":loadCodeAssist") {
return &http.Response{StatusCode: 200, Header: make(http.Header),
Body: io.NopCloser(strings.NewReader(`{"currentTier":{"id":"standard-tier"},"cloudaicompanionProject":"p1"}`))}, nil
}
return nil, fmt.Errorf("unexpected request to %s", r.URL)
})}
t.Cleanup(func() { http.DefaultClient = old })
var mu sync.Mutex
var sent []string
s := New()
s.client = &http.Client{Transport: countTransport(func(r *http.Request) (*http.Response, error) {
b, _ := io.ReadAll(r.Body)
if strings.Contains(r.URL.Path, "GenerateContent") {
mu.Lock()
sent = append(sent, string(b))
mu.Unlock()
}
rec := httptest.NewRecorder()
rec.Header().Set("Content-Type", "text/event-stream")
io.WriteString(rec, sse(`data: {"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"hi"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":1}}}`))
return rec.Result(), nil
})}
for _, cch := range []string{"aaaaa", "bbbbb"} {
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/messages?beta=true", strings.NewReader(claudeCodeTurn("gemini/gemini-3.5-pro", cch)))
req.Header.Set("User-Agent", "claude-cli/2.1.114 (external, sdk-cli)")
req.Header.Set("Authorization", "Bearer "+Token)
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
}
if len(sent) != 2 {
t.Fatalf("asked %d times, want 2", len(sent))
}
for _, b := range sent {
if strings.Contains(b, "x-anthropic-billing-header") || strings.Contains(b, "cch=") {
t.Fatalf("billing line sent: %s", b)
}
if !strings.Contains(b, "You are a Claude agent") {
t.Fatalf("prompt lost: %s", b)
}
}
a := gjson.Get(sent[0], "request.systemInstruction").Raw
if a == "" || a != gjson.Get(sent[1], "request.systemInstruction").Raw {
t.Fatalf("system instructions differ:\n%s\n%s", sent[0], sent[1])
}
}
// Every other Code Assist route is still handed the line. The built-in
// Antigravity account's cloak leaves it out on the way, and its refusal is
// told against the system as Claude Code wrote it (#666). A plugin's cloak
// takes the line to its end, Claude Code's identity sentence with it: cut
// here, the sentence reached Antigravity's plugin on its own, and a real
// account answered the 429 it gives Claude Code's prompt.
func TestBillingLineCodeAssistOthers(t *testing.T) {
ag := provider.Provider{ID: "antigravity", Account: &provider.Account{Agent: "antigravity"}}
if dropsBillingLine(ag, provider.CodeAssist, "gemini-3.5-pro", "gemini-3.5-pro") {
t.Fatal("Antigravity's line dropped before its cloak")
}
pl := provider.PluginAtForTest("antigravity-plugin", "antigravity", "https://example.com")
if dropsBillingLine(pl, provider.CodeAssist, "gemini-3.5-pro", "gemini-3.5-pro") {
t.Fatal("a Code Assist plugin's line dropped before its cloak")
}
gm := provider.Provider{ID: "gemini", Account: &provider.Account{Agent: "gemini"}}
if !dropsBillingLine(gm, provider.CodeAssist, "gemini-3.5-pro", "gemini-3.5-pro") {
t.Fatal("Gemini CLI's line kept")
}
}
+3 -2
View File
@@ -8692,8 +8692,9 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
if to == provider.CodeAssist && p.Account != nil {
// the envelope is named in there, where the id it carries is
// known: on Antigravity that is the variant the effort picked,
// not the model magpie knows
body = codeAssistBody(p, req, model, wires)
// not the model magpie knows. It is built from what goes
// (sent), the billing line left out as for buildFor
body = codeAssistBody(p, sent, model, wires)
} else if wire != model {
// the vendor's own name for the model goes in the model field
// and nowhere else: everything above shaped the request from