gateway: a Mac's Claude Code cache pick reaches the remote magpie's relay (linkaww)

linkaww's chain: Claude Code on a Mac (API-key mode) -> the Mac's
magpie -> a Docker magpie whose Claude provider is the relay. Two rules
asked for: a 5m pick on the Mac never writes an hour's cache; with
nothing picked, the relay keeps Claude Code's subscription default, an
hour.

Claude Code 2.1.316 marks five minutes with no ttl, whether its user
picked them or it is its default off a subscription (the marker names a
ttl only for 1h). So since v0.1.3256 the relay, which followed the marks,
wrote 5m with nothing picked, and an unmarked side call (Haiku's title,
the classifier) fell to the Docker computer's own pick, an hour, under a
5m pick.

Now the Mac's magpie names the pick: X-Magpie-Claude-Cache-TTL
(ClaudeCacheTTLHeader), "5m", "1h" or "default", set by passOnCaller
for a request from Claude Code on this computer (its token or its
claude-cli/ User-Agent from loopback, never Claude Desktop's) and passed
on as it came through further magpies. It is read as claudeRunTTL reads
the pick (claudePickedTTL); a settings.json that can't be read or parsed
names none (claudeSettingsKnown), and the marks decide as before. The
far magpie takes it from a magpie/ request alone (callerFrom) and takes
it off what comes in (withCaller), so no vendor sees it; native
passthrough already drops X-Magpie-*. runTTLFor: forced 5m; marks that
name an hour; else the pick (Request.pickedTTL), "default" giving
claudeRunTTL (that computer's pick or an hour); else the marks; else
claudeRunTTL. Claude Code on the relay's own computer gets the same
rule from its local pick. A Claude Code that goes straight to a remote
magpie sends no header and keeps today's marks-first behaviour. Nothing
sent to Anthropic changes beyond the run's CLAUDE_CODE_PROMPT_CACHE_TTL.

Known limits, in the bridge doc: a pick made only in Claude Code's shell
env or a project's .claude/settings.json isn't seen by magpie, so it
goes as "default" (an hour unless the marks name one);
subagentPromptCacheTtl is not told apart.

Tests: TestClaudeRunKeepsTheUsersCacheTTL gains 11 cases (the Mac's
5m/1h/default, marked and unmarked, against this computer's settings,
forced, marks naming 1h, Claude Code here, unreadable settings);
TestClaudeCacheTTLFromAMagpieOnly; TestClaudeCacheTTLOf;
TestClaudeCacheTTLReachesTheRemoteMagpie (two real handlers: 5m,
default, unreadable -> none, another agent -> none, vendor sees no
X-Magpie-* header).

Run (on mote, at this tree rebased on 3b541a7f3 = origin/main just fetched;
the targeted tests and vet again there):
- go test -count=1 -run 'TestClaudeCacheTTL|TestClaudeRunKeepsTheUsersCacheTTL|TestRemoteMagpieAgent|TestAskedCacheTTL|TestClaudeInstructionsCachedApart' ./internal/gateway: ok
- go vet ./internal/gateway, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet: ok; gofmt -l internal/: nothing
- full go test -count=1 -timeout 45m ./... through suite.lock: still
  running at push (started at base bb33142ea) (owner's rule: no verified commit waits on it); any
  red it shows gets its own issue.

Broken by hand: runTTLFor ignoring pickedTTL -> 5 table cases red
(unmarked 5m, marked 1h, default, Claude Code here); the header taken
from a non-magpie -> FromAMagpieOnly red; passOnCaller not setting it ->
ReachesTheRemoteMagpie red ("told \"\""); claudeSettingsKnown always
true -> TestClaudeCacheTTLOf "here, unreadable" and the table's
unreadable case red.

Not tried: a real Claude subscription, a real Docker magpie, or
linkaww's own Mac; cache writes were checked by the run's environment,
not by Anthropic's usage numbers.

Reported-by: linkaww on Discord
This commit is contained in:
yetone
2026-11-08 02:10:17 +08:00
parent 6b7ee4a984
commit a7113d5c92
7 changed files with 359 additions and 24 deletions
+41 -11
View File
@@ -712,17 +712,47 @@ pick (linkaww); `everyRunKept5m` in the fork, busy-retry and side
question tests.
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`.
lifetime with `runTTLFor`:
- `FORCE_PROMPT_CACHING_5M` on this computer gives 5m, as Claude Code
does.
- A request whose marks name an hour (`askedCacheTTL`,
`Request.askedTTL`: the longest TTL marked on its tools, system,
messages or the request itself) gets an hour: its client picked it.
- Else the pick of the user of the computer the request's Claude Code
runs on (`Request.pickedTTL`, `claudeTTLOf`). For Claude Code on this
computer (its token or `claude-cli/` User-Agent from loopback,
`caller.claudeHere`), it is this computer's, read as `claudeRunTTL`
reads it. For a request another magpie passed on, it is what that
magpie named in `X-Magpie-Claude-Cache-TTL` (`ClaudeCacheTTLHeader`):
`5m`, `1h`, or `default` for no pick. `passOnCaller` sends it on every
request to a Remote magpie whose caller is Claude Code here, or that
came with it. `callerFrom` takes it from a `magpie/` request alone, and
`withCaller` takes it off what comes in, so no vendor is sent it.
`default` gives `claudeRunTTL`: this computer's own pick, or an hour,
as Claude Code keeps it on a subscription.
- Else the marks decide, five minutes for a mark with no ttl.
- Else `claudeRunTTL`.
Claude Code marks five minutes with no ttl, whether its user picked them
or it is its default off a subscription (2.1.316: the marker names a ttl
only for an hour). So marks can't tell a 5m pick from no pick, and an
unmarked side call (Haiku's title, the classifier) says nothing at all.
Up to v0.1.3255 a remote relay wrote an hour's cache for a Mac set to 5m
(Linka). From v0.1.3256 the marks decided, so with nothing picked every
relayed write was five minutes, while a 5m pick still had its unmarked
side calls written for an hour (linkaww). The header carries the pick
itself. A settings.json that can't be read or parsed names no pick
(`claudeSettingsKnown`), and the marks decide as before. Not seen by
magpie: a pick made only in the shell Claude Code was started from, or
in a project's `.claude/settings.json`. Such a client is sent `default`,
an hour, unless its marks name an hour. A Claude Code that goes straight
to a remote magpie, with no magpie of its own, sends no header, and its
marks decide as before. Chat and Responses requests carry no marks and
keep `claudeRunTTL`; warmup and usage runs have no request and keep it
too (`cleanClaudeEnv`). `TestAskedCacheTTL`,
`TestClaudeRunKeepsTheUsersCacheTTL`, `TestClaudeCacheTTLFromAMagpieOnly`,
`TestClaudeCacheTTLOf`, `TestClaudeCacheTTLReachesTheRemoteMagpie`.
## Client-placed cache marks (#1717)
@@ -52,6 +52,9 @@ func TestClaudeInstructionsCachedApart(t *testing.T) {
func TestClaudeRunKeepsTheUsersCacheTTL(t *testing.T) {
for _, c := range []struct {
name, settings, env, force, marks, want string
// who the request is recorded as (claudeTTLOf): the pick another
// magpie named for its Claude Code, or this computer's Claude Code
who *caller
}{
{name: "nothing picked", want: "1h"},
// the client's own marks: its Claude Code marks as its user
@@ -66,6 +69,23 @@ func TestClaudeRunKeepsTheUsersCacheTTL(t *testing.T) {
{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"},
// linkaww's Mac → Docker magpie: Claude Code marks five minutes
// with no ttl whether its user picked them or not, so the Mac's
// magpie names the pick (ClaudeCacheTTLHeader)
{name: "the Mac's 5m, a side call unmarked, this computer's 1h", who: &caller{agent: "claude", cacheTTL: "5m"}, settings: `{"promptCacheTtl":"1h"}`, want: "5m"},
{name: "the Mac's 5m, unmarked, nothing here", who: &caller{agent: "claude", cacheTTL: "5m"}, want: "5m"},
{name: "the Mac's 5m, marked", who: &caller{agent: "claude", cacheTTL: "5m"}, marks: `{"type":"ephemeral"}`, settings: `{"promptCacheTtl":"1h"}`, want: "5m"},
{name: "the Mac's 1h, marked with no ttl", who: &caller{agent: "claude", cacheTTL: "1h"}, marks: `{"type":"ephemeral"}`, want: "1h"},
{name: "nothing picked on the Mac, marked with no ttl", who: &caller{agent: "claude", cacheTTL: "default"}, marks: `{"type":"ephemeral"}`, want: "1h"},
{name: "nothing picked on the Mac, this computer's 5m", who: &caller{agent: "claude", cacheTTL: "default"}, marks: `{"type":"ephemeral"}`, settings: `{"promptCacheTtl":"5m"}`, want: "5m"},
{name: "marks naming the hour over the Mac's 5m", who: &caller{agent: "claude", cacheTTL: "5m"}, marks: `{"type":"ephemeral","ttl":"1h"}`, want: "1h"},
{name: "forced 5m over the Mac's 1h", who: &caller{agent: "claude", cacheTTL: "1h"}, force: "1", want: "5m"},
// Claude Code on this computer: its user's pick is read here
{name: "Claude Code here, nothing picked, marked", who: &caller{agent: "claude", claudeHere: true}, marks: `{"type":"ephemeral"}`, want: "1h"},
{name: "Claude Code here, 5m picked, unmarked", who: &caller{agent: "claude", claudeHere: true}, settings: `{"promptCacheTtl":"5m"}`, want: "5m"},
// a settings.json that can't be parsed says nothing of a pick: the
// marks decide, as without magpie's word
{name: "Claude Code here, settings unreadable, marked", who: &caller{agent: "claude", claudeHere: true}, marks: `{"type":"ephemeral"}`, settings: `{"promptCacheTtl":`, 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`)
@@ -86,6 +106,7 @@ func TestClaudeRunKeepsTheUsersCacheTTL(t *testing.T) {
if c.marks != "" {
h.extra = `"cache_control":` + c.marks + `,`
}
h.who = c.who
h.ask("rules", "hello", "next")
runs := h.runs()
if len(runs) != 1 {
+9 -3
View File
@@ -1,6 +1,7 @@
package gateway
import (
"context"
"fmt"
"net/http/httptest"
"os"
@@ -26,8 +27,9 @@ type resumeHarness struct {
p provider.Provider
logs string
config string
extra string // fields each request has besides its own, each with a comma after it
from string // the requests' address, "" for httptest's (another computer's)
extra string // fields each request has besides its own, each with a comma after it
from string // the requests' address, "" for httptest's (another computer's)
who *caller // who the requests are recorded as, as withCaller notes it; nil for none
}
func newResumeHarness(t *testing.T) *resumeHarness {
@@ -117,7 +119,11 @@ func (h *resumeHarness) ask(system string, said ...string) {
body := `{"model":"claude-sonnet-5","max_tokens":100,` + h.extra + `"system":"` + system + `","tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":[` + strings.Join(msgs, ",") + `]}`
rec := httptest.NewRecorder()
var u Usage
if code, msg := h.s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, h.p, "claude-sonnet-5", []byte(body), &u); code != 200 {
r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
if h.who != nil {
r = r.WithContext(context.WithValue(r.Context(), callerCtx{}, *h.who))
}
if code, msg := h.s.serveClaudeSubscription(rec, r, provider.Anthropic, h.p, "claude-sonnet-5", []byte(body), &u); code != 200 {
h.t.Fatalf("%d %s", code, msg)
}
}
+50 -10
View File
@@ -3529,13 +3529,21 @@ func claudeForced5m(env []string) bool {
// 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 {
if ttl := claudePickedTTL(env); ttl != "" {
return ttl
}
return "1h"
}
// claudePickedTTL is the user's pick claudeRunTTL reads, "" for none.
func claudePickedTTL(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 {
if v, found := strings.CutPrefix(e, k+"="); found {
return v
}
}
@@ -3550,22 +3558,51 @@ func claudeRunTTL(env []string) string {
if v, _ := edit.GetJSON(settingsPath, "promptCacheTtl"); v == "5m" || v == "1h" {
return v
}
return "1h"
return ""
}
// claudeSettingsKnown: Claude Code's settings.json here is missing or
// reads and parses, so claudePickedTTL is the pick; a file that can't be
// read says nothing of one.
func claudeSettingsKnown() bool {
b, err := edit.Read(filepath.Join(claudeConfigDir(), "settings.json"))
return err == nil && (len(bytes.TrimSpace(b)) == 0 || edit.ValidJSONC(b))
}
// 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).
// cache:
// - five minutes when FORCE_PROMPT_CACHING_5M says so, as Claude Code
// itself would;
// - an hour when the request's marks name it: its client picked it;
// - the pick of the user of the computer the request's Claude Code runs
// on (pickedTTL: this one's, or what the magpie it came through
// named), and with none picked this computer's or an hour, as Claude
// Code keeps it on a subscription. Claude Code marks five minutes with
// no ttl, picked or as its default off a subscription, so its marks
// can't say which (linkaww: a 5m pick, relayed side calls an hour's;
// nothing picked, every relayed write five minutes');
// - else what the marks ask for, five minutes for a mark with no ttl (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
if req != nil {
if req.askedTTL == "1h" {
return "1h"
}
switch req.pickedTTL {
case "5m", "1h":
return req.pickedTTL
case "default":
return claudeRunTTL(env)
}
if req.askedTTL != "" {
return req.askedTTL
}
}
return claudeRunTTL(env)
}
@@ -6525,6 +6562,9 @@ func (s *Server) serveSubscriptionAs(w http.ResponseWriter, r *http.Request, fro
// the tools of a caller on another computer run there, not where
// Claude Code runs (envUnknownNote)
req.remoteCaller = !local(r)
// how long the user of the computer the request's Claude Code runs on
// keeps its cache, which its marks don't say (runTTLFor)
req.pickedTTL = claudeTTLOf(callerOf(r))
if req.Format != nil && req.Format.schema() == nil {
// --json-schema takes a schema only: any JSON object is asked for
// in words
+4
View File
@@ -182,6 +182,10 @@ type Request struct {
// 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
// pickedTTL is the cache lifetime the user of the computer the
// request's Claude Code runs on picked, "default" for none, "" when
// unknown (claudeTTLOf)
pickedTTL 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
+45
View File
@@ -41,6 +41,14 @@ const (
// key+URL providers the agent's, as this one would have (nb5p on
// Discord). Taken, like AgentHeader, only from a magpie's request.
ClientUAHeader = "X-Magpie-User-Agent"
// ClaudeCacheTTLHeader is how long the prompt cache of a Claude Code
// request is to be kept, as the user of the computer Claude Code runs
// on picked it: "5m", "1h", or "default" for no pick. Claude Code
// marks a five-minute cache with no ttl, picked or not, so the other
// magpie's Claude relay can't tell a pick from its marks
// (claudeTTLOf, runTTLFor; linkaww). Taken only from a magpie's
// request.
ClaudeCacheTTLHeader = "X-Magpie-Claude-Cache-TTL"
)
// caller is who a request is recorded as: its agent, and the computer it
@@ -66,6 +74,12 @@ type caller struct {
// hops: the magpies the request was passed on through before this
// one (HopsHeader)
hops int
// cacheTTL is the Claude Code cache lifetime another magpie named
// (ClaudeCacheTTLHeader); claudeHere, that the request is Claude
// Code's on this computer, whose user's pick is read here
// (claudeTTLOf)
cacheTTL string
claudeHere bool
}
type callerCtx struct{}
@@ -90,6 +104,7 @@ func withCaller(next http.Handler) http.Handler {
r.Header.Del(KeepTurnHeader)
r.Header.Del(HopsHeader)
r.Header.Del(ClientUAHeader)
r.Header.Del(ClaudeCacheTTLHeader)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
@@ -119,6 +134,10 @@ func callerFrom(r *http.Request) caller {
if v := r.Header.Get(ClientUAHeader); v != "" && len(v) <= 1024 && !magpiesOwn(v) {
c.ua, c.relayed = v, true
}
switch v := r.Header.Get(ClaudeCacheTTLHeader); v {
case "5m", "1h", "default":
c.cacheTTL = v
}
if a := label(r.Header.Get(AgentHeader)); a != "" {
c.agent = usage.AgentOf(a)
c.via = label(r.Header.Get(ViaHeader))
@@ -126,10 +145,33 @@ func callerFrom(r *http.Request) caller {
c.via, _, _ = net.SplitHostPort(r.RemoteAddr)
}
}
} else {
// Claude Code, known by its token or its User-Agent; Claude
// Desktop's keeps a settings.json of its own
c.claudeHere = (c.agent == "claude" || fromClaudeCode(r.Header)) && c.agent != "claude-desktop" && local(r)
}
return c
}
// claudeTTLOf is how long the prompt cache of c's request is to be kept,
// as the user of the computer its Claude Code runs on picked it: "5m",
// "1h", "default" for no pick, "" when unknown (not Claude Code's, from
// a magpie that didn't say, or Claude Code's settings.json unreadable).
// Claude Code on this computer: this computer's pick, as claudeRunTTL
// reads it.
func claudeTTLOf(c caller) string {
if c.cacheTTL != "" || !c.claudeHere {
return c.cacheTTL
}
if !claudeSettingsKnown() {
return ""
}
if ttl := claudePickedTTL(os.Environ()); ttl != "" {
return ttl
}
return "default"
}
// callerOf is who the request is recorded as.
func callerOf(r *http.Request) caller {
if c, ok := r.Context().Value(callerCtx{}).(caller); ok {
@@ -186,6 +228,9 @@ func passOnCaller(ctx context.Context, req *http.Request) {
if c.compact != "" {
req.Header.Set(dshCompactHeader, c.compact)
}
if v := claudeTTLOf(c); v != "" {
req.Header.Set(ClaudeCacheTTLHeader, v)
}
if c.agent == "" {
return
}
@@ -0,0 +1,189 @@
package gateway
import (
"context"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// Another magpie's word on how long its Claude Code's cache is kept is
// taken from a magpie's request alone, and only as one of its three
// values; this computer's Claude Code is known by its address.
func TestClaudeCacheTTLFromAMagpieOnly(t *testing.T) {
for _, c := range []struct {
name, ua, addr, ttl string
want string
here bool
}{
{name: "a magpie's 5m", ua: "magpie/0.1.3267", addr: "192.0.2.7:5000", ttl: "5m", want: "5m"},
{name: "a magpie's default", ua: "magpie/0.1.3267", addr: "192.0.2.7:5000", ttl: "default", want: "default"},
{name: "a magpie's unknown value", ua: "magpie/0.1.3267", addr: "192.0.2.7:5000", ttl: "7d"},
{name: "Claude Code's own header", ua: "claude-cli/2.1.316 (external, cli)", addr: "192.0.2.7:5000", ttl: "1h"},
{name: "Claude Code here", ua: "claude-cli/2.1.316 (external, cli)", addr: "127.0.0.1:5000", ttl: "1h", here: true},
{name: "Codex here", ua: "codex_cli_rs/0.50.0", addr: "127.0.0.1:5000"},
} {
t.Run(c.name, func(t *testing.T) {
r := httptest.NewRequest("POST", "/v1/messages", nil)
r.RemoteAddr = c.addr
r.Header.Set("User-Agent", c.ua)
if c.ttl != "" {
r.Header.Set(ClaudeCacheTTLHeader, c.ttl)
}
got := callerFrom(r)
if got.cacheTTL != c.want || got.claudeHere != c.here {
t.Errorf("caller: ttl %q here %v, want %q %v", got.cacheTTL, got.claudeHere, c.want, c.here)
}
var seen *http.Request
withCaller(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { seen = r })).ServeHTTP(httptest.NewRecorder(), r)
if seen == nil || seen.Header.Get(ClaudeCacheTTLHeader) != "" {
t.Errorf("the header went on past withCaller")
}
})
}
}
// What a Remote magpie is told of the cache lifetime: Claude Code's here
// is its user's pick, "default" with none, nothing when settings.json
// can't be read; another magpie's word goes on as it came; no other
// agent's request names one.
func TestClaudeCacheTTLOf(t *testing.T) {
config := t.TempDir()
t.Setenv("CLAUDE_CONFIG_DIR", config)
t.Setenv("CLAUDE_CODE_PROMPT_CACHE_TTL", "")
t.Setenv("FORCE_PROMPT_CACHING_5M", "")
settings := filepath.Join(config, "settings.json")
for _, c := range []struct {
name, settings string
who caller
want string
}{
{name: "here, nothing picked", who: caller{agent: "claude", claudeHere: true}, want: "default"},
{name: "here, empty settings", settings: " ", who: caller{agent: "claude", claudeHere: true}, want: "default"},
{name: "here, 5m", settings: `{"promptCacheTtl":"5m"}`, who: caller{agent: "claude", claudeHere: true}, want: "5m"},
{name: "here, 1h in settings' env", settings: `{"env":{"CLAUDE_CODE_PROMPT_CACHE_TTL":"1h"},"promptCacheTtl":"5m"}`, who: caller{agent: "claude", claudeHere: true}, want: "1h"},
{name: "here, forced", settings: "// picked\n{\"env\":{\"FORCE_PROMPT_CACHING_5M\":\"1\"},\"promptCacheTtl\":\"1h\",}", who: caller{agent: "claude", claudeHere: true}, want: "5m"},
{name: "here, unreadable", settings: `{"promptCacheTtl":"5m"`, who: caller{agent: "claude", claudeHere: true}},
{name: "passed on", settings: `{"promptCacheTtl":"5m"}`, who: caller{agent: "claude", cacheTTL: "1h"}, want: "1h"},
{name: "another agent", settings: `{"promptCacheTtl":"5m"}`, who: caller{agent: "codex"}},
} {
t.Run(c.name, func(t *testing.T) {
os.Remove(settings)
if c.settings != "" {
if err := os.WriteFile(settings, []byte(c.settings), 0o600); err != nil {
t.Fatal(err)
}
}
if got := claudeTTLOf(c.who); got != c.want {
t.Errorf("%q, want %q", got, c.want)
}
})
}
}
// Claude Code on a Mac, through its magpie, to a magpie on another
// computer (linkaww's Docker one): the other magpie is told the Mac's
// pick, which Claude Code's own marks can't say, and the vendor never is.
func TestClaudeCacheTTLReachesTheRemoteMagpie(t *testing.T) {
var mu sync.Mutex
var told []string // the header as the remote magpie was sent it
var leaked []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
mu.Lock()
for k := range r.Header {
if strings.HasPrefix(strings.ToLower(k), "x-magpie-") {
leaked = append(leaked, k)
}
}
mu.Unlock()
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(
`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","model":"m1","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":"hello"}}`,
`data: {"type":"content_block_stop","index":0}`,
`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":4}}`,
`data: {"type":"message_stop"}`))
}))
t.Cleanup(up.Close)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
config := t.TempDir()
t.Setenv("CLAUDE_CONFIG_DIR", config)
t.Setenv("CLAUDE_CODE_PROMPT_CACHE_TTL", "")
t.Setenv("FORCE_PROMPT_CACHING_5M", "")
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Anthropic: up.URL}); err != nil {
t.Fatal(err)
}
there := New().Handler()
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/v1/messages" {
mu.Lock()
told = append(told, r.Header.Get(ClaudeCacheTTLHeader))
mu.Unlock()
}
there.ServeHTTP(w, r)
}))
t.Cleanup(remote.Close)
id, err := provider.Add(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Chat: strings.TrimPrefix(remote.URL, "http://")})
if err != nil {
t.Fatal(err)
}
office, _ := provider.Find(id)
if _, err := office.Fetch(context.Background()); err != nil {
t.Fatal(err)
}
send := func(ua, addr, settings string) string {
t.Helper()
os.Remove(filepath.Join(config, "settings.json"))
if settings != "" {
if err := os.WriteFile(filepath.Join(config, "settings.json"), []byte(settings), 0o600); err != nil {
t.Fatal(err)
}
}
mu.Lock()
n := len(told)
mu.Unlock()
body := `{"model":"office/fake/m1","max_tokens":10,"system":[{"type":"text","text":"rules","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"hi"}]}`
req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
req.RemoteAddr = addr
req.Header.Set("User-Agent", ua)
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, req)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "hello") {
t.Fatalf("%d %s", rec.Code, rec.Body.String())
}
mu.Lock()
defer mu.Unlock()
if len(told) != n+1 {
t.Fatalf("the remote magpie was asked %d times", len(told)-n)
}
return told[n]
}
const claude, here = "claude-cli/2.1.316 (external, cli)", "127.0.0.1:51000"
if got := send(claude, here, `{"promptCacheTtl":"5m"}`); got != "5m" {
t.Errorf("a 5m pick: the remote magpie was told %q", got)
}
if got := send(claude, here, ""); got != "default" {
t.Errorf("nothing picked: the remote magpie was told %q", got)
}
if got := send(claude, here, `{"promptCacheTtl":"5m"`); got != "" {
t.Errorf("settings.json unreadable: the remote magpie was told %q", got)
}
if got := send("opencode/1.2.3", here, `{"promptCacheTtl":"5m"}`); got != "" {
t.Errorf("another agent: the remote magpie was told %q", got)
}
mu.Lock()
defer mu.Unlock()
if len(leaked) > 0 {
t.Errorf("the vendor was sent magpie's headers: %v", leaked)
}
}