From 99548470d0e72fa4e814666f0d1f1ea1d7c9a2be Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 11 Oct 2026 19:21:02 +0800 Subject: [PATCH] gateway: Claude Code's billing line no longer goes to vendors' models, so their prompt cache is read again (#1600, justrun1983) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude Code puts `x-anthropic-billing-header: cc_version=…; cc_entrypoint=…; cch=…;` in system[0], a block of its own whose cch changes every turn. magpie sent it on to every upstream, so a vendor's model read it as the first words of the prompt and its prefix cache missed from byte 0 on every turn: the reporter's Claude Code on commandcode-plan/deepseek-v4.1-flash read 4.1% of its input from the cache, ~96-99% with the line turned off in Claude Code. The line now goes on only to a Claude model asked on Anthropic's Messages API (a key's, a relay's, Bedrock's), byte for byte as Claude Code sent it (keepsBillingLine, billing_line.go). Everywhere else it is left out and the rest of the system goes as sent, cache_control included: - a vendor's model relayed on Messages (passthrough: DeepSeek's, Command Code's Provider API, a moved plugin's Messages); - every translation to Chat, Responses or Gemini (forwardTranslated, a Claude model on Chat too: it is for Anthropic only); - the subscriptions asked through their own clients' APIs: Cursor, Devin, Kiro, Qoder, Zed and Command Code's Go plan (attempt). Untouched: the Claude subscription (its run sends its own, already without the caller's: withoutBillingHeader), another magpie (it decides for the provider it picks) and Code Assist, where antigravityTurnsAway reads the line to explain Antigravity's refusal (#666). Tests use the reporter's literal block (cc_version=2.1.114.aff; cc_entrypoint=sdk-cli; cch=…): TestBillingLineLeftOutForVendors sends two turns differing only in cch through Messages (DeepSeek), Chat (DeepSeek and a Claude), Responses and Gemini upstreams and requires the same body without the line; TestBillingLineLeftOutOnCommandCode does it for Command Code's Go plan and Provider API; TestWithoutBillingLine covers the system string, the line inside a first block, a system of the line alone, and mentions that stay. TestBillingLineKeptForClaude and the existing TestClaudeCodeBodyReachesRelayAsSent require a Claude model's Messages body unchanged byte for byte. Broken by hand: dropsBillingLine returning false turns every vendor subtest and the Command Code test red; the backend strip removed turns the Go plan check red; keepsBillingLine returning false turns both Claude tests red. Run: go test -tags nogui ./internal/gateway (whole package), the full suite under the queue lock, gofmt -l, GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway. Not tried against a real DeepSeek or Command Code account: the cache-hit numbers are the reporter's. --- docs/subsystems/gateway-routing.md | 1 + internal/gateway/billing_line.go | 111 +++++++++++++ internal/gateway/billing_line_test.go | 219 ++++++++++++++++++++++++++ internal/gateway/gateway.go | 39 ++++- 4 files changed, 362 insertions(+), 8 deletions(-) create mode 100644 internal/gateway/billing_line.go create mode 100644 internal/gateway/billing_line_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 8deecee33..be1d77ae5 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -77,6 +77,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md). - A Claude that thinks only adaptively (`adaptiveOnly` in [`anthropic.go`](../../internal/gateway/anthropic.go): Opus, Sonnet and Haiku from 4.6 on, Fable and Mythos 5 and 5.1, read by `claudeVersion` however a relay spells them) is never sent a thinking budget, which they answer with 400. magpie's own request from a Chat or Responses client (`buildAnthropic`) goes as `thinking: {type: "adaptive", display: "summarized"}` with the effort in `output_config.effort`, so the client sees the reasoning Opus 4.7 and later otherwise leave out (display `omitted` by default), and a relay that refuses `display` is asked again without it (`refuseShapes`); a client's `thinking: {type: "enabled", budget_tokens}` is turned into the same in `forwardOnce` (`adaptiveThinking`), the budget as its nearest effort, above `high` as `max`, and `display: "summarized"` unless the client named its own display, so the thinking that enabled shows stays shown (the refused shapes are taken out after it, and `refuseShapes` reads the display as it is sent); and Pi, dsh and omp are written to ask it adaptively (`AdaptiveThinking`: `forceAdaptiveThinking`, omp's `anthropic-adaptive`; #1470). A client's `xhigh` goes as `xhigh`, except to Opus and Sonnet 4.6, which have no `xhigh` and are asked `max` (`noXhigh`, #1471). - 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 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 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`). diff --git a/internal/gateway/billing_line.go b/internal/gateway/billing_line.go new file mode 100644 index 000000000..a4e139416 --- /dev/null +++ b/internal/gateway/billing_line.go @@ -0,0 +1,111 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "regexp" + + "github.com/tidwall/gjson" + "github.com/yetone/magpie/internal/provider" +) + +// Claude Code begins its system prompt with a billing line, a block of its +// own: x-anthropic-billing-header: cc_version=…; cc_entrypoint=…; cch=…; +// whose cch changes every turn. It is for Anthropic; any other vendor's +// model reads it as the prompt's first words, so its prefix cache +// (DeepSeek's, behind Command Code's plan) missed from the first byte on +// every turn: 4% of a day's input read from the cache, against 96–99% +// 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). + +// billingLine is a system block that is the billing line and nothing else. +var billingLine = regexp.MustCompile(`^x-anthropic-billing-header:(\s*[A-Za-z_]+=[^;\s]*;)*\s*$`) + +// keepsBillingLine says whether a request for model (wire, the vendor's name +// for it) asked on to keeps Claude Code's billing line: a Claude model on +// Anthropic's Messages API. +func keepsBillingLine(to provider.Protocol, model, wire string) bool { + return to == provider.Anthropic && (anthropicModel.MatchString(model) || anthropicModel.MatchString(wire)) +} + +// 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) +} + +// withoutBillingLine is an Anthropic Messages body without Claude Code's +// billing line in its system: a block that is the line is left out, and the +// line at the start of the first block or of a system string is cut from +// it. Everything else goes as it was sent, byte for byte; a body without +// the line is body itself. +func withoutBillingLine(body []byte) []byte { + if !bytes.Contains(body, []byte("x-anthropic-billing-header:")) { + return body + } + sys := gjson.GetBytes(body, "system") + if sys.Index <= 0 { + return body + } + var out []byte + switch { + case sys.Type == gjson.String: + cut := withoutBillingHeader(sys.Str) + if cut == sys.Str { + return body + } + out = billingJSON(cut) + case sys.IsArray(): + var blocks []json.RawMessage + if json.Unmarshal([]byte(sys.Raw), &blocks) != nil { + return body + } + kept := make([][]byte, 0, len(blocks)) + changed := false + for i, b := range blocks { + text := gjson.GetBytes(b, "text") + if gjson.GetBytes(b, "type").Str != "text" || text.Type != gjson.String { + kept = append(kept, b) + continue + } + if billingLine.MatchString(text.Str) { + changed = true + continue + } + if i == 0 { + if cut := withoutBillingHeader(text.Str); cut != text.Str && text.Index > 0 { + b = append(append(append([]byte(nil), b[:text.Index]...), billingJSON(cut)...), b[text.Index+len(text.Raw):]...) + changed = true + } + } + kept = append(kept, b) + } + if !changed { + return body + } + if len(kept) == 0 { + // a system that was the line alone: none + return withoutFields(body, "system") + } + out = append([]byte("["), bytes.Join(kept, []byte(","))...) + out = append(out, ']') + default: + return body + } + res := make([]byte, 0, len(body)) + res = append(res, body[:sys.Index]...) + res = append(res, out...) + return append(res, body[sys.Index+len(sys.Raw):]...) +} + +// billingJSON is s as a JSON string, with <, > and & as they are. +func billingJSON(s string) []byte { + var b bytes.Buffer + enc := json.NewEncoder(&b) + enc.SetEscapeHTML(false) + _ = enc.Encode(s) + return bytes.TrimSuffix(b.Bytes(), []byte("\n")) +} diff --git a/internal/gateway/billing_line_test.go b/internal/gateway/billing_line_test.go new file mode 100644 index 000000000..c8017169f --- /dev/null +++ b/internal/gateway/billing_line_test.go @@ -0,0 +1,219 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/tidwall/gjson" + "github.com/yetone/magpie/internal/provider" +) + +// claudeCodeTurn is Claude Code 2.1.114's request as #1600 (justrun1983) +// shows it: the billing line first, a block of its own with no +// cache_control, its cch changing every turn, and the prompt after it +// marked for the cache. +func claudeCodeTurn(model, cch string) string { + return `{"model":"` + model + `","max_tokens":32000,"stream":true,` + + `"system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.114.aff; cc_entrypoint=sdk-cli; cch=` + cch + `;"},` + + `{"type":"text","text":"You are a Claude agent, built on Anthropic's Claude Agent SDK.","cache_control":{"type":"ephemeral"}},` + + `{"type":"text","text":"\nYou are an interactive agent & more","cache_control":{"type":"ephemeral"}}],` + + `"messages":[{"role":"user","content":[{"type":"text","text":"hi"}]}],"metadata":{"user_id":"u"}}` +} + +// The same turn with the billing line left out, every other byte as sent. +func claudeCodeTurnWithoutLine(model string) string { + return strings.Replace(claudeCodeTurn(model, "x"), `{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.114.aff; cc_entrypoint=sdk-cli; cch=x;"},`, "", 1) +} + +func TestWithoutBillingLine(t *testing.T) { + for _, cch := range []string{"9ebf3", "1778e", "0218c"} { + if got, want := string(withoutBillingLine([]byte(claudeCodeTurn("m", cch)))), claudeCodeTurnWithoutLine("m"); got != want { + t.Fatalf("cch %s:\n got %s\nwant %s", cch, got, want) + } + } + for _, c := range []struct{ in, want string }{ + // a system string, the line ahead of the prompt + {`{"system":"x-anthropic-billing-header: cc_version=2.1.114.aff; cch=0218c;You are .","x":1}`, `{"system":"You are .","x":1}`}, + // the line and the prompt in one first block + {`{"system":[{"type":"text","text":"x-anthropic-billing-header: cch=0218c;\nYou are it.","cache_control":{"type":"ephemeral"}}]}`, + `{"system":[{"type":"text","text":"You are it.","cache_control":{"type":"ephemeral"}}]}`}, + // a system that is the line alone: none at all + {`{"model":"m","system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.114.aff; cch=0218c;"}]}`, `{"model":"m"}`}, + // a prompt that only mentions the line, or a message that has it, + // goes as it was sent + {`{"system":[{"type":"text","text":"Rules mention x-anthropic-billing-header: here"}]}`, `{"system":[{"type":"text","text":"Rules mention x-anthropic-billing-header: here"}]}`}, + {`{"messages":[{"role":"user","content":"x-anthropic-billing-header: cch=1;"}]}`, `{"messages":[{"role":"user","content":"x-anthropic-billing-header: cch=1;"}]}`}, + {`{"system":[{"type":"text","text":"a"},{"type":"text","text":"b x-anthropic-billing-header: cch=1;"}]}`, `{"system":[{"type":"text","text":"a"},{"type":"text","text":"b x-anthropic-billing-header: cch=1;"}]}`}, + } { + if got := string(withoutBillingLine([]byte(c.in))); got != c.want { + t.Errorf("%s\n got %s\nwant %s", c.in, got, c.want) + } + } +} + +// billingUpstream is a provider at an upstream that answers each API with a +// short reply and keeps the bodies it was sent. +type billingUpstream struct { + mu sync.Mutex + bodies []string +} + +func (u *billingUpstream) last(t *testing.T) string { + t.Helper() + u.mu.Lock() + defer u.mu.Unlock() + if len(u.bodies) == 0 { + t.Fatal("nothing sent upstream") + } + return u.bodies[len(u.bodies)-1] +} + +func newBillingUpstream(t *testing.T) (*billingUpstream, string) { + t.Helper() + u := &billingUpstream{} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + u.mu.Lock() + u.bodies = append(u.bodies, string(b)) + u.mu.Unlock() + w.Header().Set("Content-Type", "text/event-stream") + switch { + case strings.HasSuffix(r.URL.Path, "/chat/completions"): + io.WriteString(w, chatSSE("ok", "", "")) + case strings.HasSuffix(r.URL.Path, "/responses"): + io.WriteString(w, sse( + `data: {"type":"response.output_text.delta","delta":"ok"}`, + `data: {"type":"response.completed","response":{"id":"r1","output":[],"usage":{"input_tokens":5,"output_tokens":2}}}`)) + case strings.Contains(r.URL.Path, ":streamGenerateContent"): + io.WriteString(w, sse(`data: {"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":7,"candidatesTokenCount":1}}`)) + default: + io.WriteString(w, sse( + `event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","model":"m","usage":{"input_tokens":7}}}`, + `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}`, + `data: {"type":"content_block_stop","index":0}`, + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`, + `data: {"type":"message_stop"}`)) + } + })) + t.Cleanup(srv.Close) + return u, srv.URL +} + +func claudeCodeSends(t *testing.T, body string) { + t.Helper() + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/messages?beta=true", strings.NewReader(body)) + req.Header.Set("User-Agent", "claude-cli/2.1.114 (external, sdk-cli)") + req.Header.Set("Authorization", "Bearer "+Token) + New().Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body.String()) + } +} + +// Claude Code's billing line changes every turn (cch), and a vendor's model +// read it as the first words of the prompt: DeepSeek's prefix cache missed +// from byte 0 on every turn, 4% of a day's input read from it (#1600, +// justrun1983). On every API magpie asks a vendor's model on, and for +// another API's Claude, two turns that differ only in cch now send the +// same prompt, without the line, the rest of it as Claude Code sent it. +func TestBillingLineLeftOutForVendors(t *testing.T) { + for _, c := range []struct { + name string + api func(p *provider.Provider, url string) + model string + }{ + {"messages", func(p *provider.Provider, url string) { p.Anthropic = url }, "deepseek-v4.1-flash"}, + {"chat", func(p *provider.Provider, url string) { p.Chat = url + "/v1" }, "deepseek-v4.1-flash"}, + {"chat claude", func(p *provider.Provider, url string) { p.Chat = url + "/v1" }, "claude-opus-5-5"}, + {"responses", func(p *provider.Provider, url string) { p.Responses = url + "/v1" }, "gpt-5.5"}, + {"gemini", func(p *provider.Provider, url string) { p.Gemini = url + "/v1beta" }, "gemini-3.5-pro"}, + } { + t.Run(c.name, func(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + u, url := newBillingUpstream(t) + p := provider.Provider{ID: "vendor", Name: "Vendor", Key: "k", Models: []string{c.model}} + c.api(&p, url) + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + var sent []string + for _, cch := range []string{"aaaaa", "bbbbb"} { + claudeCodeSends(t, claudeCodeTurn("vendor/"+c.model, cch)) + sent = append(sent, u.last(t)) + } + 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") || !strings.Contains(b, "You are an interactive agent") { + t.Fatalf("prompt lost: %s", b) + } + } + if sent[0] != sent[1] { + t.Fatalf("turns differ:\n%s\n%s", sent[0], sent[1]) + } + if c.name == "messages" { + // the rest of Claude Code's system as it was sent, its + // cache marks with it + sys := gjson.Get(sent[0], "system") + if want := gjson.Get(claudeCodeTurnWithoutLine("x"), "system").Raw; sys.Raw != want { + t.Fatalf("system %s, want %s", sys.Raw, want) + } + } + }) + } +} + +// A Claude model asked on Anthropic's Messages API (Anthropic's own, a +// relay's, Bedrock's) is sent Claude Code's request as it was, billing line +// and all: a relay in front of Claude Code's own sign-in may need it. +func TestBillingLineKeptForClaude(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + u, url := newBillingUpstream(t) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Anthropic: url, Models: []string{"claude-opus-5-5"}}); err != nil { + t.Fatal(err) + } + for _, cch := range []string{"aaaaa", "bbbbb"} { + claudeCodeSends(t, claudeCodeTurn("relay/claude-opus-5-5", cch)) + if got, want := u.last(t), claudeCodeTurn("claude-opus-5-5", cch); got != want { + t.Fatalf("claude body changed:\n got %s\nwant %s", got, want) + } + } +} + +// Command Code's plan, the reporter's route: a vendor's model on its +// Provider API (Messages) and on the Go plan's /alpha/generate both go +// without the line. +func TestBillingLineLeftOutOnCommandCode(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + var provided []string + gen := newCmdUpstream(t, cmdLines(`{"type":"text-delta","text":"ok"}`, cmdFinish)) + for _, cch := range []string{"aaaaa", "bbbbb"} { + body := claudeCodeTurn("deepseek/deepseek-v4.1-flash", cch) + if status, msg, _, _ := cmdAttempt(t, cmdAccount(gen, "go"), provider.Anthropic, "deepseek/deepseek-v4.1-flash", body); status != 200 { + t.Fatalf("go: %d %q", status, msg) + } + if sys := gjson.GetBytes(gen.body, "params.system").String(); strings.Contains(sys, "billing") || !strings.HasPrefix(sys, "You are a Claude agent") { + t.Fatalf("go system: %q", sys) + } + u, url := newBillingUpstream(t) + p := cmdAccount(gen, "pro") + p.Anthropic = url + if status, msg, _, _ := cmdAttempt(t, p, provider.Anthropic, "deepseek/deepseek-v4.1-flash", body); status != 200 { + t.Fatalf("pro: %d %q", status, msg) + } + provided = append(provided, u.last(t)) + } + if strings.Contains(provided[0], "billing") || provided[0] != provided[1] { + t.Fatalf("provider API:\n%s\n%s", provided[0], provided[1]) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 1758aa5c5..90d474b3b 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -2763,41 +2763,49 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P call.To = provider.Anthropic return s.serveClaudeSubscription(w, r, from, p, model, body, &call.Usage) } + // the subscriptions below are asked through their own clients' APIs, + // never Anthropic's: Claude Code's billing line, which changes every + // turn, would be the first words of their prompt and its cache missed + // from there on (#1600, billing_line.go) + own := body + if from == provider.Anthropic { + own = withoutBillingLine(body) + } // Cursor's through the API its CLI talks to, with the CLI's sign-in if p.Account != nil && p.Account.Agent == "cursor" { call.To = from - return s.serveCursor(w, r, from, model, body, &call.Usage) + return s.serveCursor(w, r, from, model, own, &call.Usage) } // Devin's through the API its CLI talks to, with the CLI's sign-in or // one magpie keeps beside it if p.Account != nil && p.Account.Agent == "devin" { call.To = from - return s.serveDevin(w, r, from, p.Account.Home, model, body, &call.Usage) + return s.serveDevin(w, r, from, p.Account.Home, model, own, &call.Usage) } // Kiro's is served through its own API, with kiro-cli's or the Kiro // IDE's sign-in, or a Kiro API key saved on the provider if p.Account != nil && p.Account.Agent == "kiro" { call.To = from - return s.serveKiro(w, r, from, p, model, body, &call.Usage) + return s.serveKiro(w, r, from, p, model, own, &call.Usage) } // Qoder is served through the API the client talks to, signed with the // COSY envelope, with the account magpie signed in to. if p.Account != nil && (p.Account.Agent == "qoder" || p.Account.Agent == provider.QoderCNID) { call.To = from - return s.serveQoder(w, r, from, p, model, body, &call.Usage) + return s.serveQoder(w, r, from, p, model, own, &call.Usage) } // Zed's through cloud.zed.dev, written in the API of the model's own // provider, with the account magpie signed in to if p.Account != nil && p.Account.Agent == "zed" { call.To = from - return s.serveZed(w, r, from, p, model, body, &call.Usage) + return s.serveZed(w, r, from, p, model, own, &call.Usage) } // Command Code's Go plan has no Provider API: it is asked where the // CLI asks, in the CLI's own format; its other plans go on as keys do if p.Account != nil && p.Account.Agent == provider.CommandCodePlanID { if api, key, ok := cmdGenerate(r.Context(), p); ok { call.To = from - return s.serveCommandCode(w, r, from, p, api, key, model, body, &call.Usage) + return s.serveCommandCode(w, r, from, p, api, key, model, own, &call.Usage) } } // Copilot's Auto (all a Student plan may pick) is asked which model it @@ -3292,6 +3300,12 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. // not the plain id Bedrock checks it against (#176) body = withoutFields(body, "metadata") } + if dropsBillingLine(p, proto, model, upstream) { + // Claude Code's billing line, which changes every turn, to a + // vendor's model: its prompt cache missed from the first + // byte (#1600, billing_line.go) + body = withoutBillingLine(body) + } if !anthropicModel.MatchString(model) { body = thinkingOffUnlessAsked(body) // Claude Code's auto mode classifier, on a vendor's model that @@ -3912,7 +3926,17 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to r := *req r.OwnTier, req = own, &r } - body, err := buildFor(p, to, req, model) + wire := provider.UpstreamNameIn(wires, p.ID, model) + sent := req + if dropsBillingLine(p, to, model, wire) && billingHeader.MatchString(req.System) { + // Claude Code's billing line, which changes every turn, as the + // first words of another API's prompt or a vendor's model's: + // its prompt cache missed from the first byte (#1600, + // billing_line.go) + r := *req + r.System, sent = withoutBillingHeader(r.System), &r + } + body, err := buildFor(p, to, sent, model) if err != nil { return nil, to, err } @@ -3923,7 +3947,6 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to // the other magpie searches for it (search_remote.go) body = withFields(body, map[string]any{"web_search_options": map[string]any{}}) } - wire := provider.UpstreamNameIn(wires, p.ID, model) 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,