diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 07b833109..280d498d9 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -594,8 +594,9 @@ fails the request or delays an ordinary request's keepalives. ## The caller's instructions as the system prompt (`claudeLeanPrompt`) Every run is the real Claude Code. By default it keeps Claude Code's own -system prompt, and the caller's instructions go in the run's first user -message inside ``. Settings › Models › +system prompt, and the caller's instructions go after it in the +interactive mode (below), and in the run's first user message inside +`` in `-p` or with client cache marks. Settings › Models › Replies › Short Claude system prompt (`claudeLeanPrompt`, off by default) starts a run with `--system-prompt-file` instead. The file is `system.md` in the run's temp folder, under the distro's mount in WSL (`claudeCLI.file`). @@ -605,22 +606,32 @@ 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 +Every run in the interactive mode (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`. +text), after Claude Code's own prompt, and its first message holds the +conversation alone. The helper pastes a first message as one text without +marks, so instructions pasted there lost the mark `renderClaudePrompt` puts +on their block, and every run started anew wrote them to the cache again: +Claude Code's auto mode classifier read 1,197 tokens and wrote 80k on every +check of one conversation (#2432), and a conversation whose first request +was a one-off ask (no tools, no reply; its run let go after the reply, +`ended`) had its next request's run read 1,273 of 8,565 tokens and write +the rest, the instructions in its replayed transcript where the first run +had them after Claude Code's prompt (m4rs0n on Discord, 11-03). Appended, +they end the system block Claude Code marks itself, which is the same for +every run under the same instructions (only the unmarked billing line +differs; recorded from Claude Code 2.1.316 on 2026-11-03). A session keeps +no system prompt, so a run that resumes one (shelved, branched, or a +replayed transcript, `replaySession`, which then leaves them out of its +user line) is given the file again when the session's run had it +(`savedSession.appended`). The system prompt is part of every run key, so +the file is the one the session's run had. `-p` keeps the instructions in +the first message, where its mark holds. Tested by +`TestClaudeTUIOneOffAskAppendsInstructions`, +`TestClaudeAppendInTheInteractiveMode`, +`TestClaudeTUIConversationKeepsItsInstructionsWhereTheFirstAskHadThem` and +`TestClaudeTUIResumedSessionIsGivenItsInstructions`. 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 diff --git a/internal/gateway/claude_replay.go b/internal/gateway/claude_replay.go index e35344d37..d23f4abf4 100644 --- a/internal/gateway/claude_replay.go +++ b/internal/gateway/claude_replay.go @@ -23,7 +23,9 @@ import ( // The session is two lines, the ones a run started at the reply's turn // would have written: the user's, the conversation before the reply as // renderClaudePrompt tells it (the reply's turn marked as the one to -// answer), and the assistant's, the reply's words. nil when there is no +// answer; the caller's instructions not in it when the run has them after +// Claude Code's system prompt, req.appendPrompt), and the assistant's, the +// reply's words. nil when there is no // such reply (none that calls no tool, or one with no words), or the file // can't be written; the run is then told the conversation whole. func replaySession(dirs []string, work, model string, req *Request) *savedSession { @@ -87,7 +89,7 @@ func replaySession(dirs []string, work, model string, req *Request) *savedSessio return nil } log.Printf("claude: a new Claude Code goes on with the conversation from a transcript of it (%d messages, %d images), typed the last turn's %d", split, countImages(req.Messages[:split]), len(req.Messages)-split) - return &savedSession{session: sid, sessions: dirs, since: req.Messages[split:], tui: true} + return &savedSession{session: sid, sessions: dirs, since: req.Messages[split:], tui: true, appended: req.appendPrompt} } // replyWords is what a reply says, its thinking left out. diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 477d85622..e969b472c 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -213,7 +213,7 @@ type subscriptionRun struct { 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, would have none + // message; its session, resumed, is given them so again appended bool tui bool // Claude Code's interactive mode (claudeTUI) cacheTail string @@ -986,7 +986,7 @@ 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) + // starts anew req.appendPrompt = false var sessions []string switch { @@ -1038,6 +1038,16 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, from.mu.Unlock() } } + // The interactive mode's caller instructions go after Claude Code's own + // system prompt (appendsPrompt), in the block Claude Code marks for the + // cache itself, for every run of a conversation: a session resumed + // (saved, branched or a replayed transcript) has them as its run did, + // the file given again, since a session keeps no system prompt. + if from != nil { + req.appendPrompt = from.appended && !req.leanPrompt && req.clientCache == nil + } else { + req.appendPrompt = appendsPrompt(req, binary) + } req.replayed = false if from == nil && !req.told && sessions != nil && claudePrintWhy(req, binary) == "" { // the interactive mode is given the conversation as Claude Code's @@ -1054,15 +1064,16 @@ 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 + if req.appendPrompt { + // pasted, the caller's instructions lose their cache mark (the + // paste is one text), and every new run wrote them to the cache + // anew: Claude Code's auto mode classifier, 80k tokens an ask with + // 1,197 read (#2432), and a conversation's turn after a one-off + // first one, or after a client changed a reply, 7,290 written and + // 1,273 read of 8,565 (m4rs0n on Discord). After Claude Code's + // own system prompt they are in the block it marks itself, which + // every run under the same instructions sends the same; 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 { @@ -2190,6 +2201,10 @@ type savedSession struct { // tui: the session was made by Claude Code's interactive mode; a // branch of it is too, where it can be (claudePrint) tui bool + // appended: its run had the caller's instructions after Claude Code's + // system prompt (appendsPrompt), which the session doesn't keep: the + // run that resumes it is given them so again + appended bool cachePrefix cachePrefix @@ -2204,11 +2219,11 @@ func (b *subscriptionBridge) shelve(run *subscriptionRun) { run.mu.Lock() sid, sessions, rewound, replied, tools := run.sessionID, run.sessions, run.rewound, run.replied, maps.Clone(run.tools) run.mu.Unlock() - if sid == "" || len(sessions) == 0 || rewound && !replied || run.idleKey == "" || run.appended { + if sid == "" || len(sessions) == 0 || rewound && !replied || run.idleKey == "" { return } key := run.idleKey - s := &savedSession{session: sid, sessions: sessions, owner: run.owned(), conv: run.convKey, key: key, behind: run.behindKey, loose: run.loose, tools: tools, at: run.idleAt, cachePrefix: run.cachePrefix} + s := &savedSession{session: sid, sessions: sessions, owner: run.owned(), conv: run.convKey, key: key, behind: run.behindKey, loose: run.loose, tools: tools, at: run.idleAt, cachePrefix: run.cachePrefix, appended: run.appended} if run.tui { s.behindLine = run.behindLine } else { @@ -2413,7 +2428,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.appended && !run.clientMarks && (run.tui || !claudeTUIOn()) + usable := !run.closed && !run.rewound && run.lean == req.leanPrompt && !run.clientMarks && (run.tui || !claudeTUIOn()) run.mu.Unlock() if at == "" { continue @@ -2424,7 +2439,7 @@ func (b *subscriptionBridge) branch(req *Request, owner string) *savedSession { if !usable || sid == "" || len(sessions) == 0 || said != told { return nil } - return &savedSession{session: sid, sessions: sessions, owner: owner, at: time.Now(), since: msgs[i:], cut: at, tui: run.tui, gone: true} + return &savedSession{session: sid, sessions: sessions, owner: owner, at: time.Now(), since: msgs[i:], cut: at, tui: run.tui, appended: run.appended, gone: true} } return nil } @@ -2446,7 +2461,7 @@ func (r *subscriptionRun) branchAt(at, owner string, since []Message) *savedSess return nil } log.Printf("claude: the conversation's next turn goes on in a branch of its interactive run's session, cut before the side question it answered since") - return &savedSession{session: cut, sessions: sessions, owner: owner, at: time.Now(), since: since, tui: true} + return &savedSession{session: cut, sessions: sessions, owner: owner, at: time.Now(), since: since, tui: true, appended: r.appended} } // cutWait is how long cutSession waits for the line it cuts after to be @@ -4126,13 +4141,17 @@ func toolChoiceAsk(req *Request) string { // 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. +// its first message. Every run in the interactive mode, which pastes its +// first message as one text, without the mark renderClaudePrompt puts on +// the instructions' block: there, a run started anew for the same +// instructions (the next one-off ask, a conversation's turn after a +// one-off first one, a turn whose run was lost) read nothing past Claude +// Code's own prompt. A run resuming a session is given them as the +// session's run was (savedSession.appended). A lean run has them as its +// system prompt already, a client's own marks keep theirs, and -p keeps +// the mark. func appendsPrompt(req *Request, binary claudeCLI) bool { - return !req.leanPrompt && req.clientCache == nil && len(req.Tools) == 0 && !hasReply(req.Messages) && + return !req.leanPrompt && req.clientCache == nil && withoutBillingHeader(req.System)+envNote(req)+toolChoiceAsk(req) != "" && claudePrintWhy(req, binary) == "" } diff --git a/internal/gateway/claude_tui_append_test.go b/internal/gateway/claude_tui_append_test.go index 6e862417a..075c93896 100644 --- a/internal/gateway/claude_tui_append_test.go +++ b/internal/gateway/claude_tui_append_test.go @@ -1,6 +1,7 @@ package gateway import ( + "fmt" "os" "path/filepath" "strings" @@ -81,34 +82,152 @@ func TestClaudeTUIOneOffAskAppendsInstructions(t *testing.T) { } } -// 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) { +// Every interactive run has the caller's instructions after Claude Code's +// system prompt, an agent's turn (tools) and a conversation's (a reply +// before it) too: pasted, they lost their cache mark, and a run started +// anew read nothing past Claude Code's own prompt. -p takes the client's +// marks, and a client that places its own keeps them in the first +// message, so those are unchanged. +func TestClaudeAppendInTheInteractiveMode(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 + name string + tui bool + appended bool + body string + header []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"}]}`}, + {"tools", true, true, `{"model":"claude-sonnet-5","max_tokens":64,"system":"` + classifierRules + `","tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"hi"}]}`, nil}, + {"reply", true, true, `{"model":"claude-sonnet-5","max_tokens":64,"system":"` + classifierRules + `","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":"ok"},{"role":"user","content":"again"}]}`, nil}, + {"client marks", true, false, `{"model":"claude-sonnet-5","max_tokens":64,"system":[{"type":"text","text":"` + classifierRules + `","cache_control":{"type":"ephemeral"}}],"messages":[{"role":"user","content":"hi"}]}`, []string{"X-Magpie-Cache-Marks", "client"}}, + {"print", false, false, `{"model":"claude-sonnet-5","max_tokens":64,"system":"` + classifierRules + `","messages":[{"role":"user","content":"hi"}]}`, nil}, } { 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 != "" { - t.Errorf("given %q after Claude Code's system prompt, want nothing\n%s", file, log) + h.post(c.body, c.header...) + runs := appended() + if len(runs) != 1 { + t.Fatalf("%d runs, want 1: %v", len(runs), runs) + } + for log, file := range runs { + if !c.appended { + if file != "" { + t.Errorf("given %q after Claude Code's system prompt, want nothing\n%s", file, log) + } + if !strings.Contains(log, "security monitor") { + t.Errorf("the first message lost the caller's instructions:\n%s", log) + } + continue } - if c.told && !strings.Contains(log, "security monitor") { - t.Errorf("the first message lost the caller's instructions:\n%s", log) + if !strings.HasPrefix(file, classifierRules+"\n\n") { + t.Errorf("given %q after Claude Code's system prompt, want the caller's instructions\n%s", file, log) + } + if strings.Contains(log, "security monitor") || strings.Contains(log, "external_system_instructions") { + t.Errorf("the run was typed the caller's instructions too:\n%s", log) + } + } + if c.appended { + for _, f := range h.sessionFiles() { + if strings.Contains(f, "security monitor") { + t.Errorf("a session the run resumes holds the caller's instructions, which it has after Claude Code's prompt:\n%s", f) + } } } }) } } + +// sessionFiles is the words of each session file there is. +func (h *resumeHarness) sessionFiles() []string { + files, _ := filepath.Glob(filepath.Join(h.config, "projects", "*", "*.jsonl")) + var out []string + for _, f := range files { + b, _ := os.ReadFile(f) + out = append(out, string(b)) + } + return out +} + +// m4rs0n on Discord, straight to the gateway with one long cached system +// block and no tools: the conversation's first request, sent again as it +// was, read all of it from the cache, but the request after it, the same +// one with the reply and one more user message, read 1,273 of 8,565 and +// wrote the rest, as did every request of a loop that went on from there. +// The first was a one-off ask, its instructions after Claude Code's system +// prompt and its run let go after the reply; the second's run was given +// the conversation as its transcript with the instructions in its first +// message, so what it sent differed from the first's right after Claude +// Code's own prompt. Every run of the conversation is given the same +// system prompt now, the caller's instructions after Claude Code's, and +// none has them in its messages. +func TestClaudeTUIConversationKeepsItsInstructionsWhereTheFirstAskHadThem(t *testing.T) { + h, appended := appendHarness(t, true) + first := `{"role":"user","content":"Say ok."}` + h.post(`{"model":"claude-sonnet-5","max_tokens":16,"system":"` + classifierRules + `","messages":[` + first + `]}`) + h.post(`{"model":"claude-sonnet-5","max_tokens":16,"system":"` + classifierRules + `","messages":[` + first + `,{"role":"assistant","content":"ok"},{"role":"user","content":"Now say two words."}]}`) + runs := appended() + if len(runs) != 2 { + t.Fatalf("%d runs, want 2: %v", len(runs), runs) + } + var files []string + for log, file := range runs { + files = append(files, file) + if strings.Contains(log, "security monitor") || strings.Contains(log, "external_system_instructions") { + t.Errorf("a run was typed the caller's instructions, which the conversation's first run had after Claude Code's prompt:\n%s", log) + } + } + if files[0] != files[1] || !strings.HasPrefix(files[0], classifierRules+"\n\n") { + t.Errorf("the conversation's runs were given %q and %q after Claude Code's system prompt, want the same instructions", files[0], files[1]) + } + for _, f := range h.sessionFiles() { + if strings.Contains(f, "security monitor") { + t.Errorf("the transcript the second run goes on from holds the caller's instructions:\n%s", f) + } + } +} + +// A conversation's saved session, resumed past idleMost, is given the +// caller's instructions after Claude Code's system prompt as its run had +// them: the session keeps no system prompt, and before, a run that had +// them so was never shelved, so its next turn was a new run that wrote +// the whole conversation to the cache again. +func TestClaudeTUIResumedSessionIsGivenItsInstructions(t *testing.T) { + h, appended := appendHarness(t, true) + h.ask("rules A", "a1") + var sidA string + for pid := range h.runs() { + sidA = "s" + pid + } + for i := range idleMost { + h.ask(fmt.Sprintf("rules %d", i), "x") + } + eventually(t, "A's run still going", func() bool { return len(h.s.subscription.idle) == idleMost }) + before := h.runs() + h.ask("rules A", "a1", "a2") + for log, file := range appended() { + if _, ok := before[logPID(h, log)]; ok { + continue + } + if !strings.Contains(log, "--resume "+sidA) { + t.Fatalf("A's next turn did not resume its session:\n%s", log) + } + if !strings.HasPrefix(file, "rules A\n\n") { + t.Errorf("the resumed run was given %q after Claude Code's system prompt, want A's instructions\n%s", file, log) + } + told := log[strings.Index(log, "\ntold "):] + if !strings.Contains(told, "a2") || strings.Contains(told, "a1") || strings.Contains(told, "rules A") { + t.Fatalf("the resumed run was told more than the turn:\n%s", told) + } + return + } + t.Fatal("A's next turn started no run") +} + +// logPID is the run whose log is log. +func logPID(h *resumeHarness, log string) string { + for pid, l := range h.runs() { + if l == log { + return pid + } + } + return "" +} diff --git a/internal/gateway/claude_tui_replay_test.go b/internal/gateway/claude_tui_replay_test.go index 9d60ba533..5fde47aab 100644 --- a/internal/gateway/claude_tui_replay_test.go +++ b/internal/gateway/claude_tui_replay_test.go @@ -82,9 +82,15 @@ func TestClaudeTUIReplayGoesInATranscript(t *testing.T) { t.Fatalf("the transcript:\n%s", b) } user, _ := json.Marshal(lines[0].Message.Content) - if !strings.Contains(string(user), `"data":"`+img+`"`) || !strings.Contains(string(user), "what is it") || !strings.Contains(string(user), "rules") || strings.Contains(string(user), "cache_control") { + if !strings.Contains(string(user), `"data":"`+img+`"`) || !strings.Contains(string(user), "what is it") || strings.Contains(string(user), "rules") || strings.Contains(string(user), "cache_control") { t.Fatalf("the transcript's user line: %s", user) } + // the caller's instructions are after Claude Code's system prompt, as + // a first run of the conversation had them (appendsPrompt), not in the + // transcript's user line + if !strings.Contains(args, "--append-system-prompt-file") { + t.Fatalf("the run wasn't given the caller's instructions after Claude Code's prompt: %s", args) + } reply, _ := json.Marshal(lines[1].Message.Content) if string(reply) != `[{"text":"a red square","type":"text"}]` { t.Fatalf("the transcript's reply: %s", reply)