From 8dbdcfc8b3de089f676784153889c802f77e8d0f Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 2 Oct 2026 11:24:05 +0800 Subject: [PATCH] =?UTF-8?q?gateway:=20a=20Claude=20subscription's=20turn?= =?UTF-8?q?=20at=20another=20effort=20goes=20on=20in=20the=20same=20Claude?= =?UTF-8?q?=20Code,=20told=20the=20level,=20and=20reads=20its=20cache=20(#?= =?UTF-8?q?502:=20=E7=BB=8F=E8=BF=87=E6=84=8F=E5=9B=BE=E8=B7=AF=E7=94=B1?= =?UTF-8?q?=E5=88=A4=E6=96=AD=E6=94=B9=E5=8F=98=E4=BA=86=E6=8E=A8=E7=90=86?= =?UTF-8?q?=E5=BC=BA=E5=BA=A6=E5=90=8E=EF=BC=8C=E5=A5=BD=E5=83=8F=E7=BC=93?= =?UTF-8?q?=E5=AD=98=E5=85=A8=E9=83=A8=E8=A6=81=E9=87=8D=E6=96=B0=E5=86=99?= =?UTF-8?q?=E5=85=A5)=20=E2=80=94=20a=20router=20switching=20Opus=205.5=20?= =?UTF-8?q?from=20high=20to=20low=20and=20back=20wrote=20the=20whole=20con?= =?UTF-8?q?versation=20to=20the=20cache=20each=20time=20(427,987=20and=204?= =?UTF-8?q?29,792=20tokens=20written,=2026,107=20read,=20$2.18=20and=20$2.?= =?UTF-8?q?20=20a=20turn)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Claude subscription is served through a Claude Code run that keeps the conversation for its next turn, started with --effort. The run waiting for that turn was found by turnKey, which hashed the effort: a turn the router picked another level for missed it, retire let it go, and a new Claude Code was told the whole conversation in one message, a prefix the cache had never seen (as #463 for a run let go too soon). turnKey now holds only whether an effort was asked for, and resume tells a waiting run a new level before its turn with the control request Claude Code's SDK sends for applyFlagSettings ({"type":"control_request","request":{"subtype":"apply_flag_settings","settings":{"effortLevel":"low"}}}); its control_response is read past like any other line that isn't a stream event. Checked against Claude Code 2.1.287 under a sandbox HOME and a local fake Anthropic endpoint (no real API call): started at --effort low and told high, get_settings answers applied effort "high", and the two upstream requests differ only in output_config.effort (system, tools, thinking {"type":"adaptive"} identical; the history is the same apart from where cache_control sits), which is what lets Claude Code keep its cache across a level change. A run started without an effort and a turn with one (or the reverse) still get separate runs, as --thinking-display is only set with an effort. API-key and Responses upstreams already kept the prefix: withEffort changes only output_config.effort for an adaptive Claude (thinking left as it is) and only reasoning.effort for the Responses API (instructions, tools, input and prompt_cache_key untouched, Codex's instructions not involved), which TestWithEffortKeepsTheCachedPrefix now guards. TestClaudeRunKeptAcrossEffort (a fake claude logging its stdin) fails without the change (a second process for the turn at low) and passes with it: one process, the control request before the second turn, none for a third at the same level. go vet ./internal/..., go build -tags nogui ./... (darwin, GOOS=linux), GOOS=windows go build ./..., go test -tags nogui ./... pass (internal/gui's TestFXInState failed once in the full run and passes alone and with its package; untouched here). --- internal/gateway/claude_subscription.go | 36 ++++++++- internal/gateway/claude_subscription_test.go | 82 ++++++++++++++++++++ internal/gateway/decide_test.go | 30 +++++++ 3 files changed, 145 insertions(+), 3 deletions(-) diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 7842efa15..4df50233a 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -122,6 +122,10 @@ type subscriptionRun struct { idleAt time.Time convKey string + // effort is the level its Claude Code thinks at, as it started (its + // --effort) or was told since (setEffort); "" is Claude Code's own + effort string + // told is the conversation as the client had it in its last request // here (historyKey): tool results are the run's while the client's // conversation goes on from that one. @@ -313,7 +317,7 @@ func (b *subscriptionBridge) start(ctx context.Context, req *Request, model, con return nil, nil, err } - run := &subscriptionRun{bridge: b, token: token, model: model, cmd: cmd, tmp: tmp, pending: map[string]chan mcpToolResult{}, stdin: stdin, owner: owner} + run := &subscriptionRun{bridge: b, token: token, model: model, cmd: cmd, tmp: tmp, pending: map[string]chan mcpToolResult{}, stdin: stdin, owner: owner, effort: req.Effort} // A caller may abandon a turn after receiving tool_use. Do not leave the // parked Claude process and MCP request alive forever. run.timer = time.AfterFunc(30*time.Minute, run.abort) @@ -383,6 +387,17 @@ func (b *subscriptionBridge) resume(req *Request, owner string) (*subscriptionRu run.segment = ch run.mu.Unlock() run.timer.Reset(30 * time.Minute) + // a turn the router picked another effort for (#502) goes on in the + // same Claude Code, told the level first: it asks the next turn at it + // in output_config alone, the conversation it wrote to the cache + // untouched, where a run started anew is told it in one message, a + // prefix the cache has never seen + if req.Effort != run.effort { + if err := run.setEffort(req.Effort); err != nil { + run.abort() + return nil, nil + } + } if _, err := run.stdin.Write(append(line, '\n')); err != nil { run.abort() return nil, nil @@ -390,6 +405,19 @@ func (b *subscriptionBridge) resume(req *Request, owner string) (*subscriptionRu return run, ch } +// setEffort tells the run's Claude Code to think at effort from its next +// turn, as its SDK's applyFlagSettings does: a control request, answered +// with a control_response its output is read past. +func (r *subscriptionRun) setEffort(effort string) error { + line, _ := json.Marshal(map[string]any{"type": "control_request", "request_id": "effort-" + randomToken()[:12], + "request": map[string]any{"subtype": "apply_flag_settings", "settings": map[string]any{"effortLevel": effort}}}) + if _, err := r.stdin.Write(append(line, '\n')); err != nil { + return err + } + r.effort = effort + return nil +} + // retire lets go of the runs left waiting at an earlier point of this // conversation, which a new run now carries on: its turns since went to // another model (switched to and back), so none of them comes back to @@ -522,11 +550,13 @@ func (r *subscriptionRun) park() { // to be found again: whom it runs as, the model, its settings and tools, // and the messages' words, tool calls and results. Whitespace, thinking and // how a reply is split into messages are left out, as clients keep those -// differently. +// differently. Its effort is not in it, only whether it asked for one: a +// run is told another level as its turn starts (setEffort), where one +// started anew would write the whole conversation to the cache again (#502). func turnKey(owner string, req *Request, msgs []Message) string { h := sha256.New() tools, _ := json.Marshal(req.Tools) - fmt.Fprintf(h, "%s\x00%s\x00%s\x00%s\x00%s\x00%s\x00%t", owner, req.Model, req.Effort, req.ToolChoice, req.System, tools, req.WebSearch) + fmt.Fprintf(h, "%s\x00%s\x00%t\x00%s\x00%s\x00%s\x00%t", owner, req.Model, req.Effort != "", req.ToolChoice, req.System, tools, req.WebSearch) hashMessages(h, msgs, nil) return hex.EncodeToString(h.Sum(nil)) } diff --git a/internal/gateway/claude_subscription_test.go b/internal/gateway/claude_subscription_test.go index fdca03a5d..4eb851f86 100644 --- a/internal/gateway/claude_subscription_test.go +++ b/internal/gateway/claude_subscription_test.go @@ -449,3 +449,85 @@ done } } } + +// A conversation's next turn at another effort — the router picked it +// (#502) — goes on in the same Claude Code, told the level by the control +// request its SDK's applyFlagSettings sends, before the turn: a Claude Code +// started anew is told the whole conversation in one message, and wrote all +// of it to the cache again (430k tokens a switch between high and low). +func TestClaudeRunKeptAcrossEffort(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a shell script stands in for Claude Code") + } + dir := t.TempDir() + stdin := filepath.Join(dir, "stdin.log") + script := `#!/bin/sh +echo "args $*" >> ` + stdin + ` +n=0 +while read -r line; do + printf '%s\n' "$line" >> ` + stdin + ` + case "$line" in *control_request*) + echo '{"type":"control_response","response":{"subtype":"success","request_id":"x"}}' + continue;; + esac + n=$((n+1)) + echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-opus-5-5","usage":{"input_tokens":1}}}}' + echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"pid '$$' turn '$n'"}}}' + echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":3}}}' + echo '{"type":"stream_event","event":{"type":"message_stop"}}' + echo '{"type":"result","subtype":"success","is_error":false,"result":""}' +done +` + os.WriteFile(filepath.Join(dir, "claude"), []byte(script), 0o755) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + s := New() + p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}} + ask := func(effort, msgs string) string { + t.Helper() + body := `{"model":"claude-opus-5-5","max_tokens":32000,"thinking":{"type":"adaptive"},"output_config":{"effort":"` + effort + `"},"system":"be brief","tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":` + msgs + `}` + rec := httptest.NewRecorder() + var u Usage + if code, msg := s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, p, "claude-opus-5-5", []byte(body), &u); code != 200 { + t.Fatalf("%d %s", code, msg) + } + var res struct { + Content []struct{ Text string } `json:"content"` + } + json.Unmarshal(rec.Body.Bytes(), &res) + if len(res.Content) == 0 { + t.Fatalf("no answer: %s", rec.Body) + } + return res.Content[0].Text + } + msg := func(role, text string) string { return `{"role":"` + role + `","content":` + strconv.Quote(text) + `}` } + + first := ask("high", `[`+msg("user", "hi")+`]`) + pid, _, _ := strings.Cut(strings.TrimPrefix(first, "pid "), " ") + conv := msg("user", "hi") + `,` + msg("assistant", first) + `,` + msg("user", "and?") + second := ask("low", `[`+conv+`]`) + if second != "pid "+pid+" turn 2" { + t.Fatalf("at another effort: %q, first %q", second, first) + } + third := ask("low", `[`+conv+`,`+msg("assistant", second)+`,`+msg("user", "so?")+`]`) + if third != "pid "+pid+" turn 3" { + t.Fatalf("third: %q", third) + } + b, _ := os.ReadFile(stdin) + lines := strings.Split(strings.TrimSpace(string(b)), "\n") + if len(lines) != 5 || !strings.Contains(lines[0], "--effort high") { + t.Fatalf("Claude Code was told:\n%s", b) + } + var ctl struct { + Type string + Request struct { + Subtype string + Settings map[string]any + } + } + if json.Unmarshal([]byte(lines[2]), &ctl) != nil || ctl.Type != "control_request" || ctl.Request.Subtype != "apply_flag_settings" || ctl.Request.Settings["effortLevel"] != "low" { + t.Fatalf("effort not set before the second turn: %s", lines[2]) + } + if !strings.Contains(lines[3], `"type":"user"`) || !strings.Contains(lines[4], `"type":"user"`) { + t.Fatalf("turns: %s", b) + } +} diff --git a/internal/gateway/decide_test.go b/internal/gateway/decide_test.go index a211558b0..55a25695f 100644 --- a/internal/gateway/decide_test.go +++ b/internal/gateway/decide_test.go @@ -1,6 +1,7 @@ package gateway import ( + "bytes" "cmp" "context" "encoding/json" @@ -380,6 +381,35 @@ func TestWithEffort(t *testing.T) { } } +// A turn at another effort changes nothing of what the vendor caches (#502): +// for Claude thinking adaptively, output_config's effort alone, its thinking +// as it was; for the Responses API, reasoning's effort alone — not the +// instructions, tools, input or prompt_cache_key. +func TestWithEffortKeepsTheCachedPrefix(t *testing.T) { + for _, c := range []struct { + proto provider.Protocol + in string + field string + }{ + {provider.Anthropic, `{"model":"claude-opus-5-5","max_tokens":32000,"thinking":{"type":"adaptive"},"output_config":{"effort":"max"},"system":[{"type":"text","text":"sys","cache_control":{"type":"ephemeral"}}],"tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":[{"type":"text","text":"a & c","cache_control":{"type":"ephemeral"}}]}]}`, "output_config"}, + {provider.Responses, `{"model":"gpt-6-astra","instructions":"sys","prompt_cache_key":"thread","reasoning":{"effort":"xhigh","summary":"auto"},"tools":[{"type":"function","name":"read"}],"input":[{"role":"user","content":"a & c"}]}`, "reasoning"}, + } { + lo, hi := withEffort(c.proto, []byte(c.in), "low"), withEffort(c.proto, []byte(c.in), "high") + var a, b map[string]json.RawMessage + if json.Unmarshal(lo, &a) != nil || json.Unmarshal(hi, &b) != nil { + t.Fatalf("%s: %s / %s", c.proto, lo, hi) + } + for k := range a { + if k != c.field && !bytes.Equal(a[k], b[k]) { + t.Errorf("%s: %s changed with the effort: %s / %s", c.proto, k, a[k], b[k]) + } + } + if bytes.Equal(a[c.field], b[c.field]) { + t.Errorf("%s: effort not changed: %s", c.proto, a[c.field]) + } + } +} + // Jev is told what it said of the conversation's turn before, so that // "go on" keeps that turn's kind and reasoning. func TestJevIsToldTheTurnBefore(t *testing.T) {