Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gateway: a Responses client's cache marks to Claude last an hour (#3972)
yetone8c5c83c9fcd4
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 60d613082..28882f6f0 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -275,6 +275,7 @@ recorded as a prediction failure (`noPrediction`).- 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), and Hermes Agent's earlier default persona. An Antigravity account's system instruction goes with a zero-width space after each such line's first letter (`antigravityCloak`, in `codeAssistBody`), which Google lets through and the model reads the same; 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`).- Claude Code's advisor (`/advisor`, `--advisor`) is Anthropic's server tool `advisor_20260301`, its `model` named as Claude Code names its own: on magpie, by magpie's id (the tier an alias like `opus` is on), which no vendor knows, so the request was turned away whole (JackChou on Discord). Relayed on Messages (`passthrough`), the advisor's model goes as the upstream's own name for it when it is the same provider's Claude model, or a Claude id naming no provider (`advisorTools` in [`advisor.go`](../../internal/gateway/advisor.go)); one it can't run there (another provider's, a group, not Claude's) is left out, as is every advisor when the request's own model isn't a Claude model (a vendor's Messages API knows no such tool), and the turn is answered without one. A translation drops it with every other server tool. Claude Code (2.1.300) also puts the advisor in the conversation: a `{role: "system"}` message whose text ends in its instructions ("# Advisor Tool … call advisor BEFORE substantive work") and a `tool_addition` naming it. Where the advisor is left out, that `tool_addition` goes too (and a message it leaves empty), and the instructions become Claude Code's own "The advisor tool is no longer available; disregard the earlier advisor instructions." (`withoutAdvisor` on Messages, `advisorGoneIn` in `parseAnthropic` for a translation): left there, the model called `advisor()` as one of the agent's tools and Claude Code answered "No such tool available: advisor" (JackChou on Discord). The Claude subscription's run declares only magpie's tools, so it never has one. `TestAdvisorModelAsTheUpstreamNamesIt`, `TestAdvisorLeftOutOnTranslation`.- Kiro is told where to cache the prompt (plugins#110: a Kiro subscription read 0 from its cache). Its API takes Bedrock's `cachePoint: {"type":"default"}` on a `userInputMessage`, an `assistantResponseMessage` or as a tool entry. The built-in (`buildKiro` in [`kiro.go`](../../internal/gateway/kiro.go)) marks the first message when there is a system prompt, which it folds into that message, and the current message, as `buildAnthropic` marks Anthropic's. A moved Kiro's plugin (opencode-kiro-auth 0.1.10, the mover's `min`) turns each `cache_control` in the Anthropic body it is handed into one, at most 4, the last kept.+- The cache marks `buildAnthropic` adds for a Responses client (Codex) to a Claude model last an hour (`addedMark`, `Request.hourMarks`; 7eleven on Discord): Codex's turns are often more than five minutes apart, and Codex's own vendor keeps a thread cached an hour (`chatGPTCold`). A 1h write costs 2x the input price where Anthropic's default 5m costs 1.25x and a read 0.1x or less, so one turn read after a 5 to 60 minute pause, which a 5m mark would have written again, pays for the dearer writes of dozens of turns in quick succession. Every mark it adds has the same ttl, since Anthropic refuses a 1h mark after a 5m one. The client's `prompt_cache_retention: "in_memory"` keeps them at 5m. A Chat client's marks, a model that isn't Claude's, and marks a client placed itself (an Anthropic client's, relayed as sent) are unchanged. An upstream that answers 400 naming `cache_control` and `ttl` (a relay that knows no ttl) is asked again at 5m and remembered in `unfit` (`hourMarksRefused`) until magpie restarts. A Claude subscription is served by Claude Code, which already asks 1h ([Claude subscription bridge](claude-subscription-bridge.md)). `TestResponsesToClaudeMarksLastAnHour`, `TestHourMarksRefused`.- A model that refuses a conversation ending with the assistant's message (`refusesPrefill`: OpenCode Go's Claude models over Messages, "This model does not support assistant message prefill"; Volcengine's Agent Plan, "…for a model that does not support prefill"; Gemini's, "Requests ending with a model turn are not supported") is marked for that provider, model and API (`prefillRefused`, #1447); the provider's other models keep their prefill ([`prefill.go`](../../internal/gateway/prefill.go)). A Chat or Responses client's conversation ending with the assistant's message, which those APIs read as a turn already said (`Request.LastIsTurn`), is asked again with a user turn after it (`continueText`), translated (`forwardTranslated`) or relayed (`passthrough`, `userLastBody`), and so from then on. An Anthropic client's prefill is its own ask and gets the refusal as sent. magpie's own continuation of a cut reply (`continuation.go`) isn't asked of that model again; the try the model refused ends the reply with what cut it, not with the refusal. A request magpie builds in Gemini's own shape (`buildCodeAssistSent`: Vertex AI, Gemini CLI's and Antigravity's Code Assist, Factory) never ends with the model's turn, which all of them turn away: a user turn goes after it, `continueText`, or `compactLastText` when an agent is compacting with its ask in the system prompt (`modelLastAsk`), as one goes before a history that opens with the model's. Nor does it send a user turn that mixes a tool's `functionResponse` with text, which Vertex AI answers with the same "ending with a model turn" (#1533: Codex's compaction prompt after a tool's output): what the user said goes in a user turn of its own after the tools' responses (`hasResponse`), except for a Claude model on Antigravity, whose tool_result turn holds both.- A tool's `strict` that an upstream turns away (`toolStrictRefusal` in [`strict_refused.go`](../../internal/gateway/strict_refused.go): "Unsupported Chat Completions API field: tools[0].function.strict", OpenAI-style unknown_parameter, "Extra inputs are not permitted" and pydantic's extra_forbidden on it) is asked once more without it, in Chat's `tools[].function` and Responses' `tools[]` alike, and marked for that provider and API (`toolStrictRefused`): its next requests go without it at once. OpenCode 2 sends `"strict": false` on every tool through `@ai-sdk/openai-compatible`, and a custom provider that refused it ended the session (#1980). An upstream that hasn't refused it still gets it, as the ChatGPT backend needs it (#383). `TestToolStrictLeftOutWhereRefused` (real OpenCode 2.0.25 requests), `TestToolStrictRefusalWordings`.- A history call to a tool the request doesn't declare, which an agent that loads its tools on demand sends (pi's and T3 Code's `tool_search`: the tools a search found are called in the history but not declared in the next request's `tools`, and pi sends `"tools": []` with no tools left; Gearclickist on Discord), goes as sent where it is taken: OpenAI's Chat and Responses, the ChatGPT backend and Gemini take it, and Anthropic takes a call to a tool it isn't given ([`undeclared_tools.go`](../../internal/gateway/undeclared_tools.go)). Anthropic refuses calls with no tools at all ("Requests which include `tool_use` or `tool_result` blocks must define tools"), so `anthropicBody` declares a stub for each tool the history called when the request has none (description "Called earlier in this conversation; not available now.", any object as its input) with `tool_choice` `none`, as the Kiro plugin declares its history's tools for Kiro. An upstream that turns the request away naming such a tool as not found, unknown or not defined, or that says tools must be defined beside the calls (`refusesHistoryTools`: a relay in front of Kiro or Bedrock, a vendor checking each name), is asked once more with a stub declared for each tool the history called and `tools` lacks (`withHistoryTools`, Chat, Responses and Messages bodies, relayed or translated), `tool_choice` `none` only where the client offered no tools, and marked for that provider and API (`historyToolsRefused`): its next requests carry the stubs at once. A Responses call under a namespace is the namespace's, and a request whose calls are all declared goes as it was. `TestUndeclaredHistoryToolRefusedThenStubbed`, `TestToollessHistoryToAnthropicDeclaresStubs`, `TestToollessHistoryRefusedOnChat`, `TestUndeclaredHistoryToolTakenAsSent`, `TestRefusesHistoryToolsMatch`.diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.goindex 96d136a0d..0f3101705 100644--- a/internal/gateway/anthropic.go+++ b/internal/gateway/anthropic.go@@ -77,6 +77,21 @@ func (b aBlock) MarshalJSON() ([]byte, error) {// ephemeral marks a prompt-cache breakpoint.var ephemeral = map[string]string{"type": "ephemeral"}+// addedMark is the mark anthropicBody puts on what it marks for the cache:+// Anthropic's default five minutes, or an hour for a request whose turns+// are often further apart (Request.hourMarks) to a Claude model. A 1h write+// costs 2x the input price where a 5m one costs 1.25x, and a read 0.1x or+// less: one turn after a pause of 5 to 60 minutes, read where it would+// have been written again, pays for the dearer writes of dozens of+// requests in quick succession. Every mark it adds has the same TTL, so+// none comes after a shorter one, which Anthropic refuses.+func addedMark(r *Request, model string) map[string]string {+ if r.hourMarks && anthropicModel.MatchString(model) {+ return cacheMark1h()+ }+ return ephemeral+}+type aRequest struct {Model string `json:"model"`System json.RawMessage `json:"system,omitempty"`@@ -955,11 +970,12 @@ func anthropicBody(r *Request, model, host string, replay bool) []byte {// which only adds to it, reads it from the cache; thinking can't be// marked. Two marks at most, with the one Claude's sign-in adds kept// within Anthropic's four.+ mark := addedMark(r, model)if n := len(msgs); n > 0 {c := msgs[n-1].Contentfor i := len(c) - 1; i >= 0; i-- {if c[i].Type != "thinking" && c[i].Type != "redacted_thinking" {- c[i].CacheControl = ephemeral+ c[i].CacheControl = markbreak}}@@ -969,7 +985,7 @@ func anthropicBody(r *Request, model, host string, replay bool) []byte {if r.System != "" {// the tools and system prompt, the same every turn, are cached// apart from the conversation- out["system"] = []aBlock{{Type: "text", Text: r.System, CacheControl: ephemeral}}+ out["system"] = []aBlock{{Type: "text", Text: r.System, CacheControl: mark}}}maxTokens := r.MaxTokensif maxTokens <= 0 {@@ -1057,7 +1073,7 @@ func anthropicBody(r *Request, model, host string, replay bool) []byte {tools = append(tools, map[string]any{"name": t.Name, "description": t.Description, "input_schema": schema})}if r.System == "" && len(tools) > 0 {- tools[len(tools)-1]["cache_control"] = ephemeral+ tools[len(tools)-1]["cache_control"] = mark}if r.WebSearch {tools = append(tools, map[string]any{"type": "web_search_20250305", "name": "web_search", "max_uses": 5})diff --git a/internal/gateway/anthropic_hour_marks_test.go b/internal/gateway/anthropic_hour_marks_test.gonew file mode 100644index 000000000..5d6803794--- /dev/null+++ b/internal/gateway/anthropic_hour_marks_test.go@@ -0,0 +1,157 @@+package gateway++import (+ "bytes"+ "encoding/json"+ "strings"+ "testing"++ "github.com/yetone/magpie/internal/provider"+)++// hourTurn is a Responses (Codex) turn with a system prompt, a tool call and+// its result, with extra top-level fields spliced in.+func hourTurn(extra string) []byte {+ return []byte(`{"model":"m","instructions":"be brief","stream":true` + extra + `,+ "tools":[{"type":"function","name":"shell","parameters":{"type":"object"}}],+ "input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"list files"}]},+ {"type":"function_call","call_id":"c1","name":"shell","arguments":"{\"cmd\":\"ls\"}"},+ {"type":"function_call_output","call_id":"c1","output":"a.go b.go"}]}`)+}++// markTTLs lists the ttl of every cache_control in an Anthropic body, ""+// for a mark with none (Anthropic's five minutes).+func markTTLs(t *testing.T, b []byte) []string {+ t.Helper()+ var out struct {+ System []aBlock `json:"system"`+ Tools []map[string]any `json:"tools"`+ Msgs []struct {+ Content []aBlock `json:"content"`+ } `json:"messages"`+ }+ if err := json.Unmarshal(b, &out); err != nil {+ t.Fatalf("%v: %s", err, b)+ }+ var ttls []string+ for _, s := range out.System {+ if s.CacheControl != nil {+ ttls = append(ttls, s.CacheControl["ttl"])+ }+ }+ for _, tl := range out.Tools {+ if cc, ok := tl["cache_control"].(map[string]any); ok {+ ttl, _ := cc["ttl"].(string)+ ttls = append(ttls, ttl)+ }+ }+ for _, m := range out.Msgs {+ for _, c := range m.Content {+ if c.CacheControl != nil {+ ttls = append(ttls, c.CacheControl["ttl"])+ }+ }+ }+ if n := strings.Count(string(b), `"cache_control"`); n != len(ttls) {+ t.Fatalf("%d marks, %d read: %s", n, len(ttls), b)+ }+ return ttls+}++// 7eleven (Discord #feedback, 10-28): a Codex turn served by a Claude model+// on Anthropic's Messages had magpie's cache marks at the default five+// minutes, so a thread's prompt was written again after every pause longer+// than that. A Responses client's marks last an hour, every one of them (a+// 1h mark after a 5m one is refused), unless the client asked for its+// prompt to be kept in memory only; a Chat client's, and a model that+// isn't Claude's, stay at five minutes.+func TestResponsesToClaudeMarksLastAnHour(t *testing.T) {+ for _, c := range []struct {+ name string+ parse func() (*Request, error)+ model string+ noSys bool+ want string+ }{+ {"responses", func() (*Request, error) { return parseResponses(hourTurn("")) }, "claude-sonnet-5", false, "1h"},+ {"responses, tools marked", func() (*Request, error) { return parseResponses(hourTurn("")) }, "claude-sonnet-5", true, "1h"},+ {"responses, a vendor's name", func() (*Request, error) { return parseResponses(hourTurn("")) }, "anthropic/claude-opus-5-5", false, "1h"},+ {"responses, 24h asked", func() (*Request, error) { return parseResponses(hourTurn(`,"prompt_cache_retention":"24h"`)) }, "claude-sonnet-5", false, "1h"},+ {"responses, in_memory asked", func() (*Request, error) { return parseResponses(hourTurn(`,"prompt_cache_retention":"in_memory"`)) }, "claude-sonnet-5", false, ""},+ {"responses, not claude", func() (*Request, error) { return parseResponses(hourTurn("")) }, "glm-5", false, ""},+ {"chat", func() (*Request, error) {+ return parseChat([]byte(`{"model":"m","stream":true,+ "tools":[{"type":"function","function":{"name":"shell","parameters":{"type":"object"}}}],+ "messages":[{"role":"system","content":"be brief"},{"role":"user","content":"list files"}]}`))+ }, "claude-sonnet-5", false, ""},+ } {+ t.Run(c.name, func(t *testing.T) {+ r, err := c.parse()+ if err != nil {+ t.Fatal(err)+ }+ if c.noSys {+ r.System = ""+ }+ b := buildAnthropic(r, c.model)+ ttls := markTTLs(t, b)+ if len(ttls) < 2 {+ t.Fatalf("%d marks: %s", len(ttls), b)+ }+ for _, ttl := range ttls {+ if ttl != c.want {+ t.Fatalf("marks %q, want every one %q: %s", ttls, c.want, b)+ }+ }+ })+ }+}++// A Messages upstream (a relay) that knows no ttl in cache_control turns+// the 1h marks away with a 400: the turn is sent again at five minutes,+// and the provider is remembered, so the next turn goes so at once. A 400+// for something else is not taken for it.+func TestHourMarksRefused(t *testing.T) {+ for _, c := range []struct {+ name string+ refuse func(body []byte) (int, string)+ codes []int+ calls []int+ fits bool+ }{+ {"ttl refused", func(body []byte) (int, string) {+ if bytes.Contains(body, []byte(`"ttl"`)) {+ return 400, `{"type":"error","error":{"type":"invalid_request_error","message":"system.0.cache_control.ttl: Extra inputs are not permitted"}}`+ }+ return 0, ""+ }, []int{200, 200}, []int{2, 1}, false},+ {"refused for something else", func(body []byte) (int, string) {+ return 400, `{"type":"error","error":{"type":"invalid_request_error","message":"prompt is too long"}}`+ }, []int{400, 400}, []int{1, 1}, true},+ } {+ t.Run(c.name, func(t *testing.T) {+ f := &fake{t: t, reply: anthropicAnswer, refuse: c.refuse}+ up := setup(t, provider.Anthropic, f)+ if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"claude-sonnet-5"}, Anthropic: up.URL}); err != nil {+ t.Fatal(err)+ }+ srv := New()+ for turn := range 2 {+ calls := f.calls+ code, body := postTo(t, srv, "/v1/responses", strings.Replace(string(hourTurn("")), `"model":"m"`, `"model":"fake/claude-sonnet-5"`, 1))+ if code != c.codes[turn] || f.calls-calls != c.calls[turn] {+ t.Fatalf("turn %d: %d after %d calls, want %d after %d: %s", turn, code, f.calls-calls, c.codes[turn], c.calls[turn], body)+ }+ if c.fits && !bytes.Contains(f.got, []byte(`"ttl":"1h"`)) {+ t.Fatalf("turn %d went without 1h marks: %s", turn, f.got)+ }+ if !c.fits && bytes.Contains(f.got, []byte(`"ttl"`)) {+ t.Fatalf("turn %d's last try kept a ttl: %s", turn, f.got)+ }+ }+ if srv.fits("fake", hourMarksRefused, provider.Anthropic) != c.fits {+ t.Fatalf("fits = %v, want %v", !c.fits, c.fits)+ }+ })+ }+}diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex 9e6c9daf4..cd7a0a410 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -5394,6 +5394,10 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to// (fillsOutput)filledOutput := falsefor {+ if req.hourMarks && !s.fits(p.ID, hourMarksRefused, to) {+ r := *req+ r.hourMarks, req = false, &r+ }if mayDropImageTool(p) && !s.fits(p.ID, imageToolRefused, to) {req, _ = withoutImageToolReq(req)}@@ -5637,6 +5641,16 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, tor.LoadedInPlace, req = false, &rcontinue}+ if req.hourMarks && to == provider.Anthropic && hourMarksRefusal(res.StatusCode, b) {+ // an upstream that turns the hour's cache marks away (a relay+ // that knows no ttl) is asked again with Anthropic's default+ // five minutes, and so from then on+ log.Printf("gateway: %s turned away 1h cache marks for %s (%d); marked for 5m from now on", p.ID, model, res.StatusCode)+ s.markUnfit(p.ID, hourMarksRefused, to)+ r := *req+ r.hourMarks, req = false, &r+ continue+ }if to == provider.Anthropic && res.StatusCode == http.StatusBadRequest &&samplingDeprecated.Match(b) && (req.Temp != nil || req.TopP != nil) {// a Claude by a name samplingAsTaken can't read refuses the@@ -5976,6 +5990,16 @@ func refusesField(status int, body []byte, field string) bool {return badRequest(status) && bytes.Contains(body, []byte(field))}+// hourMarksRefused is an upstream that turned away the hour-long cache+// marks magpie adds (Request.hourMarks), as remembered in unfit.+const hourMarksRefused = "cache_control.ttl"++// hourMarksRefusal is a 400 over a cache mark's ttl: a relay that knows no+// ttl, or a 1h mark after a 5m one.+func hourMarksRefusal(status int, b []byte) bool {+ return badRequest(status) && bytes.Contains(b, []byte("ttl")) && bytes.Contains(b, []byte("cache_control"))+}+// tierField is the client's service tier as a request carries it upstream// (Request.Tier); a provider that refused it is remembered under it in unfit.const tierField = "service_tier"diff --git a/internal/gateway/ir.go b/internal/gateway/ir.goindex f25f362ac..de03bcfdf 100644--- a/internal/gateway/ir.go+++ b/internal/gateway/ir.go@@ -175,6 +175,13 @@ type Request struct {// Windows with Claude Code in WSL), so the run's own prompt describes// another machine than the one the tools run on (envElsewhereNote).envElsewhere bool+ // hourMarks has the cache marks magpie adds on Anthropic's Messages+ // (anthropicBody) last an hour: a Responses client's (Codex's), whose+ // turns are often more than five minutes apart and whose own vendor+ // keeps a thread's prompt cached an hour (chatGPTCold). Off when the+ // client asked prompt_cache_retention "in_memory", or the upstream+ // turned the ttl away (hourMarksRefused).+ hourMarks boolModel stringSystem stringdiff --git a/internal/gateway/responses.go b/internal/gateway/responses.goindex 3bf250839..c7d07b7e3 100644--- a/internal/gateway/responses.go+++ b/internal/gateway/responses.go@@ -270,11 +270,14 @@ type rRequest struct {ParallelToolCalls *bool `json:"parallel_tool_calls,omitempty"`ServiceTier string `json:"service_tier,omitempty"`PromptCacheKey string `json:"prompt_cache_key,omitempty"`- Include []string `json:"include,omitempty"`- ClientMetadata json.RawMessage `json:"client_metadata,omitempty"`- AccessPrograms json.RawMessage `json:"access_programs,omitempty"`- Text json.RawMessage `json:"text,omitempty"`- Reasoning *struct {+ // PromptCacheRetention is OpenAI's "in_memory" or "24h": the client's+ // own say over how long its prompt stays cached (hourMarks)+ PromptCacheRetention string `json:"prompt_cache_retention,omitempty"`+ Include []string `json:"include,omitempty"`+ ClientMetadata json.RawMessage `json:"client_metadata,omitempty"`+ AccessPrograms json.RawMessage `json:"access_programs,omitempty"`+ Text json.RawMessage `json:"text,omitempty"`+ Reasoning *struct {Effort string `json:"effort,omitempty"`Summary string `json:"summary,omitempty"`} `json:"reasoning,omitempty"`@@ -330,6 +333,9 @@ func readResponses(body []byte, facts bool) (*Request, error) {TopP: q.TopP, Stream: q.Stream, Parallel: q.ParallelToolCalls, Fast: q.ServiceTier == "priority" || q.ServiceTier == "ultrafast", Ultrafast: q.ServiceTier == "ultrafast", Tier: q.ServiceTier, CacheKey: q.PromptCacheKey, Include: q.Include,ClientMetadata: sentRaw(q.ClientMetadata), AccessPrograms: q.AccessPrograms}r.Text, r.Format = textFormat(sentRaw(q.Text))+ // a Responses client's turns go to Claude with hour-long cache marks,+ // unless it asked for its prompt to be kept in memory only+ r.hourMarks = q.PromptCacheRetention != "in_memory"if q.Reasoning != nil {r.Effort = effortOf(q.Reasoning.Effort)r.Thinking = true