diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 5ec04c083..dbdc4ae81 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -346,8 +346,22 @@ 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 starts a new run told the whole conversation -(`setSafeguards`). Client cache marks are taken too, but not kept: the +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 +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 Code's own prompt caching (no `DISABLE_PROMPT_CACHING`, no client tail) and the reply reports every client mark as dropped diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index e969b472c..724d7c29b 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -1445,6 +1445,51 @@ func claudeExtraBody(raw json.RawMessage, tail string) string { return string(b) } +// safeguardVaries is what Claude Code's classifier context carries that +// changes from one request to the next, the parts 2.1.316 itself names as +// variable and leaves out over its 256KB budget (its "shed" list): the +// turns before (prior_turn_context), system-reminder ids, artifacts, +// Chrome's tabs, where its text came from, and git's status and remotes. +var safeguardVaries = []string{"prior_turn_context", "system_reminders", "artifacts", "text_provenance", "shed"} + +// safeguardsKept is a safety field without the parts that vary +// (safeguardVaries), for telling whether what it says the user allows +// changed: the rules, the permission and auto mode, the folders, the +// repository and branch. A field it can't read is kept whole, so any +// change to it counts. +func safeguardsKept(raw json.RawMessage) []byte { + var guards []map[string]any + if len(raw) == 0 || json.Unmarshal(raw, &guards) != nil { + return raw + } + for _, g := range guards { + ctx, ok := g["classifier_context"].(map[string]any) + if !ok { + continue + } + for _, k := range safeguardVaries { + delete(ctx, k) + } + if nav, ok := ctx["chrome_navigation"].(map[string]any); ok { + delete(nav, "tabs") + } + if git, ok := ctx["git_state"].(map[string]any); ok { + kept := map[string]any{} + for _, k := range []string{"cwd", "root", "branch", "default_branch"} { + if v, ok := git[k]; ok { + kept[k] = v + } + } + ctx["git_state"] = kept + } + } + b, err := json.Marshal(guards) + if err != nil { + return raw + } + return b +} + // setSafeguards updates the caller's safety context and opted-in cache tail. // It does not change the VPS's permission state. // A CLI unable to acknowledge the update is discarded by the caller; its old @@ -1467,7 +1512,18 @@ 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 + // 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. + if bytes.Equal(safeguardsKept(r.safeguards), safeguardsKept(req.Safeguards)) { + return nil + } return errors.New("safeguards changed; restart Claude Code's interactive mode") } err := r.cliControl(map[string]any{"subtype": "apply_flag_settings", "settings": map[string]any{ diff --git a/internal/gateway/claude_tui_extra_body_test.go b/internal/gateway/claude_tui_extra_body_test.go index 845d412f4..d18b26c9c 100644 --- a/internal/gateway/claude_tui_extra_body_test.go +++ b/internal/gateway/claude_tui_extra_body_test.go @@ -78,6 +78,51 @@ func TestClaudeTUISafeguardsInEnv(t *testing.T) { } } +// Claude Code's auto-mode context changes on nearly every request in parts +// of its own: the tool ids of the turns before, git's status, the +// system-reminder ids. A turn whose safeguards differ only there goes on in +// the interactive run; 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 spent a Pro account's 5-hour window (xybio). A change to +// what the user allows (the rules here) still starts a new run. +func TestClaudeTUISafeguardsVaryingPartsKeepTheRun(t *testing.T) { + h := tuiScriptHarness(t, `echo "extra ${CLAUDE_CODE_EXTRA_BODY-unset}" >> $log`) + varied := func(n int, deny string) string { + g := strings.Replace(reviewAsked, `"toolu_01Capture001"`, fmt.Sprintf(`"toolu_01Capture%03d"`, n), 1) + g = strings.Replace(g, `"error":"not_a_repo"}`, fmt.Sprintf(`"error":null,"status":{"clean":false,"counts":{"modified":%d},"porcelain":" M f%d.go","truncated":false},"visibility":null,"truncated":false}`, n, n), 1) + g = strings.Replace(g, `"prior_turn_context":[`, fmt.Sprintf(`"system_reminders":[{"id":"r%d"}],"shed":[],"prior_turn_context":[`, n), 1) + g = strings.Replace(g, `"deny":[]`, `"deny":[`+deny+`]`, 1) + return `"safeguards":` + g + `,` + } + said := []string{"a1"} + for n := 1; n <= 4; n++ { + h.extra = varied(n, "") + h.ask("rules", said...) + said = append(said, fmt.Sprintf("a%d", n+1)) + } + if runs := h.runs(); len(runs) != 1 { + t.Fatalf("4 turns whose safeguards differ only in Claude Code's varying parts started %d runs, want 1", len(runs)) + } + h.extra = varied(5, `"Bash(rm:*)"`) + h.ask("rules", said...) + runs := h.runs() + if len(runs) != 2 { + t.Fatalf("a changed rule went on in %d runs, want a second", len(runs)) + } + seen := false + for _, log := range runs { + if strings.Contains(log, `Bash(rm:*)`) { + seen = true + if !strings.Contains(log, "--resume ") { + t.Fatalf("the new run wasn't given the whole conversation: %s", log) + } + } + } + if !seen { + t.Fatalf("no run has the changed rule: %v", runs) + } +} + // A client's own cache marks are taken with the interactive mode on: its // words are pasted without them (claudetui's userPieces), so Claude Code // keeps its own prompt caching, not turned off for marks it never sends,