diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 04fe66f36..d86db4c5a 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -669,7 +669,7 @@ conversation is written to the cache again and its images are sent again. By default, that message holds the history in blocks of `historyChunk` messages, and magpie's one mark (Claude Code keeps three of Anthropic's four) is on the last whole block, else on the caller's instructions: a later run started -anew for the same conversation within the hour reads the history up to an +anew for the same conversation while it is cached reads the history up to an earlier run's mark, found within Anthropic's 20-block lookback. A conversation with no history (no reply that calls no tool, as a sub-agent's loop of tool calls that Claude Code's AgentSummary asks a summary of) has @@ -679,6 +679,20 @@ A turn that goes on in the run that had the last one is told only the messages since (`renderClaudeTurn`), and Anthropic reads the rest from the cache. +A run keeps its prompt cache as long as the user picked for Claude Code's +main conversation (`claudeRunTTL`): `FORCE_PROMPT_CACHING_5M`, then +`CLAUDE_CODE_PROMPT_CACHE_TTL`, in magpie's environment or settings.json's +`env`, then settings.json's `promptCacheTtl` (the Agents page's "Prompt +cache · main conversation"), and an hour with none of them, as Claude Code +writes it on a subscription within its limits. The run is given it as +`CLAUDE_CODE_PROMPT_CACHE_TTL` (`cleanClaudeEnvTTL`; a saved account's +Claude Code reads its own folder's settings, not the user's), and magpie's +mark in the first message is as long (`Request.runMark`), since Anthropic +refuses a 1h mark after a 5m one. A session a run goes on from keeps the +lifetime it started with (`cachePrefix.ttl`; one saved before it was kept +is an hour's). Until 11-07 every run was given 1h whatever the pick +(linkaww). `TestClaudeRunKeepsTheUsersCacheTTL`. + ## Client-placed cache marks (#1717) A client can send `X-Magpie-Cache-Marks: client` on a `/v1/messages` diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index fe8fa1b46..e2835ecc7 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -329,7 +329,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`. +- 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 asks 1h unless the user picked 5m ([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/claude_cache.go b/internal/gateway/claude_cache.go index 1fc9a8ba7..9be2b1384 100644 --- a/internal/gateway/claude_cache.go +++ b/internal/gateway/claude_cache.go @@ -289,6 +289,17 @@ func cacheDropped(w http.ResponseWriter, req *Request) { type cachePrefix struct { count int floor string + // ttl is how long the run's Claude Code keeps its cache, as its + // first message's marks (claudeRunTTL); "" is a session saved before + // it was kept, an hour's + ttl string +} + +func (p cachePrefix) runTTL() string { + if p.ttl == "" { + return "1h" + } + return p.ttl } func (p cachePrefix) accepts(tail string) bool { diff --git a/internal/gateway/claude_prompt_cache_test.go b/internal/gateway/claude_prompt_cache_test.go index 76e2763c6..9a85bdfcf 100644 --- a/internal/gateway/claude_prompt_cache_test.go +++ b/internal/gateway/claude_prompt_cache_test.go @@ -3,6 +3,8 @@ package gateway import ( "encoding/json" "fmt" + "os" + "path/filepath" "slices" "strings" "testing" @@ -32,12 +34,73 @@ func TestClaudeInstructionsCachedApart(t *testing.T) { if len(blocks) != 1 || blocks[0]["cache_control"] != nil { t.Fatalf("no instructions: %v", blocks) } - env := cleanClaudeEnv([]string{"CLAUDE_CODE_PROMPT_CACHE_TTL=5m"}) - if !slices.Contains(env, "CLAUDE_CODE_PROMPT_CACHE_TTL=1h") || slices.Contains(env, "CLAUDE_CODE_PROMPT_CACHE_TTL=5m") { + // a value Claude Code doesn't take is no pick: the hour stays + t.Setenv("CLAUDE_CONFIG_DIR", t.TempDir()) + env := cleanClaudeEnv([]string{"CLAUDE_CODE_PROMPT_CACHE_TTL=7d"}) + if !slices.Contains(env, "CLAUDE_CODE_PROMPT_CACHE_TTL=1h") || slices.Contains(env, "CLAUDE_CODE_PROMPT_CACHE_TTL=7d") { t.Fatalf("env: %q", env) } } +// A bridge run keeps its prompt cache as long as the user picked for +// Claude Code's main conversation, in the Agents page (settings.json's +// promptCacheTtl) or a variable, and the marks magpie puts in its first +// message are as long, since Anthropic refuses a 1h mark after a 5m one. +// With nothing picked it is an hour, as before. linkaww: 5m picked, the +// run was given CLAUDE_CODE_PROMPT_CACHE_TTL=1h, and 237 of 241 relayed +// requests wrote an hour's cache. +func TestClaudeRunKeepsTheUsersCacheTTL(t *testing.T) { + for _, c := range []struct { + name, settings, env, force, want string + }{ + {name: "nothing picked", want: "1h"}, + {name: "agents page 5m", settings: `{"promptCacheTtl":"5m"}`, want: "5m"}, + {name: "agents page 1h", settings: `{"promptCacheTtl":"1h"}`, want: "1h"}, + {name: "settings env", settings: `{"env":{"CLAUDE_CODE_PROMPT_CACHE_TTL":"5m"},"promptCacheTtl":"1h"}`, want: "5m"}, + {name: "magpie's env", env: "5m", want: "5m"}, + {name: "forced 5m", force: "1", settings: `{"promptCacheTtl":"1h"}`, want: "5m"}, + } { + t.Run(c.name, func(t *testing.T) { + h := newScriptHarness(t, "ok", `echo "ttl ${CLAUDE_CODE_PROMPT_CACHE_TTL-unset} force ${FORCE_PROMPT_CACHING_5M-unset}" >> $log`) + if c.settings != "" { + if err := os.MkdirAll(h.config, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(h.config, "settings.json"), []byte(c.settings), 0o600); err != nil { + t.Fatal(err) + } + } + if c.env != "" { + t.Setenv("CLAUDE_CODE_PROMPT_CACHE_TTL", c.env) + } + if c.force != "" { + t.Setenv("FORCE_PROMPT_CACHING_5M", c.force) + } + h.ask("rules", "hello", "next") + runs := h.runs() + if len(runs) != 1 { + t.Fatalf("runs: %d", len(runs)) + } + for _, log := range runs { + if !strings.Contains(log, "ttl "+c.want+" force unset") { + t.Fatalf("run's environment, want %s:\n%s", c.want, log) + } + var told string + for _, line := range strings.Split(log, "\n") { + if strings.HasPrefix(line, "told ") { + told = line + break + } + } + other := map[string]string{"5m": "1h", "1h": "5m"}[c.want] + if !strings.Contains(told, `"ttl":"`+c.want+`"`) || strings.Contains(told, `"ttl":"`+other+`"`) { + t.Fatalf("first message's marks, want %s: %s", c.want, told) + } + } + }) + } +} + // Claude Code's system prompt begins with a billing line whose hash follows // the request's first user message. Its auto mode classifier sends the same // policy with another transcript each time: with the line kept, no check's diff --git a/internal/gateway/claude_replay.go b/internal/gateway/claude_replay.go index 89c89212b..4db5cf1b5 100644 --- a/internal/gateway/claude_replay.go +++ b/internal/gateway/claude_replay.go @@ -96,7 +96,9 @@ func replaySession(dirs []string, work, model string, req *Request) *savedSessio return nil } log.Printf("claude: a new Claude Code goes on with the conversation from a transcript of it (%d messages, %d images), typed the last turn's %d", split, countImages(req.Messages[:split]), len(req.Messages)-split) - return &savedSession{session: sid, sessions: dirs, since: req.Messages[split:], tui: true, appended: req.appendPrompt} + // its first message has no marks: the run keeps its cache as the user + // picked (claudeRunTTL) + return &savedSession{session: sid, sessions: dirs, since: req.Messages[split:], tui: true, appended: req.appendPrompt, cachePrefix: cachePrefix{ttl: claudeRunTTL(os.Environ())}} } // replyWords is what a reply says, its thinking left out. diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index b054a49a0..8fa8e1052 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -64,6 +64,7 @@ import ( "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/claudecode" "github.com/yetone/magpie/internal/claudetui" + "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/provider" @@ -127,9 +128,9 @@ func (b *subscriptionBridge) passedOver(configDir, dir string) bool { // // It waits as long as the prompt cache it wrote lasts: on a subscription // within its limits Claude Code writes Anthropic's cache for an hour -// (claudeCacheTTL; cleanClaudeEnv pins its CLAUDE_CODE_PROMPT_CACHE_TTL to -// 1h), and a run let go sooner has its conversation told to a new one in one message, a -// prefix the cache has never seen, so the whole of it is written again +// (claudeCacheTTL; claudeRunTTL unless the user picked 5m, when a run kept +// the hour only holds its process longer), and a run let go sooner has its +// conversation told to a new one in one message, a prefix the cache has never seen, so the whole of it is written again // while what the old run wrote is still there to read (#463: a turn // after 39 minutes idle wrote the conversation again). Past the hour the cache is gone // either way, and the run would only hold a process. @@ -1161,9 +1162,12 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, var prompt []map[string]any var prefix cachePrefix if from != nil { + // the session's first message has the marks it was started with: + // its cache is kept as long as before, whatever the pick is now prefix = from.cachePrefix prompt = renderClaudeTurn(req.Messages[len(req.Messages)-len(from.since):], req.Tools) } else { + req.cacheTTL = claudeRunTTL(os.Environ()) prompt, err = renderClaudePrompt(req) if err != nil { cleanup() @@ -1172,6 +1176,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, if req.clientCache != nil { prefix = promptCachePrefix(prompt) } + prefix.ttl = req.cacheTTL } // Claude Code's interactive mode unless the user turned it off // (claudeTUI): the shim (claudetui) is handed the -p arguments, and @@ -1193,7 +1198,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, cmd = binary.command(context.Background(), args...) } cmd.Dir = work - env, err := binary.proxied(ctx, cleanClaudeEnv(os.Environ())) + env, err := binary.proxied(ctx, cleanClaudeEnvTTL(os.Environ(), prefix.runTTL())) if err != nil { cleanup() return nil, nil, err @@ -3447,11 +3452,51 @@ func inClaudeDir(env []string, configDir string) []string { return out } +// claudeRunTTL is how long the prompt cache of a bridge's Claude Code run +// is kept, "5m" or "1h": the user's own pick for Claude Code's main +// conversation, as Claude Code resolves it (FORCE_PROMPT_CACHING_5M, then +// CLAUDE_CODE_PROMPT_CACHE_TTL, in env or in settings.json's env, then +// settings.json's promptCacheTtl, which the Agents page writes), and an +// hour with none set, as Claude Code writes it on a subscription within +// its limits. The run is given it in its environment, since a saved +// account's Claude Code reads the settings of the account's folder, not +// the user's (linkaww: 5m picked, every relayed write an hour's). +func claudeRunTTL(env []string) string { + settingsPath := filepath.Join(claudeConfigDir(), "settings.json") + envOf := func(k string) string { + if v, _ := edit.GetJSON(settingsPath, "env."+k); v != "" { + return v + } + for _, e := range env { + if v, ok := strings.CutPrefix(e, k+"="); ok { + return v + } + } + return "" + } + if v := envOf("FORCE_PROMPT_CACHING_5M"); v != "" && v != "0" && v != "false" { + return "5m" + } + if v := envOf("CLAUDE_CODE_PROMPT_CACHE_TTL"); v == "5m" || v == "1h" { + return v + } + if v, _ := edit.GetJSON(settingsPath, "promptCacheTtl"); v == "5m" || v == "1h" { + return v + } + return "1h" +} + func cleanClaudeEnv(env []string) []string { + return cleanClaudeEnvTTL(env, claudeRunTTL(env)) +} + +// cleanClaudeEnvTTL is cleanClaudeEnv with the run's cache kept ttl +// (claudeRunTTL). +func cleanClaudeEnvTTL(env []string, ttl string) []string { blocked := map[string]bool{ "ANTHROPIC_BASE_URL": true, "ANTHROPIC_API_KEY": true, "ANTHROPIC_AUTH_TOKEN": true, "CLAUDECODE": true, "CLAUDE_CODE_ENTRYPOINT": true, "CLAUDE_CODE_SSE_PORT": true, - "CLAUDE_CODE_OAUTH_TOKEN": true, "CLAUDE_CODE_PROMPT_CACHE_TTL": true, + "CLAUDE_CODE_OAUTH_TOKEN": true, "CLAUDE_CODE_PROMPT_CACHE_TTL": true, "FORCE_PROMPT_CACHING_5M": true, "CLAUDE_CODE_EXTRA_BODY": true, "ANTHROPIC_BETAS": true, } out := make([]string, 0, len(env)+3) @@ -3471,10 +3516,11 @@ func cleanClaudeEnv(env []string) []string { // model that itself, and a status changing with each commit undoes // the cache from there on "CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS=1", - // an hour's cache, as Claude Code writes it on a subscription within - // its limits, always: the mark on the caller's instructions - // (renderClaudePrompt) is an hour's, which may not follow a 5m one - "CLAUDE_CODE_PROMPT_CACHE_TTL=1h") + // the cache kept as the user picked (claudeRunTTL), stated so that + // the marks magpie puts in the first message (renderClaudePrompt, + // Request.cacheTTL) are the same: Anthropic refuses a 1h mark after + // a 5m one + "CLAUDE_CODE_PROMPT_CACHE_TTL="+ttl) } type lockedWriter struct{ run *subscriptionRun } @@ -4435,11 +4481,11 @@ func renderClaudePromptAt(req *Request, split int) ([]map[string]any, error) { // in one block with the conversation a request whose messages differ // (the next item of a batch, a new conversation under the same // instructions) found nothing cached past Claude Code's own prompt. - // The mark's TTL is the one Claude Code uses (claudeCacheTTL, pinned - // in cleanClaudeEnv): Anthropic refuses a 1h mark after a 5m one. + // The mark's TTL is the one Claude Code uses (runMark): Anthropic + // refuses a 1h mark after a 5m one. block := map[string]any{"type": "text", "text": text.String()} if req.clientCache == nil { - block["cache_control"] = cacheMark1h() + block["cache_control"] = req.runMark() } blocks = append(blocks, block) text.Reset() @@ -4519,7 +4565,7 @@ func renderClaudePromptAt(req *Request, split int) ([]map[string]any, error) { if instructions >= 0 { delete(blocks[instructions], "cache_control") } - blocks[chunk]["cache_control"] = cacheMark1h() + blocks[chunk]["cache_control"] = req.runMark() } return closeBlocks(blocks, &text), nil } @@ -4624,13 +4670,21 @@ func leanSystem(req *Request) string { // mark reach a mark 320 messages earlier. const historyChunk = 16 -// cacheMark1h is the prompt-cache mark on what magpie gives a run: an -// hour's, as Claude Code's own (claudeCacheTTL, pinned in cleanClaudeEnv), -// since Anthropic refuses a 1h mark after a 5m one. +// cacheMark1h is an hour's prompt-cache mark. func cacheMark1h() map[string]string { return map[string]string{"type": "ephemeral", "ttl": "1h"} } +// runMark is the prompt-cache mark on what magpie gives a run: kept as +// long as Claude Code's own (Request.cacheTTL, given to the run by +// cleanClaudeEnvTTL), since Anthropic refuses a 1h mark after a 5m one. +func (r *Request) runMark() map[string]string { + if r.cacheTTL == "5m" { + return cacheMark("5m") + } + return cacheMark1h() +} + // historyOpen and historyClose wrap the turns a run started anew is told // were answered already, before the turn it is to answer (renderClaudePrompt). const ( diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index 8e746f14e..89029be0a 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -175,6 +175,10 @@ type Request struct { // marks: the Claude bridge's explicit opt-in, and a Messages ask // translated to an Anthropic upstream (parseTranslated, #4571). clientCache *clientCache + // cacheTTL is how long a Claude bridge run started for the request + // keeps its prompt cache (claudeRunTTL), which the marks magpie adds + // follow (runMark); "" is an hour + cacheTTL string // leanPrompt has the Claude bridge give the caller's instructions as // the run's system prompt, in place of Claude Code's (ClaudeLeanPrompt). leanPrompt bool