claude: a one-off ask's instructions go after Claude Code's system prompt in the interactive mode (#2432)

The interactive mode's helper pastes a run's first message as one text,
without the cache marks renderClaudePrompt puts on it. A one-off ask's
caller instructions were in that message, so Claude Code's auto mode
classifier wrote them to the cache on every check of one conversation:
laozhang713's six checks on one account, no 429, read 1,197 and wrote
83-85k each (#2432; j1374615791-lab saw the same at 125k).

A new interactive run for a one-off ask (no tools, no reply before it,
not lean, no client marks: appendsPrompt) now gets the instructions by
--append-system-prompt-file (append.md, the leanSystem text, the
environment note worded as a lean run's), and its first message holds
the ask alone. Such a run is let go after its reply (ended); it is never
shelved or branched (run.appended), since a session resumed without the
file would have no instructions. Every other run is unchanged.

Run:
- TestClaudeTUIOneOffAskAppendsInstructions and
  TestClaudeAppendOnlyForInteractiveOneOffs (tools, reply, -p) on mote.
  Broken by hand (appendsPrompt returning false): the first goes red.
- mote: gofmt; go vet ./internal/gateway for darwin, linux and windows;
  go test ./internal/gateway -run 'Claude|Lean|TUI|Subscription|Replay|Branch'
  ok (65s), at base a3768cdd1.
- Real Claude Code 2.1.316, interactive, in a sandbox HOME against a
  recording server, two runs with the same appended rules and different
  asks: the two marked system blocks are byte for byte the same, the
  rules at the end of the 110k one; only the unmarked billing line differs.

Not tried: a real account's cache_read on the second classifier ask;
the full internal/gateway package and the full suite (running after the
push); Windows/WSL runs of the bridge.
This commit is contained in:
yetone
2026-11-03 02:08:41 +08:00
parent 2c90922b06
commit eb8b840dd4
4 changed files with 182 additions and 9 deletions
@@ -567,6 +567,23 @@ the conversation alone. Claude Code still sends its billing block and its
identity line, so requests come from the real binary. They no longer carry
Claude Code's prompt, and that is the ban risk the setting names.
A one-off ask in the interactive mode (no tools, no reply before it, not
lean, no client marks: `appendsPrompt`) gets its caller's instructions by
`--append-system-prompt-file` instead (`append.md`, the same `leanSystem`
text), after Claude Code's own prompt, and its first message holds the ask
alone. The helper pastes a first message as one text without marks, so the
instructions pasted there were written to the cache by every ask: Claude
Code's auto mode classifier read 1,197 tokens and wrote 80k on every check
of one conversation (#2432). Appended, they end the system block Claude
Code marks itself, which is the same for every ask under the same
instructions (only the unmarked billing line differs; recorded from Claude
Code 2.1.316 on 2026-11-03). Such a run is let go after its reply
(`ended`) and is never shelved or branched (`run.appended`), since a
session resumed without the file would have no instructions. Every other
run keeps them in the first message. Tested by
`TestClaudeTUIOneOffAskAppendsInstructions` and
`TestClaudeAppendOnlyForInteractiveOneOffs`.
A request with client cache marks (#1717) is never lean: its system marks
are placed in the first message. The mode is part of the run's identity
(`cacheIdentity`, and the tool-results check in `serveSubscription`), so a
+47 -9
View File
@@ -211,10 +211,14 @@ type subscriptionRun struct {
safeguardBeta string
clientMarks bool
lean bool // started with leanSystem as its system prompt
tui bool // Claude Code's interactive mode (claudeTUI)
cacheTail string
cachePrefix cachePrefix
timer *time.Timer
// appended: started with the caller's instructions after Claude
// Code's own system prompt (req.appendPrompt), not in its first
// message; its session, resumed, would have none
appended bool
tui bool // Claude Code's interactive mode (claudeTUI)
cacheTail string
cachePrefix cachePrefix
timer *time.Timer
// Claude Code's input, kept open for the next turn; owner is the account
// it runs as (owned, named once in its life when it started unnamed:
@@ -924,6 +928,9 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
}
args = append(args, "--system-prompt-file", binary.file(systemPath))
}
// set below for a run that appends them: a request asked again
// starts anew, and a transcript replayed has them (replaySession)
req.appendPrompt = false
var sessions []string
switch {
case err != nil:
@@ -990,6 +997,23 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
// message, its earlier turns marked as such (renderClaudePrompt)
log.Printf("claude: a new Claude Code is told the whole conversation: %d messages, %d images, the last turn marked as the one to answer", len(req.Messages), countImages(req.Messages))
}
if from == nil && appendsPrompt(req, binary) {
// a one-off ask in the interactive mode, Claude Code's auto mode
// classifier above all: pasted, the caller's instructions lose
// their cache mark (the paste is one text), and every ask wrote
// them to the cache anew, 80k tokens an ask with 1,197 read
// (#2432). After Claude Code's own system prompt they are in the
// block it marks itself, and the next ask under the same
// instructions reads them; a file of the run's own, as a lean
// run's
appendPath := filepath.Join(tmp, "append.md")
req.appendPrompt = true
if err := os.WriteFile(appendPath, []byte(leanSystem(req)), 0o600); err != nil {
cleanup()
return nil, nil, err
}
args = append(args, "--append-system-prompt-file", binary.file(appendPath))
}
req.clientCache.selected(from == nil)
var prompt []map[string]any
var prefix cachePrefix
@@ -1095,6 +1119,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
run.safeguardBeta = req.SafeguardBeta
run.clientMarks = req.clientCache != nil
run.lean = req.leanPrompt
run.appended = req.appendPrompt
run.tui = tui
run.cachePrefix = prefix
if tuiBody != "" {
@@ -2088,7 +2113,7 @@ func (b *subscriptionBridge) shelve(run *subscriptionRun) {
run.mu.Lock()
sid, sessions, rewound, tools := run.sessionID, run.sessions, run.rewound, maps.Clone(run.tools)
run.mu.Unlock()
if sid == "" || len(sessions) == 0 || rewound || run.idleKey == "" {
if sid == "" || len(sessions) == 0 || rewound || run.idleKey == "" || run.appended {
return
}
key := run.idleKey
@@ -2249,7 +2274,7 @@ func (b *subscriptionBridge) branch(req *Request, owner string) *savedSession {
}
}
sid, sessions := run.sessionID, slices.Clone(run.sessions)
usable := !run.closed && !run.rewound && run.lean == req.leanPrompt && !run.clientMarks && (run.tui || !claudeTUIOn())
usable := !run.closed && !run.rewound && run.lean == req.leanPrompt && !run.appended && !run.clientMarks && (run.tui || !claudeTUIOn())
run.mu.Unlock()
if at == "" {
continue
@@ -3727,8 +3752,9 @@ func (u cliUsage) gateway() Usage {
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:") || envNote(req) != "") {
// a lean run has them as its system prompt (leanSystem), an appending
// one after Claude Code's (appendsPrompt)
if !req.leanPrompt && !req.appendPrompt && (req.System != "" || req.ToolChoice == "required" || strings.HasPrefix(req.ToolChoice, "name:") || envNote(req) != "") {
text.WriteString("<external_system_instructions>\n")
system := withoutBillingHeader(req.System)
pos := 0
@@ -3886,7 +3912,7 @@ func envNote(req *Request) string {
switch {
case req.envElsewhere && req.envInTurns:
return envTurnsNote(req.envDir)
case req.envElsewhere && req.leanPrompt:
case req.envElsewhere && (req.leanPrompt || req.appendPrompt):
return envElsewhereLeanNote
case req.envElsewhere:
return envElsewhereNote
@@ -3906,6 +3932,18 @@ func toolChoiceAsk(req *Request) string {
return ""
}
// appendsPrompt: a new run for req gives the caller's instructions after
// Claude Code's own system prompt (--append-system-prompt-file), not in
// its first message. Only a one-off ask in the interactive mode, which
// pastes its first message without the marks renderClaudePrompt puts on
// it: such a run is let go after its reply (ended), never resumed, so no
// later turn needs the instructions in its session. A lean run has them
// as its system prompt already, and a client's own marks keep theirs.
func appendsPrompt(req *Request, binary claudeCLI) bool {
return !req.leanPrompt && req.clientCache == nil && len(req.Tools) == 0 && !hasReply(req.Messages) &&
withoutBillingHeader(req.System)+envNote(req)+toolChoiceAsk(req) != "" && claudePrintWhy(req, binary) == ""
}
// 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,
+114
View File
@@ -0,0 +1,114 @@
package gateway
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/claudetui"
"github.com/yetone/magpie/internal/testenv"
)
// appendHarness is a script harness whose Claude Code keeps the file it is
// given by --append-system-prompt-file, in Claude Code's interactive mode
// (through a stand-in helper) when tui says so. appended is each run's
// file by the run's log.
func appendHarness(t *testing.T, tui bool) (*resumeHarness, func() map[string]string) {
t.Helper()
kept := t.TempDir()
h := newScriptHarness(t, "ok", `prev=
for a in "$@"; do
if [ "$prev" = "--append-system-prompt-file" ]; then cp "$a" `+kept+`/$$; fi
prev=$a
done`)
if tui {
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 h, func() map[string]string {
out := map[string]string{}
for pid, log := range h.runs() {
b, err := os.ReadFile(filepath.Join(kept, pid))
if err != nil {
out[log] = "<none>"
continue
}
out[log] = string(b)
}
return out
}
}
const classifierRules = "You are a security monitor. Block destructive actions; the rules run long."
// The auto mode classifier's asks, one-off asks under the same long
// instructions, are pasted into the interactive mode as one text, so the
// instructions lost their cache mark and every ask wrote them to the
// cache anew: 80k tokens written and 1,197 read an ask, the same account
// and conversation, no 429 (#2432, laozhang713 and j1374615791-lab). They
// go after Claude Code's own system prompt now, in the block it marks
// itself, and the ask's first message has the action only.
func TestClaudeTUIOneOffAskAppendsInstructions(t *testing.T) {
h, appended := appendHarness(t, true)
for _, action := range []string{"rm -rf build", "git push --force"} {
h.post(`{"model":"claude-sonnet-5","max_tokens":64,"system":"` + classifierRules + `","messages":[{"role":"user","content":"<transcript>` + action + `</transcript>"}]}`)
}
runs := appended()
if len(runs) != 2 {
t.Fatalf("%d runs, want 2: %v", len(runs), runs)
}
for log, file := range runs {
// a test's request comes from another computer: where its tools
// run follows the instructions, as in a lean run's
if !strings.HasPrefix(file, classifierRules+"\n\n") || !strings.HasSuffix(file, strings.TrimSpace(envUnknownNote)) {
t.Errorf("a one-off ask's run was given %q after Claude Code's system prompt, want the caller's instructions\n%s", file, log)
}
if strings.Contains(log, "external_system_instructions") || strings.Contains(log, "security monitor") {
t.Errorf("a one-off ask's first message still has the caller's instructions:\n%s", log)
}
if !strings.Contains(log, "rm -rf build") && !strings.Contains(log, "git push --force") {
t.Errorf("a one-off ask's first message lost the action:\n%s", log)
}
}
}
// A turn of an agent (tools, or a reply before it) keeps its instructions
// in its first message: its run is resumed and branched, and a session
// resumed without the appended file would go on with none. -p takes the
// client's marks, so a -p run is unchanged too.
func TestClaudeAppendOnlyForInteractiveOneOffs(t *testing.T) {
for _, c := range []struct {
name string
tui bool
// told: the instructions are in what the run is typed; a
// conversation's are in the transcript it resumes
told bool
body string
}{
{"tools", true, true, `{"model":"claude-sonnet-5","max_tokens":64,"system":"` + classifierRules + `","tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"hi"}]}`},
{"reply", true, false, `{"model":"claude-sonnet-5","max_tokens":64,"system":"` + classifierRules + `","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"ok"},{"role":"user","content":"again"}]}`},
{"print", false, true, `{"model":"claude-sonnet-5","max_tokens":64,"system":"` + classifierRules + `","messages":[{"role":"user","content":"hi"}]}`},
} {
t.Run(c.name, func(t *testing.T) {
h, appended := appendHarness(t, c.tui)
h.post(c.body)
for log, file := range appended() {
if file != "<none>" {
t.Errorf("given %q after Claude Code's system prompt, want nothing\n%s", file, log)
}
if c.told && !strings.Contains(log, "security monitor") {
t.Errorf("the first message lost the caller's instructions:\n%s", log)
}
}
})
}
}
+4
View File
@@ -178,6 +178,10 @@ type Request struct {
// leanPrompt has the Claude bridge give the caller's instructions as
// the run's system prompt, in place of Claude Code's (ClaudeLeanPrompt).
leanPrompt bool
// appendPrompt: the Claude bridge gives the caller's instructions
// after Claude Code's own system prompt (appendsPrompt), set as the
// run starts.
appendPrompt bool
// envElsewhere: the caller's instructions name a working directory the
// Claude bridge's run is not in (a client on another computer, or in
// Windows with Claude Code in WSL), so the run's own prompt describes