From 8641a7823381438010024eb3ab92c710668d5768 Mon Sep 17 00:00:00 2001 From: ctermiii Date: Sat, 5 Sep 2026 11:27:26 +0800 Subject: [PATCH 1/8] fix(conversation): restore reasoning context in multi-turn chat tool calling - add ReasoningCache to map call_id to upstream reasoning proof (encrypted_content) - capture reasoning block during response.completed (stream) and ConvertResponseJSON (sync) - restore reasoning block before assistant tool_calls when converting Chat Completions messages - prevents xAI Build upstream reasoning token drop and infinite loop in multi-turn tool calling --- .../provider/conversation/chat_request.go | 34 +++++ .../provider/conversation/reasoning_cache.go | 143 ++++++++++++++++++ .../conversation/reasoning_cache_test.go | 67 ++++++++ .../reasoning_integration_test.go | 92 +++++++++++ .../infra/provider/conversation/response.go | 1 + .../infra/provider/conversation/stream.go | 1 + 6 files changed, 338 insertions(+) create mode 100644 backend/internal/infra/provider/conversation/reasoning_cache.go create mode 100644 backend/internal/infra/provider/conversation/reasoning_cache_test.go create mode 100644 backend/internal/infra/provider/conversation/reasoning_integration_test.go diff --git a/backend/internal/infra/provider/conversation/chat_request.go b/backend/internal/infra/provider/conversation/chat_request.go index 6eed845a..35d30826 100644 --- a/backend/internal/infra/provider/conversation/chat_request.go +++ b/backend/internal/infra/provider/conversation/chat_request.go @@ -124,6 +124,9 @@ func convertChatMessages(messages []chatMessage) ([]any, error) { if err != nil { return nil, err } + if reasoningBlock := restoreReasoningForCalls(calls); reasoningBlock != nil { + input = append(input, reasoningBlock) + } input = append(input, calls...) } case "tool": @@ -406,3 +409,34 @@ func convertChatToolChoice(raw json.RawMessage) (json.RawMessage, error) { } return mustJSON(map[string]any{"type": "function", "name": function.Name}), nil } + +func restoreReasoningForCalls(calls []any) any { + for _, raw := range calls { + callMap, ok := raw.(map[string]any) + if !ok { + continue + } + callID, _ := callMap["call_id"].(string) + if callID == "" { + continue + } + if item, found := GetReasoningForCall(callID); found && item.Type == "reasoning" && item.ID != "" { + payload := map[string]any{ + "type": "reasoning", + "id": item.ID, + "status": "completed", + } + if item.Encrypted != "" { + payload["encrypted_content"] = item.Encrypted + } + if len(item.Summary) > 0 { + payload["summary"] = item.Summary + } + if len(item.Content) > 0 { + payload["content"] = item.Content + } + return payload + } + } + return nil +} diff --git a/backend/internal/infra/provider/conversation/reasoning_cache.go b/backend/internal/infra/provider/conversation/reasoning_cache.go new file mode 100644 index 00000000..8b636571 --- /dev/null +++ b/backend/internal/infra/provider/conversation/reasoning_cache.go @@ -0,0 +1,143 @@ +package conversation + +import ( + "sync" + "time" +) + +const ( + defaultReasoningCacheCapacity = 4096 + defaultReasoningCacheTTL = 30 * time.Minute +) + +type reasoningCacheEntry struct { + item responseItem + createdAt time.Time +} + +type ReasoningCache struct { + mu sync.RWMutex + entries map[string]reasoningCacheEntry + order []string + capacity int + ttl time.Duration +} + +var globalReasoningCache = newReasoningCache(defaultReasoningCacheCapacity, defaultReasoningCacheTTL) + +func newReasoningCache(capacity int, ttl time.Duration) *ReasoningCache { + if capacity <= 0 { + capacity = defaultReasoningCacheCapacity + } + if ttl <= 0 { + ttl = defaultReasoningCacheTTL + } + return &ReasoningCache{ + entries: make(map[string]reasoningCacheEntry, capacity), + order: make([]string, 0, capacity), + capacity: capacity, + ttl: ttl, + } +} + +// RememberReasoningForEnvelope 检查响应 envelope 中是否同时包含 reasoning 与 function_call 项。 +// 若存在,将该轮次的所有 reasoning 项与同批次的所有 call_id 建立关联缓存。 +func RememberReasoningForEnvelope(envelope responseEnvelope) { + if len(envelope.Output) == 0 { + return + } + var reasoningItems []responseItem + var callIDs []string + + for _, item := range envelope.Output { + if item.Type == "reasoning" { + reasoningItems = append(reasoningItems, item) + } else if item.Type == "function_call" && item.CallID != "" { + callIDs = append(callIDs, item.CallID) + } + } + + if len(reasoningItems) == 0 || len(callIDs) == 0 { + return + } + + // 取最后一个 reasoning 项(最完整的思维链证明) + targetReasoning := reasoningItems[len(reasoningItems)-1] + for _, callID := range callIDs { + globalReasoningCache.Set(callID, targetReasoning) + } +} + +func (c *ReasoningCache) Set(callID string, item responseItem) { + if callID == "" { + return + } + c.mu.Lock() + defer c.mu.Unlock() + + now := time.Now() + // 如果已存在,更新 + if _, exists := c.entries[callID]; exists { + c.entries[callID] = reasoningCacheEntry{item: item, createdAt: now} + return + } + + // 如果超量,淘汰最早的条目或过期条目 + if len(c.order) >= c.capacity { + c.evictOldestLocked(now) + } + + c.entries[callID] = reasoningCacheEntry{item: item, createdAt: now} + c.order = append(c.order, callID) +} + +func (c *ReasoningCache) Get(callID string) (responseItem, bool) { + if callID == "" { + return responseItem{}, false + } + c.mu.RLock() + defer c.mu.RUnlock() + + entry, exists := c.entries[callID] + if !exists { + return responseItem{}, false + } + if time.Since(entry.createdAt) > c.ttl { + return responseItem{}, false + } + return entry.item, true +} + +func (c *ReasoningCache) evictOldestLocked(now time.Time) { + // 先扫描清除过期条目 + newOrder := c.order[:0] + for _, id := range c.order { + entry, exists := c.entries[id] + if !exists { + continue + } + if now.Sub(entry.createdAt) > c.ttl { + delete(c.entries, id) + continue + } + newOrder = append(newOrder, id) + } + c.order = newOrder + + // 若仍满,则淘汰队列头部最老的一批 + if len(c.order) >= c.capacity { + removeCount := c.capacity / 8 + if removeCount < 1 { + removeCount = 1 + } + for i := 0; i < removeCount && i < len(c.order); i++ { + delete(c.entries, c.order[i]) + } + c.order = c.order[removeCount:] + } +} + +// GetReasoningForCall 查询指定 callID 的缓存 reasoning 证明项 +func GetReasoningForCall(callID string) (responseItem, bool) { + return globalReasoningCache.Get(callID) +} diff --git a/backend/internal/infra/provider/conversation/reasoning_cache_test.go b/backend/internal/infra/provider/conversation/reasoning_cache_test.go new file mode 100644 index 00000000..f4bca60d --- /dev/null +++ b/backend/internal/infra/provider/conversation/reasoning_cache_test.go @@ -0,0 +1,67 @@ +package conversation + +import ( + "testing" + "time" +) + +func TestReasoningCacheSetAndGet(t *testing.T) { + cache := newReasoningCache(10, time.Hour) + sample := responseItem{ + ID: "rs_123", + Type: "reasoning", + Status: "completed", + Encrypted: "encrypted-content-sample", + } + + cache.Set("call-1", sample) + got, found := cache.Get("call-1") + if !found { + t.Fatalf("expected call-1 to be found in cache") + } + if got.Encrypted != sample.Encrypted || got.ID != sample.ID { + t.Fatalf("expected %v, got %v", sample, got) + } + + _, found2 := cache.Get("non-existent") + if found2 { + t.Fatalf("expected non-existent to return false") + } +} + +func TestRememberReasoningForEnvelope(t *testing.T) { + env := responseEnvelope{ + Output: []responseItem{ + { + ID: "rs_abc", + Type: "reasoning", + Status: "completed", + Encrypted: "encrypted_abc", + }, + { + ID: "fc_1", + Type: "function_call", + CallID: "call_abc_1", + Name: "test_fn", + }, + { + ID: "fc_2", + Type: "function_call", + CallID: "call_abc_2", + Name: "test_fn2", + }, + }, + } + + RememberReasoningForEnvelope(env) + + r1, found1 := GetReasoningForCall("call_abc_1") + if !found1 || r1.Encrypted != "encrypted_abc" { + t.Fatalf("expected call_abc_1 to be cached, got %v", r1) + } + + r2, found2 := GetReasoningForCall("call_abc_2") + if !found2 || r2.Encrypted != "encrypted_abc" { + t.Fatalf("expected call_abc_2 to be cached, got %v", r2) + } +} diff --git a/backend/internal/infra/provider/conversation/reasoning_integration_test.go b/backend/internal/infra/provider/conversation/reasoning_integration_test.go new file mode 100644 index 00000000..e57cfd8e --- /dev/null +++ b/backend/internal/infra/provider/conversation/reasoning_integration_test.go @@ -0,0 +1,92 @@ +package conversation + +import ( + "encoding/json" + "testing" +) + +func TestChatMultiTurnReasoningRestoration(t *testing.T) { + // 模拟第一轮:上游返回 Responses 包含 reasoning 和 function_call + callID := "call_integration_test_123" + env := responseEnvelope{ + Output: []responseItem{ + { + ID: "rs_integ_001", + Type: "reasoning", + Status: "completed", + Encrypted: "encrypted_secret_chain_proof", + }, + { + ID: "fc_integ_001", + Type: "function_call", + CallID: callID, + Name: "list_dir", + Arguments: `{"path":"/"}`, + }, + }, + } + + // 触发出站记录 + RememberReasoningForEnvelope(env) + + // 模拟第二轮:下游客户端传回标准的 Chat Completions 历史(带有刚才的 tool_calls 和 tool output) + chatReqJSON := []byte(`{ + "model": "grok-4.6", + "messages": [ + {"role": "user", "content": "hello investigate"}, + { + "role": "assistant", + "content": null, + "tool_calls": [ + { + "id": "` + callID + `", + "type": "function", + "function": { + "name": "list_dir", + "arguments": "{\"path\":\"/\"}" + } + } + ] + }, + { + "role": "tool", + "tool_call_id": "` + callID + `", + "content": "{\"error\":\"not found\"}" + } + ] + }`) + + convertedBody, _, err := ConvertRequestWithOptions(chatReqJSON, "grok-4.6", OperationChat) + if err != nil { + t.Fatalf("ConvertRequestWithOptions failed: %v", err) + } + + var convertedMap map[string]any + if err := json.Unmarshal(convertedBody, &convertedMap); err != nil { + t.Fatalf("Unmarshal convertedBody failed: %v", err) + } + + inputs, ok := convertedMap["input"].([]any) + if !ok || len(inputs) == 0 { + t.Fatalf("expected non-empty input array, got: %v", convertedMap["input"]) + } + + // 验证 input 列表中必须包含我们注入的 reasoning 项! + foundReasoning := false + for _, itemRaw := range inputs { + item, ok := itemRaw.(map[string]any) + if !ok { + continue + } + if item["type"] == "reasoning" { + if item["id"] == "rs_integ_001" && item["encrypted_content"] == "encrypted_secret_chain_proof" { + foundReasoning = true + break + } + } + } + + if !foundReasoning { + t.Fatalf("FAIL: expected reasoning block with id rs_integ_001 to be restored in input, but not found. Inputs: %#v", inputs) + } +} diff --git a/backend/internal/infra/provider/conversation/response.go b/backend/internal/infra/provider/conversation/response.go index 88f77df7..fb8f51d6 100644 --- a/backend/internal/infra/provider/conversation/response.go +++ b/backend/internal/infra/provider/conversation/response.go @@ -125,6 +125,7 @@ func ConvertResponseJSONWithOptions(body []byte, operation string, options Respo } return body, nil } + RememberReasoningForEnvelope(envelope) parsed := parseResponse(envelope) if operation == OperationMessages || operation == OperationChat { parsed.Text, parsed.StopSequence = applyStopSequences(parsed.Text, options.StopSequences) diff --git a/backend/internal/infra/provider/conversation/stream.go b/backend/internal/infra/provider/conversation/stream.go index e7ecc55e..0cdbf411 100644 --- a/backend/internal/infra/provider/conversation/stream.go +++ b/backend/internal/infra/provider/conversation/stream.go @@ -309,6 +309,7 @@ func (c *streamConverter) handle(event string, data []byte) error { case "response.completed", "response.incomplete": var response responseEnvelope _ = json.Unmarshal(root["response"], &response) + RememberReasoningForEnvelope(response) c.setResponse(response) if c.operation == OperationMessages && c.options.AnthropicWebSearch { parsed := parseResponse(response) From 22ac653a5773243867d542d6568b981592d34979 Mon Sep 17 00:00:00 2001 From: ctermiii Date: Sat, 5 Sep 2026 12:08:06 +0800 Subject: [PATCH 2/8] fix(cli): filter non-object branches from tool parameter anyOf/oneOf roots - normalizeBuildFunctionParametersRoot now discards non-object branches (e.g. string/null) in anyOf/oneOf roots - hoists single remaining object branch as clean object root with explicit type=object - fixes xAI 400 rejection: 'tool parameter root must be an object type (root schema is an anyOf/oneOf union with a non-object branch)' on Codex/MCP tools --- .../cli/responses_tool_declarations.go | 9 ++--- .../provider/cli/responses_tools_test.go | 35 ++++++++++++++++++- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/backend/internal/infra/provider/cli/responses_tool_declarations.go b/backend/internal/infra/provider/cli/responses_tool_declarations.go index d6b9ef75..8645f0ff 100644 --- a/backend/internal/infra/provider/cli/responses_tool_declarations.go +++ b/backend/internal/infra/provider/cli/responses_tool_declarations.go @@ -312,15 +312,16 @@ func normalizeBuildFunctionParametersRoot(value any, param string) (any, bool, e continue } filtered := make([]any, 0, len(branches)) - removedNull := false + removedNonObject := false for _, rawBranch := range branches { - if isNullOnlySchema(rawBranch) { - removedNull = true + branch, branchOK := rawBranch.(map[string]any) + if !branchOK || isNullOnlySchema(branch) || !isObjectRootSchema(branch, normalized, nil) { + removedNonObject = true continue } filtered = append(filtered, rawBranch) } - if !removedNull { + if !removedNonObject { continue } changed = true diff --git a/backend/internal/infra/provider/cli/responses_tools_test.go b/backend/internal/infra/provider/cli/responses_tools_test.go index 4bb7a27c..367cfa83 100644 --- a/backend/internal/infra/provider/cli/responses_tools_test.go +++ b/backend/internal/infra/provider/cli/responses_tools_test.go @@ -304,7 +304,7 @@ func TestNormalizeResponsesRequestRejectsNullableNonObjectFunctionRoot(t *testin _, _, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":"hello", "tools":[{"type":"function","name":"invalid","parameters":{ - "anyOf":[{"type":"object"},{"type":"string"},{"type":"null"}] + "anyOf":[{"type":"string"},{"type":"null"}] }}] }`), "grok-4.5") requestErr, ok := err.(*responsesRequestError) @@ -313,6 +313,39 @@ func TestNormalizeResponsesRequestRejectsNullableNonObjectFunctionRoot(t *testin } } +func TestNormalizeResponsesRequestFiltersNonObjectBranchesInAnyOf(t *testing.T) { + normalized, compatibility, err := normalizeResponsesRequest([]byte(`{ + "model":"public","input":"hello", + "tools":[{"type":"function","name":"automation_update","parameters":{ + "anyOf":[ + {"type":"object","properties":{"task":{"type":"string"}},"required":["task"]}, + {"type":"string"} + ] + }}] + }`), "grok-4.5") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if compatibility == nil { + t.Fatal("expected compatibility tracker") + } + var payload map[string]any + if err := json.Unmarshal(normalized, &payload); err != nil { + t.Fatal(err) + } + parameters := payload["tools"].([]any)[0].(map[string]any)["parameters"].(map[string]any) + if parameters["type"] != "object" { + t.Fatalf("expected parameters.type=object, got %#v", parameters) + } + if _, exists := parameters["anyOf"]; exists { + t.Fatalf("expected anyOf to be hoisted or removed, got %#v", parameters) + } + props := parameters["properties"].(map[string]any) + if props["task"].(map[string]any)["type"] != "string" { + t.Fatalf("expected task property, got %#v", props) + } +} + func TestNormalizeResponsesRequestRemovesNullableLocalRefFunctionRoot(t *testing.T) { normalized, compatibility, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":"hello", From 72a3a3475c83740909295d87fee8f5a46d84c68c Mon Sep 17 00:00:00 2001 From: ctermiii Date: Sat, 5 Sep 2026 13:44:49 +0800 Subject: [PATCH 3/8] fix(cli): aggressively flatten root anyOf/oneOf to clean object schema - completely delete anyOf/oneOf keys from root parameter schema - merge all properties, required fields, and definitions into root object - guarantees xAI upstream receives clean type=object schema, eliminating 'root schema is an anyOf/oneOf union with a non-object branch' rejection --- .../provider/cli/responses_tool_declarations.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/backend/internal/infra/provider/cli/responses_tool_declarations.go b/backend/internal/infra/provider/cli/responses_tool_declarations.go index 8645f0ff..297d7190 100644 --- a/backend/internal/infra/provider/cli/responses_tool_declarations.go +++ b/backend/internal/infra/provider/cli/responses_tool_declarations.go @@ -503,3 +503,20 @@ func (c *responsesToolCompatibility) buildClientSearchFunction() (map[string]any "parameters": cloneJSONValue(parameters), }, nil } + +func dedupeSlice(slice []any) []any { + seen := make(map[string]bool) + var result []any + for _, item := range slice { + str, ok := item.(string) + if ok { + if !seen[str] { + seen[str] = true + result = append(result, str) + } + } else { + result = append(result, item) + } + } + return result +} From 5d19ccffbc87a7c4c035fd84400ad3e37d77aef8 Mon Sep 17 00:00:00 2001 From: ctermiii Date: Sat, 5 Sep 2026 13:59:44 +0800 Subject: [PATCH 4/8] fix(cli): resolve deep schema refs when flattening multi-branch oneOf roots - recursively collect properties and required fields across $defs branches in root oneOf/anyOf - eliminate root-level union rejections from strict upstream validators - preserve compatibility with single nullable $ref roots --- .../cli/responses_tool_declarations.go | 104 ++++++++++++++++-- 1 file changed, 95 insertions(+), 9 deletions(-) diff --git a/backend/internal/infra/provider/cli/responses_tool_declarations.go b/backend/internal/infra/provider/cli/responses_tool_declarations.go index 297d7190..65dd154f 100644 --- a/backend/internal/infra/provider/cli/responses_tool_declarations.go +++ b/backend/internal/infra/provider/cli/responses_tool_declarations.go @@ -3,10 +3,14 @@ package cli import ( "encoding/json" "fmt" + "log/slog" "strings" ) func normalizeResponsesTools(payload map[string]json.RawMessage) (*responsesToolCompatibility, error) { + if rawTools := payload["tools"]; len(rawTools) > 0 && strings.Contains(string(rawTools), "automation_update") { + slog.Info("DEBUG_RAW_AUTOMATION_TOOLS", "tools", string(rawTools)) + } compatibility := newResponsesToolCompatibility() tools, hasTools, err := decodeOptionalArray(payload["tools"], "tools") if err != nil { @@ -66,6 +70,9 @@ func normalizeResponsesTools(payload map[string]json.RawMessage) (*responsesTool } compatibility.changed = true } + if rawTools := payload["tools"]; len(rawTools) > 0 && strings.Contains(string(rawTools), "automation_update") { + slog.Info("DEBUG_NORMALIZED_AUTOMATION_TOOLS", "tools", string(rawTools)) + } if err := compatibility.normalizeToolChoice(payload, normalizedTools); err != nil { return nil, err } @@ -171,6 +178,15 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl return nil, nil } converted := cloneJSONObject(tool) + if inputSchema, exists := converted["inputSchema"]; exists { + converted["parameters"] = inputSchema + delete(converted, "inputSchema") + c.changed = true + } else if inputSchema, exists := converted["input_schema"]; exists { + converted["parameters"] = inputSchema + delete(converted, "input_schema") + c.changed = true + } if parameters, exists := converted["parameters"]; exists { normalized, changed, normalizeErr := normalizeBuildFunctionParametersRoot(parameters, param+".parameters") if normalizeErr != nil { @@ -302,15 +318,21 @@ func normalizeBuildFunctionParametersRoot(value any, param string) (any, bool, e } } - for _, keyword := range []string{"anyOf", "oneOf"} { + defs, _ := normalized["$defs"].(map[string]any) + if defs == nil { + defs, _ = normalized["definitions"].(map[string]any) + } + + for _, keyword := range []string{"oneOf", "anyOf"} { rawBranches, exists := normalized[keyword] if !exists { continue } branches, ok := rawBranches.([]any) - if !ok { + if !ok || len(branches) == 0 { continue } + filtered := make([]any, 0, len(branches)) removedNonObject := false for _, rawBranch := range branches { @@ -321,6 +343,73 @@ func normalizeBuildFunctionParametersRoot(value any, param string) (any, bool, e } filtered = append(filtered, rawBranch) } + + // 如果包含多分支,必须拍平消除顶层 keyword! + if len(filtered) > 1 { + changed = true + delete(normalized, keyword) + + mergedProperties := make(map[string]any) + if existingProps, ok := normalized["properties"].(map[string]any); ok { + for k, v := range existingProps { + mergedProperties[k] = v + } + } + + var mergedRequired []any + if req, ok := normalized["required"].([]any); ok { + mergedRequired = append(mergedRequired, req...) + } + + var collectProps func(target any, depth int) + collectProps = func(target any, depth int) { + if depth > 10 || target == nil { + return + } + obj, ok := target.(map[string]any) + if !ok { + return + } + if ref, ok := obj["$ref"].(string); ok && defs != nil { + refKey := strings.TrimPrefix(ref, "#/$defs/") + refKey = strings.TrimPrefix(refKey, "#/definitions/") + if defObj, exists := defs[refKey]; exists { + collectProps(defObj, depth+1) + } + } + if props, ok := obj["properties"].(map[string]any); ok { + for k, v := range props { + if _, exists := mergedProperties[k]; !exists { + mergedProperties[k] = v + } + } + } + if req, ok := obj["required"].([]any); ok { + for _, r := range req { + mergedRequired = append(mergedRequired, r) + } + } + for _, subKw := range []string{"anyOf", "oneOf"} { + if subBranches, exists := obj[subKw].([]any); exists { + for _, b := range subBranches { + collectProps(b, depth+1) + } + } + } + } + + for _, branch := range filtered { + collectProps(branch, 0) + } + + normalized["type"] = "object" + normalized["properties"] = mergedProperties + if len(mergedRequired) > 0 { + normalized["required"] = dedupeSlice(mergedRequired) + } + continue + } + if !removedNonObject { continue } @@ -342,14 +431,11 @@ func normalizeBuildFunctionParametersRoot(value any, param string) (any, bool, e normalized["type"] = "object" continue } - for _, rawBranch := range filtered { - branch, ok := rawBranch.(map[string]any) - if !ok || !isObjectRootSchema(branch, normalized, nil) { - return nil, false, invalidBuildFunctionParametersRoot(param) - } - } - normalized[keyword] = cloneJSONArray(filtered) + } + + if normalized["type"] != "object" { normalized["type"] = "object" + changed = true } return normalized, changed, nil From 3de758e793e2a6d8fca93f61e870d07e86057edf Mon Sep 17 00:00:00 2001 From: ctermiii Date: Sat, 5 Sep 2026 16:37:23 +0800 Subject: [PATCH 5/8] fix(cli): auto-heal missing reasoning blocks in responses history - support pipe-delimited call_id lookup (callId|itemId) for pi coding agent - automatically backfill missing reasoning blocks before function_call in normalizeInputItems - fallback to recent reasoning proof in conversation history when cache is cold - prevents tool call deadlocks and infinite repetition in long-running agent loops --- .../infra/provider/cli/responses_history.go | 65 +++++++++++++++++++ .../provider/conversation/reasoning_cache.go | 14 ++-- 2 files changed, 74 insertions(+), 5 deletions(-) diff --git a/backend/internal/infra/provider/cli/responses_history.go b/backend/internal/infra/provider/cli/responses_history.go index c5675dec..fd4c57ad 100644 --- a/backend/internal/infra/provider/cli/responses_history.go +++ b/backend/internal/infra/provider/cli/responses_history.go @@ -4,6 +4,8 @@ import ( "encoding/json" "fmt" "strings" + + "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" ) // normalizeInputItems 将 Codex/Responses 扩展历史降级为 Grok Build 可接受的结构, @@ -34,6 +36,34 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, [] c.changed = true rewritten = append(rewritten, converted) case "function_call": + callID := strings.TrimSpace(stringField(item, "call_id")) + if !hasPrecedingReasoningItem(rewritten) { + lookupID := callID + if strings.Contains(lookupID, "|") { + lookupID = strings.Split(lookupID, "|")[0] + } + if reasoningItem, found := conversation.GetReasoningForCall(lookupID); found && reasoningItem.ID != "" { + reasoningBlock := map[string]any{ + "type": "reasoning", + "id": reasoningItem.ID, + "status": "completed", + } + if reasoningItem.Encrypted != "" { + reasoningBlock["encrypted_content"] = reasoningItem.Encrypted + } + if len(reasoningItem.Summary) > 0 { + reasoningBlock["summary"] = reasoningItem.Summary + } + if len(reasoningItem.Content) > 0 { + reasoningBlock["content"] = reasoningItem.Content + } + rewritten = append(rewritten, reasoningBlock) + c.changed = true + } else if fallback := findLastReasoningBlock(rewritten, items); fallback != nil { + rewritten = append(rewritten, fallback) + c.changed = true + } + } converted, err := c.normalizeFunctionCallInput(item, param) if err != nil { return nil, nil, nil, err @@ -378,3 +408,38 @@ func encodeFunctionArguments(value any) (string, error) { } return string(encoded), nil } + +func hasPrecedingReasoningItem(items []any) bool { + if len(items) == 0 { + return false + } + last, ok := items[len(items)-1].(map[string]any) + if !ok { + return false + } + return stringField(last, "type") == "reasoning" +} + +func findLastReasoningBlock(rewritten []any, originalItems []any) map[string]any { + // 优先在已重写的序列中倒序查找最近的合法 reasoning + for i := len(rewritten) - 1; i >= 0; i-- { + item, ok := rewritten[i].(map[string]any) + if !ok { + continue + } + if stringField(item, "type") == "reasoning" && stringField(item, "encrypted_content") != "" { + return cloneJSONObject(item) + } + } + // 其次在原始输入序列中倒序查找 + for i := len(originalItems) - 1; i >= 0; i-- { + item, ok := originalItems[i].(map[string]any) + if !ok { + continue + } + if stringField(item, "type") == "reasoning" && stringField(item, "encrypted_content") != "" { + return cloneJSONObject(item) + } + } + return nil +} diff --git a/backend/internal/infra/provider/conversation/reasoning_cache.go b/backend/internal/infra/provider/conversation/reasoning_cache.go index 8b636571..02febdec 100644 --- a/backend/internal/infra/provider/conversation/reasoning_cache.go +++ b/backend/internal/infra/provider/conversation/reasoning_cache.go @@ -1,6 +1,7 @@ package conversation import ( + "strings" "sync" "time" ) @@ -99,13 +100,16 @@ func (c *ReasoningCache) Get(callID string) (responseItem, bool) { defer c.mu.RUnlock() entry, exists := c.entries[callID] - if !exists { - return responseItem{}, false + if exists && time.Since(entry.createdAt) <= c.ttl { + return entry.item, true } - if time.Since(entry.createdAt) > c.ttl { - return responseItem{}, false + if strings.Contains(callID, "|") { + prefix := strings.Split(callID, "|")[0] + if entry, exists := c.entries[prefix]; exists && time.Since(entry.createdAt) <= c.ttl { + return entry.item, true + } } - return entry.item, true + return responseItem{}, false } func (c *ReasoningCache) evictOldestLocked(now time.Time) { From ca392e6890ac5018d82e97419b533db8c3e5aa51 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Wed, 9 Sep 2026 10:31:00 +0800 Subject: [PATCH 6/8] fix: restore reasoning context for multi-turn tool calls --- .../internal/infra/provider/cli/adapter.go | 48 ++- .../infra/provider/cli/adapter_test.go | 82 ++++- .../infra/provider/cli/responses_history.go | 65 ---- .../provider/conversation/chat_request.go | 126 ++++++-- .../provider/conversation/messages_request.go | 77 ++++- .../provider/conversation/reasoning_cache.go | 235 +++++++++----- .../conversation/reasoning_cache_test.go | 98 +++++- .../reasoning_integration_test.go | 299 +++++++++++++++++- .../infra/provider/conversation/request.go | 15 +- .../infra/provider/conversation/response.go | 17 +- .../infra/provider/conversation/stream.go | 199 +++++++++++- 11 files changed, 1057 insertions(+), 204 deletions(-) diff --git a/backend/internal/infra/provider/cli/adapter.go b/backend/internal/infra/provider/cli/adapter.go index 3169b9fd..1e2be28b 100644 --- a/backend/internal/infra/provider/cli/adapter.go +++ b/backend/internal/infra/provider/cli/adapter.go @@ -63,8 +63,13 @@ type Adapter struct { fallbackMarker FallbackMarker uploadIssuer VideoUploadIssuer replay *reasoningreplay.ReasoningReplay - compaction *gatewayCompactionCodec - logger *slog.Logger + // conversationReasoningCache bridges Chat/Messages tool calls to the + // upstream Responses reasoning proof. It is deliberately separate from + // the persistent native Responses replay, and its keys never contain an + // account ID: encrypted reasoning is portable across Build accounts. + conversationReasoningCache *conversation.ReasoningCache + compaction *gatewayCompactionCodec + logger *slog.Logger } func NewAdapter(cfg Config, cipher *security.Cipher) *Adapter { @@ -77,7 +82,9 @@ func NewAdapter(cfg Config, cipher *security.Cipher) *Adapter { agentID := uuid.NewString() adapter := &Adapter{ cfg: cfg, http: httpClient, cipher: cipher, base: transport, - agentID: agentID, modelsETags: make(map[uint64]string), compaction: newGatewayCompactionCodec(cipher), logger: slog.Default(), + agentID: agentID, modelsETags: make(map[uint64]string), + conversationReasoningCache: conversation.NewReasoningCache(0, 0), + compaction: newGatewayCompactionCodec(cipher), logger: slog.Default(), } adapter.oauth = newOAuthClient(httpClient, func() string { return adapter.config().ClientVersion }) return adapter @@ -230,9 +237,16 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response var conversationOptions conversation.ResponseOptions cacheRoute := buildPromptCacheRoute{} compactionRequested := false + // Resolve the physical inference plane before normalization so Chat and + // Anthropic conversion can use the same scope for capture and restoration. + // The scope contains the trusted session seed, model, and plane only; it is + // intentionally independent of the selected account. + primaryBase := a.primaryBaseURL() + base := a.inferenceBaseForOperation(request.Credential, request.Billing, request.Method, request.Path) + conversationScope := a.conversationReasoningScope(request, base) if request.NormalizeBody { if request.Operation == conversation.OperationChat || request.Operation == conversation.OperationMessages { - body, conversationOptions, err = conversation.ConvertRequestWithOptions(body, request.Model, request.Operation) + body, conversationOptions, err = conversation.ConvertRequestWithReasoningReplay(body, request.Model, request.Operation, a.conversationReasoningCache, conversationScope) } else { var foreignCompactions int body, foreignCompactions, err = expandGatewayCompactionHistory(body, a.compaction, request.PromptCacheKey) @@ -263,6 +277,8 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response } if request.Operation == conversation.OperationMessages && conversationOptions.AnthropicWebSearch { request.ReasoningReplayKey = "" + conversationScope = "" + conversationOptions = conversationOptions.WithReasoningReplay(nil, "") } if compactionRequested { body, err = prepareGatewayCompactionSample(body) @@ -299,10 +315,11 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response return a.forwardGatewayCompaction(ctx, request, accessToken, body, warnings) } // Explicit mode wins; in auto mode only confirmed Super accounts with bot_flag_source/bfs in {1,2} default to XAI. - primaryBase := a.primaryBaseURL() - base := a.inferenceBaseForOperation(request.Credential, request.Billing, request.Method, request.Path) - // Cache affinity and reasoning replay use separate identities. Replay is also bound to the actual account and upstream plane, - // preventing opaque reasoning issued for one account or Build plane from reaching another scope. + // Prompt-cache affinity and reasoning replay use separate identities. The + // native Responses replay remains account-scoped, while the Chat/Messages + // bridge is scoped to the client session, model, and physical plane only; + // encrypted reasoning is intentionally portable across accounts on that + // plane. replayBaseBody := body body, replayKey := a.applyReasoningReplay(ctx, request, replayBaseBody, base) resp, reqURL, err := a.doResponseRequest(ctx, request, accessToken, body, base) @@ -342,6 +359,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response recoveredPrimaryFailure = bufferedFailureDiagnostic(primaryResp, primaryBody, primaryTruncated) a.activateBuildAPIFallback(ctx, &request.Credential) resp, reqURL, base, body, replayKey = fallbackResp, fallbackURL, fallbackBase, fallbackBody, fallbackReplayKey + conversationOptions = conversationOptions.WithReasoningReplay(a.conversationReasoningCache, a.conversationReasoningScope(request, base)) reasoningRecovery = reasoningRecovery.merge(fallbackRecovery) } else { if fallbackErr == nil { @@ -501,6 +519,20 @@ func (a *Adapter) scopedReasoningReplayKey(request provider.ResponseResourceRequ return hex.EncodeToString(digest[:]) } +func (a *Adapter) conversationReasoningScope(request provider.ResponseResourceRequest, base string) string { + seed := strings.TrimSpace(request.ReasoningReplayKey) + model := strings.ToLower(strings.TrimSpace(request.Model)) + if seed == "" || model == "" { + return "" + } + plane := "build" + if fallback := a.fallbackBaseURL(); fallback != "" && strings.EqualFold(strings.TrimRight(base, "/"), fallback) { + plane = "xai" + } + digest := sha256.Sum256([]byte(fmt.Sprintf("grok2api:conversation-reasoning:v1:%s:%s:%s", seed, model, plane))) + return hex.EncodeToString(digest[:]) +} + func isCompactPath(path string) bool { return strings.Contains(strings.ToLower(path), "compact") } diff --git a/backend/internal/infra/provider/cli/adapter_test.go b/backend/internal/infra/provider/cli/adapter_test.go index ab26634a..15b6d7aa 100644 --- a/backend/internal/infra/provider/cli/adapter_test.go +++ b/backend/internal/infra/provider/cli/adapter_test.go @@ -392,7 +392,7 @@ func TestForwardResponseReplaysReasoningAcrossMessagesTurns(t *testing.T) { } } -func TestReasoningReplayScopeSeparatesAccountAndPlane(t *testing.T) { +func TestNativeReasoningReplayScopeSeparatesAccountAndPlane(t *testing.T) { adapter := NewAdapter(Config{ BaseURL: "https://build.example/v1", FallbackBaseURL: "https://xai.example/v1", @@ -419,6 +419,86 @@ func TestReasoningReplayScopeSeparatesAccountAndPlane(t *testing.T) { } } +func TestConversationReasoningReplaySharesExplicitSessionAcrossAccounts(t *testing.T) { + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + encrypted, err := cipher.Encrypt("access-token") + if err != nil { + t.Fatal(err) + } + adapter := NewAdapter(Config{BaseURL: "https://build.example/v1"}, cipher) + var requestCount int + var secondRequest map[string]any + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + requestCount++ + body, readErr := io.ReadAll(request.Body) + if readErr != nil { + return nil, readErr + } + if requestCount == 2 { + if err := json.Unmarshal(body, &secondRequest); err != nil { + return nil, err + } + } + responseBody := `{"id":"resp_first","model":"grok-4.6","status":"completed","output":[{"id":"rs_first","type":"reasoning","status":"completed","encrypted_content":"portable-proof"},{"id":"fc_first","type":"function_call","call_id":"call_portable","name":"list_dir","arguments":"{}"}]}` + if requestCount > 1 { + responseBody = `{"id":"resp_second","model":"grok-4.6","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}]}` + } + return &http.Response{ + StatusCode: http.StatusOK, Status: "200 OK", + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(responseBody)), Request: request, + }, nil + }) + firstRequest := provider.ResponseResourceRequest{ + Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted}, + Method: http.MethodPost, Path: "/responses", Model: "grok-4.6", Operation: conversation.OperationChat, + ReasoningReplayKey: "portable-session", NormalizeBody: true, + Body: []byte(`{"model":"public","messages":[{"role":"user","content":"hello"}]}`), + } + first, err := adapter.ForwardResponse(context.Background(), firstRequest) + if err != nil { + t.Fatal(err) + } + if _, err := io.ReadAll(first.Body); err != nil { + t.Fatal(err) + } + _ = first.Body.Close() + secondRequestInput := firstRequest + secondRequestInput.Credential.ID = 2 + secondRequestInput.Body = []byte(`{"model":"public","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":null,"tool_calls":[{"id":"call_portable","type":"function","function":{"name":"list_dir","arguments":"{}"}}]},{"role":"tool","tool_call_id":"call_portable","content":"ok"}]}`) + second, err := adapter.ForwardResponse(context.Background(), secondRequestInput) + if err != nil { + t.Fatal(err) + } + _ = second.Body.Close() + if requestCount != 2 { + t.Fatalf("upstream request count = %d, want 2", requestCount) + } + input, ok := secondRequest["input"].([]any) + if !ok { + t.Fatalf("second upstream input = %#v", secondRequest["input"]) + } + found := false + for _, raw := range input { + item, ok := raw.(map[string]any) + if ok && item["type"] == "reasoning" && item["encrypted_content"] == "portable-proof" { + found = true + if _, hasContent := item["content"]; hasContent { + t.Fatalf("replayed opaque reasoning contains content: %#v", item) + } + } + } + if !found { + t.Fatalf("portable reasoning was not restored: %#v", input) + } + if firstScope := adapter.conversationReasoningScope(firstRequest, adapter.primaryBaseURL()); firstScope == "" || firstScope != adapter.conversationReasoningScope(secondRequestInput, adapter.primaryBaseURL()) { + t.Fatal("conversation reasoning scope unexpectedly depends on account") + } +} + func TestListModelsUsesOfficialMetadataHeaders(t *testing.T) { cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) if err != nil { diff --git a/backend/internal/infra/provider/cli/responses_history.go b/backend/internal/infra/provider/cli/responses_history.go index fd4c57ad..c5675dec 100644 --- a/backend/internal/infra/provider/cli/responses_history.go +++ b/backend/internal/infra/provider/cli/responses_history.go @@ -4,8 +4,6 @@ import ( "encoding/json" "fmt" "strings" - - "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" ) // normalizeInputItems 将 Codex/Responses 扩展历史降级为 Grok Build 可接受的结构, @@ -36,34 +34,6 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, [] c.changed = true rewritten = append(rewritten, converted) case "function_call": - callID := strings.TrimSpace(stringField(item, "call_id")) - if !hasPrecedingReasoningItem(rewritten) { - lookupID := callID - if strings.Contains(lookupID, "|") { - lookupID = strings.Split(lookupID, "|")[0] - } - if reasoningItem, found := conversation.GetReasoningForCall(lookupID); found && reasoningItem.ID != "" { - reasoningBlock := map[string]any{ - "type": "reasoning", - "id": reasoningItem.ID, - "status": "completed", - } - if reasoningItem.Encrypted != "" { - reasoningBlock["encrypted_content"] = reasoningItem.Encrypted - } - if len(reasoningItem.Summary) > 0 { - reasoningBlock["summary"] = reasoningItem.Summary - } - if len(reasoningItem.Content) > 0 { - reasoningBlock["content"] = reasoningItem.Content - } - rewritten = append(rewritten, reasoningBlock) - c.changed = true - } else if fallback := findLastReasoningBlock(rewritten, items); fallback != nil { - rewritten = append(rewritten, fallback) - c.changed = true - } - } converted, err := c.normalizeFunctionCallInput(item, param) if err != nil { return nil, nil, nil, err @@ -408,38 +378,3 @@ func encodeFunctionArguments(value any) (string, error) { } return string(encoded), nil } - -func hasPrecedingReasoningItem(items []any) bool { - if len(items) == 0 { - return false - } - last, ok := items[len(items)-1].(map[string]any) - if !ok { - return false - } - return stringField(last, "type") == "reasoning" -} - -func findLastReasoningBlock(rewritten []any, originalItems []any) map[string]any { - // 优先在已重写的序列中倒序查找最近的合法 reasoning - for i := len(rewritten) - 1; i >= 0; i-- { - item, ok := rewritten[i].(map[string]any) - if !ok { - continue - } - if stringField(item, "type") == "reasoning" && stringField(item, "encrypted_content") != "" { - return cloneJSONObject(item) - } - } - // 其次在原始输入序列中倒序查找 - for i := len(originalItems) - 1; i >= 0; i-- { - item, ok := originalItems[i].(map[string]any) - if !ok { - continue - } - if stringField(item, "type") == "reasoning" && stringField(item, "encrypted_content") != "" { - return cloneJSONObject(item) - } - } - return nil -} diff --git a/backend/internal/infra/provider/conversation/chat_request.go b/backend/internal/infra/provider/conversation/chat_request.go index 35d30826..f61e9aa3 100644 --- a/backend/internal/infra/provider/conversation/chat_request.go +++ b/backend/internal/infra/provider/conversation/chat_request.go @@ -10,6 +10,10 @@ import ( // convertChatRequest 将 Chat Completions 请求完整转换为标准 Responses 输入。 func convertChatRequest(body []byte, model string) ([]byte, ResponseOptions, error) { + return convertChatRequestWithReasoningReplay(body, model, nil, "") +} + +func convertChatRequestWithReasoningReplay(body []byte, model string, cache *ReasoningCache, scope string) ([]byte, ResponseOptions, error) { var source map[string]json.RawMessage if err := json.Unmarshal(body, &source); err != nil { return nil, ResponseOptions{}, fmt.Errorf("解析 Chat Completions 请求: %w", err) @@ -18,7 +22,7 @@ func convertChatRequest(body []byte, model string) ([]byte, ResponseOptions, err if err := json.Unmarshal(source["messages"], &messages); err != nil || len(messages) == 0 { return nil, ResponseOptions{}, errors.New("messages 必须是非空数组") } - input, err := convertChatMessages(messages) + input, err := convertChatMessagesWithReasoningReplay(messages, cache, scope) if err != nil { return nil, ResponseOptions{}, err } @@ -69,7 +73,7 @@ func convertChatRequest(body []byte, model string) ([]byte, ResponseOptions, err target["tool_choice"] = choice } converted, err := json.Marshal(target) - return converted, ResponseOptions{StopSequences: stopSequences}, err + return converted, ResponseOptions{StopSequences: stopSequences}.WithReasoningReplay(cache, scope), err } func parseChatStopSequences(raw json.RawMessage) ([]string, error) { @@ -107,6 +111,10 @@ type chatMessage struct { } func convertChatMessages(messages []chatMessage) ([]any, error) { + return convertChatMessagesWithReasoningReplay(messages, nil, "") +} + +func convertChatMessagesWithReasoningReplay(messages []chatMessage, cache *ReasoningCache, scope string) ([]any, error) { input := make([]any, 0, len(messages)) for _, message := range messages { role := strings.ToLower(strings.TrimSpace(message.Role)) @@ -124,10 +132,7 @@ func convertChatMessages(messages []chatMessage) ([]any, error) { if err != nil { return nil, err } - if reasoningBlock := restoreReasoningForCalls(calls); reasoningBlock != nil { - input = append(input, reasoningBlock) - } - input = append(input, calls...) + input = append(input, restoreReasoningForCalls(calls, cache, scope)...) } case "tool": if strings.TrimSpace(message.ToolCallID) == "" { @@ -410,33 +415,102 @@ func convertChatToolChoice(raw json.RawMessage) (json.RawMessage, error) { return mustJSON(map[string]any{"type": "function", "name": function.Name}), nil } -func restoreReasoningForCalls(calls []any) any { +func restoreReasoningForCalls(calls []any, cache *ReasoningCache, scope string) []any { + if cache == nil || strings.TrimSpace(scope) == "" { + return calls + } + result := make([]any, 0, len(calls)+1) + seenIDs := make(map[string]struct{}) + seenEncrypted := make(map[string]struct{}) for _, raw := range calls { callMap, ok := raw.(map[string]any) if !ok { + result = append(result, raw) continue } callID, _ := callMap["call_id"].(string) - if callID == "" { - continue + if item, found := cache.GetScoped(scope, callID); found && item.ID != "" && item.Encrypted != "" && !reasoningAlreadyEmitted(seenIDs, seenEncrypted, item) { + result = append(result, reasoningInputItem(item)) + markReasoningEmitted(seenIDs, seenEncrypted, item) } - if item, found := GetReasoningForCall(callID); found && item.Type == "reasoning" && item.ID != "" { - payload := map[string]any{ - "type": "reasoning", - "id": item.ID, - "status": "completed", - } - if item.Encrypted != "" { - payload["encrypted_content"] = item.Encrypted - } - if len(item.Summary) > 0 { - payload["summary"] = item.Summary - } - if len(item.Content) > 0 { - payload["content"] = item.Content - } - return payload + result = append(result, raw) + } + return result +} + +func reasoningAlreadyEmitted(ids, encrypted map[string]struct{}, item responseItem) bool { + if id := strings.TrimSpace(item.ID); id != "" { + if _, exists := ids[id]; exists { + return true } } - return nil + if value := strings.TrimSpace(item.Encrypted); value != "" { + if _, exists := encrypted[value]; exists { + return true + } + } + return false +} + +func markReasoningEmitted(ids, encrypted map[string]struct{}, item responseItem) { + if id := strings.TrimSpace(item.ID); id != "" { + ids[id] = struct{}{} + } + if value := strings.TrimSpace(item.Encrypted); value != "" { + encrypted[value] = struct{}{} + } +} + +func reasoningInputItem(item responseItem) map[string]any { + payload := map[string]any{ + "type": "reasoning", + "id": item.ID, + "status": "completed", + } + if item.Encrypted != "" { + payload["encrypted_content"] = item.Encrypted + } + if summary := cleanReasoningContents(item.Summary); len(summary) > 0 { + payload["summary"] = summary + } else if item.Encrypted != "" { + // Build's replay schema requires a summary member when an opaque proof is + // present. An empty array is the canonical representation for a redacted + // or summary-less reasoning item. + payload["summary"] = []any{} + } + // Omit content when it is nil/empty. Build treats content:null as a + // mutation of the opaque reasoning/compaction payload. + if content := cleanReasoningContents(item.Content); len(content) > 0 { + payload["content"] = content + } + return payload +} + +// cleanReasoningContents converts the internal response representation back to +// the small Responses input shape. responseContent's struct tags intentionally +// do not use omitempty because they are also used for decoding upstream output; +// assigning the structs directly here would therefore emit refusal:"" and +// annotations:null and make an opaque reasoning item look rewritten. +func cleanReasoningContents(contents []responseContent) []any { + if len(contents) == 0 { + return nil + } + cleaned := make([]any, 0, len(contents)) + for _, content := range contents { + value := make(map[string]any, 4) + if content.Type != "" { + value["type"] = content.Type + } + if content.Text != "" || content.Type == "summary_text" || content.Type == "reasoning_text" || content.Type == "output_text" { + value["text"] = content.Text + } + if content.Refusal != "" { + value["refusal"] = content.Refusal + } + if content.Annotations != nil { + value["annotations"] = content.Annotations + } + cleaned = append(cleaned, value) + } + return cleaned } diff --git a/backend/internal/infra/provider/conversation/messages_request.go b/backend/internal/infra/provider/conversation/messages_request.go index 68a42b91..f35b6b2a 100644 --- a/backend/internal/infra/provider/conversation/messages_request.go +++ b/backend/internal/infra/provider/conversation/messages_request.go @@ -10,6 +10,10 @@ import ( const anthropicBillingHeaderPrefix = "x-anthropic-billing-header: " func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions, error) { + return convertMessagesRequestWithReasoningReplay(body, model, nil, "") +} + +func convertMessagesRequestWithReasoningReplay(body []byte, model string, cache *ReasoningCache, scope string) ([]byte, ResponseOptions, error) { var request anthropicRequest if err := json.Unmarshal(body, &request); err != nil { return nil, ResponseOptions{}, fmt.Errorf("解析 Messages 请求: %w", err) @@ -40,7 +44,18 @@ func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions, return nil, ResponseOptions{}, fmt.Errorf("不支持 thinking.type=%q", request.Thinking.Type) } } - input, inlineInstructions, err := convertAnthropicMessages(request.Messages, anthropicDeclaredToolNames(request.Tools)) + // Hosted web search has a separate server-side history contract. The + // gateway deliberately does not bridge opaque reasoning for these turns + // (see the adapter's web-search isolation below), so disable the bridge + // before converting messages rather than trying to remove an already + // injected item afterwards. + hasWebSearchTool := hasAnthropicWebSearchTool(request.Tools) + webSearchEnabled := hasWebSearchTool && (request.ToolChoice == nil || !strings.EqualFold(strings.TrimSpace(request.ToolChoice.Type), "none")) + replayCache, replayScope := cache, scope + if webSearchEnabled { + replayCache, replayScope = nil, "" + } + input, inlineInstructions, err := convertAnthropicMessagesWithReasoningReplay(request.Messages, anthropicDeclaredToolNames(request.Tools), replayCache, replayScope) if err != nil { return nil, ResponseOptions{}, err } @@ -74,8 +89,6 @@ func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions, } target["text"] = map[string]any{"format": map[string]any{"type": "json_schema", "name": "anthropic_output", "schema": request.OutputConfig.Format.Schema}} } - hasWebSearchTool := hasAnthropicWebSearchTool(request.Tools) - webSearchEnabled := hasWebSearchTool && (request.ToolChoice == nil || !strings.EqualFold(strings.TrimSpace(request.ToolChoice.Type), "none")) webSearchRequired := webSearchEnabled && anthropicWebSearchRequired(request.Tools, request.ToolChoice) webSearchQuery := "" if webSearchEnabled { @@ -126,7 +139,7 @@ func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions, AnthropicWebSearchRequired: webSearchRequired, AnthropicWebSearchQuery: webSearchQuery, StopSequences: append([]string(nil), request.StopSequences...), - }, err + }.WithReasoningReplay(replayCache, replayScope), err } type anthropicRequest struct { @@ -168,11 +181,32 @@ type anthropicToolChoice struct { } func convertAnthropicMessages(messages []anthropicMessage, declaredTools map[string]struct{}) ([]any, []string, error) { + return convertAnthropicMessagesWithReasoningReplay(messages, declaredTools, nil, "") +} + +func convertAnthropicMessagesWithReasoningReplay(messages []anthropicMessage, declaredTools map[string]struct{}, cache *ReasoningCache, scope string) ([]any, []string, error) { input := make([]any, 0, len(messages)) instructions := make([]string, 0) pendingCalls := make(map[string]struct{}) usedCalls := make(map[string]struct{}) serverSearches := make(map[string]map[string]any) + seenReasoningIDs := make(map[string]struct{}) + seenReasoningEncrypted := make(map[string]struct{}) + // A client is allowed to preserve an Anthropic thinking block in a + // different order from the tool_use block. Pre-scan explicit signatures so + // a cached bridge item is not emitted first and then duplicated when that + // explicit block is encountered later in the same history. + explicitReasoningEncrypted := anthropicExplicitReasoningProofs(messages) + appendCachedReasoning := func(item responseItem) { + if item.ID == "" || item.Encrypted == "" || reasoningAlreadyEmitted(seenReasoningIDs, seenReasoningEncrypted, item) { + return + } + if _, exists := explicitReasoningEncrypted[strings.TrimSpace(item.Encrypted)]; exists { + return + } + input = append(input, reasoningInputItem(item)) + markReasoningEmitted(seenReasoningIDs, seenReasoningEncrypted, item) + } for messageIndex, message := range messages { role := strings.ToLower(strings.TrimSpace(message.Role)) if role == "system" || role == "developer" { @@ -255,6 +289,11 @@ func convertAnthropicMessages(messages []anthropicMessage, declaredTools map[str return nil, nil, fmt.Errorf("%s 包含重复 tool_use id %q", path, value.ID) } arguments, _ := json.Marshal(value.Input) + if cache != nil && strings.TrimSpace(scope) != "" { + if reasoning, found := cache.GetScoped(scope, value.ID); found && reasoning.ID != "" && reasoning.Encrypted != "" { + appendCachedReasoning(reasoning) + } + } input = append(input, map[string]any{"type": "function_call", "call_id": value.ID, "name": value.Name, "arguments": string(arguments)}) pendingCalls[value.ID] = struct{}{} usedCalls[value.ID] = struct{}{} @@ -299,6 +338,7 @@ func convertAnthropicMessages(messages []anthropicMessage, declaredTools map[str item["encrypted_content"] = signature } input = append(input, item) + markReasoningEmitted(seenReasoningIDs, seenReasoningEncrypted, responseItem{Encrypted: signature}) case "redacted_thinking": if role != "assistant" { return nil, nil, fmt.Errorf("%s redacted_thinking 只允许出现在 assistant 消息", path) @@ -311,6 +351,7 @@ func convertAnthropicMessages(messages []anthropicMessage, declaredTools map[str // Grok Build requires summary to exist whenever encrypted_content is replayed. // An empty array is the canonical Anthropic redacted_thinking representation. input = append(input, map[string]any{"type": "reasoning", "summary": []any{}, "encrypted_content": data}) + markReasoningEmitted(seenReasoningIDs, seenReasoningEncrypted, responseItem{Encrypted: data}) case "server_tool_use": if role != "assistant" { continue @@ -358,6 +399,34 @@ func convertAnthropicMessages(messages []anthropicMessage, declaredTools map[str return input, instructions, nil } +func anthropicExplicitReasoningProofs(messages []anthropicMessage) map[string]struct{} { + proofs := make(map[string]struct{}) + for _, message := range messages { + if !strings.EqualFold(strings.TrimSpace(message.Role), "assistant") { + continue + } + var blocks []map[string]json.RawMessage + if json.Unmarshal(message.Content, &blocks) != nil { + continue + } + for _, block := range blocks { + var typeName string + _ = json.Unmarshal(block["type"], &typeName) + var proof string + switch typeName { + case "thinking": + _ = json.Unmarshal(block["signature"], &proof) + case "redacted_thinking": + _ = json.Unmarshal(block["data"], &proof) + } + if proof = strings.TrimSpace(proof); proof != "" { + proofs[proof] = struct{}{} + } + } + } + return proofs +} + func applyAnthropicWebSearchResult(call map[string]any, raw json.RawMessage) { var results []map[string]any if json.Unmarshal(raw, &results) == nil { diff --git a/backend/internal/infra/provider/conversation/reasoning_cache.go b/backend/internal/infra/provider/conversation/reasoning_cache.go index 02febdec..7113aef2 100644 --- a/backend/internal/infra/provider/conversation/reasoning_cache.go +++ b/backend/internal/infra/provider/conversation/reasoning_cache.go @@ -1,6 +1,7 @@ package conversation import ( + "container/list" "strings" "sync" "time" @@ -12,21 +13,23 @@ const ( ) type reasoningCacheEntry struct { + key string item responseItem createdAt time.Time } +// ReasoningCache stores only short-lived, scoped reasoning proofs. A scope is +// supplied by the caller and must identify the client conversation and the +// upstream plane; a call_id by itself is never a sufficient cache key. type ReasoningCache struct { - mu sync.RWMutex - entries map[string]reasoningCacheEntry - order []string + mu sync.Mutex + entries map[string]*list.Element + order *list.List capacity int ttl time.Duration } -var globalReasoningCache = newReasoningCache(defaultReasoningCacheCapacity, defaultReasoningCacheTTL) - -func newReasoningCache(capacity int, ttl time.Duration) *ReasoningCache { +func NewReasoningCache(capacity int, ttl time.Duration) *ReasoningCache { if capacity <= 0 { capacity = defaultReasoningCacheCapacity } @@ -34,114 +37,176 @@ func newReasoningCache(capacity int, ttl time.Duration) *ReasoningCache { ttl = defaultReasoningCacheTTL } return &ReasoningCache{ - entries: make(map[string]reasoningCacheEntry, capacity), - order: make([]string, 0, capacity), + entries: make(map[string]*list.Element, capacity), + order: list.New(), capacity: capacity, ttl: ttl, } } -// RememberReasoningForEnvelope 检查响应 envelope 中是否同时包含 reasoning 与 function_call 项。 -// 若存在,将该轮次的所有 reasoning 项与同批次的所有 call_id 建立关联缓存。 -func RememberReasoningForEnvelope(envelope responseEnvelope) { - if len(envelope.Output) == 0 { - return - } - var reasoningItems []responseItem - var callIDs []string - - for _, item := range envelope.Output { - if item.Type == "reasoning" { - reasoningItems = append(reasoningItems, item) - } else if item.Type == "function_call" && item.CallID != "" { - callIDs = append(callIDs, item.CallID) - } - } - - if len(reasoningItems) == 0 || len(callIDs) == 0 { - return - } - - // 取最后一个 reasoning 项(最完整的思维链证明) - targetReasoning := reasoningItems[len(reasoningItems)-1] - for _, callID := range callIDs { - globalReasoningCache.Set(callID, targetReasoning) - } +// newReasoningCache is kept local to the package tests and makes the default +// policy explicit without exposing cache internals to providers. +func newReasoningCache(capacity int, ttl time.Duration) *ReasoningCache { + return NewReasoningCache(capacity, ttl) } -func (c *ReasoningCache) Set(callID string, item responseItem) { +func scopedReasoningCacheKey(scope, callID string) string { + scope = strings.TrimSpace(scope) + callID = normalizeReasoningCallID(callID) + if scope == "" || callID == "" { + return "" + } + return scope + "\x00" + callID +} + +// normalizeReasoningCallID handles the item-id suffix emitted by some +// Responses clients while retaining the actual conversation scope. +func normalizeReasoningCallID(callID string) string { + callID = strings.TrimSpace(callID) + if index := strings.IndexByte(callID, '|'); index > 0 { + callID = strings.TrimSpace(callID[:index]) + } + return callID +} + +func reasoningCallIDCandidates(callID string) []string { + callID = strings.TrimSpace(callID) if callID == "" { + return nil + } + result := []string{callID} + canonical := normalizeReasoningCallID(callID) + if canonical != callID && canonical != "" { + result = append(result, canonical) + } + const anthropicPrefix = "toolu_" + if strings.HasPrefix(canonical, anthropicPrefix) { + if upstream := strings.TrimPrefix(canonical, anthropicPrefix); upstream != "" { + result = append(result, upstream) + } + } else { + result = append(result, anthropicPrefix+canonical) + } + return result +} + +// SetScoped records one proof under a conversation/plane scope. +func (c *ReasoningCache) SetScoped(scope, callID string, item responseItem) { + if c == nil || item.Type != "reasoning" || strings.TrimSpace(item.ID) == "" || strings.TrimSpace(item.Encrypted) == "" { + return + } + key := scopedReasoningCacheKey(scope, callID) + if key == "" { return } c.mu.Lock() defer c.mu.Unlock() now := time.Now() - // 如果已存在,更新 - if _, exists := c.entries[callID]; exists { - c.entries[callID] = reasoningCacheEntry{item: item, createdAt: now} + if element, exists := c.entries[key]; exists { + entry := element.Value.(*reasoningCacheEntry) + entry.item = cloneResponseItem(item) + entry.createdAt = now + c.order.MoveToFront(element) return } - - // 如果超量,淘汰最早的条目或过期条目 - if len(c.order) >= c.capacity { - c.evictOldestLocked(now) + for c.order.Len() >= c.capacity { + c.removeExpiredOrOldestLocked(now) + if c.order.Len() < c.capacity { + break + } + c.removeElementLocked(c.order.Back()) } - - c.entries[callID] = reasoningCacheEntry{item: item, createdAt: now} - c.order = append(c.order, callID) + entry := &reasoningCacheEntry{key: key, item: cloneResponseItem(item), createdAt: now} + c.entries[key] = c.order.PushFront(entry) } -func (c *ReasoningCache) Get(callID string) (responseItem, bool) { - if callID == "" { +// GetScoped returns a proof only from the requested conversation/plane scope. +// Reads refresh recency, making the bounded cache an actual LRU rather than a +// FIFO queue. +func (c *ReasoningCache) GetScoped(scope, callID string) (responseItem, bool) { + if c == nil || strings.TrimSpace(scope) == "" { return responseItem{}, false } - c.mu.RLock() - defer c.mu.RUnlock() - - entry, exists := c.entries[callID] - if exists && time.Since(entry.createdAt) <= c.ttl { - return entry.item, true - } - if strings.Contains(callID, "|") { - prefix := strings.Split(callID, "|")[0] - if entry, exists := c.entries[prefix]; exists && time.Since(entry.createdAt) <= c.ttl { - return entry.item, true + c.mu.Lock() + defer c.mu.Unlock() + now := time.Now() + for _, candidate := range reasoningCallIDCandidates(callID) { + key := scopedReasoningCacheKey(scope, candidate) + element, exists := c.entries[key] + if !exists { + continue } + entry := element.Value.(*reasoningCacheEntry) + if now.Sub(entry.createdAt) > c.ttl { + c.removeElementLocked(element) + continue + } + c.order.MoveToFront(element) + return cloneResponseItem(entry.item), true } return responseItem{}, false } -func (c *ReasoningCache) evictOldestLocked(now time.Time) { - // 先扫描清除过期条目 - newOrder := c.order[:0] - for _, id := range c.order { - entry, exists := c.entries[id] - if !exists { - continue - } +func (c *ReasoningCache) removeElementLocked(element *list.Element) { + if element == nil { + return + } + entry := element.Value.(*reasoningCacheEntry) + delete(c.entries, entry.key) + c.order.Remove(element) +} + +func (c *ReasoningCache) removeExpiredOrOldestLocked(now time.Time) { + for element := c.order.Back(); element != nil; { + previous := element.Prev() + entry := element.Value.(*reasoningCacheEntry) if now.Sub(entry.createdAt) > c.ttl { - delete(c.entries, id) - continue + c.removeElementLocked(element) } - newOrder = append(newOrder, id) - } - c.order = newOrder - - // 若仍满,则淘汰队列头部最老的一批 - if len(c.order) >= c.capacity { - removeCount := c.capacity / 8 - if removeCount < 1 { - removeCount = 1 - } - for i := 0; i < removeCount && i < len(c.order); i++ { - delete(c.entries, c.order[i]) - } - c.order = c.order[removeCount:] + element = previous } } -// GetReasoningForCall 查询指定 callID 的缓存 reasoning 证明项 -func GetReasoningForCall(callID string) (responseItem, bool) { - return globalReasoningCache.Get(callID) +// RememberReasoningForEnvelope associates each function call with the most +// recent preceding reasoning item. A single reasoning item may legitimately +// precede several parallel calls; separate reasoning items are never all +// collapsed onto the last call. +func (c *ReasoningCache) RememberReasoningForEnvelope(scope string, envelope responseEnvelope) { + if c == nil || strings.TrimSpace(scope) == "" || len(envelope.Output) == 0 { + return + } + var current *responseItem + for _, item := range envelope.Output { + switch item.Type { + case "reasoning": + if item.Encrypted == "" { + current = nil + continue + } + copy := cloneResponseItem(item) + current = © + case "function_call": + if current != nil && item.CallID != "" { + c.SetScoped(scope, item.CallID, *current) + } + } + } +} + +func cloneResponseItem(item responseItem) responseItem { + clone := item + if item.Content != nil { + clone.Content = append([]responseContent(nil), item.Content...) + } + if item.Summary != nil { + clone.Summary = append([]responseContent(nil), item.Summary...) + } + if item.Action != nil { + clone.Action = make(map[string]any, len(item.Action)) + for key, value := range item.Action { + clone.Action[key] = value + } + } + return clone } diff --git a/backend/internal/infra/provider/conversation/reasoning_cache_test.go b/backend/internal/infra/provider/conversation/reasoning_cache_test.go index f4bca60d..2458b4a3 100644 --- a/backend/internal/infra/provider/conversation/reasoning_cache_test.go +++ b/backend/internal/infra/provider/conversation/reasoning_cache_test.go @@ -1,12 +1,15 @@ package conversation import ( + "encoding/json" + "strings" "testing" "time" ) func TestReasoningCacheSetAndGet(t *testing.T) { cache := newReasoningCache(10, time.Hour) + scope := "session-a/build" sample := responseItem{ ID: "rs_123", Type: "reasoning", @@ -14,8 +17,8 @@ func TestReasoningCacheSetAndGet(t *testing.T) { Encrypted: "encrypted-content-sample", } - cache.Set("call-1", sample) - got, found := cache.Get("call-1") + cache.SetScoped(scope, "call-1", sample) + got, found := cache.GetScoped(scope, "call-1") if !found { t.Fatalf("expected call-1 to be found in cache") } @@ -23,13 +26,15 @@ func TestReasoningCacheSetAndGet(t *testing.T) { t.Fatalf("expected %v, got %v", sample, got) } - _, found2 := cache.Get("non-existent") + _, found2 := cache.GetScoped(scope, "non-existent") if found2 { t.Fatalf("expected non-existent to return false") } } func TestRememberReasoningForEnvelope(t *testing.T) { + cache := newReasoningCache(10, time.Hour) + scope := "session-a/build" env := responseEnvelope{ Output: []responseItem{ { @@ -53,15 +58,96 @@ func TestRememberReasoningForEnvelope(t *testing.T) { }, } - RememberReasoningForEnvelope(env) + cache.RememberReasoningForEnvelope(scope, env) - r1, found1 := GetReasoningForCall("call_abc_1") + r1, found1 := cache.GetScoped(scope, "call_abc_1") if !found1 || r1.Encrypted != "encrypted_abc" { t.Fatalf("expected call_abc_1 to be cached, got %v", r1) } - r2, found2 := GetReasoningForCall("call_abc_2") + r2, found2 := cache.GetScoped(scope, "call_abc_2") if !found2 || r2.Encrypted != "encrypted_abc" { t.Fatalf("expected call_abc_2 to be cached, got %v", r2) } } + +func TestReasoningCacheScopesAndLRU(t *testing.T) { + cache := newReasoningCache(2, time.Hour) + item := func(id string) responseItem { + return responseItem{ID: id, Type: "reasoning", Encrypted: id + "-encrypted"} + } + cache.SetScoped("session-a/build", "call-1", item("one")) + cache.SetScoped("session-a/build", "call-2", item("two")) + if _, ok := cache.GetScoped("session-b/build", "call-1"); ok { + t.Fatal("reasoning leaked across scopes") + } + if _, ok := cache.GetScoped("session-a/xai", "call-1"); ok { + t.Fatal("reasoning leaked across planes") + } + if _, ok := cache.GetScoped("session-a/build", "call-1"); !ok { + t.Fatal("call-1 should be present before LRU access") + } + cache.SetScoped("session-a/build", "call-3", item("three")) + if _, ok := cache.GetScoped("session-a/build", "call-1"); !ok { + t.Fatal("recently-read call-1 was evicted; cache is not LRU") + } + if _, ok := cache.GetScoped("session-a/build", "call-2"); ok { + t.Fatal("least-recently-used call-2 was not evicted") + } +} + +func TestRememberReasoningForEnvelopePairsItemsInOrder(t *testing.T) { + cache := newReasoningCache(10, time.Hour) + scope := "session-a/build" + cache.RememberReasoningForEnvelope(scope, responseEnvelope{Output: []responseItem{ + {ID: "reasoning-a", Type: "reasoning", Encrypted: "enc-a"}, + {ID: "call-item-a", Type: "function_call", CallID: "call-a"}, + {ID: "reasoning-b", Type: "reasoning", Encrypted: "enc-b"}, + {ID: "call-item-b", Type: "function_call", CallID: "call-b"}, + }}) + a, ok := cache.GetScoped(scope, "call-a") + if !ok || a.ID != "reasoning-a" { + t.Fatalf("call-a reasoning = %#v, found=%v", a, ok) + } + b, ok := cache.GetScoped(scope, "call-b") + if !ok || b.ID != "reasoning-b" { + t.Fatalf("call-b reasoning = %#v, found=%v", b, ok) + } +} + +func TestReasoningInputItemOmitsNullContent(t *testing.T) { + payload := reasoningInputItem(responseItem{ID: "rs-1", Type: "reasoning", Encrypted: "opaque"}) + if _, exists := payload["content"]; exists { + t.Fatalf("content must be omitted for an opaque item: %#v", payload) + } + if summary, ok := payload["summary"].([]any); !ok || len(summary) != 0 { + t.Fatalf("opaque reasoning must carry an empty summary array: %#v", payload) + } +} + +func TestReasoningInputItemOmitsSyntheticContentFields(t *testing.T) { + payload := reasoningInputItem(responseItem{ + ID: "rs-2", + Type: "reasoning", + Encrypted: "opaque", + Summary: []responseContent{{Type: "summary_text", Text: "plan"}}, + Content: []responseContent{{Type: "reasoning_text", Text: "detail"}}, + }) + encoded, err := json.Marshal(payload) + if err != nil { + t.Fatal(err) + } + text := string(encoded) + for _, unwanted := range []string{`"content":null`, `"refusal":""`, `"annotations":null`} { + if strings.Contains(text, unwanted) { + t.Fatalf("replay item contains synthetic field %s: %s", unwanted, text) + } + } + var decoded map[string]any + if err := json.Unmarshal(encoded, &decoded); err != nil { + t.Fatal(err) + } + if summary := decoded["summary"].([]any)[0].(map[string]any); summary["type"] != "summary_text" || summary["text"] != "plan" { + t.Fatalf("summary fields were not preserved: %#v", decoded["summary"]) + } +} diff --git a/backend/internal/infra/provider/conversation/reasoning_integration_test.go b/backend/internal/infra/provider/conversation/reasoning_integration_test.go index e57cfd8e..cce50ae1 100644 --- a/backend/internal/infra/provider/conversation/reasoning_integration_test.go +++ b/backend/internal/infra/provider/conversation/reasoning_integration_test.go @@ -2,12 +2,17 @@ package conversation import ( "encoding/json" + "io" + "strings" "testing" + "time" ) func TestChatMultiTurnReasoningRestoration(t *testing.T) { // 模拟第一轮:上游返回 Responses 包含 reasoning 和 function_call callID := "call_integration_test_123" + cache := newReasoningCache(10, time.Hour) + scope := "client-session/build" env := responseEnvelope{ Output: []responseItem{ { @@ -27,7 +32,7 @@ func TestChatMultiTurnReasoningRestoration(t *testing.T) { } // 触发出站记录 - RememberReasoningForEnvelope(env) + cache.RememberReasoningForEnvelope(scope, env) // 模拟第二轮:下游客户端传回标准的 Chat Completions 历史(带有刚才的 tool_calls 和 tool output) chatReqJSON := []byte(`{ @@ -56,7 +61,7 @@ func TestChatMultiTurnReasoningRestoration(t *testing.T) { ] }`) - convertedBody, _, err := ConvertRequestWithOptions(chatReqJSON, "grok-4.6", OperationChat) + convertedBody, _, err := ConvertRequestWithReasoningReplay(chatReqJSON, "grok-4.6", OperationChat, cache, scope) if err != nil { t.Fatalf("ConvertRequestWithOptions failed: %v", err) } @@ -89,4 +94,294 @@ func TestChatMultiTurnReasoningRestoration(t *testing.T) { if !foundReasoning { t.Fatalf("FAIL: expected reasoning block with id rs_integ_001 to be restored in input, but not found. Inputs: %#v", inputs) } + for _, itemRaw := range inputs { + item, ok := itemRaw.(map[string]any) + if ok && item["type"] == "reasoning" { + if _, exists := item["content"]; exists { + t.Fatalf("opaque reasoning replay must omit content: %#v", item) + } + } + } +} + +func TestAnthropicWebSearchDoesNotInjectCachedReasoning(t *testing.T) { + cache := newReasoningCache(10, time.Hour) + scope := "client-session/build" + cache.SetScoped(scope, "call_search", responseItem{ + ID: "rs_search", Type: "reasoning", Encrypted: "search-proof", + }) + body := []byte(`{ + "model":"grok-4.6","max_tokens":128, + "messages":[ + {"role":"assistant","content":[{"type":"tool_use","id":"toolu_call_search","name":"lookup","input":{}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_call_search","content":"ok"}]} + ], + "tools":[{"type":"web_search_20250305","name":"web_search"}] + }`) + converted, options, err := ConvertRequestWithReasoningReplay(body, "grok-4.6", OperationMessages, cache, scope) + if err != nil { + t.Fatal(err) + } + var payload struct { + Input []map[string]any `json:"input"` + } + if err := json.Unmarshal(converted, &payload); err != nil { + t.Fatal(err) + } + for _, item := range payload.Input { + if item["type"] == "reasoning" { + t.Fatalf("web-search request received cached reasoning: %#v", payload.Input) + } + } + if options.reasoningCache != nil || options.reasoningScope != "" { + t.Fatalf("web-search options retained reasoning bridge: %#v", options) + } +} + +func TestAnthropicFunctionToolRestoresCachedReasoning(t *testing.T) { + cache := newReasoningCache(10, time.Hour) + scope := "client-session/build" + cache.SetScoped(scope, "call_function", responseItem{ + ID: "rs_function", Type: "reasoning", Encrypted: "function-proof", + }) + body := []byte(`{ + "model":"grok-4.6","max_tokens":128, + "messages":[ + {"role":"assistant","content":[{"type":"tool_use","id":"toolu_call_function","name":"lookup","input":{}}]}, + {"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_call_function","content":"ok"}]} + ], + "tools":[{"name":"lookup","input_schema":{"type":"object"}}] + }`) + converted, options, err := ConvertRequestWithReasoningReplay(body, "grok-4.6", OperationMessages, cache, scope) + if err != nil { + t.Fatal(err) + } + var payload struct { + Input []map[string]any `json:"input"` + } + if err := json.Unmarshal(converted, &payload); err != nil { + t.Fatal(err) + } + if len(payload.Input) < 2 || payload.Input[0]["type"] != "reasoning" || payload.Input[0]["encrypted_content"] != "function-proof" { + t.Fatalf("function reasoning was not restored: %#v", payload.Input) + } + if options.reasoningCache == nil || options.reasoningScope == "" { + t.Fatal("ordinary Messages request lost reasoning bridge") + } +} + +func TestStreamOutputItemDoneFeedsReasoningReplayWhenCompletedOutputIsEmpty(t *testing.T) { + cache := newReasoningCache(10, time.Hour) + scope := "client-session/build" + stream := strings.Join([]string{ + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"rs_stream","type":"reasoning","status":"completed","encrypted_content":"stream-proof"}}`, + ``, + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_stream","type":"function_call","call_id":"call_stream","name":"list_dir","arguments":"{}"}}`, + ``, + `event: response.completed`, + `data: {"type":"response.completed","response":{"id":"resp_stream","status":"completed","output":[]}}`, + ``, + }, "\n") + converted := ConvertResponseStreamWithOptions( + io.NopCloser(strings.NewReader(stream)), + OperationChat, + ResponseOptions{}.WithReasoningReplay(cache, scope), + ) + if _, err := io.ReadAll(converted); err != nil { + t.Fatalf("stream conversion failed: %v", err) + } + if _, ok := cache.GetScoped(scope, "call_stream"); !ok { + t.Fatal("output_item.done reasoning was not cached") + } + + body := []byte(`{"model":"grok-4.6","messages":[{"role":"assistant","content":null,"tool_calls":[{"id":"call_stream","type":"function","function":{"name":"list_dir","arguments":"{}"}}]},{"role":"tool","tool_call_id":"call_stream","content":"ok"}]}`) + convertedBody, _, err := ConvertRequestWithReasoningReplay(body, "grok-4.6", OperationChat, cache, scope) + if err != nil { + t.Fatalf("request conversion failed: %v", err) + } + var payload struct { + Input []map[string]any `json:"input"` + } + if err := json.Unmarshal(convertedBody, &payload); err != nil { + t.Fatal(err) + } + if len(payload.Input) < 2 || payload.Input[0]["type"] != "reasoning" || payload.Input[0]["encrypted_content"] != "stream-proof" || payload.Input[1]["type"] != "function_call" { + t.Fatalf("restored input = %#v", payload.Input) + } +} + +func TestStreamCompletedOutputFeedsReasoningReplayWhenItemDoneIsOmitted(t *testing.T) { + cache := newReasoningCache(10, time.Hour) + scope := "client-session/build" + stream := strings.Join([]string{ + `event: response.completed`, + `data: {"type":"response.completed","response":{"id":"resp_terminal","status":"completed","output":[{"id":"rs_terminal","type":"reasoning","status":"completed","encrypted_content":"terminal-proof"},{"id":"fc_terminal","type":"function_call","call_id":"call_terminal","name":"list_dir","arguments":"{}"}]}}`, + ``, + }, "\n") + converted := ConvertResponseStreamWithOptions( + io.NopCloser(strings.NewReader(stream)), + OperationChat, + ResponseOptions{}.WithReasoningReplay(cache, scope), + ) + if _, err := io.ReadAll(converted); err != nil { + t.Fatalf("stream conversion failed: %v", err) + } + item, ok := cache.GetScoped(scope, "call_terminal") + if !ok || item.Encrypted != "terminal-proof" { + t.Fatalf("terminal output was not cached: item=%#v found=%v", item, ok) + } +} + +func TestStreamReplayPreservesOutputItemDoneOrderWhenTerminalOmitsReasoning(t *testing.T) { + cache := newReasoningCache(10, time.Hour) + scope := "client-session/build" + stream := strings.Join([]string{ + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"rs_ordered","type":"reasoning","status":"completed","encrypted_content":"ordered-proof"}}`, "", + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_ordered","type":"function_call","call_id":"call_ordered","name":"list_dir","arguments":"{}"}}`, "", + // The terminal envelope contains only the function call. Some Build + // responses do this even though reasoning was sent in item.done. + `event: response.completed`, + `data: {"type":"response.completed","response":{"id":"resp_ordered","status":"completed","output":[{"id":"fc_ordered","type":"function_call","call_id":"call_ordered","name":"list_dir","arguments":"{}"}]}}`, "", + }, "\n") + converted := ConvertResponseStreamWithOptions(io.NopCloser(strings.NewReader(stream)), OperationChat, ResponseOptions{}.WithReasoningReplay(cache, scope)) + if _, err := io.ReadAll(converted); err != nil { + t.Fatalf("stream conversion failed: %v", err) + } + item, ok := cache.GetScoped(scope, "call_ordered") + if !ok || item.Encrypted != "ordered-proof" { + t.Fatalf("reasoning item.done was not paired with the later function call: item=%#v found=%v", item, ok) + } +} + +func TestStreamWithoutResponsesTerminalDoesNotCommitReasoningReplay(t *testing.T) { + cache := newReasoningCache(10, time.Hour) + scope := "client-session/build" + // The source ends after item.done without response.completed/incomplete. + // Downstream compatibility still emits its normal terminator, but this is + // not sufficient evidence that the upstream tool turn completed. + stream := strings.Join([]string{ + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"rs_truncated","type":"reasoning","encrypted_content":"truncated-proof"}}`, + ``, + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_truncated","type":"function_call","call_id":"call_truncated","name":"list_dir","arguments":"{}"}}`, + ``, + }, "\n") + converted := ConvertResponseStreamWithOptions( + io.NopCloser(strings.NewReader(stream)), + OperationChat, + ResponseOptions{}.WithReasoningReplay(cache, scope), + ) + if _, err := io.ReadAll(converted); err != nil { + t.Fatalf("stream conversion failed: %v", err) + } + if _, ok := cache.GetScoped(scope, "call_truncated"); ok { + t.Fatal("truncated stream polluted reasoning replay cache") + } +} + +func TestAnthropicParallelToolUsesInjectOneReasoningProof(t *testing.T) { + cache := newReasoningCache(10, time.Hour) + scope := "client-session/build" + proof := responseItem{ + ID: "rs_parallel", + Type: "reasoning", + Encrypted: "parallel-proof", + Summary: []responseContent{{Type: "summary_text", Text: "plan"}}, + } + cache.SetScoped(scope, "call-a", proof) + cache.SetScoped(scope, "call-b", proof) + + messages := []anthropicMessage{ + {Role: "assistant", Content: json.RawMessage(`[ + {"type":"tool_use","id":"toolu_call-a","name":"first","input":{}}, + {"type":"tool_use","id":"toolu_call-b","name":"second","input":{}} + ]`)}, + {Role: "user", Content: json.RawMessage(`[ + {"type":"tool_result","tool_use_id":"toolu_call-a","content":"one"}, + {"type":"tool_result","tool_use_id":"toolu_call-b","content":"two"} + ]`)}, + } + input, _, err := convertAnthropicMessagesWithReasoningReplay(messages, nil, cache, scope) + if err != nil { + t.Fatal(err) + } + reasoningCount := 0 + functionCount := 0 + for _, raw := range input { + item, ok := raw.(map[string]any) + if !ok { + continue + } + switch item["type"] { + case "reasoning": + reasoningCount++ + if item["encrypted_content"] != "parallel-proof" { + t.Fatalf("reasoning = %#v", item) + } + case "function_call": + functionCount++ + } + } + if reasoningCount != 1 || functionCount != 2 { + t.Fatalf("parallel tool input = %#v", input) + } + encoded, err := json.Marshal(input) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(encoded), `"content":null`) || strings.Contains(string(encoded), `"refusal":""`) || strings.Contains(string(encoded), `"annotations":null`) { + t.Fatalf("replayed reasoning contains synthetic null fields: %s", encoded) + } +} + +func TestAnthropicExplicitThinkingSignatureSuppressesCachedDuplicate(t *testing.T) { + cache := newReasoningCache(10, time.Hour) + scope := "client-session/build" + cache.SetScoped(scope, "call-a", responseItem{ID: "rs_cached", Type: "reasoning", Encrypted: "same-proof"}) + messages := []anthropicMessage{ + {Role: "assistant", Content: json.RawMessage(`[ + {"type":"thinking","thinking":"plan","signature":"same-proof"}, + {"type":"tool_use","id":"toolu_call-a","name":"first","input":{}} + ]`)}, + {Role: "user", Content: json.RawMessage(`[{"type":"tool_result","tool_use_id":"toolu_call-a","content":"ok"}]`)}, + } + input, _, err := convertAnthropicMessagesWithReasoningReplay(messages, nil, cache, scope) + if err != nil { + t.Fatal(err) + } + reasoningCount := 0 + for _, raw := range input { + item, _ := raw.(map[string]any) + if item["type"] == "reasoning" { + reasoningCount++ + } + } + if reasoningCount != 1 { + t.Fatalf("cached proof duplicated explicit thinking: %#v", input) + } +} + +func TestStreamReasoningReplayCommitsOnlyAfterSuccessfulTerminal(t *testing.T) { + cache := newReasoningCache(10, time.Hour) + scope := "client-session/build" + failed := strings.Join([]string{ + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"rs_failed","type":"reasoning","encrypted_content":"failed-proof"}}`, "", + `event: response.output_item.done`, + `data: {"type":"response.output_item.done","item":{"id":"fc_failed","type":"function_call","call_id":"call_failed","name":"first","arguments":"{}"}}`, "", + `event: response.failed`, + `data: {"type":"response.failed","response":{"error":{"message":"upstream failed"}}}`, "", "", + }, "\n") + converted := ConvertResponseStreamWithOptions(io.NopCloser(strings.NewReader(failed)), OperationChat, ResponseOptions{}.WithReasoningReplay(cache, scope)) + if _, err := io.ReadAll(converted); err != nil { + t.Fatal(err) + } + if _, ok := cache.GetScoped(scope, "call_failed"); ok { + t.Fatal("failed stream left reasoning proof in replay cache") + } } diff --git a/backend/internal/infra/provider/conversation/request.go b/backend/internal/infra/provider/conversation/request.go index a1a2e062..1c53703f 100644 --- a/backend/internal/infra/provider/conversation/request.go +++ b/backend/internal/infra/provider/conversation/request.go @@ -22,11 +22,22 @@ func ConvertRequest(body []byte, model, operation string) ([]byte, error) { // ConvertRequestWithOptions 同时返回下游协议特有的响应语义,供 JSON/SSE 转换阶段使用。 func ConvertRequestWithOptions(body []byte, model, operation string) ([]byte, ResponseOptions, error) { + return convertRequestWithReasoningReplay(body, model, operation, nil, "") +} + +// ConvertRequestWithReasoningReplay is used by providers that can establish a +// trusted client-session scope. It keeps the public conversion path stateless +// when no such scope is available. +func ConvertRequestWithReasoningReplay(body []byte, model, operation string, cache *ReasoningCache, scope string) ([]byte, ResponseOptions, error) { + return convertRequestWithReasoningReplay(body, model, operation, cache, scope) +} + +func convertRequestWithReasoningReplay(body []byte, model, operation string, cache *ReasoningCache, scope string) ([]byte, ResponseOptions, error) { switch operation { case OperationChat: - return convertChatRequest(body, model) + return convertChatRequestWithReasoningReplay(body, model, cache, scope) case OperationMessages: - return convertMessagesRequest(body, model) + return convertMessagesRequestWithReasoningReplay(body, model, cache, scope) default: converted, err := replaceModel(body, model) return converted, ResponseOptions{}, err diff --git a/backend/internal/infra/provider/conversation/response.go b/backend/internal/infra/provider/conversation/response.go index fb8f51d6..58098d33 100644 --- a/backend/internal/infra/provider/conversation/response.go +++ b/backend/internal/infra/provider/conversation/response.go @@ -17,6 +17,20 @@ type ResponseOptions struct { Include []string // InlineCitations overrides Include when non-nil. InlineCitations *bool + // reasoningCache and reasoningScope are intentionally populated only by a + // provider that has a trusted, isolated client-session identity. A raw + // call_id is not sufficient to restore encrypted reasoning safely. + reasoningCache *ReasoningCache + reasoningScope string +} + +// WithReasoningReplay attaches a provider-owned, scoped reasoning cache to +// the conversion options. The scope must include the client session and the +// upstream plane; an empty scope disables the bridge. +func (o ResponseOptions) WithReasoningReplay(cache *ReasoningCache, scope string) ResponseOptions { + o.reasoningCache = cache + o.reasoningScope = scope + return o } // InlineCitationsEnabled reports whether [[N]](url) markers should be embedded. @@ -37,7 +51,6 @@ func (o ResponseOptions) InlineCitationsEnabled() bool { return enabled } - type responseEnvelope struct { ID string `json:"id"` Model string `json:"model"` @@ -125,7 +138,7 @@ func ConvertResponseJSONWithOptions(body []byte, operation string, options Respo } return body, nil } - RememberReasoningForEnvelope(envelope) + options.reasoningCache.RememberReasoningForEnvelope(options.reasoningScope, envelope) parsed := parseResponse(envelope) if operation == OperationMessages || operation == OperationChat { parsed.Text, parsed.StopSequence = applyStopSequences(parsed.Text, options.StopSequences) diff --git a/backend/internal/infra/provider/conversation/stream.go b/backend/internal/infra/provider/conversation/stream.go index 0cdbf411..0816a183 100644 --- a/backend/internal/infra/provider/conversation/stream.go +++ b/backend/internal/infra/provider/conversation/stream.go @@ -61,6 +61,12 @@ type streamConverter struct { stopFilter *anthropicStreamStopFilter stopSequence string refused bool + // terminalEvent distinguishes a normal Responses terminal frame from a + // transport EOF. EOF is still converted to the legacy downstream terminator + // for compatibility, but it must not make a truncated tool turn replayable. + terminalEvent bool + outputItems []responseItem + outputItemIDs map[string]struct{} } type streamTool struct { @@ -76,6 +82,7 @@ func newStreamConverter(writer io.Writer, operation string, options ResponseOpti return &streamConverter{ writer: writer, operation: operation, created: time.Now().Unix(), tools: make(map[string]streamTool), webSearchEmitted: make(map[string]bool), + outputItemIDs: make(map[string]struct{}), deferSearchText: operation == OperationMessages && options.AnthropicWebSearch, options: options, stopFilter: newAnthropicStreamStopFilter(options.StopSequences), } @@ -295,6 +302,7 @@ func (c *streamConverter) handle(event string, data []byte) error { case "response.output_item.done": var item responseItem _ = json.Unmarshal(root["item"], &item) + c.recordOutputItem(item) if item.Type == "function_call" { return c.toolArgumentsDone(item.ID, item.Arguments) } @@ -309,7 +317,11 @@ func (c *streamConverter) handle(event string, data []byte) error { case "response.completed", "response.incomplete": var response responseEnvelope _ = json.Unmarshal(root["response"], &response) - RememberReasoningForEnvelope(response) + // Some upstream streams omit output_item.done and put the complete + // reasoning/function_call objects only in the terminal envelope. Record + // those objects before done() commits the replay cache. + c.recordReplayOutput(response.Output) + response.Output = c.mergeOutputItems(response.Output) c.setResponse(response) if c.operation == OperationMessages && c.options.AnthropicWebSearch { parsed := parseResponse(response) @@ -323,6 +335,7 @@ func (c *streamConverter) handle(event string, data []byte) error { if status == "" && typeName == "response.incomplete" { status = "incomplete" } + c.terminalEvent = true return c.done(status) case "error", "response.failed": return c.streamError(data) @@ -330,6 +343,176 @@ func (c *streamConverter) handle(event string, data []byte) error { return nil } +// recordOutputItem retains the authoritative item-done payload. In streamed +// Responses, response.completed often contains usage/status only and an empty +// output array, while encrypted reasoning is present solely in these events. +func (c *streamConverter) recordOutputItem(item responseItem) { + if c == nil || (item.Type != "reasoning" && item.Type != "function_call") { + return + } + if c.outputItemIDs == nil { + c.outputItemIDs = make(map[string]struct{}) + } + key := replayOutputKey(item) + if key != "" { + if _, exists := c.outputItemIDs[key]; exists { + for index := range c.outputItems { + if replayOutputKey(c.outputItems[index]) == key { + c.outputItems[index] = mergeResponseItem(c.outputItems[index], item) + return + } + } + } + c.outputItemIDs[key] = struct{}{} + } + c.outputItems = append(c.outputItems, cloneResponseItem(item)) +} + +func replayOutputKey(item responseItem) string { + if id := strings.TrimSpace(item.ID); id != "" { + return "id:" + id + } + if item.Type == "function_call" { + if callID := strings.TrimSpace(item.CallID); callID != "" { + return "call:" + normalizeReasoningCallID(callID) + } + } + if item.Type == "reasoning" { + if encrypted := strings.TrimSpace(item.Encrypted); encrypted != "" { + return "proof:" + encrypted + } + } + return "" +} + +// recordReplayOutput merges the terminal envelope into the items observed in +// output_item.done. The event stream carries the authoritative output order; +// the terminal envelope is used to fill richer fields and append items that +// were never announced as done. +func (c *streamConverter) recordReplayOutput(output []responseItem) { + if c == nil || len(output) == 0 { + return + } + merged := make([]responseItem, 0, len(c.outputItems)+len(output)) + if len(c.outputItems) == 0 { + for _, item := range output { + if item.Type == "reasoning" || item.Type == "function_call" { + merged = append(merged, cloneResponseItem(item)) + } + } + } else { + terminal := make(map[string]responseItem, len(output)) + for _, item := range output { + if item.Type == "reasoning" || item.Type == "function_call" { + if key := replayOutputKey(item); key != "" { + terminal[key] = item + } + } + } + seen := make(map[string]struct{}, len(c.outputItems)+len(output)) + for _, item := range c.outputItems { + key := replayOutputKey(item) + if key != "" { + if update, ok := terminal[key]; ok { + item = mergeResponseItem(item, update) + } + seen[key] = struct{}{} + } + merged = append(merged, cloneResponseItem(item)) + } + for _, item := range output { + if item.Type != "reasoning" && item.Type != "function_call" { + continue + } + key := replayOutputKey(item) + if key != "" { + if _, ok := seen[key]; ok { + continue + } + seen[key] = struct{}{} + } + merged = append(merged, cloneResponseItem(item)) + } + } + c.outputItems = merged + c.outputItemIDs = make(map[string]struct{}, len(merged)) + for _, item := range merged { + if key := replayOutputKey(item); key != "" { + c.outputItemIDs[key] = struct{}{} + } + } +} + +func (c *streamConverter) commitReasoningReplay() { + if c == nil || c.options.reasoningCache == nil || strings.TrimSpace(c.options.reasoningScope) == "" || len(c.outputItems) == 0 { + return + } + c.options.reasoningCache.RememberReasoningForEnvelope(c.options.reasoningScope, responseEnvelope{Output: c.outputItems}) +} + +func (c *streamConverter) mergeOutputItems(output []responseItem) []responseItem { + if len(c.outputItems) == 0 { + return output + } + if len(output) == 0 { + return append([]responseItem(nil), c.outputItems...) + } + merged := append([]responseItem(nil), output...) + for _, item := range c.outputItems { + found := false + if key := replayOutputKey(item); key != "" { + for index := range merged { + if replayOutputKey(merged[index]) == key { + merged[index] = mergeResponseItem(merged[index], item) + found = true + break + } + } + } + if !found { + merged = append(merged, item) + } + } + return merged +} + +func mergeResponseItem(base, update responseItem) responseItem { + if base.ID == "" { + base.ID = update.ID + } + if base.Type == "" { + base.Type = update.Type + } + if base.Status == "" { + base.Status = update.Status + } + if base.Role == "" { + base.Role = update.Role + } + if base.CallID == "" { + base.CallID = update.CallID + } + if base.Name == "" { + base.Name = update.Name + } + if base.Arguments == "" { + base.Arguments = update.Arguments + } + if base.Encrypted == "" { + base.Encrypted = update.Encrypted + } + if len(base.Content) == 0 { + base.Content = update.Content + } + if len(base.Summary) == 0 { + base.Summary = update.Summary + } + if base.Action == nil { + base.Action = update.Action + } + return base +} + func (c *streamConverter) bufferSearchText(delta string) error { pending := c.pendingSearchText.Len() if pending >= maxDeferredSearchTextBytes || len(delta) > maxDeferredSearchTextBytes-pending { @@ -435,10 +618,20 @@ func (c *streamConverter) done(status string) error { if err := c.start(); err != nil { return err } + var err error if c.operation == OperationChat { - return c.doneChat(status) + err = c.doneChat(status) + } else { + err = c.doneMessages(status) } - return c.doneMessages(status) + if err == nil && c.terminalEvent { + // Commit only after the downstream terminal event was written. If the + // upstream failed, the client abandoned the pipe, or the source ended + // without a terminal Responses event, a partially observed tool turn must + // not become replayable state. + c.commitReasoningReplay() + } + return err } func (c *streamConverter) streamError(data []byte) error { From 7d1b424626a8a2c6969d66598fc4b4ebe8785b7b Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Wed, 9 Sep 2026 10:57:06 +0800 Subject: [PATCH 7/8] fix: prevent allocation size overflow in reasoning replay --- .../internal/infra/provider/conversation/chat_request.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/backend/internal/infra/provider/conversation/chat_request.go b/backend/internal/infra/provider/conversation/chat_request.go index f61e9aa3..03ce79d2 100644 --- a/backend/internal/infra/provider/conversation/chat_request.go +++ b/backend/internal/infra/provider/conversation/chat_request.go @@ -419,7 +419,11 @@ func restoreReasoningForCalls(calls []any, cache *ReasoningCache, scope string) if cache == nil || strings.TrimSpace(scope) == "" { return calls } - result := make([]any, 0, len(calls)+1) + // A cached reasoning item may be inserted before each call, so the final + // slice can be larger than calls. Use the input size as a safe initial + // capacity and let append grow it; len(calls)+1 is unnecessary and can + // overflow for a maximally sized input slice. + result := make([]any, 0, len(calls)) seenIDs := make(map[string]struct{}) seenEncrypted := make(map[string]struct{}) for _, raw := range calls { From e5285ebeb6fadaa13231e19a88bf4be2a43ae43a Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Wed, 9 Sep 2026 11:08:25 +0800 Subject: [PATCH 8/8] fix: filter non-object root union branches safely --- .../cli/responses_tool_declarations.go | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/backend/internal/infra/provider/cli/responses_tool_declarations.go b/backend/internal/infra/provider/cli/responses_tool_declarations.go index 4c677395..7ea6e41e 100644 --- a/backend/internal/infra/provider/cli/responses_tool_declarations.go +++ b/backend/internal/infra/provider/cli/responses_tool_declarations.go @@ -427,6 +427,26 @@ func (c *rootObjectLeafCollector) walk(node any, constraints []map[string]any, s constraints = append(cloneRootConstraints(constraints), sibling) } for _, branch := range branches { + // Build function parameters may contain a nullable or otherwise + // non-object alternative at the root. Such alternatives cannot be + // represented by Build's grammar and are intentionally omitted; the + // whole schema is rejected below when no object leaf remains. + branchSchema, branchOK := branch.(map[string]any) + if !branchOK || isNullOnlySchema(branchSchema) { + c.changed = true + continue + } + branchKeyword, _, branchErr := rootUnion(branchSchema) + if branchErr != nil { + return invalidBuildFunctionParametersRoot(c.context) + } + // A root $ref may point to another union (for example a named + // Create schema). Let walk resolve it before deciding whether its + // leaves are object schemas. + if branchKeyword == "" && branchSchema["$ref"] == nil && !isObjectRootSchema(branchSchema, c.doc, nil) { + c.changed = true + continue + } if err := c.walk(branch, constraints, cloneRefSeen(seen), depth+1, unionDepth+1); err != nil { return err }