diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index a51874f64..3c95f1aa3 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -704,6 +704,19 @@ 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`. +A new run (and one started from a transcript, `replaySession`) picks its +lifetime with `runTTLFor`: `FORCE_PROMPT_CACHING_5M` on this computer +gives 5m, as Claude Code does; else the request's own marks decide, the +longest TTL marked on its tools, system, messages or the request itself +(`askedCacheTTL`, `Request.askedTTL`); else `claudeRunTTL` as above. A +client's Claude Code marks as its own user picked, 5m unless asked for an +hour, so a remote magpie (Docker, another machine) follows the client's +pick, not its own settings, which the client's never reach. Chat and +Responses requests carry no marks and keep `claudeRunTTL`; warmup and +usage runs have no request and keep it too (`cleanClaudeEnv`). Up to +v0.1.3255, a remote relay wrote an hour's cache for a Mac set to 5m +(Linka). `TestAskedCacheTTL`. + ## Client-placed cache marks (#1717) A client can send `X-Magpie-Cache-Marks: client` on a `/v1/messages` diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go index 672e93e60..2f4c79cc7 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.go @@ -156,6 +156,9 @@ func readAnthropic(body []byte, clientMarks, facts bool) (*Request, error) { } r := &Request{Model: a.Model, System: stringOrText(a.System), MaxTokens: a.MaxTokens, Temp: a.Temperature, TopP: a.TopP, Stop: a.StopSequences, Stream: a.Stream, Fast: a.Speed == "fast"} + if !facts { + r.askedTTL = askedCacheTTL(&a) + } if clientMarks { var err error r.clientCache, err = readClientCache(a) diff --git a/internal/gateway/claude_cache.go b/internal/gateway/claude_cache.go index 9be2b1384..5e0633b38 100644 --- a/internal/gateway/claude_cache.go +++ b/internal/gateway/claude_cache.go @@ -103,6 +103,62 @@ func cacheTTL(cc map[string]string) string { return cc["ttl"] } +// askedCacheTTL is the longest TTL a Messages request's own cache marks +// ask for, on its tools, its system, its messages or the request itself, +// "" for one that marks nothing. A Claude bridge run started for it keeps +// its cache that long (runTTLFor): the client's Claude Code marks as its +// user picked, an hour only when asked (Linka, a Docker magpie's relay +// writing an hour's cache for a Mac set to 5m). +func askedCacheTTL(a *aRequest) string { + ttl := "" + take := func(raw json.RawMessage) { + if len(raw) == 0 || ttl == "1h" { + return + } + var cc map[string]string + if json.Unmarshal(raw, &cc) != nil { + return + } + switch t := cacheTTL(cc); t { + case "5m", "1h": + if ttl == "" || t == "1h" { + ttl = t + } + } + } + take(a.CacheControl) + for _, t := range a.Tools { + take(t.CacheControl) + } + if bytes.Contains(a.System, cacheControlField) { + var system []struct { + CacheControl json.RawMessage `json:"cache_control"` + } + if json.Unmarshal(a.System, &system) == nil { + for _, b := range system { + take(b.CacheControl) + } + } + } + for _, m := range a.Messages { + if ttl == "1h" { + break + } + if !bytes.Contains(m.Content, cacheControlField) { + continue + } + var blocks []struct { + CacheControl json.RawMessage `json:"cache_control"` + } + if json.Unmarshal(m.Content, &blocks) == nil { + for _, b := range blocks { + take(b.CacheControl) + } + } + } + return ttl +} + func renderedCacheBlock(b aBlock) bool { switch b.Type { case "text": diff --git a/internal/gateway/claude_prompt_cache_test.go b/internal/gateway/claude_prompt_cache_test.go index 9a85bdfcf..d0312ae48 100644 --- a/internal/gateway/claude_prompt_cache_test.go +++ b/internal/gateway/claude_prompt_cache_test.go @@ -51,9 +51,16 @@ func TestClaudeInstructionsCachedApart(t *testing.T) { // requests wrote an hour's cache. func TestClaudeRunKeepsTheUsersCacheTTL(t *testing.T) { for _, c := range []struct { - name, settings, env, force, want string + name, settings, env, force, marks, want string }{ {name: "nothing picked", want: "1h"}, + // the client's own marks: its Claude Code marks as its user + // picked, five minutes by default (Linka: a Docker magpie's + // relay wrote an hour's cache for a Mac set to 5m) + {name: "client marks 5m", marks: `{"type":"ephemeral"}`, want: "5m"}, + {name: "client marks 5m over this computer's 1h", marks: `{"type":"ephemeral","ttl":"5m"}`, settings: `{"promptCacheTtl":"1h"}`, want: "5m"}, + {name: "client marks 1h over this computer's 5m", marks: `{"type":"ephemeral","ttl":"1h"}`, settings: `{"promptCacheTtl":"5m"}`, want: "1h"}, + {name: "forced 5m over client marks 1h", marks: `{"type":"ephemeral","ttl":"1h"}`, force: "1", want: "5m"}, {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"}, @@ -76,6 +83,9 @@ func TestClaudeRunKeepsTheUsersCacheTTL(t *testing.T) { if c.force != "" { t.Setenv("FORCE_PROMPT_CACHING_5M", c.force) } + if c.marks != "" { + h.extra = `"cache_control":` + c.marks + `,` + } h.ask("rules", "hello", "next") runs := h.runs() if len(runs) != 1 { @@ -101,6 +111,28 @@ func TestClaudeRunKeepsTheUsersCacheTTL(t *testing.T) { } } +// The TTL a Messages request asks for is its longest mark's, wherever it +// is: Claude Code marks its system blocks and its last message (Linka). +func TestAskedCacheTTL(t *testing.T) { + for _, c := range []struct{ body, want string }{ + {`{"model":"m","messages":[{"role":"user","content":"hi"}]}`, ""}, + {`{"model":"m","system":"rules","messages":[{"role":"user","content":"cache_control"}]}`, ""}, + {`{"model":"m","system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.319"},{"type":"text","text":"You are Claude Code.","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":[{"type":"text","text":"hi","cache_control":{"type":"ephemeral"}}]}]}`, "5m"}, + {`{"model":"m","system":[{"type":"text","text":"You are Claude Code.","cache_control":{"type":"ephemeral","ttl":"1h"}}],"messages":[{"role":"user","content":[{"type":"text","text":"hi","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`, "1h"}, + {`{"model":"m","tools":[{"name":"read","input_schema":{},"cache_control":{"type":"ephemeral","ttl":"1h"}}],"messages":[{"role":"user","content":[{"type":"text","text":"hi","cache_control":{"type":"ephemeral"}}]}]}`, "1h"}, + {`{"model":"m","messages":[{"role":"user","content":[{"type":"text","text":"hi","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`, "1h"}, + {`{"model":"m","cache_control":{"type":"ephemeral"},"messages":[{"role":"user","content":"hi"}]}`, "5m"}, + } { + req, err := parseAnthropic([]byte(c.body)) + if err != nil { + t.Fatal(err) + } + if req.askedTTL != c.want { + t.Errorf("%s: %q, want %q", c.body, req.askedTTL, c.want) + } + } +} + // 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 4db5cf1b5..9d62dd918 100644 --- a/internal/gateway/claude_replay.go +++ b/internal/gateway/claude_replay.go @@ -97,8 +97,8 @@ func replaySession(dirs []string, work, model string, req *Request) *savedSessio } 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) // 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())}} + // picked (runTTLFor) + return &savedSession{session: sid, sessions: dirs, since: req.Messages[split:], tui: true, appended: req.appendPrompt, cachePrefix: cachePrefix{ttl: runTTLFor(req, 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 8cc8f52d8..7b1c0188f 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -1167,7 +1167,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, prefix = from.cachePrefix prompt = renderClaudeTurn(req.Messages[len(req.Messages)-len(from.since):], req.Tools) } else { - req.cacheTTL = claudeRunTTL(os.Environ()) + req.cacheTTL = runTTLFor(req, os.Environ()) prompt, err = renderClaudePrompt(req) if err != nil { cleanup() @@ -3499,6 +3499,22 @@ func inClaudeDir(env []string, configDir string) []string { return out } +func forced(v string) bool { return v != "" && v != "0" && v != "false" } + +// claudeForced5m: FORCE_PROMPT_CACHING_5M is set, in env or in Claude +// Code's settings.json's env, as claudeRunTTL reads it. +func claudeForced5m(env []string) bool { + if v, _ := edit.GetJSON(filepath.Join(claudeConfigDir(), "settings.json"), "env.FORCE_PROMPT_CACHING_5M"); v != "" { + return forced(v) + } + for _, e := range env { + if v, ok := strings.CutPrefix(e, "FORCE_PROMPT_CACHING_5M="); ok { + return forced(v) + } + } + return false +} + // 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 @@ -3521,7 +3537,7 @@ func claudeRunTTL(env []string) string { } return "" } - if v := envOf("FORCE_PROMPT_CACHING_5M"); v != "" && v != "0" && v != "false" { + if forced(envOf("FORCE_PROMPT_CACHING_5M")) { return "5m" } if v := envOf("CLAUDE_CODE_PROMPT_CACHE_TTL"); v == "5m" || v == "1h" { @@ -3533,6 +3549,23 @@ func claudeRunTTL(env []string) string { return "1h" } +// runTTLFor is how long a bridge run started for req keeps its prompt +// cache: five minutes when FORCE_PROMPT_CACHING_5M says so, as Claude Code +// itself would; else what the request's own marks ask for, its client's +// Claude Code marking as that computer's user picked, five minutes by +// default (a remote magpie's relay was given the hour of its own setting, +// never the Mac's, Linka); else, for a request with no marks, this +// computer's pick or an hour (claudeRunTTL). +func runTTLFor(req *Request, env []string) string { + if claudeForced5m(env) { + return "5m" + } + if req != nil && req.askedTTL != "" { + return req.askedTTL + } + return claudeRunTTL(env) +} + func cleanClaudeEnv(env []string) []string { return cleanClaudeEnvTTL(env, claudeRunTTL(env)) } diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index 89029be0a..83821e82a 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -179,6 +179,9 @@ type Request struct { // keeps its prompt cache (claudeRunTTL), which the marks magpie adds // follow (runMark); "" is an hour cacheTTL string + // askedTTL is the longest TTL the request's own cache marks ask for + // (askedCacheTTL), "" for one that marks nothing or came in another API + askedTTL 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