claude: Claude Code runs share a folder only the user owns, the caller's system prompt is cached apart, and auto memory is off (#626, yg3415) — main already ran every Claude Code run in one $TMPDIR/magpie-claude so Anthropic's prompt cache is read again; this takes yg3415's version of that: the folder is magpie-claude-work-<uid> (the uid where the temp folder is shared, as /tmp is on Linux), made 0700 and used only when it is a real folder the user owns that no one else can write to (else the run works in a folder of its own, as before), so nobody else can put a CLAUDE.md in front of every run; the caller's system prompt goes to Claude Code as a block of its own with a 1h cache_control breakpoint (CLAUDE_CODE_PROMPT_CACHE_TTL=1h, since Anthropic refuses a 1h breakpoint after a 5m one), so requests with one system prompt and different conversations share its cache entry; and CLAUDE_CODE_DISABLE_AUTO_MEMORY=1, so a memory Claude Code writes in one caller's conversation doesn't show up in every other one in the shared folder. Merged onto main by hand: the run still starts through binary.command/binary.env, so a Claude Code in WSL works in the shared folder too; on Windows the folder is in the user's own %TEMP% and Go reports every folder there as 0777, so the mode check is skipped there (it refused every run before). Tests from the PR (TestClaudeRunsShareAWorkDir with a home kept in git, TestClaudeWorkDirOthersCanWriteIsAvoided, TestClaudeInstructionsCachedApart) pass; go vet (darwin, GOOS=windows), builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass.

Co-authored-by: yg3415 <115795347+yg3415@users.noreply.github.com>
This commit is contained in:
yetone
2026-10-04 18:25:44 +08:00
co-authored by yg3415
parent ee508d0ce9
commit 17363b7e30
6 changed files with 246 additions and 74 deletions
@@ -0,0 +1,37 @@
package gateway
import (
"slices"
"strings"
"testing"
)
// The caller's instructions are a block of their own, marked for an hour's
// cache, ahead of the messages: two requests with the same instructions
// and different messages share them in the cache. Claude Code writes an
// hour's cache too, as a 1h mark may not follow a 5m one.
func TestClaudeInstructionsCachedApart(t *testing.T) {
for _, said := range []string{"one", "two"} {
blocks, err := renderClaudePrompt(&Request{System: "rules", Messages: []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: said}}}}})
if err != nil {
t.Fatal(err)
}
if len(blocks) != 2 || blocks[0]["text"] != "<external_system_instructions>\nrules\n</external_system_instructions>\n\n" {
t.Fatalf("blocks: %v", blocks)
}
if cc, _ := blocks[0]["cache_control"].(map[string]string); cc["ttl"] != "1h" || blocks[1]["cache_control"] != nil {
t.Fatalf("cache marks: %v", blocks)
}
if !strings.Contains(blocks[1]["text"].(string), "Human: "+said) {
t.Fatalf("messages: %v", blocks[1])
}
}
blocks, _ := renderClaudePrompt(&Request{Messages: []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}}}})
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") {
t.Fatalf("env: %q", env)
}
}
+59 -18
View File
@@ -63,8 +63,8 @@ type subscriptionBridge struct {
//
// 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, with its CLAUDE_CODE_PROMPT_CACHE_TTL unset), and a run
// let go sooner has its conversation told to a new one in one message, a
// (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
// 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
@@ -245,16 +245,38 @@ func sweepBridgeProjects(claudeDir, tempDir string) {
}
}
// claudeRunDir is the folder every bridge run works in, the same one each
// time: Claude Code writes its working directory into the system prompt,
// so a folder of each run's own made every new turn's prompt a new one and
// Anthropic's prompt cache was written again for the whole conversation and
// never read — a long Claude Code conversation through magpie waited for
// all of it each turn. A run's own files (tools.json) stay in its own
// folder, which isn't in the prompt.
func claudeRunDir() (string, error) {
dir := filepath.Join(os.TempDir(), "magpie-claude")
return dir, os.MkdirAll(dir, 0o700)
// claudeWorkDir is the folder every run works in. Claude Code tells its
// model the working directory in its system prompt, after its own fixed
// part and before the conversation: a folder of its own for each run made
// every prompt new to Anthropic's cache from there on, a caller's system
// prompt and its history written again each time, with only Claude Code's
// own part (some 2.8k tokens) read.
//
// It is in the temp folder, which is in no git repository: Claude Code puts
// the status and recent commits of the repository its folder is in into
// the prompt, so a folder under a home kept in git (dotfiles) would send
// them with every request, and break the cache whenever they change. The
// folder is the user's own (claudeWorkName: their uid in its name where
// the temp folder is shared, as /tmp is on Linux), and used only when it
// is a folder they own that no one else can write to: one someone else
// made, or could put a CLAUDE.md in, would be read by every run.
func claudeWorkDir() (string, error) {
dir := filepath.Join(os.TempDir(), claudeWorkName())
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", err
}
fi, err := os.Lstat(dir)
switch {
case err != nil:
return "", err
case !fi.IsDir():
return "", fmt.Errorf("%s is not a folder", dir)
case othersCanWrite(fi):
return "", fmt.Errorf("%s can be written by others (%v)", dir, fi.Mode().Perm())
case !ownedByMe(fi):
return "", fmt.Errorf("%s belongs to another user", dir)
}
return dir, nil
}
func evalSymlinks(path string) string {
@@ -379,13 +401,15 @@ func (b *subscriptionBridge) start(ctx context.Context, req *Request, model, con
if len(req.Schema) > 0 {
args = append(args, "--json-schema", string(req.Schema))
}
cwd, err := claudeRunDir()
work, err := claudeWorkDir()
if err != nil {
cleanup()
return nil, nil, err
// a run of its own folder answers all the same, its prompt only
// read from the cache as far as Claude Code's own part
log.Printf("claude: working in a folder of the run's own: %v", err)
work = tmp
}
cmd := binary.command(context.Background(), args...)
cmd.Dir = cwd
cmd.Dir = work
cmd.Env = binary.env(netproxy.EnvWith(claudeProxy(ctx), cleanClaudeEnv(os.Environ())), configDir)
stdin, err := cmd.StdinPipe()
if err != nil {
@@ -792,7 +816,7 @@ func cleanClaudeEnv(env []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_OAUTH_TOKEN": true, "CLAUDE_CODE_PROMPT_CACHE_TTL": true,
}
out := make([]string, 0, len(env)+3)
for _, e := range env {
@@ -801,7 +825,15 @@ func cleanClaudeEnv(env []string) []string {
out = append(out, e)
}
}
return append(out, "ENABLE_CLAUDEAI_MCP_SERVERS=0", "DISABLE_AUTO_COMPACT=1", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1")
// no auto memory: every run works in one folder (claudeWorkDir), so a
// memory one conversation's caller wrote there would be in the system
// prompt of all the account's others, and a change to it would undo
// the cache from there on
return append(out, "ENABLE_CLAUDEAI_MCP_SERVERS=0", "DISABLE_AUTO_COMPACT=1", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1", "CLAUDE_CODE_DISABLE_AUTO_MEMORY=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")
}
type lockedWriter struct{ run *subscriptionRun }
@@ -1313,6 +1345,15 @@ func renderClaudePrompt(req *Request) ([]map[string]any, error) {
fmt.Fprintf(&text, "\nYou must call the %s tool.", strings.TrimPrefix(req.ToolChoice, "name:"))
}
text.WriteString("\n</external_system_instructions>\n\n")
// The caller's instructions are a block of their own, marked for the
// cache: Claude Code marks only the end of the message, so with them
// 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.
blocks = append(blocks, map[string]any{"type": "text", "text": text.String(), "cache_control": map[string]string{"type": "ephemeral", "ttl": "1h"}})
text.Reset()
}
for _, m := range req.Messages {
label := "Human"
+1 -56
View File
@@ -70,7 +70,7 @@ func TestCleanClaudeEnvRemovesGatewayOverrides(t *testing.T) {
t.Fatalf("kept %s in %q", forbidden, joined)
}
}
for _, want := range []string{"PATH=/bin", "KEEP=yes", "ENABLE_CLAUDEAI_MCP_SERVERS=0", "DISABLE_AUTO_COMPACT=1"} {
for _, want := range []string{"PATH=/bin", "KEEP=yes", "ENABLE_CLAUDEAI_MCP_SERVERS=0", "DISABLE_AUTO_COMPACT=1", "CLAUDE_CODE_DISABLE_AUTO_MEMORY=1"} {
if !strings.Contains(joined, want) {
t.Fatalf("missing %s in %q", want, joined)
}
@@ -144,61 +144,6 @@ func TestClaudeRunKeptForTheNextTurn(t *testing.T) {
}
}
// Every Claude Code magpie starts works in the same folder, one that
// outlives its runs: Claude Code writes its working directory into the
// system prompt, and a folder of each run's own made every conversation's
// next run a prompt Anthropic's cache had never seen, the whole
// conversation written to the cache again and never read (X: Chen, "the
// model got heavy" through magpie).
func TestClaudeRunsShareAWorkingDirectory(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("a shell script stands in for Claude Code")
}
tmp := t.TempDir()
t.Setenv("TMPDIR", tmp)
bin := t.TempDir()
script := `#!/bin/sh
while read -r line; do
echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-sonnet-5","usage":{"input_tokens":1}}}}'
echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"cwd '"$(pwd -P)"'"}}}'
echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":3}}}'
echo '{"type":"stream_event","event":{"type":"message_stop"}}'
echo '{"type":"result","subtype":"success","is_error":false,"result":""}'
done
`
os.WriteFile(filepath.Join(bin, "claude"), []byte(script), 0o755)
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
s := New()
p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}}
ask := func(text string) string {
t.Helper()
body := `{"model":"claude-sonnet-5","max_tokens":100,"messages":[{"role":"user","content":` + strconv.Quote(text) + `}]}`
rec := httptest.NewRecorder()
var u Usage
if code, msg := s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, p, "claude-sonnet-5", []byte(body), &u); code != 200 {
t.Fatalf("%d %s", code, msg)
}
var res struct {
Content []struct{ Text string } `json:"content"`
}
json.Unmarshal(rec.Body.Bytes(), &res)
if len(res.Content) == 0 {
t.Fatalf("no answer: %s", rec.Body)
}
return strings.TrimPrefix(res.Content[0].Text, "cwd ")
}
first, second := ask("one conversation"), ask("another")
if first != second {
t.Fatalf("runs worked in %q and %q", first, second)
}
if want := evalSymlinks(filepath.Join(tmp, "magpie-claude")); first != want {
t.Fatalf("cwd %q, want %q", first, want)
}
if _, err := os.Stat(first); err != nil {
t.Fatalf("the folder went with its run: %v", err)
}
}
// A one-off ask — a lone message and no tools, as an agent's title or the
// router's classifier sends — leaves no Claude Code waiting for a next
// turn that won't come; a conversation already going on keeps its run.
@@ -0,0 +1,22 @@
//go:build !windows
package gateway
import (
"os"
"strconv"
"syscall"
)
// ownedByMe says the file belongs to the user magpie runs as.
func ownedByMe(fi os.FileInfo) bool {
st, ok := fi.Sys().(*syscall.Stat_t)
return ok && int(st.Uid) == os.Getuid()
}
// othersCanWrite says the group or anyone else may write in the folder.
func othersCanWrite(fi os.FileInfo) bool { return fi.Mode().Perm()&0o022 != 0 }
// claudeWorkName is the work folder's name in the temp folder, which on
// Linux every user shares.
func claudeWorkName() string { return "magpie-claude-work-" + strconv.Itoa(os.Getuid()) }
@@ -0,0 +1,16 @@
package gateway
import "os"
// ownedByMe says the file belongs to the user magpie runs as: on Windows
// the folder is in the user's own %TEMP%, which no one else writes.
func ownedByMe(os.FileInfo) bool { return true }
// othersCanWrite is false on Windows: Go reports every folder that isn't
// read-only as 0777 there, ACLs not being mode bits, and the folder is in
// the user's own %TEMP%.
func othersCanWrite(os.FileInfo) bool { return false }
// claudeWorkName is the work folder's name in the temp folder, the user's
// own on Windows.
func claudeWorkName() string { return "magpie-claude-work" }
+111
View File
@@ -0,0 +1,111 @@
package gateway
import (
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// claudeWorkDirs runs two Claude subscription requests through a script
// standing in for Claude Code, with a temp folder of the test's own and a
// home kept in git, and gives the folders the two runs worked in and the
// folder they should share.
func claudeWorkDirs(t *testing.T, prepare func(work string)) (dirs []string, work string) {
t.Helper()
if runtime.GOOS == "windows" {
t.Skip("a shell script stands in for Claude Code")
}
home := t.TempDir()
if err := os.Mkdir(filepath.Join(home, ".git"), 0o700); err != nil {
t.Fatal(err)
}
t.Setenv("HOME", home)
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
t.Setenv("TMPDIR", t.TempDir())
work = filepath.Join(os.TempDir(), claudeWorkName())
if prepare != nil {
prepare(work)
}
dir := t.TempDir()
script := `#!/bin/sh
pwd -P >> ` + dir + `/dirs
while read -r line; do
echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-sonnet-5","usage":{"input_tokens":1}}}}'
echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}}'
echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}}'
echo '{"type":"stream_event","event":{"type":"message_stop"}}'
echo '{"type":"result","subtype":"success","is_error":false,"result":""}'
done
`
os.WriteFile(filepath.Join(dir, "claude"), []byte(script), 0o755)
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
s := New()
p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}}
for _, said := range []string{"one", "two"} {
body := `{"model":"claude-sonnet-5","max_tokens":100,"system":"rules","messages":[{"role":"user","content":"` + said + `"}]}`
rec := httptest.NewRecorder()
var u Usage
if code, msg := s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, p, "claude-sonnet-5", []byte(body), &u); code != 200 {
t.Fatalf("%d %s", code, msg)
}
}
b, _ := os.ReadFile(filepath.Join(dir, "dirs"))
return strings.Fields(string(b)), evalSymlinks(work)
}
// Every run works in the same folder: Claude Code puts its working
// directory in the system prompt, ahead of the conversation, so a folder of
// each run's own left nothing past Claude Code's own part of the prompt to
// be read from the cache. The folder is the user's own, made for them
// alone, in the temp folder: not under a home kept in git, whose status
// Claude Code would put in the prompt.
func TestClaudeRunsShareAWorkDir(t *testing.T) {
dirs, work := claudeWorkDirs(t, nil)
if len(dirs) != 2 || dirs[0] != work || dirs[1] != work {
t.Fatalf("working directories: %q, want %s", dirs, work)
}
if home := evalSymlinks(os.Getenv("HOME")); strings.HasPrefix(work, home+string(filepath.Separator)) || !strings.HasPrefix(work, evalSymlinks(os.TempDir())+string(filepath.Separator)) {
t.Fatalf("work folder %s: in the home %s, or not in the temp folder", work, home)
}
fi, err := os.Stat(work)
if err != nil || fi.Mode().Perm() != 0o700 {
t.Fatalf("work folder: %v %v", fi.Mode(), err)
}
}
// A work folder others can write to is not worked in, as anything put
// there (a CLAUDE.md) would be read by every run: each run works in a
// folder of its own instead.
func TestClaudeWorkDirOthersCanWriteIsAvoided(t *testing.T) {
dirs, work := claudeWorkDirs(t, func(work string) {
if err := os.MkdirAll(work, 0o700); err != nil {
t.Fatal(err)
}
os.Chmod(work, 0o777)
})
if len(dirs) != 2 || dirs[0] == work || dirs[1] == work || dirs[0] == dirs[1] {
t.Fatalf("working directories: %q, shared %s", dirs, work)
}
}
// A symlink where the work folder goes, to a folder anyone could have
// filled, is not followed: each run works in a folder of its own.
func TestClaudeWorkDirSymlinkIsAvoided(t *testing.T) {
var target string
dirs, work := claudeWorkDirs(t, func(work string) {
target = t.TempDir()
if err := os.Symlink(target, work); err != nil {
t.Fatal(err)
}
})
target = evalSymlinks(target)
if len(dirs) != 2 || dirs[0] == target || dirs[1] == target || dirs[0] == dirs[1] {
t.Fatalf("working directories: %q, linked %s (%s)", dirs, target, work)
}
}