claude bridge: a caller on another computer naming no folder is told the tools run elsewhere
packinggoods on Discord: magpie on a Windows machine, the agent on a Mac.
Every shell command came wrapped in PowerShell. The model's prompt held
Claude Code's own environment section from the bridge's run: "Primary
working directory: C:\Users\...\Temp\magpie-claude-work, Platform: win32,
Shell: PowerShell". That describes the gateway, and no tool of the run
runs there: every tool is the caller's.
Claude Code has no option to leave that section out. With the real
claude 2.1.312 against a capture server (sandbox HOME, fake key), it is a
<system-reminder> in the run's first message, before magpie's text, with
the default prompt and with --system-prompt-file alike; the SDK's
excludeDynamicSections only moves it there. claude.exe on xiaomi-gpu gives
the same section with the Windows platform, temp folder and OS version.
13f9c7fca already told a run that the caller's environment wins, but only
when the caller's instructions name a folder in a form clientNamedWorkDir
reads, and never a lean run. Now:
- serveSubscription marks a request not from this computer
(Request.remoteCaller = !local(r)). A run in magpie's folder for such a
caller that names no folder (envUnknown) gets envUnknownNote after its
instructions: the environment given elsewhere is not where the tools
run, so no platform, shell or path is taken from it. A caller with no
system prompt gets the instructions block for the note alone.
- a lean run gets the note in its system prompt (leanSystem), the named-
folder one worded envElsewhereLeanNote since the environment comes after
it there. startRun now picks the folder before writing system.md.
- A caller on this computer that names no folder, a run in the caller's
own folder, and a named-folder caller in the non-lean run are told what
they were before, so their cached prompts are unchanged.
The notes name no app and no vendor. Nothing else of the request changes:
no flag, header, env or Claude Code prompt text. Gateway facts beyond the
environment section don't reach the prompt: --setting-sources "" (no
CLAUDE.md), CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 and
CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS=1 were already set.
Tests: TestClaudeRemoteCallerNamingNoFolderIsToldToolsAreElsewhere (IPv4
and IPv6 remote, with and without a system prompt, loopback, remote
naming a folder) and TestClaudeLeanPromptSaysWhereToolsRun. Both are red
on origin/main's claude_subscription.go and ir.go (0 of 2 runs told; lean
system prompt "Rules."). TestClaudeLeanPromptIsTheRunsSystemPrompt and
TestClaudeClientCacheAbsentUnchanged now send from loopback, which they
were about all along (httptest's address is another computer's).
Run (mote-run): go test ./internal/gateway -run
'Claude|Bridge|Subscription|Lean|Prompt|WorkDir|Resume' ok;
go test -timeout 45m ./internal/gateway: ok (532s); go vet ./internal/gateway
for darwin, linux (-tags nogui) and windows ok; gofmt -l clean. win-run on
xiaomi-gpu: the touched tests ok (the script-driven ones skip on Windows).
Real claude 2.1.312 fed the new first message: the note follows the
environment reminder inside external_system_instructions.
Not tried: a real model turn from a Mac client through a Windows
gateway, so whether the model now stops wrapping commands in PowerShell
is not measured; packinggoods's client and magpie version are not known.
This commit is contained in:
@@ -579,9 +579,26 @@ a Mac client of a Linux gateway). Since every tool is the caller's,
|
||||
`renderClaudePrompt` ends the caller's instructions with
|
||||
`envElsewhereNote`: the environment they describe is where every tool
|
||||
runs, and goes before one given earlier. It names no app or vendor, since
|
||||
it goes upstream. A lean run (`claudeLeanPrompt`) and a caller that names
|
||||
no folder are not told it. Not measured: how many tool calls it saves on
|
||||
a real run.
|
||||
it goes upstream. Not measured: how many tool calls it saves on a real
|
||||
run.
|
||||
|
||||
A caller on another computer (`Request.remoteCaller`, not `local`) that
|
||||
names no folder (`Request.envUnknown`) has only Claude Code's environment
|
||||
to go on, and that is the gateway's. packinggoods on Discord, a Mac
|
||||
client of a Windows gateway, had every command wrapped in PowerShell.
|
||||
Such a caller's instructions end with `envUnknownNote`: the environment
|
||||
given elsewhere is not where the tools run, so no platform, shell or path
|
||||
is taken from it. A caller with no instructions of its own gets the
|
||||
block for the note alone. A caller on this computer that names no folder
|
||||
is told nothing more: Claude Code's platform and shell are its own.
|
||||
|
||||
Claude Code has no option to leave its environment out. In 2.1.312 it
|
||||
is a `<system-reminder>` in the run's first message, before magpie's
|
||||
text, with `--system-prompt-file` too; the SDK's `excludeDynamicSections`
|
||||
only moves it there. So a lean run (`claudeLeanPrompt`) is told the same
|
||||
in its system prompt (`leanSystem`), the named-folder note worded as
|
||||
`envElsewhereLeanNote` since the environment comes after it there
|
||||
(`envNote` picks the note).
|
||||
|
||||
Nothing else of the folder reaches the run. `--setting-sources ""` loads
|
||||
no CLAUDE.md, settings or skills from it. Auto memory is off, and
|
||||
|
||||
@@ -200,6 +200,9 @@ func cacheAsk(t *testing.T, h *resumeHarness, fields, messages, mode string) *ht
|
||||
t.Helper()
|
||||
body := `{"model":"claude-sonnet-5","max_tokens":100,` + fields + `"messages":` + messages + `}`
|
||||
r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
|
||||
if h.from != "" {
|
||||
r.RemoteAddr = h.from
|
||||
}
|
||||
if mode != "" {
|
||||
r.Header.Set("X-Magpie-Cache-Marks", mode)
|
||||
}
|
||||
@@ -278,6 +281,7 @@ func TestClaudeClientCacheRunningTailAndDrops(t *testing.T) {
|
||||
func TestClaudeClientCacheAbsentUnchanged(t *testing.T) {
|
||||
h := newScriptHarness(t, "ok", `echo "cache-disabled ${DISABLE_PROMPT_CACHING-unset}" >> $log`)
|
||||
t.Setenv("DISABLE_PROMPT_CACHING", "0")
|
||||
h.from = "127.0.0.1:51000" // a caller elsewhere is told where its tools run
|
||||
fields := `"system":[{"type":"text","text":"shared","cache_control":{"type":"ephemeral","ttl":"5m"}}],"cache_control":{"type":"ephemeral","ttl":"1h"},`
|
||||
w := cacheAsk(t, h, fields, `[{"role":"user","content":"hello"}]`, "")
|
||||
if w.Header().Get("X-Magpie-Cache-Marks-Dropped") != "" {
|
||||
|
||||
@@ -67,6 +67,9 @@ func leanSetting(t *testing.T, on bool) {
|
||||
func (h *resumeHarness) post(body string, header ...string) {
|
||||
h.t.Helper()
|
||||
r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
|
||||
if h.from != "" {
|
||||
r.RemoteAddr = h.from
|
||||
}
|
||||
for i := 0; i+1 < len(header); i += 2 {
|
||||
r.Header.Set(header[i], header[i+1])
|
||||
}
|
||||
@@ -83,6 +86,7 @@ func (h *resumeHarness) post(body string, header ...string) {
|
||||
// instructions are in the first message, as before.
|
||||
func TestClaudeLeanPromptIsTheRunsSystemPrompt(t *testing.T) {
|
||||
h, runs := newLeanHarness(t)
|
||||
h.from = "127.0.0.1:51000" // a caller elsewhere is told where its tools run
|
||||
leanSetting(t, true)
|
||||
h.post(`{"model":"claude-sonnet-5","max_tokens":100,"system":[{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.301.eca; cc_entrypoint=cli; cch=00000;"},{"type":"text","text":"You are Aria, a notes assistant."}],"messages":[{"role":"user","content":"one"}]}`)
|
||||
h.post(`{"model":"claude-sonnet-5","max_tokens":100,"system":"Rules.","tools":[{"name":"look","input_schema":{"type":"object"}}],"tool_choice":{"type":"any"},"messages":[{"role":"user","content":"two"}]}`)
|
||||
@@ -156,3 +160,28 @@ func TestClaudeLeanPromptFileInWSL(t *testing.T) {
|
||||
t.Fatalf("%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A lean run's system prompt says where the caller's tools run when the
|
||||
// caller is elsewhere, as a run that keeps Claude Code's prompt is told
|
||||
// after the caller's instructions: Claude Code gives the gateway's
|
||||
// environment in the run's first message all the same, after the system
|
||||
// prompt. A caller on this computer naming no folder is told nothing more.
|
||||
func TestClaudeLeanPromptSaysWhereToolsRun(t *testing.T) {
|
||||
h, runs := newLeanHarness(t)
|
||||
leanSetting(t, true)
|
||||
h.from = "192.0.2.7:51000"
|
||||
h.post(`{"model":"claude-sonnet-5","max_tokens":100,"system":"Rules.","messages":[{"role":"user","content":"one"}]}`)
|
||||
h.post(`{"model":"claude-sonnet-5","max_tokens":100,"system":"Rules.\n - Primary working directory: /no/such/folder/here","messages":[{"role":"user","content":"two"}]}`)
|
||||
h.from = "127.0.0.1:51000"
|
||||
h.post(`{"model":"claude-sonnet-5","max_tokens":100,"system":"Rules.","messages":[{"role":"user","content":"three"}]}`)
|
||||
|
||||
if one := told(t, runs(), "one"); one.system != "Rules."+envUnknownNote {
|
||||
t.Fatalf("a caller elsewhere naming no folder: %q", one.system)
|
||||
}
|
||||
if two := told(t, runs(), "two"); !strings.HasSuffix(two.system, envElsewhereLeanNote) {
|
||||
t.Fatalf("a caller naming a folder elsewhere: %q", two.system)
|
||||
}
|
||||
if three := told(t, runs(), "three"); three.system != "Rules." {
|
||||
t.Fatalf("a caller on this computer: %q", three.system)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ type resumeHarness struct {
|
||||
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)
|
||||
}
|
||||
|
||||
func newResumeHarness(t *testing.T) *resumeHarness {
|
||||
|
||||
@@ -715,16 +715,6 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
|
||||
"magpie": map[string]any{"command": exe, "args": []string{"claude-mcp-helper", callbackPath, toolsPath}},
|
||||
}})
|
||||
args := claudeCLIArgs(model, string(mcpConfig), req.Effort, req.WebSearch)
|
||||
if req.leanPrompt {
|
||||
// in a file of the run's own: instructions can be longer than
|
||||
// Windows lets a command line be
|
||||
systemPath := filepath.Join(tmp, "system.md")
|
||||
if err := os.WriteFile(systemPath, []byte(leanSystem(req)), 0o600); err != nil {
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
args = append(args, "--system-prompt-file", binary.file(systemPath))
|
||||
}
|
||||
if req.ThinkOff {
|
||||
// the client turned thinking off, as Claude Code's auto mode
|
||||
// classifier and its small asks do: a run at Claude Code's own
|
||||
@@ -747,6 +737,21 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
|
||||
if !client {
|
||||
work, err = claudeWorkDir()
|
||||
req.envElsewhere = clientNamedWorkDir(req) != ""
|
||||
// a caller on another computer that names no folder: Claude Code's
|
||||
// environment is this computer's, and the tools run on the
|
||||
// caller's (packinggoods on Discord: a Mac client of a Windows
|
||||
// gateway had its commands wrapped in PowerShell)
|
||||
req.envUnknown = !req.envElsewhere && req.remoteCaller
|
||||
}
|
||||
if req.leanPrompt {
|
||||
// in a file of the run's own: instructions can be longer than
|
||||
// Windows lets a command line be
|
||||
systemPath := filepath.Join(tmp, "system.md")
|
||||
if err := os.WriteFile(systemPath, []byte(leanSystem(req)), 0o600); err != nil {
|
||||
cleanup()
|
||||
return nil, nil, err
|
||||
}
|
||||
args = append(args, "--system-prompt-file", binary.file(systemPath))
|
||||
}
|
||||
var sessions []string
|
||||
switch {
|
||||
@@ -2742,7 +2747,7 @@ func renderClaudePrompt(req *Request) ([]map[string]any, error) {
|
||||
var blocks []map[string]any
|
||||
var text strings.Builder
|
||||
// a lean run has them as its system prompt (leanSystem)
|
||||
if !req.leanPrompt && (req.System != "" || req.ToolChoice == "required" || strings.HasPrefix(req.ToolChoice, "name:")) {
|
||||
if !req.leanPrompt && (req.System != "" || req.ToolChoice == "required" || strings.HasPrefix(req.ToolChoice, "name:") || envNote(req) != "") {
|
||||
text.WriteString("<external_system_instructions>\n")
|
||||
system := withoutBillingHeader(req.System)
|
||||
pos := 0
|
||||
@@ -2761,9 +2766,7 @@ func renderClaudePrompt(req *Request) ([]map[string]any, error) {
|
||||
}
|
||||
}
|
||||
text.WriteString(system[pos:])
|
||||
if req.envElsewhere {
|
||||
text.WriteString(envElsewhereNote)
|
||||
}
|
||||
text.WriteString(envNote(req))
|
||||
text.WriteString(toolChoiceAsk(req))
|
||||
text.WriteString("\n</external_system_instructions>\n\n")
|
||||
// The caller's instructions are a block of their own, marked for the
|
||||
@@ -2865,6 +2868,33 @@ func renderClaudePrompt(req *Request) ([]map[string]any, error) {
|
||||
// app and no vendor: it goes to the vendor with the prompt.
|
||||
const envElsewhereNote = "\n\nThe environment these instructions describe (working directory, platform, OS, shell, git status) is the one every tool runs in. Where an environment given before them differs, go by these instructions; nothing has changed and there is no need to check."
|
||||
|
||||
// envElsewhereLeanNote is envElsewhereNote for a lean run, whose
|
||||
// instructions are its system prompt: Claude Code gives its environment
|
||||
// after them, in the run's first message, not before.
|
||||
const envElsewhereLeanNote = "\n\nThe environment these instructions describe (working directory, platform, OS, shell, git status) is the one every tool runs in. Where an environment given elsewhere in this conversation differs, go by these instructions; nothing has changed and there is no need to check."
|
||||
|
||||
// envUnknownNote follows the caller's instructions when the caller is on
|
||||
// another computer and names no folder: Claude Code's environment (its
|
||||
// platform, OS, shell and folder) is the gateway's, which no tool runs
|
||||
// on, and a model told only that one wrapped the caller's commands in the
|
||||
// gateway's shell. It names no app and no vendor.
|
||||
const envUnknownNote = "\n\nThe environment given elsewhere in this conversation (its working directory, platform, OS and shell) is not the one the tools run on: don't take a platform, shell or path for a tool call from it."
|
||||
|
||||
// envNote is what a run is told after the caller's instructions of where
|
||||
// its tools run: "" for a run in the caller's own folder, or for a caller
|
||||
// on this computer that names none.
|
||||
func envNote(req *Request) string {
|
||||
switch {
|
||||
case req.envElsewhere && req.leanPrompt:
|
||||
return envElsewhereLeanNote
|
||||
case req.envElsewhere:
|
||||
return envElsewhereNote
|
||||
case req.envUnknown:
|
||||
return envUnknownNote
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func toolChoiceAsk(req *Request) string {
|
||||
switch {
|
||||
case req.ToolChoice == "required":
|
||||
@@ -2878,10 +2908,11 @@ func toolChoiceAsk(req *Request) string {
|
||||
// leanSystem is a lean run's system prompt (ClaudeLeanPrompt): the
|
||||
// caller's instructions without the client Claude Code's billing line, as
|
||||
// renderClaudePrompt tells them to a run that keeps Claude Code's own,
|
||||
// with its tool choice. Claude Code still puts its billing line and its
|
||||
// with where its tools run (envNote) and its tool choice. Claude Code
|
||||
// still puts its billing line and its
|
||||
// identity line before it, and marks it for the cache itself.
|
||||
func leanSystem(req *Request) string {
|
||||
return strings.TrimSpace(withoutBillingHeader(req.System) + toolChoiceAsk(req))
|
||||
return strings.TrimSpace(withoutBillingHeader(req.System) + envNote(req) + toolChoiceAsk(req))
|
||||
}
|
||||
|
||||
// historyChunk is how many messages of the history renderClaudePrompt puts
|
||||
@@ -4441,6 +4472,9 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from
|
||||
// a client that places its own cache marks keeps Claude Code's prompt:
|
||||
// its system marks are placed in the run's first message (#1717)
|
||||
req.leanPrompt = name == "Claude Code" && req.clientCache == nil && settings.Load().ClaudeLeanPrompt
|
||||
// the tools of a caller on another computer run there, not where
|
||||
// Claude Code runs (envUnknownNote)
|
||||
req.remoteCaller = !local(r)
|
||||
if req.Format != nil && req.Format.schema() == nil {
|
||||
// --json-schema takes a schema only: any JSON object is asked for
|
||||
// in words
|
||||
|
||||
@@ -28,6 +28,13 @@ func claudeWorkDirs(t *testing.T, prepare func(work string)) (dirs []string, wor
|
||||
// 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, told string) {
|
||||
t.Helper()
|
||||
return claudeWorkDirsFrom(t, "", prepare, system)
|
||||
}
|
||||
|
||||
// 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()
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("a shell script stands in for Claude Code")
|
||||
@@ -66,7 +73,11 @@ done
|
||||
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 {
|
||||
r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))
|
||||
if from != "" {
|
||||
r.RemoteAddr = from
|
||||
}
|
||||
if code, msg := s.serveClaudeSubscription(rec, r, provider.Anthropic, p, "claude-sonnet-5", []byte(body), &u); code != 200 {
|
||||
t.Fatalf("%d %s", code, msg)
|
||||
}
|
||||
}
|
||||
@@ -221,3 +232,37 @@ func btoi(b bool) int {
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// A caller on another computer that names no folder (packinggoods on
|
||||
// Discord: a Mac client of a Windows gateway) is told after its
|
||||
// instructions that the environment Claude Code gives, the gateway's
|
||||
// platform, shell and temp folder, is not where its tools run: told only
|
||||
// that one, the model wrapped every command in the gateway's PowerShell.
|
||||
// It is told so with no instructions of its own too. A caller on this
|
||||
// computer naming none is told nothing more, and one naming a folder
|
||||
// elsewhere is told the note for that, not this one.
|
||||
func TestClaudeRemoteCallerNamingNoFolderIsToldToolsAreElsewhere(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
from, said string
|
||||
unknown bool
|
||||
}{
|
||||
{"192.0.2.7:51000", "You are a coding agent.", true},
|
||||
{"[2001:db8::7]:51000", "", true},
|
||||
{"127.0.0.1:51000", "You are a coding agent.", false},
|
||||
{"192.0.2.7:51000", " - Primary working directory: /no/such/folder/here", false},
|
||||
} {
|
||||
dirs, work, _, _, told := claudeWorkDirsFrom(t, c.from, nil, func(string) string { return c.said })
|
||||
if len(dirs) != 2 || dirs[0] != work || dirs[1] != work {
|
||||
t.Fatalf("%s %q: working directories %q, want %s", c.from, c.said, dirs, work)
|
||||
}
|
||||
if got := strings.Count(told, "not the one the tools run on"); got != 2*btoi(c.unknown) {
|
||||
t.Fatalf("%s %q: told the tools run elsewhere in %d of 2 runs, want %v: %s", c.from, c.said, got, c.unknown, told)
|
||||
}
|
||||
if c.unknown && strings.Index(told, "not the one the tools run on") > strings.Index(told, "/external_system_instructions") {
|
||||
t.Fatalf("%s %q: the note is not with the caller's instructions: %s", c.from, c.said, told)
|
||||
}
|
||||
if c.unknown && strings.Contains(told, "every tool runs in") {
|
||||
t.Fatalf("%s %q: told the named-folder note too: %s", c.from, c.said, told)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,6 +175,13 @@ type Request struct {
|
||||
// Windows with Claude Code in WSL), so the run's own prompt describes
|
||||
// another machine than the one the tools run on (envElsewhereNote).
|
||||
envElsewhere bool
|
||||
// envUnknown: the caller is on another computer (remoteCaller) and its
|
||||
// instructions name no working directory, so the run's own prompt
|
||||
// describes a machine no tool runs on, and nothing says which does
|
||||
// (envUnknownNote).
|
||||
envUnknown bool
|
||||
// remoteCaller: the request came from another computer (not local).
|
||||
remoteCaller bool
|
||||
// hourMarks has the cache marks magpie adds on Anthropic's Messages
|
||||
// (anthropicBody) last an hour: a Responses client's (Codex's), whose
|
||||
// turns are often more than five minutes apart and whose own vendor
|
||||
|
||||
Reference in New Issue
Block a user