gateway: a Claude subscription's turn at another effort goes on in the same Claude Code, told the level, and reads its cache (#502: 经过意图路由判断改变了推理强度后,好像缓存全部要重新写入) — a router switching Opus 5.5 from high to low and back wrote the whole conversation to the cache each time (427,987 and 429,792 tokens written, 26,107 read, $2.18 and $2.20 a turn)

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).
This commit is contained in:
yetone
2026-10-02 11:29:02 +08:00
parent d3308f567f
commit 8dbdcfc8b3
3 changed files with 145 additions and 3 deletions
+33 -3
View File
@@ -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))
}
@@ -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)
}
}
+30
View File
@@ -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 <b> & 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 <b> & 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) {