claude: an auto-mode client's tool loop keeps its interactive run (#4804)
Auto mode's safeguards change with every tool batch: prior_turn_context grows by the turn before. An interactive Claude Code run read them once, from CLAUDE_CODE_EXTRA_BODY in its environment as it started. So a tool loop either started the run again (the whole conversation written to the cache again), or kept it and sent the classifier the context it started with, which is not what real Claude Code sends. Each turn's safeguards now reach the running run: - The bridge writes the extra body to <run tmp>/guard.json and hands its path to the helper as MAGPIE_CLAUDE_GUARD (mapped for WSL in newTap). - tap.js, on each /v1/messages request whose string body has a safeguards key, reads the file and puts its safeguards in the body. It also sets CLAUDE_CODE_EXTRA_BODY to the file's text, so Claude Code's own later reads agree. The first time, it writes guard.json.live. - setSafeguards rewrites the file (temp and rename, retried for Windows) instead of restarting, once .live exists. Without .live (a Claude Code that doesn't load the tap), it falls back to the old rule: keep the run when only the varying parts changed, otherwise restart. A beta change, or safeguards appearing or going, still restarts. The tap changes only the safeguards value; any other byte of the body is Claude Code's own. Bodies without safeguards, count_tokens and non-string bodies are passed through untouched. The tool-results path logged "process expired" alone while the run's end read "magpie ended it". It now aborts the run with the reason and logs "tool results process expired: <reason>". continueWith's "not waiting for tool results" does the same. Tests: - TestClaudeTUIToolLoopCarriesEachBatchsSafeguards: three tool batches with growing prior_turn_context, then the answer. Checks one run and that each request carried its own batch's safeguards. - TestClaudeTUIToolResultsLogWhyTheRunEnded: no tap and the rules change. Checks that the log has the reason. - TestTapPutsTheGuardFilesSafeguards (bun and node): the rewrite, the bodies left alone, the env, and .live. - TestTapEnv: MAGPIE_CLAUDE_GUARD is passed through, WSL-mapped. Run (worktree atc360d9d30+ this change): - mote: go test -run 'TestClaudeTUI|TestClaudeBridgeSafeguard| TestClaudeToolResults|TestClaudeNoRunSaysWhy' ./internal/gateway ok (73 PASS); go test -run TestTap ./internal/claudetui ok (bun and node); go vet ./internal/claudetui ./internal/gateway on darwin, linux and windows ok; gofmt -l internal clean. - Full suite, go test -timeout 45m ./..., ran on the Linux box (wsl-run, magpie-desktop), not mote. mote had two other sessions' GUI suites sitting at 0% CPU for 3h42m at load 300, and one suite per machine. Result: 80 packages ok, internal/claudetui ok. Red: - TestGrokInstalled (#3548) - TestCodexBodyLimitFromMemory (#5118) - TestMoveCutShort (#5119) - TestCCListingKeepsItsNames (#4925) All four are red the same way run alone at origin/maind8b3749efon that box. Root, internal/cli and internal/gui don't build there without GTK4 (#5120). - Real use, macOS: - Sandbox HOME and CLAUDE_CONFIG_DIR, the owner's Max account copied to the sandbox dir's keychain item and deleted after. The refresh token didn't rotate. - A gateway on 127.0.0.1:3496; magpie built -tags dev atc360d9d30(before) and with this change (after). - Client: real interactive Claude Code 2.1.316 in tmux, --permission-mode auto, sonnet 5.5 through the gateway. - One turn, three sequential Bash calls (echo one, ls -la, echo three), four upstream requests. - Before: one run (pid 49488), cache_write 23005/86/162/86 (the first request cold). Its CLAUDE_CODE_EXTRA_BODY stayed the first request's safeguards, with no prior_turn_context, so requests 2 to 4 sent the classifier stale context. - After: one run (pid 64000), cache_read 23005/23091/23091/23253, cache_write 0/0/162/86. guard.json.live was written; the tap logged 3 "guard":"set" (requests 2 to 4), and guard.json ended with 3 prior_turn_context entries. Broken by hand: - The old claude_subscription.go makes both gateway tests red ("request 0 carried ..."; the log said "tool results process expired" alone). - tap.js without the rewrite makes TestTapPutsTheGuardFilesSafeguards red in bun and node. Not tried: - A tool loop whose rules change mid-loop with a real client (restart path; only the fake covers it). - Linux or WSL with a real Claude Code (the TUI isn't used on Windows). - Comparing the before/after upstream bodies byte for byte (the tap logs that it set the value, not the bodies). - The gateway package as its own -timeout 45m run on macOS: only the targeted tests ran on mote, and the full package ran on Linux.
This commit is contained in:
@@ -342,24 +342,43 @@ over each turn. One that can't be had fails the request, saying which
|
||||
and why; no Claude Code runs it. With the bytes in, the request is an
|
||||
ordinary one with a pasted image (`TestClaudeTUIImageByURL`).
|
||||
|
||||
Safeguards are taken: interactive Claude Code reads
|
||||
`CLAUDE_CODE_EXTRA_BODY` only as it starts (2.1.316: a later
|
||||
`apply_flag_settings` or a rewritten `--settings` file changes nothing it
|
||||
sends), so `startRun` puts them in its environment, and a turn whose
|
||||
safeguards changed in what the user allows starts a new run told the
|
||||
whole conversation (`setSafeguards`). Claude Code's classifier context
|
||||
also carries parts that change on nearly every request, the ones it
|
||||
names as variable and sheds over its 256KB budget: `prior_turn_context`,
|
||||
`system_reminders`, `artifacts`, `text_provenance`, `shed`, Chrome's
|
||||
tabs, and git's status, remotes and error. `safeguardsKept` leaves those
|
||||
out of the comparison (git keeps cwd, root, branch and default branch),
|
||||
and a run whose turn differs only there goes on with the context it
|
||||
started with. Restarting for them began a new run for every turn and
|
||||
tool round, each writing the whole conversation to the cache again, and
|
||||
one message drained a Pro account's 5-hour window (xybio;
|
||||
`TestClaudeTUISafeguardsVaryingPartsKeepTheRun`). The cost: the server
|
||||
classifier sees those parts as they were when the run started, not
|
||||
current. A rules, permission-mode, auto-mode, folder or branch change
|
||||
Safeguards are taken, each turn's in every request (#4804). Interactive
|
||||
Claude Code reads `CLAUDE_CODE_EXTRA_BODY` from its own environment as
|
||||
it builds each request, and nothing outside it changes that once it runs
|
||||
(2.1.316: a later `apply_flag_settings` or a rewritten `--settings` file
|
||||
changes nothing it sends). `startRun` puts them in its environment, and
|
||||
writes the same extra body to `guard.json` in the run's temp folder,
|
||||
named to the helper by `MAGPIE_CLAUDE_GUARD` (`claudetui.GuardEnv`). The
|
||||
helper hands it to Claude Code as WSL reads it, and takes it out of the
|
||||
environment otherwise. On each `/v1/messages` request whose body is a
|
||||
string with a `safeguards` key, `tap.js` reads the file, puts its
|
||||
`safeguards` there in place of Claude Code's, and sets
|
||||
`CLAUDE_CODE_EXTRA_BODY` in Claude Code's environment to it, so the
|
||||
requests after are built with it. A JSON parse and stringify of a
|
||||
2.1.316 body is byte for byte the same, so the request is what Claude
|
||||
Code sends with that variable. At the first such request it writes
|
||||
`guard.json.live`. `setSafeguards` replaces the file (temp file and
|
||||
rename) before the turn or tool results go to the run, and the run goes
|
||||
on, its cache too: an auto-mode tool loop's classifier context grows by
|
||||
a `prior_turn_context` entry each batch, and restarting for that began
|
||||
a new run for every tool round, each writing the whole conversation to
|
||||
the cache again (3 to 10 times the cost;
|
||||
`TestClaudeTUIToolLoopCarriesEachBatchsSafeguards`,
|
||||
`TestTapPutsTheGuardFilesSafeguards`). A changed safety beta, or
|
||||
safeguards appearing or going, still restarts.
|
||||
|
||||
A run with no `.live` file (no tap, a Claude Code not on
|
||||
`FetchSession`, or no request yet) can't be given them. Its classifier
|
||||
context also carries parts that change on nearly every request, the
|
||||
ones Claude Code names as variable and sheds over its 256KB budget:
|
||||
`prior_turn_context`, `system_reminders`, `artifacts`,
|
||||
`text_provenance`, `shed`, Chrome's tabs, and git's status, remotes and
|
||||
error. `safeguardsKept` leaves those out of the comparison (git keeps
|
||||
cwd, root, branch and default branch), and such a run whose turn
|
||||
differs only there goes on with the context it started with
|
||||
(xybio; `TestClaudeTUISafeguardsVaryingPartsKeepTheRun`). The server
|
||||
classifier then sees those parts as they were when the run started. A
|
||||
rules, permission-mode, auto-mode, folder or branch change
|
||||
still restarts. The `-p` run takes every change in place
|
||||
(`apply_flag_settings`). Client cache marks are taken too, but not kept: the
|
||||
helper pastes the words without their marks, so the run keeps Claude
|
||||
@@ -836,7 +855,12 @@ busy with another request, ended (how long ago, and why: `endWhy`, set by
|
||||
conversation. Tool results that find no run waiting add what became of
|
||||
the run that made the calls ("the run that made the calls ended …",
|
||||
`whyCallsLost`, from `b.lostCalls`, which `removeRun` fills with the calls
|
||||
the run waited on and the results it was last handed).
|
||||
the run waited on and the results it was last handed). Tool results a
|
||||
waiting run can't take (its safeguards can't be set, or it isn't
|
||||
waiting on those calls) end it with `abortFor`, and the log says why:
|
||||
"tool results process expired: <why>", where it said "process expired"
|
||||
alone and the run's end read "magpie ended it" (#4804,
|
||||
`TestClaudeTUIToolResultsLogWhyTheRunEnded`).
|
||||
|
||||
## A turn the client gives up on (`letGo`, #780, #1365)
|
||||
|
||||
|
||||
@@ -33,6 +33,14 @@ const tapPrefix = "magpie-claude-tap-"
|
||||
// tapEnv names the file tap.js writes to.
|
||||
const tapEnv = "MAGPIE_CLAUDE_TAP"
|
||||
|
||||
// GuardEnv names, to the helper, a file of the bridge's that holds the
|
||||
// extra body (CLAUDE_CODE_EXTRA_BODY) of the client's latest turn: tap.js
|
||||
// puts its safeguards in each request Claude Code makes, which reads that
|
||||
// variable only from an environment nothing outside it can change. The
|
||||
// bridge rewrites the file as a turn brings new ones, and tap.js writes
|
||||
// <file>.live once it has seen a request it puts them in.
|
||||
const GuardEnv = "MAGPIE_CLAUDE_GUARD"
|
||||
|
||||
// how long a message of the transcript waits for its stream, and a turn's
|
||||
// end for its streams to end; and how often the tap is read while one
|
||||
// goes on
|
||||
@@ -102,7 +110,11 @@ func newTap(path func(string) string) (*tap, []string) {
|
||||
if v := strings.TrimSpace(os.Getenv("BUN_OPTIONS")); v != "" && os.Getenv(WSLEnv) == "" {
|
||||
opts = v + " " + opts
|
||||
}
|
||||
return t, []string{"BUN_OPTIONS=" + opts, tapEnv + "=" + path(out)}
|
||||
env := []string{"BUN_OPTIONS=" + opts, tapEnv + "=" + path(out)}
|
||||
if g := os.Getenv(GuardEnv); g != "" {
|
||||
env = append(env, GuardEnv+"="+path(g))
|
||||
}
|
||||
return t, env
|
||||
}
|
||||
|
||||
// drop removes the tap's folder.
|
||||
|
||||
@@ -6,8 +6,19 @@
|
||||
// requests (x-claude-code-request-class: main), as it streams, to the
|
||||
// file MAGPIE_CLAUDE_TAP names: a JSON line an event. Claude Code reads
|
||||
// its own copy of the stream as before.
|
||||
//
|
||||
// MAGPIE_CLAUDE_GUARD names a file of the bridge's holding the
|
||||
// CLAUDE_CODE_EXTRA_BODY a turn of the client's gave (its safeguards).
|
||||
// Claude Code reads that variable as it builds each request, but only
|
||||
// from its own environment, which nothing outside can change once it
|
||||
// runs: each request to /v1/messages is given the file's safeguards, as
|
||||
// Claude Code would have put them there had the variable said so, and
|
||||
// the variable is set to it for the requests after. The file says it was
|
||||
// seen (<file>.live) at the first request it could be put in.
|
||||
(() => {
|
||||
const file = process.env.MAGPIE_CLAUDE_TAP;
|
||||
const guard = process.env.MAGPIE_CLAUDE_GUARD;
|
||||
delete process.env.MAGPIE_CLAUDE_GUARD;
|
||||
if (!file) return;
|
||||
// none of it is handed on to what Claude Code runs, nor says it is here
|
||||
delete process.env.MAGPIE_CLAUDE_TAP;
|
||||
@@ -40,6 +51,39 @@
|
||||
return;
|
||||
}
|
||||
let streams = 0;
|
||||
let live = false;
|
||||
// body is a request's body with the guard file's safeguards: the same
|
||||
// bytes when they are what it has, or when it has none to replace (a
|
||||
// request Claude Code builds without the extra body)
|
||||
const guarded = (body) => {
|
||||
if (!guard || typeof body !== "string" || body.indexOf('"safeguards"') < 0) return body;
|
||||
let extra, now;
|
||||
try {
|
||||
extra = fs.readFileSync(guard, "utf8");
|
||||
now = JSON.parse(extra);
|
||||
} catch {
|
||||
return body;
|
||||
}
|
||||
if (!now || typeof now !== "object" || !("safeguards" in now)) return body;
|
||||
let req;
|
||||
try {
|
||||
req = JSON.parse(body);
|
||||
} catch {
|
||||
return body;
|
||||
}
|
||||
if (!req || typeof req !== "object" || !("safeguards" in req)) return body;
|
||||
if (!live) {
|
||||
live = true;
|
||||
try {
|
||||
fs.writeFileSync(guard + ".live", "");
|
||||
} catch {}
|
||||
}
|
||||
if (process.env.CLAUDE_CODE_EXTRA_BODY !== extra) process.env.CLAUDE_CODE_EXTRA_BODY = extra;
|
||||
if (JSON.stringify(req.safeguards) === JSON.stringify(now.safeguards)) return body;
|
||||
req.safeguards = now.safeguards;
|
||||
put({ guard: "set" });
|
||||
return JSON.stringify(req);
|
||||
};
|
||||
// read tells each event of stream s, then its end: cut when it broke
|
||||
// off, as a dropped connection or Claude Code's own Esc ends it
|
||||
const read = async (s, body) => {
|
||||
@@ -77,6 +121,13 @@
|
||||
};
|
||||
class FetchSession extends Real {
|
||||
async fetch(input, init) {
|
||||
try {
|
||||
const url = String((input && input.url) || input);
|
||||
if (init && /\/v1\/messages(\?|$)/.test(url)) {
|
||||
const body = guarded(init.body);
|
||||
if (body !== init.body) init = { ...init, body };
|
||||
}
|
||||
} catch {}
|
||||
const res = await super.fetch(input, init);
|
||||
try {
|
||||
const url = String((input && input.url) || input);
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
package claudetui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// guardStub stands in for Bun's FetchSession: what each request was sent
|
||||
// with is printed, a JSON line a request.
|
||||
const guardStub = `if (!globalThis.Bun) globalThis.Bun = {};
|
||||
Bun.FetchSession = class {
|
||||
async fetch(input, init) {
|
||||
console.log(JSON.stringify({ body: typeof init.body === "string" ? init.body : null, keys: Object.keys(init) }));
|
||||
return new Response("", { headers: { "content-type": "text/plain" } });
|
||||
}
|
||||
};
|
||||
`
|
||||
|
||||
// guardMain makes requests as Claude Code does, the bridge's guard file
|
||||
// rewritten between them as a turn's safeguards change.
|
||||
const guardMain = `const fs = require("fs");
|
||||
const guard = process.argv[process.argv.length - 1];
|
||||
const url = "https://api.anthropic.com/v1/messages?beta=true";
|
||||
const headers = { "x-claude-code-request-class": "main" };
|
||||
const body = (sg) => JSON.stringify({ model: "m", messages: [{ role: "user", content: "hi" }], safeguards: sg, stream: true });
|
||||
(async () => {
|
||||
const s = new Bun.FetchSession();
|
||||
const ask = (u, b) => s.fetch(u, { signal: undefined, method: "POST", headers, body: b });
|
||||
// the run's own: sent as Claude Code made it
|
||||
await ask(url, body([{ c: "a" }]));
|
||||
// a turn's new ones, put in its next request in Claude Code's place
|
||||
fs.writeFileSync(guard, JSON.stringify({ safeguards: [{ c: "b", x: "<&>", n: [1, 2] }] }));
|
||||
await ask(url, body([{ c: "a" }]));
|
||||
// what Claude Code builds from the variable they now are: as it is
|
||||
await ask(url, body(JSON.parse(process.env.CLAUDE_CODE_EXTRA_BODY).safeguards));
|
||||
// a request without safeguards, another endpoint, a body not a string
|
||||
await ask(url, JSON.stringify({ model: "m", messages: [] }));
|
||||
await ask("https://api.anthropic.com/v1/messages/count_tokens", body([{ c: "a" }]));
|
||||
await s.fetch(url, { method: "POST", headers, body: new TextEncoder().encode(body([{ c: "a" }])) });
|
||||
console.log(JSON.stringify({ env: process.env.CLAUDE_CODE_EXTRA_BODY, guardEnv: process.env.MAGPIE_CLAUDE_GUARD || null }));
|
||||
})();
|
||||
`
|
||||
|
||||
// #4804: Claude Code reads CLAUDE_CODE_EXTRA_BODY from its environment as
|
||||
// it builds each request, and nothing outside it can change that once it
|
||||
// runs. tap.js puts the guard file's safeguards in each request to
|
||||
// /v1/messages in their place, the body otherwise byte for byte Claude
|
||||
// Code's, and sets the variable to them for the requests after; a request
|
||||
// it has nothing to replace in goes as it was. Run with Bun, Claude
|
||||
// Code's runtime, and Node, whichever are here.
|
||||
func TestTapPutsTheGuardFilesSafeguards(t *testing.T) {
|
||||
ran := false
|
||||
for _, rt := range []string{"bun", "node"} {
|
||||
path, err := exec.LookPath(rt)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ran = true
|
||||
t.Run(rt, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
for name, js := range map[string]string{"stub.js": guardStub, "main.js": guardMain, "tap.js": string(tapJS)} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(js), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
guard := filepath.Join(dir, "guard.json")
|
||||
start := `{"safeguards":[{"c":"a"}]}`
|
||||
if err := os.WriteFile(guard, []byte(start), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pre := "--preload"
|
||||
if rt == "node" {
|
||||
pre = "-r"
|
||||
}
|
||||
cmd := exec.Command(path, pre, filepath.Join(dir, "stub.js"), pre, filepath.Join(dir, "tap.js"), filepath.Join(dir, "main.js"), guard)
|
||||
cmd.Env = append(os.Environ(), tapEnv+"="+filepath.Join(dir, "tap.jsonl"), GuardEnv+"="+guard, "CLAUDE_CODE_EXTRA_BODY="+start)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
t.Fatalf("%v: %s", err, out)
|
||||
}
|
||||
var got []map[string]any
|
||||
for _, l := range strings.Split(strings.TrimSpace(string(out)), "\n") {
|
||||
var m map[string]any
|
||||
if json.Unmarshal([]byte(l), &m) != nil {
|
||||
t.Fatalf("not a line of the stub's: %q\n%s", l, out)
|
||||
}
|
||||
got = append(got, m)
|
||||
}
|
||||
body := func(sg string) string {
|
||||
return `{"model":"m","messages":[{"role":"user","content":"hi"}],"safeguards":` + sg + `,"stream":true}`
|
||||
}
|
||||
now := `[{"c":"b","x":"<&>","n":[1,2]}]`
|
||||
want := []any{body(`[{"c":"a"}]`), body(now), body(now), `{"model":"m","messages":[]}`, body(`[{"c":"a"}]`), nil}
|
||||
if len(got) != len(want)+1 {
|
||||
t.Fatalf("told %s", out)
|
||||
}
|
||||
for i, w := range want {
|
||||
if got[i]["body"] != w {
|
||||
t.Fatalf("request %d was sent\n%v\nwant\n%v", i, got[i]["body"], w)
|
||||
}
|
||||
if k, _ := json.Marshal(got[i]["keys"]); i < 5 && string(k) != `["signal","method","headers","body"]` {
|
||||
t.Fatalf("request %d's init is %s", i, k)
|
||||
}
|
||||
}
|
||||
end := got[len(got)-1]
|
||||
if end["env"] != `{"safeguards":[{"c":"b","x":"<&>","n":[1,2]}]}` || end["guardEnv"] != nil {
|
||||
t.Fatalf("Claude Code's environment after: %v", end)
|
||||
}
|
||||
if _, err := os.Stat(guard + ".live"); err != nil {
|
||||
t.Fatalf("the tap never said it puts them in: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
if !ran {
|
||||
t.Skip("neither Bun nor Node is here to run tap.js")
|
||||
}
|
||||
}
|
||||
@@ -235,6 +235,13 @@ func TestTapEnv(t *testing.T) {
|
||||
if want := []string{"BUN_OPTIONS=--preload /mnt/c/tap.js", tapEnv + "=/mnt/c/tap.jsonl"}; !slices.Equal(env, want) {
|
||||
t.Fatalf("WSL env %q, want %q", env, want)
|
||||
}
|
||||
// the bridge's guard file, where Claude Code reads it (#4804)
|
||||
t.Setenv(GuardEnv, filepath.Join(tmp, "guard.json"))
|
||||
guarded, env := newTap(func(p string) string { return "/mnt/c/" + filepath.Base(p) })
|
||||
defer guarded.drop()
|
||||
if want := []string{"BUN_OPTIONS=--preload /mnt/c/tap.js", tapEnv + "=/mnt/c/tap.jsonl", GuardEnv + "=/mnt/c/guard.json"}; !slices.Equal(env, want) {
|
||||
t.Fatalf("guarded env %q, want %q", env, want)
|
||||
}
|
||||
if runtime.GOOS != "windows" {
|
||||
spaced := filepath.Join(tmp, "a b")
|
||||
_ = os.Mkdir(spaced, 0o700)
|
||||
|
||||
@@ -253,7 +253,7 @@ func childEnv(extra ...string) []string {
|
||||
case k == "CLAUDECODE", k == "CLAUDE_CODE_ENTRYPOINT", k == "CLAUDE_CODE_CHILD_SESSION",
|
||||
k == "CLAUDE_CODE_SESSION_ID", k == "CLAUDE_CODE_SESSION_ATTENDED", k == "CLAUDE_CODE_EXECPATH",
|
||||
k == "CLAUDE_PID", k == "CLAUDE_EFFORT", k == "TERM", k == "COLUMNS", k == "LINES",
|
||||
strings.HasPrefix(k, "CLAUDE_CODE_MESSAGING_"), k == WSLEnv:
|
||||
strings.HasPrefix(k, "CLAUDE_CODE_MESSAGING_"), k == WSLEnv, k == GuardEnv:
|
||||
continue
|
||||
case slices.ContainsFunc(extra, func(x string) bool { return strings.HasPrefix(x, k+"=") }):
|
||||
continue
|
||||
|
||||
@@ -209,8 +209,11 @@ type subscriptionRun struct {
|
||||
settingsMu sync.Mutex
|
||||
safeguards json.RawMessage
|
||||
safeguardBeta string
|
||||
clientMarks bool
|
||||
lean bool // started with leanSystem as its system prompt
|
||||
// guard is the file the interactive mode's tap reads its safeguards
|
||||
// from on each request (claudetui.GuardEnv); "" with none
|
||||
guard string
|
||||
clientMarks bool
|
||||
lean bool // started with leanSystem as its system prompt
|
||||
// appended: started with the caller's instructions after Claude
|
||||
// Code's own system prompt (req.appendPrompt), not in its first
|
||||
// message; its session, resumed, is given them so again
|
||||
@@ -1132,16 +1135,23 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
|
||||
if len(req.Safeguards) > 0 {
|
||||
env = append(env, "ANTHROPIC_BETAS="+req.SafeguardBeta)
|
||||
}
|
||||
// The interactive mode's Claude Code reads CLAUDE_CODE_EXTRA_BODY once,
|
||||
// as it starts: one handed over later (apply_flag_settings, or a
|
||||
// --settings file rewritten) changes nothing it sends, so the run is
|
||||
// given the safeguards here, and one whose turn changes them is
|
||||
// started again (setSafeguards). A client's cache tail isn't added to
|
||||
// Claude Code's own marks, which it keeps (clientCache.pasted).
|
||||
tuiBody := ""
|
||||
// The interactive mode's Claude Code reads CLAUDE_CODE_EXTRA_BODY from
|
||||
// its own environment, which apply_flag_settings or a --settings file
|
||||
// rewritten don't reach once it runs: the run is given the safeguards
|
||||
// here, and a file (guard) its tap puts each later turn's in every
|
||||
// request from (claudetui.GuardEnv, setSafeguards). A client's cache
|
||||
// tail isn't added to Claude Code's own marks, which it keeps
|
||||
// (clientCache.pasted).
|
||||
tuiBody, guard := "", ""
|
||||
if tui && len(req.Safeguards) > 0 {
|
||||
tuiBody = claudeExtraBody(req.Safeguards, "")
|
||||
env = append(env, "CLAUDE_CODE_EXTRA_BODY="+tuiBody)
|
||||
guard = filepath.Join(tmp, "guard.json")
|
||||
if writeGuard(guard, tuiBody) == nil {
|
||||
env = append(env, claudetui.GuardEnv+"="+guard)
|
||||
} else {
|
||||
guard = ""
|
||||
}
|
||||
}
|
||||
if tui && (!client || configDir != "") {
|
||||
// a folder of magpie's, or an account folder of magpie's whose
|
||||
@@ -1192,6 +1202,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
|
||||
run.cachePrefix = prefix
|
||||
if tuiBody != "" {
|
||||
run.safeguards = bytes.Clone(req.Safeguards)
|
||||
run.guard = guard
|
||||
}
|
||||
run.allowed = allowedTools(req)
|
||||
if user, _ := ownerAccount(owner); user != "" {
|
||||
@@ -1512,15 +1523,27 @@ func (r *subscriptionRun) setSafeguards(req *Request) error {
|
||||
return errors.New("safety beta changed; restart Claude Code")
|
||||
}
|
||||
if r.tui {
|
||||
// It read them as it started (startRun), and reads them no more.
|
||||
// Claude Code's classifier context changes on nearly every
|
||||
// request in parts of its own (the tool ids of the turns before,
|
||||
// git status, system-reminder ids): restarting for those started
|
||||
// a new run for every tool round and every turn, each one
|
||||
// writing the whole conversation to the cache again, and one
|
||||
// message of xybio's spent a Pro account's 5-hour window. The run
|
||||
// goes on with what it started with unless a part that says what
|
||||
// the user allows changed.
|
||||
// Its tap puts the guard file's safeguards in each request it
|
||||
// makes from now on, as Claude Code would with them in its
|
||||
// environment, once it has seen a request to put them in
|
||||
// (guardLive): the run goes on, its cache too, and upstream is
|
||||
// sent this turn's classifier context whole (#4804).
|
||||
if len(req.Safeguards) > 0 && r.guardLive() {
|
||||
if err := writeGuard(r.guard, claudeExtraBody(req.Safeguards, "")); err != nil {
|
||||
return fmt.Errorf("the turn's safeguards could not be handed to Claude Code (%v); restart it", err)
|
||||
}
|
||||
r.safeguards = bytes.Clone(req.Safeguards)
|
||||
return nil
|
||||
}
|
||||
// A Claude Code without the tap read them as it started
|
||||
// (startRun), and reads them no more. Its classifier context
|
||||
// changes on nearly every request in parts of its own (the tool
|
||||
// ids of the turns before, git status, system-reminder ids):
|
||||
// restarting for those started a new run for every tool round
|
||||
// and every turn, each one writing the whole conversation to the
|
||||
// cache again, and one message of xybio's spent a Pro account's
|
||||
// 5-hour window. Such a run goes on with what it started with
|
||||
// unless a part that says what the user allows changed.
|
||||
if bytes.Equal(safeguardsKept(r.safeguards), safeguardsKept(req.Safeguards)) {
|
||||
return nil
|
||||
}
|
||||
@@ -1535,6 +1558,47 @@ func (r *subscriptionRun) setSafeguards(req *Request) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// guardLive is whether the run's tap puts the guard file's safeguards in
|
||||
// Claude Code's requests: it said so (<guard>.live) at the first one.
|
||||
func (r *subscriptionRun) guardLive() bool {
|
||||
if r.guard == "" {
|
||||
return false
|
||||
}
|
||||
_, err := os.Stat(r.guard + ".live")
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// writeGuard replaces the guard file with body whole: the tap reads it as
|
||||
// Claude Code makes a request, never half-written.
|
||||
func writeGuard(path, body string) error {
|
||||
f, err := os.CreateTemp(filepath.Dir(path), "guard-*.tmp")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = f.WriteString(body)
|
||||
if err == nil {
|
||||
err = f.Sync()
|
||||
}
|
||||
if cerr := f.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err != nil {
|
||||
_ = os.Remove(f.Name())
|
||||
return err
|
||||
}
|
||||
// on Windows a rename over a file being read fails a moment
|
||||
for i := 0; ; i++ {
|
||||
if err = os.Rename(f.Name(), path); err == nil || i == 20 {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if err != nil {
|
||||
_ = os.Remove(f.Name())
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// tuiCommand is the interactive mode's helper (claudetui) running this
|
||||
// Claude Code with the -p arguments args; tuiEnv adds to its environment.
|
||||
func (c claudeCLI) tuiCommand(ctx context.Context, args ...string) (*exec.Cmd, error) {
|
||||
@@ -5082,8 +5146,9 @@ func (r *subscriptionRun) continueWith(results []Part, said string, tools []brid
|
||||
close(waiter)
|
||||
}
|
||||
if delivered == 0 {
|
||||
r.abort()
|
||||
return nil, fmt.Errorf("the agent is not waiting for tool results %s", callIDs(results))
|
||||
err := fmt.Errorf("the agent is not waiting for tool results %s", callIDs(results))
|
||||
r.abortFor(err.Error())
|
||||
return nil, err
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.results = r.results[:0]
|
||||
@@ -6095,10 +6160,11 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from
|
||||
events, err = run.continueWith(withTaskNotices(results, req.Messages), saidWithResults(req.Messages), more)
|
||||
}
|
||||
if err != nil {
|
||||
run.abort()
|
||||
// it ended while it waited: a new one is told the whole
|
||||
// conversation
|
||||
run, how = nil, runExpired
|
||||
// it ended while it waited, or can't take the results: a new
|
||||
// one is told the whole conversation, and the log, and what a
|
||||
// later request is told of it (whyLost), say why
|
||||
run.abortFor(err.Error())
|
||||
run, how = nil, runExpired+": "+err.Error()
|
||||
}
|
||||
}
|
||||
// how tool results found the run waiting on them, or why a new one is
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/claudetui"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// guardClaude stands in for an interactive Claude Code whose tap puts the
|
||||
// guard file's safeguards in each request (claudetui's tap.js): it says
|
||||
// it saw a request to put them in (<file>.live) unless FAKE_NO_TAP is
|
||||
// set, and logs the file as each of its requests would carry it. A turn
|
||||
// saying CALL3 calls the client's read tool three times, one call a
|
||||
// request, before it answers. Its log is returned.
|
||||
func guardClaude(t *testing.T) string {
|
||||
t.Helper()
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("a shell script stands in for Claude Code")
|
||||
}
|
||||
if _, err := exec.LookPath("curl"); err != nil {
|
||||
t.Skip("the script makes its MCP calls with curl")
|
||||
}
|
||||
home := t.TempDir()
|
||||
testenv.SetHome(t, home)
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||
t.Setenv("TMPDIR", t.TempDir())
|
||||
t.Setenv("CLAUDE_CODE_TMPDIR", t.TempDir())
|
||||
t.Setenv("CLAUDE_CONFIG_DIR", filepath.Join(home, ".claude"))
|
||||
dir := t.TempDir()
|
||||
log := filepath.Join(dir, "claude.log")
|
||||
script := `#!/bin/sh
|
||||
echo "args $*" >> ` + log + `
|
||||
cb=$(cat "$(printf '%s\n' "$@" | grep -o '"claude-mcp-helper","[^"]*"' | head -1 | sed 's/.*","//; s/"$//')")
|
||||
me=$$
|
||||
sent() { echo "sent $(cat "$MAGPIE_CLAUDE_GUARD" 2>/dev/null)" >> ` + log + `; }
|
||||
start() { echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m'$1'","model":"claude-sonnet-5","usage":{"input_tokens":1}}}}'; }
|
||||
stop() {
|
||||
echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"'$1'"},"usage":{"output_tokens":3}}}'
|
||||
echo '{"type":"stream_event","event":{"type":"message_stop"}}'
|
||||
}
|
||||
while read -r line; do
|
||||
case "$line" in *control_request*)
|
||||
id=$(printf '%s' "$line" | sed -n 's/.*"request_id":"\([^"]*\)".*/\1/p')
|
||||
echo '{"type":"control_response","response":{"subtype":"success","request_id":"'$id'"}}'
|
||||
continue;;
|
||||
esac
|
||||
printf 'told %s\n' "$line" >> ` + log + `
|
||||
if [ -n "$MAGPIE_CLAUDE_GUARD" ] && [ -z "$FAKE_NO_TAP" ]; then : > "$MAGPIE_CLAUDE_GUARD.live"; fi
|
||||
case "$line" in *CALL3*) ;; *)
|
||||
sent; start 0
|
||||
echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"pid '$me'"}}}'
|
||||
stop end_turn
|
||||
echo '{"type":"result","subtype":"success","is_error":false,"result":""}'
|
||||
continue;;
|
||||
esac
|
||||
for k in 1 2 3; do
|
||||
sent; start $k
|
||||
echo '{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_G'$me'_'$k'","name":"mcp__magpie__read"}}}'
|
||||
echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{}"}}}'
|
||||
echo '{"type":"stream_event","event":{"type":"content_block_stop","index":0}}'
|
||||
stop tool_use
|
||||
got=$(curl --noproxy '*' -sS -X POST -H 'Content-Type: application/json' --data '{"tool_call_id":"toolu_G'$me'_'$k'","name":"read","arguments":{}}' "$cb" 2>> ` + log + `)
|
||||
echo "got $got" >> ` + log + `
|
||||
done
|
||||
sent; start 4
|
||||
echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"pid '$me' done"}}}'
|
||||
stop end_turn
|
||||
echo '{"type":"result","subtype":"success","is_error":false,"result":""}'
|
||||
done
|
||||
`
|
||||
testenv.Program(t, filepath.Join(dir, "claude"), script)
|
||||
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
claudeTUIRuns = true
|
||||
t.Cleanup(func() { claudeTUIRuns = false })
|
||||
helper := filepath.Join(t.TempDir(), "magpie")
|
||||
testenv.Program(t, helper, `#!/bin/sh
|
||||
[ "$1" = "`+claudetui.Command+`" ] || exit 9
|
||||
shift; claude=$1; shift
|
||||
exec "$claude" "$@"
|
||||
`)
|
||||
claudeTUIHelper = helper
|
||||
t.Cleanup(func() { claudeTUIHelper = "" })
|
||||
return log
|
||||
}
|
||||
|
||||
// guardsAt is auto mode's safeguards as Claude Code sends them with tool
|
||||
// batch n: the turns before (prior_turn_context) grow by one each batch,
|
||||
// as a real auto-mode tool loop's do, and deny is the rules' deny list.
|
||||
func guardsAt(n int, deny string) string {
|
||||
var prior []string
|
||||
for i := 0; i <= n; i++ {
|
||||
prior = append(prior, fmt.Sprintf(`{"tool_use_ids":["toolu_01Capture%03d"],"context":{"live_cwd":"/Users/lc/work","platform":"macos"}}`, i))
|
||||
}
|
||||
g := strings.Replace(reviewAsked, `{"tool_use_ids":["toolu_01Capture001"],"context":{"live_cwd":"/Users/lc/work","platform":"macos"}}`, strings.Join(prior, ","), 1)
|
||||
return strings.Replace(g, `"deny":[]`, `"deny":[`+deny+`]`, 1)
|
||||
}
|
||||
|
||||
// guardTurn sends the conversation so far with safeguards guards, and
|
||||
// returns the reply's tool call's id, "" for a reply in words (text).
|
||||
func guardTurn(t *testing.T, s *Server, conv, guards string) (id, text string) {
|
||||
t.Helper()
|
||||
body := `{"model":"claude-sonnet-5","max_tokens":100,"safeguards":` + guards + `,"system":"be brief","tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":[` + conv + `]}`
|
||||
rec := httptest.NewRecorder()
|
||||
var u Usage
|
||||
p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}}
|
||||
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{ Type, ID, Text string } `json:"content"`
|
||||
}
|
||||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
if len(res.Content) == 0 {
|
||||
t.Fatalf("no reply: %s", rec.Body)
|
||||
}
|
||||
last := res.Content[len(res.Content)-1]
|
||||
if last.Type == "tool_use" {
|
||||
// the run's call reaches magpie after its reply is told
|
||||
eventually(t, "the run's call "+last.ID, func() bool {
|
||||
s.subscription.mu.Lock()
|
||||
defer s.subscription.mu.Unlock()
|
||||
return s.subscription.calls[last.ID] != nil
|
||||
})
|
||||
return last.ID, ""
|
||||
}
|
||||
return "", last.Text
|
||||
}
|
||||
|
||||
// guardServer is a gateway the run's MCP calls reach.
|
||||
func guardServer(t *testing.T) *Server {
|
||||
s := New()
|
||||
srv := httptest.NewServer(s.Handler())
|
||||
t.Cleanup(srv.Close)
|
||||
t.Cleanup(s.subscription.abortAll) // before srv.Close: a run's MCP call holds a request open
|
||||
t.Setenv("MAGPIE_ADDR", srv.Listener.Addr().String())
|
||||
return s
|
||||
}
|
||||
|
||||
// #4804: auto mode's classifier context grows with every tool batch (the
|
||||
// turns before, prior_turn_context). The interactive run read it only as
|
||||
// it started, so it either started again for each batch, the whole
|
||||
// conversation written to the cache again each time, or went on sending
|
||||
// the classifier the context it started with. Each batch's safeguards now
|
||||
// reach the run's tap through its guard file, and every request of the
|
||||
// one run carries the safeguards its batch was sent with.
|
||||
func TestClaudeTUIToolLoopCarriesEachBatchsSafeguards(t *testing.T) {
|
||||
log := guardClaude(t)
|
||||
s := guardServer(t)
|
||||
conv := rmsg("user", "CALL3 read three files")
|
||||
var sent []string
|
||||
text := ""
|
||||
for n := 0; n <= 3; n++ {
|
||||
g := guardsAt(n, "")
|
||||
sent = append(sent, claudeExtraBody(json.RawMessage(g), ""))
|
||||
var id string
|
||||
id, text = guardTurn(t, s, conv, g)
|
||||
if n == 3 {
|
||||
if id != "" {
|
||||
t.Fatalf("a fourth call after three batches")
|
||||
}
|
||||
break
|
||||
}
|
||||
if id == "" {
|
||||
t.Fatalf("batch %d answered %q, not a call", n, text)
|
||||
}
|
||||
conv += `,{"role":"assistant","content":[{"type":"tool_use","id":"` + id + `","name":"read","input":{}}]}` +
|
||||
`,{"role":"user","content":[{"type":"tool_result","tool_use_id":"` + id + `","content":"file ` + fmt.Sprint(n) + `"}]}`
|
||||
}
|
||||
b, _ := os.ReadFile(log)
|
||||
if starts := strings.Count(string(b), "args "); starts != 1 {
|
||||
t.Fatalf("the tool loop started %d runs, want one:\n%s", starts, b)
|
||||
}
|
||||
if !strings.HasSuffix(text, " done") {
|
||||
t.Fatalf("the turn's end: %q\n%s", text, b)
|
||||
}
|
||||
var got []string
|
||||
for _, l := range strings.Split(string(b), "\n") {
|
||||
if v, ok := strings.CutPrefix(l, "sent "); ok {
|
||||
got = append(got, v)
|
||||
}
|
||||
}
|
||||
if len(got) != len(sent) {
|
||||
t.Fatalf("%d requests, want %d:\n%s", len(got), len(sent), b)
|
||||
}
|
||||
for i := range sent {
|
||||
if got[i] != sent[i] {
|
||||
t.Fatalf("request %d carried\n%s\nwant its batch's\n%s", i, got[i], sent[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A run without the tap (a Claude Code that doesn't load it) can't be
|
||||
// given a batch's safeguards: one whose rules changed is let go, and the
|
||||
// log says why, where it said "process expired" alone and the run's end
|
||||
// read "magpie ended it" (vibbow, #4804).
|
||||
func TestClaudeTUIToolResultsLogWhyTheRunEnded(t *testing.T) {
|
||||
log := guardClaude(t)
|
||||
t.Setenv("FAKE_NO_TAP", "1")
|
||||
logs := keepLog(t)
|
||||
s := guardServer(t)
|
||||
conv := rmsg("user", "CALL3 read three files")
|
||||
id, text := guardTurn(t, s, conv, guardsAt(0, ""))
|
||||
if id == "" {
|
||||
t.Fatalf("answered %q, not a call", text)
|
||||
}
|
||||
conv += `,{"role":"assistant","content":[{"type":"tool_use","id":"` + id + `","name":"read","input":{}}]}` +
|
||||
`,{"role":"user","content":[{"type":"tool_result","tool_use_id":"` + id + `","content":"file"}]}`
|
||||
guardTurn(t, s, conv, guardsAt(1, `"Bash(rm:*)"`))
|
||||
want := "tool results process expired: safeguards changed; restart Claude Code's interactive mode"
|
||||
for deadline := time.Now().Add(5 * time.Second); !strings.Contains(logs.String(), want); time.Sleep(10 * time.Millisecond) {
|
||||
if time.Now().After(deadline) {
|
||||
b, _ := os.ReadFile(log)
|
||||
t.Fatalf("the log doesn't say why the run ended (%q):\n%s\n%s", want, logs, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user