Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

claude: a run works in the caller's own folder, not magpie's temp folder

yetone680b5056870e
diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md
index ddf2cb77c..f31bdd686 100644
--- a/docs/subsystems/claude-subscription-bridge.md
+++ b/docs/subsystems/claude-subscription-bridge.md
@@ -502,19 +502,60 @@ run time, how it ended and its peak RSS (`proc.PeakRSS`, rusage
`ru_maxrss`; not on Windows) when it ends: an OOM report's pid can be found
in magpie's log.
+## The run's working folder (`clientWorkDir`)
+
+Claude Code tells its model the folder it runs in as the "Primary working
+directory". A run has no tools of its own: the client's run in the
+client's folder. Run in magpie's shared work folder (`claudeWorkDir`,
+`<tmp>/magpie-claude-work-<uid>`), the model was told that folder. It then
+wrote the client's files there, through the client's own tools, while the
+client's own prompt named another folder. Under a real Claude Code client,
+`pelican.html` landed in magpie's folder.
+
+A run therefore starts in the folder the caller names. `clientWorkDir`
+reads the system prompt and every message that is not the model's, and
+takes the last folder named. It knows four ways of naming it:
+
+- Claude Code: "Primary working directory: X";
+- Codex: `<cwd>X</cwd>`;
+- OpenCode: "Working directory: X";
+- pi: "Current working directory: X".
+
+The folder is taken only when it is an absolute path to a folder on this
+computer. Otherwise, as for a caller elsewhere, a Windows path on a Mac,
+or no folder named, the run starts in the shared folder as before. A
+Claude Code in WSL always takes the shared folder.
+
+Nothing else of the folder reaches the run. `--setting-sources ""` loads
+no CLAUDE.md, settings or skills from it. Auto memory is off, and
+`CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS=1` keeps the repository's status out
+of the prompt, which would change it, and Anthropic's cache with it,
+whenever a file changes. The system prompt magpie sends is unchanged; only
+the folder Claude Code runs in is.
+
+A run's sessions are saved in that folder's project
+(`<config>/projects/<the caller's folder>`), beside the user's own Claude
+Code sessions there when the run is on the user's own sign-in. Claude
+Code's `--resume` picker lists them while they last. That project is never
+swept: only magpie's own folder is (`sweepSessions`). A run's session is
+removed there by its id, when it ends or is discarded (`removeSession`).
+A session that a stopped gateway left there, and its temp files, stay
+there as the user's own sessions do; a sweep can't tell them apart.
+
## Files a run leaves
- Its session: `<config>/projects/<work project>/<session>.jsonl`, for
`--resume` (`claudeSessions`). It is removed when the run ends unless
shelved, and when a saved session is discarded (`removeSession`).
- `sweepSessions` removes those a stopped gateway left, once older than
- `idleLongest`.
+ `sweepSessions` removes those a stopped gateway left in magpie's own
+ work folder's project, once older than `idleLongest`; a caller's folder
+ is never swept (`clientWorkDir`).
- Claude Code's temp files for the session, the images it was given:
`<CLAUDE_CODE_TMPDIR or /tmp>/claude-<uid>/<work project>/<session>`
(`claudeTempDir`, not on Windows). They are removed with the session
(`removeSession`). The sweep removes those whose session file is gone and
in which nothing changed for `tempLongest` (a day). The folder is
- the work folder's for every account, and another account's session files
+ the run's work folder's for every account, and another account's session files
are in its own config folder.
A run started anew still sends every image in the conversation. Replacing
diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go
index 15470c8fb..ac1a277a7 100644
--- a/internal/gateway/claude_subscription.go
+++ b/internal/gateway/claude_subscription.go
@@ -399,6 +399,46 @@ 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 (<cwd>), 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 {
+ texts := []string{req.System}
+ for _, m := range req.Messages {
+ if m.Role == "assistant" {
+ continue
+ }
+ for _, p := range m.Parts {
+ if p.Kind == Text {
+ texts = append(texts, p.Text)
+ }
+ }
+ }
+ dir := ""
+ for _, t := range texts {
+ for _, m := range clientCwdPattern.FindAllStringSubmatch(t, -1) {
+ for _, g := range m[1:] {
+ if g = strings.Trim(strings.TrimSpace(g), "`'\""); g != "" {
+ dir = g
+ }
+ }
+ }
+ }
+ if dir == "" || !filepath.IsAbs(dir) {
+ return ""
+ }
+ dir = filepath.Clean(dir)
+ if fi, err := os.Stat(dir); err != nil || !fi.IsDir() {
+ return ""
+ }
+ return dir
+}
+
+var clientCwdPattern = regexp.MustCompile(`(?m)(?:Primary working directory|^\s*(?:-\s*)?Working directory|Current working directory): *([^\r\n]+)$|<cwd>([^<\r\n]+)</cwd>`)
+
func evalSymlinks(path string) string {
if p, err := filepath.EvalSymlinks(path); err == nil {
return p
@@ -679,7 +719,18 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
if len(req.Format.schema()) > 0 {
args = append(args, "--json-schema", string(cliSchema(req.Format.schema())))
}
- work, err := claudeWorkDir()
+ // in the caller's own folder when it says which it is and it is one
+ // here (clientWorkDir): Claude Code tells the model the folder it runs
+ // in as its working directory, and a model told magpie's folder wrote
+ // the caller's files there, through tools that run in the caller's
+ work := ""
+ if binary.wsl == nil {
+ work = clientWorkDir(req)
+ }
+ client := work != ""
+ if !client {
+ work, err = claudeWorkDir()
+ }
var sessions []string
switch {
case err != nil:
@@ -692,7 +743,11 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
// go on with it (claudeSessions)
sessions = claudeSessions(configDir, work)
args = slices.DeleteFunc(args, func(a string) bool { return a == "--no-session-persistence" })
- b.sweepSessions(sessions)
+ // a caller's folder keeps its own sessions beside the runs': only
+ // magpie's own folder is swept, a run's session removed by its id
+ if !client {
+ b.sweepSessions(sessions)
+ }
}
if from != nil {
defer from.discard() // unless the run took it
@@ -2007,6 +2062,11 @@ func cleanClaudeEnv(env []string) []string {
// 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",
+ // run in a caller's folder (clientWorkDir), Claude Code would put
+ // its repository's status in the prompt too: the caller tells its
+ // 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
diff --git a/internal/gateway/claude_workdir_test.go b/internal/gateway/claude_workdir_test.go
index 52dfdb4f9..f10fa24de 100644
--- a/internal/gateway/claude_workdir_test.go
+++ b/internal/gateway/claude_workdir_test.go
@@ -1,12 +1,14 @@
package gateway
import (
+ "encoding/json"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
+ "time"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/testenv"
@@ -17,6 +19,15 @@ import (
// 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()
+ dirs, work, _, _ = claudeWorkDirsTold(t, prepare, func(string) string { return "rules" })
+ return dirs, work
+}
+
+// claudeWorkDirsTold is claudeWorkDirs with the caller's instructions
+// system gives, from the test's home; it gives the gateway too, and the
+// environment the runs had.
+func claudeWorkDirsTold(t *testing.T, prepare func(work string), system func(home string) string) (dirs []string, work string, s *Server, env string) {
t.Helper()
if runtime.GOOS == "windows" {
t.Skip("a shell script stands in for Claude Code")
@@ -35,6 +46,7 @@ func claudeWorkDirs(t *testing.T, prepare func(work string)) (dirs []string, wor
dir := t.TempDir()
script := `#!/bin/sh
pwd -P >> ` + dir + `/dirs
+env >> ` + dir + `/env
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"}}}'
@@ -46,10 +58,11 @@ done
testenv.Program(t, filepath.Join(dir, "claude"), script)
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
- s := New()
+ 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":"rules","messages":[{"role":"user","content":"` + said + `"}]}`
+ body := `{"model":"claude-sonnet-5","max_tokens":100,"system":` + string(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 {
@@ -57,7 +70,8 @@ done
}
}
b, _ := os.ReadFile(filepath.Join(dir, "dirs"))
- return strings.Fields(string(b)), evalSymlinks(work)
+ e, _ := os.ReadFile(filepath.Join(dir, "env"))
+ return strings.Fields(string(b)), evalSymlinks(work), s, string(e)
}
// Every run works in the same folder: Claude Code puts its working
@@ -110,3 +124,74 @@ func TestClaudeWorkDirSymlinkIsAvoided(t *testing.T) {
t.Fatalf("working directories: %q, linked %s (%s)", dirs, target, work)
}
}
+
+// A caller that says which folder it works in has Claude Code run there:
+// Claude Code tells its model the folder it runs in as the working
+// directory, and a model told magpie's own folder wrote the caller's files
+// into it (a pelican.html left in magpie-claude-work), through tools that
+// run in the caller's. Each client's way of saying it is read, the last
+// said counting. The caller's folder keeps sessions of its own, which are
+// never swept, and its repository's status is not added to the prompt.
+func TestClaudeRunsInTheCallersWorkDir(t *testing.T) {
+ for _, c := range []struct{ name, said string }{
+ {"Claude Code", "# Environment\nYou have been invoked in the following environment: \n - Primary working directory: %s\n - Is a git repository: true\n"},
+ {"Codex", "<environment_context>\n <cwd>%s</cwd>\n <shell>zsh</shell>\n</environment_context>"},
+ {"OpenCode", "<env>\n Working directory: %s\n Is directory a git repo: yes\n</env>"},
+ {"pi", "Current date: 2026-10-26\nCurrent working directory: %s"},
+ {"said twice", " - Primary working directory: /nowhere/at/all\nlater:\n - Primary working directory: %s"},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ var proj, old string
+ dirs, work, s, env := claudeWorkDirsTold(t, nil, func(home string) string {
+ proj = filepath.Join(home, "proj")
+ if err := os.MkdirAll(proj, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ // a session of the user's own in that folder, older than
+ // any the bridge keeps
+ sessions := claudeSessions("", evalSymlinks(proj))
+ old = filepath.Join(sessions[0], "mine.jsonl")
+ if err := os.MkdirAll(sessions[0], 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(old, []byte("{}\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ then := time.Now().Add(-48 * time.Hour)
+ _ = os.Chtimes(old, then, then)
+ return strings.ReplaceAll(c.said, "%s", proj)
+ })
+ proj = evalSymlinks(proj)
+ if len(dirs) != 2 || dirs[0] != proj || dirs[1] != proj {
+ t.Fatalf("working directories: %q, want the caller's %s (not %s)", dirs, proj, work)
+ }
+ for _, d := range claudeSessions("", proj) {
+ if _, swept := s.subscription.swept.Load(d); swept {
+ t.Fatalf("the caller's sessions in %s were swept", d)
+ }
+ }
+ if _, err := os.Stat(old); err != nil {
+ t.Fatalf("the user's own session: %v", err)
+ }
+ if !strings.Contains(env, "CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS=1") {
+ t.Fatal("Claude Code would add the repository's status to the prompt")
+ }
+ })
+ }
+}
+
+// A folder the caller names that isn't one here (a caller on another
+// computer), or isn't absolute, leaves the runs in magpie's own folder.
+func TestClaudeCallersWorkDirElsewhereIsNotUsed(t *testing.T) {
+ for _, said := range []string{
+ " - Primary working directory: /no/such/folder/here",
+ " - Primary working directory: relative/proj",
+ "<cwd>C:\\Users\\someone\\proj</cwd>",
+ "no folder named",
+ } {
+ dirs, work, _, _ := claudeWorkDirsTold(t, nil, func(string) string { return said })
+ if len(dirs) != 2 || dirs[0] != work || dirs[1] != work {
+ t.Fatalf("%q: working directories %q, want %s", said, dirs, work)
+ }
+ }
+}