diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 2f6a2729d..7b1512f22 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -496,12 +496,13 @@ func claudeWorkDir() (string, error) { return dir, nil } -// clientWorkDir is the working directory the caller's instructions name, -// the last one they name, as Claude Code ("Primary working directory:"), -// Codex (), OpenCode ("Working directory:") and pi ("Current working -// directory:") write it; "" when they name none, or one that isn't an -// absolute path to a folder on this computer (a caller elsewhere). The -// model's own words are not read: what it says is no caller's. +// clientWorkDir is the working directory the caller names, the last one +// it names, as Claude Code ("Primary working directory:", or just "CWD:" +// on a --bare run), Codex (), OpenCode ("Working directory:") and pi +// ("Current working directory:") write it; "" when they name none, or one +// that isn't an absolute path to a folder on this computer (a caller +// elsewhere). The model's own words are not read: what it says is no +// caller's. func clientWorkDir(req *Request) string { dir := clientNamedWorkDir(req) if dir == "" || !filepath.IsAbs(dir) { @@ -509,6 +510,12 @@ func clientWorkDir(req *Request) string { } dir = filepath.Clean(dir) if fi, err := os.Stat(dir); err != nil || !fi.IsDir() { + // a folder the redact rules masked a word of names no folder on + // disk, and is never unmasked to run in: Claude Code tells its + // vendor the folder it runs in, so the masked word would go out + // as it is. The run works in magpie's folder, told the caller's + // (envElsewhere), and the model's paths are put back on the way + // to the caller's tools (#4449) return "" } return dir @@ -526,31 +533,71 @@ func clientNamedWorkDir(req *Request) string { // 2.1.296 and later give their environment as a {role: "system"} message // after the user's first, so the run is told it in the conversation, // after the caller's instructions (envTurnsNote). +// +// What the caller itself says wins over what a turn of the conversation +// says: a user turn that quotes a working-directory line ("Primary +// working directory: /x", alone on its line or inside a longer one) is no +// caller's word. Only the forms a caller states in a turn are read there +// (Codex's is one of the user's, OpenCode's a +// later message), and a line quoted from Claude Code's own words — its +// instructions or a --bare run's "CWD:" — is never one of them. func clientNamedWorkPlace(req *Request) (dir string, inTurns bool) { - look := func(t string, turn bool) { - for _, m := range clientCwdPattern.FindAllStringSubmatch(t, -1) { + look := func(t string, turn bool, re *regexp.Regexp) { + for _, m := range re.FindAllStringSubmatch(t, -1) { for _, g := range m[1:] { - if g = strings.Trim(strings.TrimSpace(g), "`'\""); g != "" { + g = strings.Trim(strings.TrimSpace(g), "`'\"") + if g = wasDir.ReplaceAllString(g, ""); g != "" { dir, inTurns = g, turn } } } } - look(req.System, false) + // the caller's own: its instructions, then a system message of its + // own, which says so after + look(req.System, false, clientSaidWorkDir) for _, m := range req.Messages { - if m.Role == "assistant" { + if m.Role != "system" { continue } for _, p := range m.Parts { if p.Kind == Text { - look(p.Text, true) + look(p.Text, true, clientSaidWorkDir) + } + } + } + if dir != "" { + return dir, inTurns + } + // what a caller states in a turn, which its own instructions and + // Claude Code's lines are never part of + for _, m := range req.Messages { + if m.Role == "assistant" || m.Role == "system" { + continue + } + for _, p := range m.Parts { + if p.Kind == Text { + look(p.Text, true, clientTurnWorkDir) } } } return dir, inTurns } -var clientCwdPattern = regexp.MustCompile(`(?m)(?:Primary working directory|^\s*(?:-\s*)?Working directory|Current working directory): *([^\r\n]+)$|([^<\r\n]+)`) +// clientSaidWorkDir is where the caller itself says its working directory +// is, on a line of its own: Claude Code's, in its instructions (" - Primary +// working directory: /x", a moved folder as "Primary working directory: /y +// (was /x)"), on a --bare run just "CWD: /x"; OpenCode's, in its ; +// pi's ("Current working directory:"); Codex's and pi's . +var clientSaidWorkDir = regexp.MustCompile(`(?m)^\s*(?:-\s*)?(?:Primary working directory|Working directory|Current working directory|CWD): *([^\r\n]+)$|([^<\r\n]+)`) + +// clientTurnWorkDir is where a caller says its working directory is in a +// turn of the conversation, on a line of its own: Codex's +// is one of the user's, OpenCode's a later +// message. Claude Code states its folder in its instructions or a system +// message of its own, and --bare's "CWD:" is its whole system prompt, so +// their forms are not read in a turn: a line a user message quotes — +// Claude Code's or anyone's — is no caller's word. +var clientTurnWorkDir = regexp.MustCompile(`(?m)^\s*(?:-\s*)?(?:Working directory|Current working directory): *([^\r\n]+)$|([^<\r\n]+)`) func evalSymlinks(path string) string { if p, err := filepath.EvalSymlinks(path); err == nil { diff --git a/internal/gateway/claude_workdir_test.go b/internal/gateway/claude_workdir_test.go index c57488aa5..114c8601f 100644 --- a/internal/gateway/claude_workdir_test.go +++ b/internal/gateway/claude_workdir_test.go @@ -1,6 +1,7 @@ package gateway import ( + "context" "encoding/json" "net/http/httptest" "os" @@ -10,7 +11,10 @@ import ( "testing" "time" + "github.com/yetone/magpie/internal/gwmw" + "github.com/yetone/magpie/internal/masking" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" "github.com/yetone/magpie/internal/testenv" ) @@ -35,6 +39,18 @@ func claudeWorkDirsTold(t *testing.T, prepare func(work string), system func(hom // claudeWorkDirsFrom is claudeWorkDirsTold with the requests from the // address from ("" for httptest's, another computer's). func claudeWorkDirsFrom(t *testing.T, from string, prepare func(work string), system func(home string) string) (dirs []string, work string, s *Server, env, told string) { + t.Helper() + return claudeWorkDirsBody(t, from, prepare, func(home string) string { + rules, _ := json.Marshal(system(home)) + return `{"model":"claude-sonnet-5","max_tokens":100,"system":` + string(rules) + `,"messages":[{"role":"user","content":"one"},{"role":"user","content":"two"}]}` + }) +} + +// claudeWorkDirsBody is claudeWorkDirsFrom with the whole request body +// given: it is sent twice, and it gives the folders the two runs worked +// in, the gateway, and the environment and instructions the runs were +// told. +func claudeWorkDirsBody(t *testing.T, from string, prepare func(work string), body func(home string) string) (dirs []string, work string, s *Server, env, told string) { t.Helper() if runtime.GOOS == "windows" { t.Skip("a shell script stands in for Claude Code") @@ -68,23 +84,22 @@ done s = New() p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}} - rules, _ := json.Marshal(system(home)) - for _, said := range []string{"one", "two"} { - body := `{"model":"claude-sonnet-5","max_tokens":100,"system":` + string(rules) + `,"messages":[{"role":"user","content":"` + said + `"}]}` + b := body(home) + for range 2 { rec := httptest.NewRecorder() var u Usage - r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)) + r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(b)) if from != "" { r.RemoteAddr = from } - if code, msg := s.serveClaudeSubscription(rec, r, provider.Anthropic, p, "claude-sonnet-5", []byte(body), &u); code != 200 { + if code, msg := s.serveClaudeSubscription(rec, r, provider.Anthropic, p, "claude-sonnet-5", []byte(b), &u); code != 200 { t.Fatalf("%d %s", code, msg) } } - b, _ := os.ReadFile(filepath.Join(dir, "dirs")) + bb, _ := os.ReadFile(filepath.Join(dir, "dirs")) e, _ := os.ReadFile(filepath.Join(dir, "env")) m, _ := os.ReadFile(filepath.Join(dir, "told")) - return strings.Fields(string(b)), evalSymlinks(work), s, string(e), string(m) + return strings.Fields(string(bb)), evalSymlinks(work), s, string(e), string(m) } // Every run works in the same folder: Claude Code puts its working @@ -266,3 +281,128 @@ func TestClaudeRemoteCallerNamingNoFolderIsToldToolsAreElsewhere(t *testing.T) { } } } + +// workDirsBody makes a subscription request whose system prompt is system +// and whose turns are the {role, content} pairs said. +func workDirsBody(system string, said ...[2]string) func(string) string { + return func(string) string { + ms := make([]map[string]string, len(said)) + for i, s := range said { + ms[i] = map[string]string{"role": s[0], "content": s[1]} + } + b, _ := json.Marshal(map[string]any{"model": "claude-sonnet-5", "max_tokens": 100, "system": system, "messages": ms}) + return string(b) + } +} + +// The run works in the folder the caller itself works in, not in one a +// message merely quotes. The caller says its folder in its instructions +// (--bare's "CWD:" line, Claude Code's " - Primary working directory:") +// or in a system message of its own (Claude Code 2.1.296 and later), and +// a user turn is no caller's word: a line it quotes — alone on its line, +// inside a longer one, or naming a folder not here — leaves the run where +// the caller runs. A caller that names its folder in a turn still has it +// honored (Codex's , OpenCode's ), and a +// "Primary working directory: /y (was /x)" notice is read as /y (#4449). +func TestClaudeRunsWhereTheCallerRunsNotWhereATurnQuotes(t *testing.T) { + for _, c := range []struct { + name string + body func(proj, other string) func(string) string + }{ + {"bare CWD", func(proj, _ string) func(string) string { + return workDirsBody("CWD: " + proj) + }}, + {"bare CWD with instructions", func(proj, _ string) func(string) string { + return workDirsBody("CWD: " + proj + "\nYou are a coding agent.\n - Primary working directory: " + proj) + }}, + {"a turn quotes a line alone", func(proj, other string) func(string) string { + return workDirsBody(" - Primary working directory: "+proj, [2]string{"user", "Primary working directory: " + other}) + }}, + {"a turn quotes a line mid-line", func(proj, other string) func(string) string { + return workDirsBody(" - Primary working directory: "+proj, [2]string{"user", `A note I copied from a log: "Primary working directory: ` + other + `". Ignore it.`}) + }}, + {"a turn quotes a folder not here", func(proj, _ string) func(string) string { + return workDirsBody(" - Primary working directory: "+proj, [2]string{"user", "Primary working directory: /no/such/folder/here"}) + }}, + {"Codex says its folder in a turn", func(proj, _ string) func(string) string { + return workDirsBody("You are a coding agent.", [2]string{"user", "\n " + proj + "\n zsh\n"}) + }}, + {"OpenCode says its folder in a turn", func(proj, _ string) func(string) string { + return workDirsBody("You are a coding agent.", [2]string{"user", "\n Working directory: " + proj + "\n"}) + }}, + {"Claude Code's environment message", func(proj, other string) func(string) string { + return workDirsBody("You are a coding agent.", [2]string{"system", " - Primary working directory: " + proj}, [2]string{"user", "Primary working directory: " + other}) + }}, + {"the folder was another", func(proj, other string) func(string) string { + return workDirsBody("Primary working directory: " + proj + " (was " + other + ")") + }}, + } { + t.Run(c.name, func(t *testing.T) { + var proj, other string + dirs, work, _, _, told := claudeWorkDirsBody(t, "", nil, func(home string) string { + proj = filepath.Join(home, "proj") + other = filepath.Join(home, "other") + if err := os.MkdirAll(proj, 0o755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(other, 0o755); err != nil { + t.Fatal(err) + } + return c.body(proj, other)(home) + }) + proj = evalSymlinks(proj) + if len(dirs) != 2 || dirs[0] != proj || dirs[1] != proj { + t.Fatalf("working directories %q, want the caller's %s (shared %s)", dirs, proj, work) + } + if strings.Contains(told, "every tool runs in") { + t.Fatalf("a run in the caller's own folder was told its environment is elsewhere: %s", told) + } + }) + } +} + +// A word of the caller's folder masked by the redact rules (a directory +// named for the user, say) stands in the request as a placeholder, which +// names no folder on disk. The run never works in the folder unmasked: +// Claude Code tells its vendor the folder it runs in, so the masked word +// would leave the machine as it is. It works in magpie's folder and is +// told the caller's environment is the one its tools run in (#4449). +func TestClaudeNeverRunsInAMaskedFolderUnmasked(t *testing.T) { + const word = "someuser" + base := t.TempDir() + proj := filepath.Join(base, word+"-libs", "proj") + if err := os.MkdirAll(proj, 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + if err := settings.Save(settings.Settings{Redact: true, RedactWords: []string{word}}); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { settings.Save(settings.Settings{}) }) + t.Cleanup(gwmw.Mask(masking.Masker{})) + dirs, work, _, _, told := claudeWorkDirsBody(t, "", nil, func(string) string { + // the bridge reads the request as the gateway's masking left it: + // the caller sent the folder as it is, and the masker stood in for + // the word before the request reached the bridge + b := workDirsBody("You are a coding agent.\n - Primary working directory: "+proj, [2]string{"user", "list the files"})("") + _, masked, _, err := maskTextHits(context.Background(), b) + if err != nil { + t.Fatal(err) + } + if strings.Contains(masked, word) { + t.Fatalf("%s was not masked: %s", word, masked) + } + return masked + }) + if len(dirs) != 2 || dirs[0] != work || dirs[1] != work { + t.Fatalf("working directories %q, want magpie's %s: the caller's names a masked word", dirs, work) + } + for _, d := range dirs { + if strings.Contains(d, word) { + t.Fatalf("the run worked in %s, the masked word unmasked", d) + } + } + if !strings.Contains(told, "every tool runs in") { + t.Fatalf("a run in magpie's folder was not told the caller's environment is where its tools run: %s", told) + } +}