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) {