From fcaeb672ff453b2c9186825d366563e59757a17c Mon Sep 17 00:00:00 2001 From: Hhy812 <1572878897@qq.com> Date: Fri, 17 Jul 2026 16:12:43 +0800 Subject: [PATCH 1/2] fix: rebuild Codex Responses history for Grok Build ModelInput Codex multi-turn requests were replaying raw history into Grok Build input[], which rejects untagged ModelInput shapes (null reasoning fields, private Codex metadata, extra function_call fields, unknown item types). Allowlist-rebuild message / function_call / reasoning items, degrade null reasoning to developer boundary, use role-aware text part types, strip external tools optionally, and document the contract in backend/docs/RESPONSES_MODELINPUT_NOTES.md. --- backend/docs/RESPONSES_MODELINPUT_NOTES.md | 287 ++++++++++++++++ .../infra/provider/cli/adapter_test.go | 2 +- .../infra/provider/cli/normalize_test.go | 2 +- .../provider/cli/responses_codex_tools.go | 147 +++++++- .../cli/responses_codex_tools_test.go | 315 +++++++++++++++++- .../infra/provider/cli/responses_history.go | 208 ++++++++++-- .../infra/provider/cli/responses_input.go | 86 +++++ .../provider/cli/responses_tool_choice.go | 11 + .../cli/responses_tool_declarations.go | 10 +- .../provider/cli/responses_tool_state.go | 93 ++++++ 10 files changed, 1106 insertions(+), 55 deletions(-) create mode 100644 backend/docs/RESPONSES_MODELINPUT_NOTES.md diff --git a/backend/docs/RESPONSES_MODELINPUT_NOTES.md b/backend/docs/RESPONSES_MODELINPUT_NOTES.md new file mode 100644 index 00000000..51bfd65d --- /dev/null +++ b/backend/docs/RESPONSES_MODELINPUT_NOTES.md @@ -0,0 +1,287 @@ +# Grok Build Responses / ModelInput 注意事项 + +> 适用:Codex / OpenAI Responses 客户端 → `grok2api` → Grok Build `POST /v1/responses` +> 现象:首轮常成功,后续多轮历史回放时 422 +> 错误: +> +> ```text +> unexpected status 422 Unprocessable Entity: +> {"error":"Failed to deserialize the JSON body into the target type: +> data did not match any variant of untagged enum ModelInput"} +> ``` + +## 1. 结论(先看这个) + +Grok Build 0.2.99 的 `input[]` 使用 **Rust 风格 untagged enum `ModelInput`**,对历史 item 形状很严格: + +1. **不要原样透传 Codex 历史** +2. **必须白名单重建**每个 `input[]` item / content part +3. **禁止输出 `null` 字段**(尤其是 `reasoning`) +4. **禁止保留 Codex 私有字段** + +相关实现主要在: + +- `backend/internal/infra/provider/cli/responses_history.go` +- `backend/internal/infra/provider/cli/responses_input.go` +- `backend/internal/infra/provider/cli/responses_codex_tools.go` +- `backend/internal/infra/provider/cli/responses_tool_state.go` +- `backend/internal/infra/provider/cli/responses_tool_declarations.go` +- `backend/internal/infra/provider/cli/responses_tool_choice.go` + +## 2. 已确认会 422 的形状 + +### 2.1 `reasoning` 带 null 字段(高频,会话已复现) + +Codex 第二轮经常带回: + +```json +{ + "type": "reasoning", + "id": "rs_xxx", + "summary": [{"type": "summary_text", "text": "..."}], + "content": null, + "encrypted_content": null, + "internal_chat_message_metadata_passthrough": {"turn_id": "..."} +} +``` + +错误处理: + +```json +{ + "type": "reasoning", + "id": "rs_xxx", + "summary": [...], + "content": null, + "encrypted_content": null +} +``` + +正确处理: + +- 有可用 `encrypted_content`:只保留非 null 白名单字段回放 +- `encrypted_content` 缺失 / null / 空:降级为 developer boundary,保留 summary 文本 + **绝不要回放带 null 的 reasoning 对象** + +复现会话:`019f64fa-984d-73e2-be0e-c732978d3321` +(首轮 200,第二轮带 null reasoning 后 422) + +### 2.2 Codex 私有字段 + +几乎每条 Codex history 都会带: + +- `internal_chat_message_metadata_passthrough` +- `phase` + +这些字段不能进入上游 `input[]`。 + +### 2.3 assistant 文本类型写错 + +| role | 正确 content part type | +|---|---| +| `assistant` / `model` | `output_text` | +| `user` / `developer` / `system` | `input_text` | + +**错误做法:** 把 assistant 的 `output_text` 全改成 `input_text` +**正确做法:** 按 role 选择类型(对齐 CLIProxyAPI 的 construction 路径) + +### 2.4 function 历史字段过多 + +`function_call` 只允许: + +```json +{"type":"function_call","call_id":"...","name":"...","arguments":"..."} +``` + +`function_call_output` 只允许: + +```json +{"type":"function_call_output","call_id":"...","output":"..."} +``` + +不要带: + +- `id` +- `status` +- `namespace` +- `internal_chat_message_metadata_passthrough` +- 其他私有/扩展字段 + +`output` 必须是 **字符串**;对象要先 `json.Marshal` 成字符串。 + +### 2.5 未知 / 外部工具历史原样透传 + +以下类型不能原样发给 Grok Build,应改写成 developer boundary 或兼容 function 协议: + +- `web_search_call` +- 原始 `shell_call`(若上游不接受) +- 其他未知 `type` + +`GROK2API_STRIP_EXTERNAL_TOOLS=true` 时,还应剥离工具声明: + +- `web_search*` +- `computer_use_preview` + +保留 function-backed 工具:`function` / `apply_patch` / `tool_search` / `shell|local_shell`。 + +## 3. 推荐白名单模型 + +只向 Grok Build 发送这些 `input[]` 形态: + +### message + +```json +{ + "type": "message", + "role": "user|assistant|developer", + "content": [ + {"type": "input_text|output_text", "text": "..."}, + {"type": "input_image", "image_url": "..."}, + {"type": "input_file", "file_data": "...", "filename": "..."} + ] +} +``` + +注意: + +- 不带 `id` / `status` / `phase` / metadata +- content part 不带 `annotations` +- 有 `role` 但缺 `type` 时,先补 `"type":"message"` + +### function_call + +```json +{ + "type": "function_call", + "call_id": "call_xxx", + "name": "tool_name", + "arguments": "{}" +} +``` + +### function_call_output + +```json +{ + "type": "function_call_output", + "call_id": "call_xxx", + "output": "string only" +} +``` + +### reasoning + +```json +{ + "type": "reasoning", + "id": "rs_xxx", + "summary": [{"type":"summary_text","text":"..."}], + "encrypted_content": "non-empty cipher" +} +``` + +规则: + +- 只保留非 null 字段 +- 没有可用 `encrypted_content` 时,不要发 `type=reasoning`,改发 developer boundary + +### shell_call_output(如需保留) + +- `output` 必须是结构化数组块 +- outcome 使用 `exit_code`(不是 `exitCode`) +- 去掉未知块字段(如 `command`) + +### 其他未知类型 + +```json +{ + "type": "message", + "role": "developer", + "content": [ + { + "type": "input_text", + "text": "A prior Responses history item was omitted ..." + } + ] +} +``` + +## 4. 实现原则 + +1. **白名单重建,不要 clone 后删字段** + clone 容易把 `null` / 私有字段带回去。 + +2. **JSON 里不要出现 `null` 值** + Go 里 `map[string]any{"content": nil}` 会编码成 `"content":null`,对 untagged enum 很危险。 + +3. **对齐 CLIProxyAPI 的 construction,而不是它的 Responses passthrough** + CLIProxyAPI 没有 Grok 专用 adapter;它从 Chat/Claude/Gemini 构造 Codex input 时才会发出干净 item。 + Responses→Codex 本身几乎是 top-level 清洗,历史深字段不会帮你修。 + +4. **多轮问题优先查第二轮历史** + 典型模式: + - 第 1 轮:只有 user/developer message → 200 + - 第 2 轮:附带 assistant + reasoning(+null) / tool history → 422 + +5. **修完后要替换正在运行的 Docker 二进制** + 只改源码不重建容器,Codex 仍打旧逻辑。 + +## 5. 排查清单 + +遇到新的 ModelInput 422 时: + +1. 从 Docker 日志拿 `request_id` 与时间点 +2. 找到对应 Codex session rollout(`~/.codex/sessions/...jsonl`) +3. 统计第二轮 `response_item` 的 `type` 与额外字段 +4. 特别检查: + - `reasoning.content` / `reasoning.encrypted_content` 是否为 null + - 是否残留 `internal_chat_message_metadata_passthrough` / `phase` + - assistant content 是否不是 `output_text` + - `function_call*` 是否多了 `id/status` +5. 用 normalize 单测 / 临时 fixture 验证清洗结果里: + - 无 `null` + - 无私有字段 + - item 类型都在白名单 +6. `go test ./internal/infra/provider/cli/` +7. 编译 Linux 二进制并替换容器: + +```bash +cd backend +GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o ../out/grok2api ./cmd/grok2api +docker cp ../out/grok2api grok2api:/app/grok2api +docker restart grok2api +curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:8000/healthz +docker commit grok2api grok2api:local +``` + +8. **新开 Codex 任务验证**(旧会话可能已污染) + +## 6. 相关测试 + +优先看 / 补充这些回归: + +- `TestAssistantOutputMessageHistoryKeepsOutputText` +- `TestNullEncryptedReasoningBecomesBoundary` +- `TestCodexPrivateMetadataIsStrippedFromHistory` +- `TestFunctionCallOutputHistoryEncodesStructuredOutput` +- `TestStripExternalClientToolHistory` +- `TestRoleMissingTypeBecomesMessageAndFunctionCallIsAllowlisted` + +## 7. 环境变量 + +| 变量 | 作用 | +|---|---| +| `GROK2API_STRIP_EXTERNAL_TOOLS=true` | 剥离 Grok Build 难托管的外部工具声明与对应历史,保留 function-backed 工具 | + +Docker Compose override 示例见仓库根目录 `docker-compose.override.yml`。 + +## 8. 参考会话 + +| Session ID | 现象 | +|---|---| +| `019f5ed1-ebd0-7183-8229-ae0bdaf88c9e` | 多轮 Codex 历史复杂,首次系统性排查 ModelInput 422 | +| `019f64fa-984d-73e2-be0e-c732978d3321` | 首轮 200,第二轮因 null `reasoning.encrypted_content` 422 | + +## 9. 一句话记住 + +> **Codex 历史不能透传;按白名单重建,role 决定 text 类型,reasoning 没有 cipher 就降级,任何 null / 私有字段都不要发给 Grok Build。** diff --git a/backend/internal/infra/provider/cli/adapter_test.go b/backend/internal/infra/provider/cli/adapter_test.go index 89830738..2c1b9eb4 100644 --- a/backend/internal/infra/provider/cli/adapter_test.go +++ b/backend/internal/infra/provider/cli/adapter_test.go @@ -90,7 +90,7 @@ func TestForwardResponseMatchesGrokBuildHeadersAndPreservesReasoning(t *testing. } _ = response.Body.Close() input := captured["input"].([]any) - if captured["model"] != "grok-4.5" || captured["prompt_cache_key"] != "isolated-key" || len(input) != 1 || input[0].(map[string]any)["encrypted_content"] != "cipher" { + if captured["model"] != "grok-4.5" || captured["prompt_cache_key"] != "isolated-key" || len(input) != 1 || input[0].(map[string]any)["type"] != "reasoning" || input[0].(map[string]any)["encrypted_content"] != "cipher" { t.Fatalf("captured = %#v", captured) } } diff --git a/backend/internal/infra/provider/cli/normalize_test.go b/backend/internal/infra/provider/cli/normalize_test.go index bcf3c58e..6ce4a60a 100644 --- a/backend/internal/infra/provider/cli/normalize_test.go +++ b/backend/internal/infra/provider/cli/normalize_test.go @@ -24,7 +24,7 @@ func TestNormalizeResponsesRequest(t *testing.T) { t.Fatalf("模型或缓存键未正确改写: %#v", payload) } input := payload["input"].([]any) - if len(input) != 2 || input[0].(map[string]any)["encrypted_content"] != "cipher" { + if len(input) != 2 || input[0].(map[string]any)["type"] != "reasoning" || input[0].(map[string]any)["encrypted_content"] != "cipher" { t.Fatalf("reasoning 回放项未保留: %#v", input) } reasoningContent := input[0].(map[string]any)["content"].([]any)[0].(map[string]any) diff --git a/backend/internal/infra/provider/cli/responses_codex_tools.go b/backend/internal/infra/provider/cli/responses_codex_tools.go index a7ef88c2..085e3279 100644 --- a/backend/internal/infra/provider/cli/responses_codex_tools.go +++ b/backend/internal/infra/provider/cli/responses_codex_tools.go @@ -19,7 +19,7 @@ func (c *responsesToolCompatibility) normalizeShellTool(tool map[string]any, par return c.normalizeNativeTool(tool, param) } -// normalizeLegacyLocalShellTool 将旧 Codex local_shell 升级为 0.2.101 原生 local shell 环境。 +// normalizeLegacyLocalShellTool 将旧 Codex local_shell 升级为 0.2.99 原生 local shell 环境。 func (c *responsesToolCompatibility) normalizeLegacyLocalShellTool(tool map[string]any, param string) ([]any, error) { if c.nativeShell || c.legacyLocalShell { return nil, &responsesRequestError{ @@ -27,8 +27,13 @@ func (c *responsesToolCompatibility) normalizeLegacyLocalShellTool(tool map[stri Param: param + ".type", Code: "invalid_parameter", } } - if len(tool) > 1 { - c.addWarning("legacy_local_shell_controls_ignored") + for key := range tool { + if key != "type" { + return nil, &responsesRequestError{ + Message: "旧版 local_shell 不支持额外配置字段", + Param: param + "." + key, Code: "unsupported_parameter", + } + } } c.legacyLocalShell = true c.changed = true @@ -40,9 +45,20 @@ func (c *responsesToolCompatibility) normalizeLegacyLocalShellTool(tool map[stri } // normalizeApplyPatchTool 将客户端执行的 apply_patch 包装为严格 function。 -func (c *responsesToolCompatibility) normalizeApplyPatchTool(tool map[string]any, param string) ([]any, error) { - if len(tool) > 1 { - c.addWarning("apply_patch_controls_ignored") +func (c *responsesToolCompatibility) normalizeApplyPatchTool(tool map[string]any, namespace, param string) ([]any, error) { + if namespace != "" { + return nil, &responsesRequestError{ + Message: "namespace 内暂不支持 apply_patch", + Param: param + ".type", Code: "unsupported_parameter", + } + } + for key := range tool { + if key != "type" { + return nil, &responsesRequestError{ + Message: "apply_patch 不接受自定义字段", + Param: param + "." + key, Code: "unsupported_parameter", + } + } } identity := responsesToolIdentity{Kind: responsesApplyPatchTool, Name: "apply_patch"} c.changed = true @@ -186,7 +202,7 @@ func legacyShellAction(value any, param string) (map[string]any, error) { return nil, &responsesRequestError{Message: "local_shell_call.action 必须是对象", Param: param, Code: "invalid_parameter"} } if kind := strings.TrimSpace(stringField(action, "type")); kind != "" && kind != "exec" { - return nil, &responsesRequestError{Message: "local_shell_call.action.type 必须是 exec", Param: param + ".type", Code: "invalid_parameter"} + return nil, &responsesRequestError{Message: "local_shell_call.action.type 只支持 exec", Param: param + ".type", Code: "unsupported_parameter"} } command, err := legacyShellCommand(action, param) if err != nil { @@ -282,6 +298,121 @@ func normalizeLegacyLocalShellOutputInput(item map[string]any, param string) (ma return converted, nil } +func normalizeShellCallOutputInput(item map[string]any, param string) (map[string]any, error) { + callID := strings.TrimSpace(stringField(item, "call_id")) + if callID == "" { + return nil, &responsesRequestError{Message: param + ".call_id 不能为空", Param: param + ".call_id", Code: "invalid_parameter"} + } + output, err := normalizeShellOutputBlocks(item["output"], item["status"], param+".output") + if err != nil { + return nil, err + } + converted := map[string]any{"type": "shell_call_output", "call_id": callID, "output": output} + if value, exists := item["max_output_length"]; exists { + converted["max_output_length"] = cloneJSONValue(value) + } + return converted, nil +} + +func normalizeFunctionCallOutputInput(item map[string]any, param string) (map[string]any, error) { + callID := strings.TrimSpace(stringField(item, "call_id")) + if callID == "" { + return nil, &responsesRequestError{Message: param + ".call_id 不能为空", Param: param + ".call_id", Code: "invalid_parameter"} + } + output, err := encodeToolOutput(item["output"], param+".output") + if err != nil { + return nil, err + } + // Allowlist only. CLIProxyAPI builds function_call_output without id/status. + return map[string]any{"type": "function_call_output", "call_id": callID, "output": output}, nil +} + +func encodeToolOutput(value any, param string) (string, error) { + switch typed := value.(type) { + case nil: + return "", nil + case string: + return typed, nil + default: + encoded, err := json.Marshal(typed) + if err != nil { + return "", &responsesRequestError{Message: param + " 无法编码", Param: param, Code: "invalid_parameter"} + } + return string(encoded), nil + } +} + +func normalizeShellOutputBlocks(value, status any, param string) ([]any, error) { + switch typed := value.(type) { + case []any: + output := make([]any, 0, len(typed)) + for index, raw := range typed { + block, ok := raw.(map[string]any) + if !ok { + return nil, &responsesRequestError{Message: fmt.Sprintf("%s[%d] 必须是对象", param, index), Param: fmt.Sprintf("%s[%d]", param, index), Code: "invalid_parameter"} + } + normalized, err := normalizeShellOutputBlock(block, fmt.Sprintf("%s[%d]", param, index)) + if err != nil { + return nil, err + } + output = append(output, normalized) + } + return output, nil + case string: + exitCode := 0 + if strings.EqualFold(fmt.Sprint(status), "failed") { + exitCode = 1 + } + return []any{map[string]any{ + "stdout": typed, "stderr": "", + "outcome": map[string]any{"type": "exit", "exit_code": exitCode}, + }}, nil + default: + return nil, &responsesRequestError{Message: param + " 必须是字符串或数组", Param: param, Code: "invalid_parameter"} + } +} + +func normalizeShellOutputBlock(block map[string]any, param string) (map[string]any, error) { + stdout, _ := block["stdout"].(string) + stderr, _ := block["stderr"].(string) + outcome, ok := block["outcome"].(map[string]any) + if !ok { + return nil, &responsesRequestError{Message: param + ".outcome 必须是对象", Param: param + ".outcome", Code: "invalid_parameter"} + } + normalizedOutcome := map[string]any{"type": strings.TrimSpace(stringField(outcome, "type"))} + switch normalizedOutcome["type"] { + case "exit": + exitCode, ok := shellExitCode(outcome["exit_code"]) + if !ok { + exitCode, ok = shellExitCode(outcome["exitCode"]) + } + if !ok { + return nil, &responsesRequestError{Message: param + ".outcome.exit_code 必须是数字", Param: param + ".outcome.exit_code", Code: "invalid_parameter"} + } + normalizedOutcome["exit_code"] = exitCode + case "timeout": + default: + return nil, &responsesRequestError{Message: param + ".outcome.type 无效", Param: param + ".outcome.type", Code: "invalid_parameter"} + } + return map[string]any{"stdout": stdout, "stderr": stderr, "outcome": normalizedOutcome}, nil +} + +func shellExitCode(value any) (int, bool) { + switch typed := value.(type) { + case float64: + return int(typed), true + case int: + return typed, true + case int64: + return int(typed), true + case json.Number: + parsed, err := typed.Int64() + return int(parsed), err == nil + default: + return 0, false + } +} + func rewriteLegacyShellAction(value any) map[string]any { action, _ := value.(map[string]any) commands, _ := action["commands"].([]any) @@ -327,7 +458,7 @@ func validEnvironmentName(value string) bool { func (c *responsesToolCompatibility) normalizeAdditionalToolsInput(item map[string]any, param string) (map[string]any, []any, []any, error) { if role := strings.TrimSpace(stringField(item, "role")); role != "" && role != "developer" { - c.addWarning("additional_tools_role_approximated") + return nil, nil, nil, &responsesRequestError{Message: "additional_tools.role 只支持 developer", Param: param + ".role", Code: "unsupported_parameter"} } tools, ok := item["tools"].([]any) if !ok { diff --git a/backend/internal/infra/provider/cli/responses_codex_tools_test.go b/backend/internal/infra/provider/cli/responses_codex_tools_test.go index dc50a051..e536d58a 100644 --- a/backend/internal/infra/provider/cli/responses_codex_tools_test.go +++ b/backend/internal/infra/provider/cli/responses_codex_tools_test.go @@ -10,13 +10,13 @@ import ( func TestLegacyLocalShellUsesNativeLocalShellAndRestoresJSON(t *testing.T) { normalized, compatibility, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":"show cwd", - "tools":[{"type":"local_shell","timeout_ms":30000}], + "tools":[{"type":"local_shell"}], "tool_choice":{"type":"local_shell"} }`), "grok-4.5") if err != nil { t.Fatal(err) } - if compatibility == nil || !compatibility.legacyLocalShell || !strings.Contains(compatibility.warningHeader(), "legacy_local_shell_controls_ignored") { + if compatibility == nil || !compatibility.legacyLocalShell { t.Fatal("legacy local_shell 未启用兼容层") } var request map[string]any @@ -78,6 +78,306 @@ func TestLegacyLocalShellHistoryBecomesStructuredShellHistory(t *testing.T) { } } +func TestNativeShellOutputHistoryIsSanitizedForBuild(t *testing.T) { + normalized, _, err := normalizeResponsesRequest([]byte(`{ + "model":"public","tools":[{"type":"shell","environment":{"type":"local"}}],"input":[ + {"type":"shell_call_output","call_id":"call_1","status":"completed","output":[ + {"command":"pwd","stdout":"/workspace\n","stderr":"","outcome":{"type":"exit","exitCode":0}} + ],"max_output_length":2048} + ] + }`), "grok-4.5") + if err != nil { + t.Fatal(err) + } + var request map[string]any + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + item := request["input"].([]any)[0].(map[string]any) + block := item["output"].([]any)[0].(map[string]any) + outcome := block["outcome"].(map[string]any) + if item["type"] != "shell_call_output" || block["command"] != nil || outcome["exit_code"] != float64(0) || outcome["exitCode"] != nil { + t.Fatalf("shell output history = %#v", item) + } +} + +func TestFunctionCallOutputHistoryEncodesStructuredOutput(t *testing.T) { + normalized, _, err := normalizeResponsesRequest([]byte(`{ + "model":"public","tools":[{"type":"function","name":"shell_command","parameters":{"type":"object"}}],"input":[ + {"type":"function_call_output","call_id":"call_1","status":"completed","output":{"exit_code":0,"stdout":"ok","stderr":""}} + ] + }`), "grok-4.5") + if err != nil { + t.Fatal(err) + } + var request map[string]any + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + item := request["input"].([]any)[0].(map[string]any) + output, ok := item["output"].(string) + if item["type"] != "function_call_output" || !ok || !strings.Contains(output, `"stdout":"ok"`) { + t.Fatalf("function output history = %#v", item) + } +} + +func TestAssistantOutputMessageHistoryKeepsOutputText(t *testing.T) { + normalized, _, err := normalizeResponsesRequest([]byte(`{ + "model":"public","input":[ + {"id":"msg_1","type":"message","status":"completed","role":"assistant","content":[ + {"type":"output_text","text":"Hi there","annotations":[]} + ]}, + {"type":"message","role":"user","content":[{"type":"input_text","text":"继续"}]} + ] + }`), "grok-4.5") + if err != nil { + t.Fatal(err) + } + var request map[string]any + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + items := request["input"].([]any) + first := items[0].(map[string]any) + second := items[1].(map[string]any) + firstContent := first["content"].([]any)[0].(map[string]any) + secondContent := second["content"].([]any)[0].(map[string]any) + if first["id"] != nil || first["status"] != nil || firstContent["type"] != "output_text" || firstContent["annotations"] != nil { + t.Fatalf("assistant message history = %#v", first) + } + if secondContent["type"] != "input_text" { + t.Fatalf("user message history = %#v", second) + } +} + +func TestRoleMissingTypeBecomesMessageAndFunctionCallIsAllowlisted(t *testing.T) { + normalized, _, err := normalizeResponsesRequest([]byte(`{ + "model":"public","input":[ + {"role":"user","content":"hello"}, + {"type":"function_call","id":"fc_1","status":"completed","call_id":"call_1","name":"shell_command","arguments":"{}","namespace":"","internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, + {"type":"function_call_output","id":"fco_1","status":"completed","call_id":"call_1","output":"ok"} + ] + }`), "grok-4.5") + if err != nil { + t.Fatal(err) + } + var request map[string]any + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + items := request["input"].([]any) + user := items[0].(map[string]any) + call := items[1].(map[string]any) + output := items[2].(map[string]any) + if user["type"] != "message" || user["content"].([]any)[0].(map[string]any)["type"] != "input_text" { + t.Fatalf("user history = %#v", user) + } + if call["type"] != "function_call" || call["id"] != nil || call["status"] != nil || call["internal_chat_message_metadata_passthrough"] != nil { + t.Fatalf("function_call history = %#v", call) + } + if output["type"] != "function_call_output" || output["id"] != nil || output["status"] != nil { + t.Fatalf("function_call_output history = %#v", output) + } +} + +func TestUnsupportedResponsesHistoryItemsBecomeBoundaries(t *testing.T) { + normalized, _, err := normalizeResponsesRequest([]byte(`{ + "model":"public","input":[ + {"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"kept summary"}],"encrypted_content":"cipher"}, + {"type":"web_search_call","id":"ws_1","status":"completed"}, + {"type":"shell_call","call_id":"call_1","status":"completed","action":{"type":"exec","commands":["pwd"]}}, + {"type":"message","role":"user","content":[{"type":"input_text","text":"continue"}]} + ] + }`), "grok-4.5") + if err != nil { + t.Fatal(err) + } + var request map[string]any + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + items := request["input"].([]any) + if items[0].(map[string]any)["type"] != "reasoning" || items[0].(map[string]any)["encrypted_content"] != "cipher" { + t.Fatalf("reasoning history = %#v", items[0]) + } + for index, raw := range items[1:3] { + item := raw.(map[string]any) + text := item["content"].([]any)[0].(map[string]any)["text"].(string) + if item["type"] != "message" || item["role"] != "developer" || !strings.Contains(text, "Type: ") { + t.Fatalf("item %d was not downgraded: %#v", index+1, item) + } + } + if items[3].(map[string]any)["role"] != "user" { + t.Fatalf("user message changed unexpectedly: %#v", items[3]) + } +} + +func TestNullEncryptedReasoningBecomesBoundary(t *testing.T) { + normalized, _, err := normalizeResponsesRequest([]byte(`{ + "model":"public","input":[ + {"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"who am I"}],"content":null,"encrypted_content":null,"internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, + {"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}, + {"type":"message","role":"user","content":[{"type":"input_text","text":"嗯"}]} + ] + }`), "grok-4.5") + if err != nil { + t.Fatal(err) + } + var request map[string]any + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + items := request["input"].([]any) + first := items[0].(map[string]any) + text := first["content"].([]any)[0].(map[string]any)["text"].(string) + if first["type"] != "message" || first["role"] != "developer" || first["encrypted_content"] != nil || first["content"] == nil { + t.Fatalf("null reasoning should become boundary: %#v", first) + } + if !strings.Contains(text, "who am I") || strings.Contains(text, "null") { + t.Fatalf("boundary text = %q", text) + } + if items[1].(map[string]any)["content"].([]any)[0].(map[string]any)["type"] != "output_text" { + t.Fatalf("assistant history = %#v", items[1]) + } +} + +func TestCodexPrivateMetadataIsStrippedFromHistory(t *testing.T) { + normalized, _, err := normalizeResponsesRequest([]byte(`{ + "model":"public","input":[ + {"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"plan"}],"encrypted_content":"cipher","internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, + {"type":"function_call","id":"fc_1","call_id":"call_1","name":"shell_command","arguments":"{}","internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, + {"type":"function_call_output","id":"fco_1","call_id":"call_1","output":"ok","internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, + {"type":"custom_tool_call","id":"ctc_1","call_id":"call_2","name":"apply_patch","input":"patch","status":"completed","internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, + {"type":"custom_tool_call_output","id":"ctco_1","call_id":"call_2","output":"done","internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, + {"type":"message","role":"assistant","phase":"final_answer","content":[{"type":"output_text","text":"hi"}],"internal_chat_message_metadata_passthrough":{"turn_id":"t1"}} + ] + }`), "grok-4.5") + if err != nil { + t.Fatal(err) + } + var request map[string]any + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + for index, raw := range request["input"].([]any) { + item := raw.(map[string]any) + if item["internal_chat_message_metadata_passthrough"] != nil || item["phase"] != nil { + t.Fatalf("input[%d] still has private fields: %#v", index, item) + } + } + items := request["input"].([]any) + if items[0].(map[string]any)["type"] != "reasoning" || items[0].(map[string]any)["encrypted_content"] != "cipher" { + t.Fatalf("reasoning history = %#v", items[0]) + } + if items[1].(map[string]any)["type"] != "function_call" || items[3].(map[string]any)["type"] != "function_call" { + t.Fatalf("tool call history = %#v", items) + } + if items[5].(map[string]any)["role"] != "assistant" { + t.Fatalf("assistant message history = %#v", items[5]) + } +} + +func TestStripExternalClientToolsKeepsFunctionBackedTools(t *testing.T) { + t.Setenv("GROK2API_STRIP_EXTERNAL_TOOLS", "true") + normalized, compatibility, err := normalizeResponsesRequest([]byte(`{ + "model":"public","input":"hello", + "tools":[ + {"type":"function","name":"read_file","parameters":{"type":"object"}}, + {"type":"apply_patch"}, + {"type":"tool_search","execution":"client"}, + {"type":"web_search","external_web_access":false}, + {"type":"local_shell"} + ], + "tool_choice":{"type":"apply_patch"} + }`), "grok-4.5") + if err != nil { + t.Fatal(err) + } + if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "external_tools_omitted") { + t.Fatalf("compatibility warnings = %#v", compatibility) + } + var request map[string]any + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + tools := request["tools"].([]any) + if len(tools) != 4 { + t.Fatalf("normalized tools = %#v choice=%#v", tools, request["tool_choice"]) + } + seen := map[string]bool{} + for _, rawTool := range tools { + tool := rawTool.(map[string]any) + switch tool["type"] { + case "function": + seen[tool["name"].(string)] = true + case "shell": + seen["shell"] = true + } + if tool["type"] == "web_search" { + t.Fatalf("web_search should be omitted: %#v", tools) + } + } + choice := request["tool_choice"].(map[string]any) + if !seen["read_file"] || !seen["grok2api_apply_patch"] || !seen["grok2api_tool_search"] || !seen["shell"] || + choice["type"] != "function" || choice["name"] != "grok2api_apply_patch" { + t.Fatalf("normalized tools = %#v choice=%#v", tools, request["tool_choice"]) + } + input := request["input"].([]any) + if input[0].(map[string]any)["role"] != "developer" || input[1].(map[string]any)["role"] != "user" { + t.Fatalf("input boundary = %#v", input) + } +} + +func TestStripExternalClientToolsRemovesStringToolChoice(t *testing.T) { + t.Setenv("GROK2API_STRIP_EXTERNAL_TOOLS", "true") + normalized, _, err := normalizeResponsesRequest([]byte(`{ + "model":"public","input":"hello", + "tools":[{"type":"web_search","external_web_access":false}], + "tool_choice":"auto" + }`), "grok-4.5") + if err != nil { + t.Fatal(err) + } + var request map[string]any + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + if request["tools"] != nil || request["tool_choice"] != nil { + t.Fatalf("tools/tool_choice should be omitted: %#v", request) + } +} + +func TestStripExternalClientToolHistory(t *testing.T) { + t.Setenv("GROK2API_STRIP_EXTERNAL_TOOLS", "true") + normalized, compatibility, err := normalizeResponsesRequest([]byte(`{ + "model":"public","input":[ + {"type":"web_search_call","id":"ws_1","status":"completed"}, + {"type":"function_call","call_id":"call_1","name":"read_file","arguments":"{}"}, + {"type":"function_call_output","call_id":"call_1","output":"done"}, + {"type":"message","role":"user","content":"next"} + ] + }`), "grok-4.5") + if err != nil { + t.Fatal(err) + } + if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "external_tool_history_omitted") { + t.Fatalf("compatibility warnings = %#v", compatibility) + } + var request map[string]any + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + items := request["input"].([]any) + if items[0].(map[string]any)["role"] != "developer" { + t.Fatalf("input[0] = %#v", items[0]) + } + if items[1].(map[string]any)["type"] != "function_call" || + items[2].(map[string]any)["type"] != "function_call_output" || + items[3].(map[string]any)["role"] != "user" { + t.Fatalf("function history should be preserved: %#v", items) + } +} + func TestRequestRejectsAmbiguousShellDeclarations(t *testing.T) { _, _, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":"hello", @@ -92,13 +392,13 @@ func TestRequestRejectsAmbiguousShellDeclarations(t *testing.T) { func TestApplyPatchToolRequestHistoryAndJSONResponse(t *testing.T) { normalized, compatibility, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":"edit file", - "tools":[{"type":"apply_patch","strict":false}], + "tools":[{"type":"apply_patch"}], "tool_choice":{"type":"apply_patch"} }`), "grok-4.5") if err != nil { t.Fatal(err) } - if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "apply_patch_controls_ignored") { + if compatibility == nil { t.Fatal("apply_patch 未启用兼容层") } var request map[string]any @@ -194,20 +494,17 @@ func TestApplyPatchStreamBuffersFunctionProtocolAndRestoresItems(t *testing.T) { } func TestAdditionalToolsAndCompactionBoundaryRemainVisible(t *testing.T) { - normalized, compatibility, err := normalizeResponsesRequest([]byte(`{ + normalized, _, err := normalizeResponsesRequest([]byte(`{ "model":"public","tools":[{"type":"function","name":"lookup","description":"old","parameters":{"type":"object"}}], "input":[ {"type":"compaction_trigger"}, - {"type":"additional_tools","role":"user","tools":[{"type":"function","name":"lookup","description":"new","parameters":{"type":"object"}},{"type":"apply_patch"}]}, + {"type":"additional_tools","role":"developer","tools":[{"type":"function","name":"lookup","description":"new","parameters":{"type":"object"}},{"type":"apply_patch"}]}, {"type":"message","role":"user","content":[{"type":"input_text","text":"continue"}]} ] }`), "grok-4.5") if err != nil { t.Fatal(err) } - if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "additional_tools_role_approximated") { - t.Fatalf("compatibility = %#v", compatibility) - } var request map[string]any if err := json.Unmarshal(normalized, &request); err != nil { t.Fatal(err) diff --git a/backend/internal/infra/provider/cli/responses_history.go b/backend/internal/infra/provider/cli/responses_history.go index 9e52b741..fb8b13d9 100644 --- a/backend/internal/infra/provider/cli/responses_history.go +++ b/backend/internal/infra/provider/cli/responses_history.go @@ -19,22 +19,40 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, [] continue } param := fmt.Sprintf("input[%d]", index) - switch stringField(item, "type") { - case "function_call": - namespace := strings.TrimSpace(stringField(item, "namespace")) - if namespace == "" { - rewritten = append(rewritten, cloneJSONValue(item)) - continue + itemType := strings.TrimSpace(stringField(item, "type")) + // Codex/OpenAI may omit type on role-bearing message items. Force a + // known type before rewrite so untyped objects never reach ModelInput. + if itemType == "" && strings.TrimSpace(stringField(item, "role")) != "" { + itemType = "message" + } + switch itemType { + case "message": + converted, err := normalizeMessageInput(item, param) + if err != nil { + return nil, nil, nil, err } - name := strings.TrimSpace(stringField(item, "name")) - if name == "" { - return nil, nil, nil, &responsesRequestError{Message: param + ".name 不能为空", Param: param + ".name", Code: "invalid_parameter"} - } - converted := cloneJSONObject(item) - converted["name"] = c.alias(responsesToolIdentity{Kind: responsesFunctionTool, Namespace: namespace, Name: name}) - delete(converted, "namespace") c.changed = true rewritten = append(rewritten, converted) + case "function_call": + converted, err := c.normalizeFunctionCallInput(item, param) + if err != nil { + return nil, nil, nil, err + } + c.changed = true + rewritten = append(rewritten, converted) + case "function_call_output": + converted, err := normalizeFunctionCallOutputInput(item, param) + if err != nil { + return nil, nil, nil, err + } + c.changed = true + rewritten = append(rewritten, converted) + case "reasoning": + converted, changed := sanitizeReasoningInput(item) + if changed { + c.changed = true + } + rewritten = append(rewritten, converted) case "tool_search_call": callID := strings.TrimSpace(stringField(item, "call_id")) if callID == "" { @@ -49,7 +67,7 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, [] continue } if execution != "client" { - return nil, nil, nil, &responsesRequestError{Message: "tool_search_call.execution 必须是 client 或 server", Param: param + ".execution", Code: "invalid_parameter"} + return nil, nil, nil, &responsesRequestError{Message: "tool_search_call.execution 只支持 client 或 server", Param: param + ".execution", Code: "invalid_parameter"} } arguments, err := encodeFunctionArguments(item["arguments"]) if err != nil { @@ -63,7 +81,7 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, [] case "tool_search_output": execution := strings.ToLower(strings.TrimSpace(stringField(item, "execution"))) if execution != "" && execution != "client" && execution != "server" { - return nil, nil, nil, &responsesRequestError{Message: "tool_search_output.execution 必须是 client 或 server", Param: param + ".execution", Code: "invalid_parameter"} + return nil, nil, nil, &responsesRequestError{Message: "tool_search_output.execution 只支持 client 或 server", Param: param + ".execution", Code: "invalid_parameter"} } callID := strings.TrimSpace(stringField(item, "call_id")) if callID == "" { @@ -91,32 +109,17 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, [] rewritten = append(rewritten, compatibilityBoundaryMessage(message)) } case "custom_tool_call": - name := strings.TrimSpace(stringField(item, "name")) - if name == "" { - return nil, nil, nil, &responsesRequestError{Message: param + ".name 不能为空", Param: param + ".name", Code: "invalid_parameter"} - } - input, ok := item["input"].(string) - if !ok { - return nil, nil, nil, &responsesRequestError{Message: param + ".input 必须是字符串", Param: param + ".input", Code: "invalid_parameter"} - } - arguments, err := encodeCustomToolArguments(input) + converted, err := c.normalizeCustomToolCallInput(item, param) if err != nil { return nil, nil, nil, err } - namespace := strings.TrimSpace(stringField(item, "namespace")) - converted := cloneJSONObject(item) - converted["type"] = "function_call" - converted["name"] = c.alias(responsesToolIdentity{Kind: responsesCustomTool, Namespace: namespace, Name: name}) - converted["arguments"] = arguments - delete(converted, "input") - delete(converted, "namespace") c.changed = true rewritten = append(rewritten, converted) case "custom_tool_call_output": - converted := cloneJSONObject(item) - converted["type"] = "function_call_output" - delete(converted, "name") - delete(converted, "namespace") + converted, err := normalizeFunctionCallOutputInput(item, param) + if err != nil { + return nil, nil, nil, err + } c.changed = true rewritten = append(rewritten, converted) case "apply_patch_call": @@ -157,6 +160,13 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, [] } c.changed = true rewritten = append(rewritten, converted) + case "shell_call_output": + converted, err := normalizeShellCallOutputInput(item, param) + if err != nil { + return nil, nil, nil, err + } + c.changed = true + rewritten = append(rewritten, converted) case "mcp_tool_call_output": converted, err := normalizeMCPOutputInput(item, param) if err != nil { @@ -178,12 +188,140 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, [] c.changed = true rewritten = append(rewritten, marker) default: + if kind := strings.TrimSpace(stringField(item, "type")); kind != "" { + if c.stripExternal { + rewritten = append(rewritten, c.externalHistoryBoundary(item, kind)) + continue + } + c.changed = true + c.addWarning("unsupported_input_history_omitted") + rewritten = append(rewritten, unsupportedInputHistoryBoundary(item, kind)) + continue + } rewritten = append(rewritten, cloneJSONValue(item)) } } return rewritten, loadedTools, visibleTools, nil } +func (c *responsesToolCompatibility) normalizeFunctionCallInput(item map[string]any, param string) (map[string]any, error) { + name := strings.TrimSpace(stringField(item, "name")) + if name == "" { + return nil, &responsesRequestError{Message: param + ".name 不能为空", Param: param + ".name", Code: "invalid_parameter"} + } + callID := strings.TrimSpace(stringField(item, "call_id")) + if callID == "" { + return nil, &responsesRequestError{Message: param + ".call_id 不能为空", Param: param + ".call_id", Code: "invalid_parameter"} + } + arguments, err := encodeFunctionArguments(item["arguments"]) + if err != nil { + return nil, &responsesRequestError{Message: param + ".arguments 无法编码", Param: param + ".arguments", Code: "invalid_parameter"} + } + namespace := strings.TrimSpace(stringField(item, "namespace")) + if namespace != "" { + name = c.alias(responsesToolIdentity{Kind: responsesFunctionTool, Namespace: namespace, Name: name}) + } + // CLIProxyAPI constructs function_call with only type/call_id/name/arguments. + // Extra fields (id/status/namespace/metadata) break Grok's untagged ModelInput. + return map[string]any{"type": "function_call", "call_id": callID, "name": name, "arguments": arguments}, nil +} + +func (c *responsesToolCompatibility) normalizeCustomToolCallInput(item map[string]any, param string) (map[string]any, error) { + name := strings.TrimSpace(stringField(item, "name")) + if name == "" { + return nil, &responsesRequestError{Message: param + ".name 不能为空", Param: param + ".name", Code: "invalid_parameter"} + } + input, ok := item["input"].(string) + if !ok { + return nil, &responsesRequestError{Message: param + ".input 必须是字符串", Param: param + ".input", Code: "invalid_parameter"} + } + arguments, err := encodeCustomToolArguments(input) + if err != nil { + return nil, err + } + callID := strings.TrimSpace(stringField(item, "call_id")) + if callID == "" { + return nil, &responsesRequestError{Message: param + ".call_id 不能为空", Param: param + ".call_id", Code: "invalid_parameter"} + } + namespace := strings.TrimSpace(stringField(item, "namespace")) + return map[string]any{ + "type": "function_call", "call_id": callID, + "name": c.alias(responsesToolIdentity{Kind: responsesCustomTool, Namespace: namespace, Name: name}), + "arguments": arguments, + }, nil +} + +func sanitizeReasoningInput(item map[string]any) (map[string]any, bool) { + // Grok Build's untagged ModelInput rejects null-valued fields and Codex + // private metadata. Only keep portable non-null reasoning fields. + // + // Codex may emit reasoning items with summary text but null + // encrypted_content (common when the model returns a summary-only item). + // Replaying that shape 422s, so fall back to a developer boundary that + // preserves the visible summary without claiming encrypted state. + encrypted, hasEncrypted := nonNullJSONValue(item["encrypted_content"]) + if !hasEncrypted || strings.TrimSpace(fmt.Sprint(encrypted)) == "" { + summary := reasoningSummaryText(item["summary"]) + text := "A prior model reasoning item was omitted because it has no portable encrypted_content for Grok Build." + if summary != "" { + text += "\nSummary:\n" + summary + } + return compatibilityBoundaryMessage(text), true + } + + converted := map[string]any{"type": "reasoning", "encrypted_content": cloneJSONValue(encrypted)} + for _, key := range []string{"id", "summary", "content", "status"} { + if value, ok := nonNullJSONValue(item[key]); ok { + converted[key] = cloneJSONValue(value) + } + } + return converted, true +} + +func nonNullJSONValue(value any) (any, bool) { + if value == nil { + return nil, false + } + return value, true +} + +func reasoningSummaryText(raw any) string { + items, ok := raw.([]any) + if !ok { + return "" + } + parts := make([]string, 0, len(items)) + for _, rawItem := range items { + item, ok := rawItem.(map[string]any) + if !ok { + continue + } + if text := strings.TrimSpace(stringField(item, "text")); text != "" { + parts = append(parts, text) + } + } + return strings.Join(parts, "\n") +} + +func hasPrivateInputFields(item map[string]any) bool { + for _, key := range []string{"internal_chat_message_metadata_passthrough", "phase"} { + if _, exists := item[key]; exists { + return true + } + } + return false +} + +func unsupportedInputHistoryBoundary(item map[string]any, kind string) map[string]any { + parts := []string{"A prior Responses history item was omitted because Grok Build cannot deserialize this Codex item type.", "Type: " + kind} + for _, key := range []string{"id", "call_id", "name", "status"} { + if value := strings.TrimSpace(stringField(item, key)); value != "" { + parts = append(parts, strings.ReplaceAll(key, "_", " ")+": "+value) + } + } + return compatibilityBoundaryMessage(strings.Join(parts, "\n")) +} + func encodeFunctionArguments(value any) (string, error) { if text, ok := value.(string); ok { return text, nil diff --git a/backend/internal/infra/provider/cli/responses_input.go b/backend/internal/infra/provider/cli/responses_input.go index bb0cea08..e680177c 100644 --- a/backend/internal/infra/provider/cli/responses_input.go +++ b/backend/internal/infra/provider/cli/responses_input.go @@ -2,6 +2,7 @@ package cli import ( "encoding/json" + "fmt" "strings" ) @@ -57,6 +58,91 @@ func normalizeMCPOutputInput(item map[string]any, param string) (map[string]any, }, nil } +func normalizeMessageInput(item map[string]any, param string) (map[string]any, error) { + role := strings.TrimSpace(stringField(item, "role")) + if role == "" { + role = "assistant" + } + if role == "system" { + role = "developer" + } + content, err := normalizeMessageContent(item["content"], role, param+".content") + if err != nil { + return nil, err + } + // Rebuild with an allowlist only. Codex private fields (phase, metadata + // passthrough, status/id) are intentionally dropped for Grok ModelInput. + return map[string]any{"type": "message", "role": role, "content": content}, nil +} + +func messageTextPartType(role string) string { + switch strings.ToLower(strings.TrimSpace(role)) { + case "assistant", "model": + // Match CLIProxyAPI / OpenAI Responses construction: assistant history + // uses output_text; user/developer use input_text. + return "output_text" + default: + return "input_text" + } +} + +func normalizeMessageContent(value any, role, param string) (any, error) { + textPartType := messageTextPartType(role) + if text, ok := value.(string); ok { + return []any{map[string]any{"type": textPartType, "text": text}}, nil + } + items, ok := value.([]any) + if !ok { + return nil, &responsesRequestError{Message: param + " 必须是字符串或数组", Param: param, Code: "invalid_parameter"} + } + normalized := make([]any, 0, len(items)) + for index, raw := range items { + item, ok := raw.(map[string]any) + if !ok { + return nil, &responsesRequestError{Message: param + "[] 必须是对象", Param: fmt.Sprintf("%s[%d]", param, index), Code: "invalid_parameter"} + } + switch stringField(item, "type") { + case "text", "input_text", "output_text": + // Role-aware typing: do not coerce assistant output_text into input_text. + normalized = append(normalized, map[string]any{"type": textPartType, "text": stringField(item, "text")}) + case "refusal": + normalized = append(normalized, map[string]any{"type": textPartType, "text": stringField(item, "refusal")}) + case "input_image": + normalized = append(normalized, normalizeInputImagePart(item)) + case "input_file": + normalized = append(normalized, normalizeInputFilePart(item)) + default: + return nil, &responsesRequestError{Message: "Grok Build 0.2.99 不支持该 message.content 类型", Param: fmt.Sprintf("%s[%d].type", param, index), Code: "unsupported_parameter"} + } + } + return normalized, nil +} + +func normalizeInputImagePart(item map[string]any) map[string]any { + converted := map[string]any{"type": "input_image"} + if value, exists := item["image_url"]; exists { + converted["image_url"] = cloneJSONValue(value) + } else if value, exists := item["url"]; exists { + converted["image_url"] = cloneJSONValue(value) + } + for _, key := range []string{"detail", "file_id"} { + if value, exists := item[key]; exists { + converted[key] = cloneJSONValue(value) + } + } + return converted +} + +func normalizeInputFilePart(item map[string]any) map[string]any { + converted := map[string]any{"type": "input_file"} + for _, key := range []string{"file_data", "file_id", "filename", "file_url"} { + if value, exists := item[key]; exists { + converted[key] = cloneJSONValue(value) + } + } + return converted +} + func textInputContent(raw any) (string, bool) { if text, ok := raw.(string); ok { return text, true diff --git a/backend/internal/infra/provider/cli/responses_tool_choice.go b/backend/internal/infra/provider/cli/responses_tool_choice.go index fbbb2492..94cb96d2 100644 --- a/backend/internal/infra/provider/cli/responses_tool_choice.go +++ b/backend/internal/infra/provider/cli/responses_tool_choice.go @@ -11,6 +11,11 @@ func (c *responsesToolCompatibility) normalizeToolChoice(payload map[string]json if isEmptyJSON(raw) { return nil } + if c.stripExternal && len(normalizedTools) == 0 { + delete(payload, "tool_choice") + c.changed = true + return nil + } if len(normalizedTools) == 0 { delete(payload, "tool_choice") c.changed = true @@ -34,6 +39,12 @@ func (c *responsesToolCompatibility) normalizeToolChoice(payload map[string]json return nil } kind := stringField(object, "type") + if c.stripExternal && isExternalClientToolKind(kind) { + delete(payload, "tool_choice") + c.changed = true + c.addWarning("external_tool_choice_omitted") + return nil + } if c.webSearchDisabled && normalizeHostedToolChoiceKind(kind) == "web_search" && !hasToolType(normalizedTools, "web_search") { payload["tool_choice"] = mustJSON("none") c.changed = true diff --git a/backend/internal/infra/provider/cli/responses_tool_declarations.go b/backend/internal/infra/provider/cli/responses_tool_declarations.go index 2e2e7ec5..49905f08 100644 --- a/backend/internal/infra/provider/cli/responses_tool_declarations.go +++ b/backend/internal/infra/provider/cli/responses_tool_declarations.go @@ -69,6 +69,9 @@ func normalizeResponsesTools(payload map[string]json.RawMessage) (*responsesTool if err := compatibility.normalizeToolChoice(payload, normalizedTools); err != nil { return nil, err } + if err := compatibility.addDroppedToolsBoundary(payload); err != nil { + return nil, err + } if !compatibility.changed { return nil, nil } @@ -152,6 +155,10 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl return nil, &responsesRequestError{Message: param + " 必须是对象", Param: param, Code: "invalid_parameter"} } kind := strings.TrimSpace(stringField(tool, "type")) + if c.stripExternal && isExternalClientToolKind(kind) { + c.dropExternalTool(tool, namespace) + return nil, nil + } switch kind { case "function": name := strings.TrimSpace(stringField(tool, "name")) @@ -244,7 +251,7 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl case "local_shell": return c.normalizeLegacyLocalShellTool(tool, param) case "apply_patch": - return c.normalizeApplyPatchTool(tool, param) + return c.normalizeApplyPatchTool(tool, namespace, param) case "x_search", "image_generation", "collections_search", "file_search", "code_execution", "code_interpreter": return c.normalizeNativeTool(tool, param) case "computer_use_preview": @@ -304,3 +311,4 @@ func (c *responsesToolCompatibility) buildClientSearchFunction() (map[string]any "parameters": cloneJSONValue(parameters), }, nil } + diff --git a/backend/internal/infra/provider/cli/responses_tool_state.go b/backend/internal/infra/provider/cli/responses_tool_state.go index 015576d2..c8789199 100644 --- a/backend/internal/infra/provider/cli/responses_tool_state.go +++ b/backend/internal/infra/provider/cli/responses_tool_state.go @@ -5,6 +5,7 @@ import ( "encoding/hex" "encoding/json" "fmt" + "os" "strings" ) @@ -48,6 +49,8 @@ type responsesToolCompatibility struct { warnings []string warningSet map[string]struct{} changed bool + stripExternal bool + droppedTools []string } // responsesRequestError 表示可直接映射为 OpenAI 错误结构的 Provider 请求错误。 @@ -65,9 +68,99 @@ func newResponsesToolCompatibility() *responsesToolCompatibility { identityAliases: make(map[string]string), streamCalls: make(map[string]*responsesStreamCall), warningSet: make(map[string]struct{}), + stripExternal: stripExternalClientTools(), } } + +func stripExternalClientTools() bool { + switch strings.ToLower(strings.TrimSpace(os.Getenv("GROK2API_STRIP_EXTERNAL_TOOLS"))) { + case "1", "true", "yes", "on": + return true + default: + return false + } +} + +func isExternalClientToolKind(kind string) bool { + switch strings.TrimSpace(kind) { + case "computer_use_preview", + "web_search", "web_search_preview", "web_search_preview_2025_03_11", "web_search_2025_08_26": + return true + default: + return false + } +} + +func (c *responsesToolCompatibility) dropExternalTool(tool map[string]any, namespace string) { + name := strings.TrimSpace(stringField(tool, "name")) + if name == "" { + name = strings.TrimSpace(stringField(tool, "server_label")) + } + if name == "" { + name = strings.TrimSpace(stringField(tool, "type")) + } + if namespace != "" && name != "" { + name = namespace + "." + name + } + if name != "" { + c.droppedTools = append(c.droppedTools, name) + } + c.changed = true + c.addWarning("external_tools_omitted") +} + +func (c *responsesToolCompatibility) externalHistoryBoundary(item map[string]any, label string) map[string]any { + c.changed = true + c.addWarning("external_tool_history_omitted") + name := strings.TrimSpace(stringField(item, "name")) + if name == "" { + name = strings.TrimSpace(stringField(item, "type")) + } + callID := strings.TrimSpace(stringField(item, "call_id")) + text := "External tool history omitted for Grok Build compatibility." + if label != "" { + text += "\nKind: " + label + } + if name != "" { + text += "\nName: " + name + } + if callID != "" { + text += "\nCall ID: " + callID + } + return compatibilityBoundaryMessage(text) +} + +func (c *responsesToolCompatibility) addDroppedToolsBoundary(payload map[string]json.RawMessage) error { + if !c.stripExternal || len(c.droppedTools) == 0 { + return nil + } + text := "Client-side external tools are not available through this Grok Build upstream. Continue without calling those tools." + boundary := compatibilityBoundaryMessage(text) + raw := payload["input"] + if isEmptyJSON(raw) { + payload["input"] = mustJSON([]any{boundary}) + return nil + } + var input any + if err := json.Unmarshal(raw, &input); err != nil { + return &responsesRequestError{Message: "input 必须是字符串或数组", Param: "input", Code: "invalid_parameter"} + } + switch typed := input.(type) { + case string: + payload["input"] = mustJSON([]any{ + boundary, + map[string]any{"type": "message", "role": "user", "content": typed}, + }) + case []any: + payload["input"] = mustJSON(append([]any{boundary}, typed...)) + default: + return &responsesRequestError{Message: "input 必须是字符串或数组", Param: "input", Code: "invalid_parameter"} + } + c.changed = true + return nil +} + func (c *responsesToolCompatibility) alias(identity responsesToolIdentity) string { key := identity.key() if alias, exists := c.identityAliases[key]; exists { From 8bcf824bb841439878bba60efb4fa33e28eff2b2 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Fri, 17 Jul 2026 17:28:04 +0800 Subject: [PATCH 2/2] refactor: update Codex responses handling to support Grok Build 0.2.102 --- backend/docs/RESPONSES_MODELINPUT_NOTES.md | 287 ------------------ .../provider/cli/responses_codex_tools.go | 48 +-- .../cli/responses_codex_tools_test.go | 250 +++++++-------- .../infra/provider/cli/responses_history.go | 158 ++++++---- .../infra/provider/cli/responses_input.go | 65 ++-- .../provider/cli/responses_tool_choice.go | 11 - .../cli/responses_tool_declarations.go | 10 +- .../provider/cli/responses_tool_state.go | 93 ------ 8 files changed, 265 insertions(+), 657 deletions(-) delete mode 100644 backend/docs/RESPONSES_MODELINPUT_NOTES.md diff --git a/backend/docs/RESPONSES_MODELINPUT_NOTES.md b/backend/docs/RESPONSES_MODELINPUT_NOTES.md deleted file mode 100644 index 51bfd65d..00000000 --- a/backend/docs/RESPONSES_MODELINPUT_NOTES.md +++ /dev/null @@ -1,287 +0,0 @@ -# Grok Build Responses / ModelInput 注意事项 - -> 适用:Codex / OpenAI Responses 客户端 → `grok2api` → Grok Build `POST /v1/responses` -> 现象:首轮常成功,后续多轮历史回放时 422 -> 错误: -> -> ```text -> unexpected status 422 Unprocessable Entity: -> {"error":"Failed to deserialize the JSON body into the target type: -> data did not match any variant of untagged enum ModelInput"} -> ``` - -## 1. 结论(先看这个) - -Grok Build 0.2.99 的 `input[]` 使用 **Rust 风格 untagged enum `ModelInput`**,对历史 item 形状很严格: - -1. **不要原样透传 Codex 历史** -2. **必须白名单重建**每个 `input[]` item / content part -3. **禁止输出 `null` 字段**(尤其是 `reasoning`) -4. **禁止保留 Codex 私有字段** - -相关实现主要在: - -- `backend/internal/infra/provider/cli/responses_history.go` -- `backend/internal/infra/provider/cli/responses_input.go` -- `backend/internal/infra/provider/cli/responses_codex_tools.go` -- `backend/internal/infra/provider/cli/responses_tool_state.go` -- `backend/internal/infra/provider/cli/responses_tool_declarations.go` -- `backend/internal/infra/provider/cli/responses_tool_choice.go` - -## 2. 已确认会 422 的形状 - -### 2.1 `reasoning` 带 null 字段(高频,会话已复现) - -Codex 第二轮经常带回: - -```json -{ - "type": "reasoning", - "id": "rs_xxx", - "summary": [{"type": "summary_text", "text": "..."}], - "content": null, - "encrypted_content": null, - "internal_chat_message_metadata_passthrough": {"turn_id": "..."} -} -``` - -错误处理: - -```json -{ - "type": "reasoning", - "id": "rs_xxx", - "summary": [...], - "content": null, - "encrypted_content": null -} -``` - -正确处理: - -- 有可用 `encrypted_content`:只保留非 null 白名单字段回放 -- `encrypted_content` 缺失 / null / 空:降级为 developer boundary,保留 summary 文本 - **绝不要回放带 null 的 reasoning 对象** - -复现会话:`019f64fa-984d-73e2-be0e-c732978d3321` -(首轮 200,第二轮带 null reasoning 后 422) - -### 2.2 Codex 私有字段 - -几乎每条 Codex history 都会带: - -- `internal_chat_message_metadata_passthrough` -- `phase` - -这些字段不能进入上游 `input[]`。 - -### 2.3 assistant 文本类型写错 - -| role | 正确 content part type | -|---|---| -| `assistant` / `model` | `output_text` | -| `user` / `developer` / `system` | `input_text` | - -**错误做法:** 把 assistant 的 `output_text` 全改成 `input_text` -**正确做法:** 按 role 选择类型(对齐 CLIProxyAPI 的 construction 路径) - -### 2.4 function 历史字段过多 - -`function_call` 只允许: - -```json -{"type":"function_call","call_id":"...","name":"...","arguments":"..."} -``` - -`function_call_output` 只允许: - -```json -{"type":"function_call_output","call_id":"...","output":"..."} -``` - -不要带: - -- `id` -- `status` -- `namespace` -- `internal_chat_message_metadata_passthrough` -- 其他私有/扩展字段 - -`output` 必须是 **字符串**;对象要先 `json.Marshal` 成字符串。 - -### 2.5 未知 / 外部工具历史原样透传 - -以下类型不能原样发给 Grok Build,应改写成 developer boundary 或兼容 function 协议: - -- `web_search_call` -- 原始 `shell_call`(若上游不接受) -- 其他未知 `type` - -`GROK2API_STRIP_EXTERNAL_TOOLS=true` 时,还应剥离工具声明: - -- `web_search*` -- `computer_use_preview` - -保留 function-backed 工具:`function` / `apply_patch` / `tool_search` / `shell|local_shell`。 - -## 3. 推荐白名单模型 - -只向 Grok Build 发送这些 `input[]` 形态: - -### message - -```json -{ - "type": "message", - "role": "user|assistant|developer", - "content": [ - {"type": "input_text|output_text", "text": "..."}, - {"type": "input_image", "image_url": "..."}, - {"type": "input_file", "file_data": "...", "filename": "..."} - ] -} -``` - -注意: - -- 不带 `id` / `status` / `phase` / metadata -- content part 不带 `annotations` -- 有 `role` 但缺 `type` 时,先补 `"type":"message"` - -### function_call - -```json -{ - "type": "function_call", - "call_id": "call_xxx", - "name": "tool_name", - "arguments": "{}" -} -``` - -### function_call_output - -```json -{ - "type": "function_call_output", - "call_id": "call_xxx", - "output": "string only" -} -``` - -### reasoning - -```json -{ - "type": "reasoning", - "id": "rs_xxx", - "summary": [{"type":"summary_text","text":"..."}], - "encrypted_content": "non-empty cipher" -} -``` - -规则: - -- 只保留非 null 字段 -- 没有可用 `encrypted_content` 时,不要发 `type=reasoning`,改发 developer boundary - -### shell_call_output(如需保留) - -- `output` 必须是结构化数组块 -- outcome 使用 `exit_code`(不是 `exitCode`) -- 去掉未知块字段(如 `command`) - -### 其他未知类型 - -```json -{ - "type": "message", - "role": "developer", - "content": [ - { - "type": "input_text", - "text": "A prior Responses history item was omitted ..." - } - ] -} -``` - -## 4. 实现原则 - -1. **白名单重建,不要 clone 后删字段** - clone 容易把 `null` / 私有字段带回去。 - -2. **JSON 里不要出现 `null` 值** - Go 里 `map[string]any{"content": nil}` 会编码成 `"content":null`,对 untagged enum 很危险。 - -3. **对齐 CLIProxyAPI 的 construction,而不是它的 Responses passthrough** - CLIProxyAPI 没有 Grok 专用 adapter;它从 Chat/Claude/Gemini 构造 Codex input 时才会发出干净 item。 - Responses→Codex 本身几乎是 top-level 清洗,历史深字段不会帮你修。 - -4. **多轮问题优先查第二轮历史** - 典型模式: - - 第 1 轮:只有 user/developer message → 200 - - 第 2 轮:附带 assistant + reasoning(+null) / tool history → 422 - -5. **修完后要替换正在运行的 Docker 二进制** - 只改源码不重建容器,Codex 仍打旧逻辑。 - -## 5. 排查清单 - -遇到新的 ModelInput 422 时: - -1. 从 Docker 日志拿 `request_id` 与时间点 -2. 找到对应 Codex session rollout(`~/.codex/sessions/...jsonl`) -3. 统计第二轮 `response_item` 的 `type` 与额外字段 -4. 特别检查: - - `reasoning.content` / `reasoning.encrypted_content` 是否为 null - - 是否残留 `internal_chat_message_metadata_passthrough` / `phase` - - assistant content 是否不是 `output_text` - - `function_call*` 是否多了 `id/status` -5. 用 normalize 单测 / 临时 fixture 验证清洗结果里: - - 无 `null` - - 无私有字段 - - item 类型都在白名单 -6. `go test ./internal/infra/provider/cli/` -7. 编译 Linux 二进制并替换容器: - -```bash -cd backend -GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -o ../out/grok2api ./cmd/grok2api -docker cp ../out/grok2api grok2api:/app/grok2api -docker restart grok2api -curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:8000/healthz -docker commit grok2api grok2api:local -``` - -8. **新开 Codex 任务验证**(旧会话可能已污染) - -## 6. 相关测试 - -优先看 / 补充这些回归: - -- `TestAssistantOutputMessageHistoryKeepsOutputText` -- `TestNullEncryptedReasoningBecomesBoundary` -- `TestCodexPrivateMetadataIsStrippedFromHistory` -- `TestFunctionCallOutputHistoryEncodesStructuredOutput` -- `TestStripExternalClientToolHistory` -- `TestRoleMissingTypeBecomesMessageAndFunctionCallIsAllowlisted` - -## 7. 环境变量 - -| 变量 | 作用 | -|---|---| -| `GROK2API_STRIP_EXTERNAL_TOOLS=true` | 剥离 Grok Build 难托管的外部工具声明与对应历史,保留 function-backed 工具 | - -Docker Compose override 示例见仓库根目录 `docker-compose.override.yml`。 - -## 8. 参考会话 - -| Session ID | 现象 | -|---|---| -| `019f5ed1-ebd0-7183-8229-ae0bdaf88c9e` | 多轮 Codex 历史复杂,首次系统性排查 ModelInput 422 | -| `019f64fa-984d-73e2-be0e-c732978d3321` | 首轮 200,第二轮因 null `reasoning.encrypted_content` 422 | - -## 9. 一句话记住 - -> **Codex 历史不能透传;按白名单重建,role 决定 text 类型,reasoning 没有 cipher 就降级,任何 null / 私有字段都不要发给 Grok Build。** diff --git a/backend/internal/infra/provider/cli/responses_codex_tools.go b/backend/internal/infra/provider/cli/responses_codex_tools.go index 085e3279..6e58d3fa 100644 --- a/backend/internal/infra/provider/cli/responses_codex_tools.go +++ b/backend/internal/infra/provider/cli/responses_codex_tools.go @@ -19,7 +19,7 @@ func (c *responsesToolCompatibility) normalizeShellTool(tool map[string]any, par return c.normalizeNativeTool(tool, param) } -// normalizeLegacyLocalShellTool 将旧 Codex local_shell 升级为 0.2.99 原生 local shell 环境。 +// normalizeLegacyLocalShellTool 将旧 Codex local_shell 升级为 0.2.101 原生 local shell 环境。 func (c *responsesToolCompatibility) normalizeLegacyLocalShellTool(tool map[string]any, param string) ([]any, error) { if c.nativeShell || c.legacyLocalShell { return nil, &responsesRequestError{ @@ -27,13 +27,8 @@ func (c *responsesToolCompatibility) normalizeLegacyLocalShellTool(tool map[stri Param: param + ".type", Code: "invalid_parameter", } } - for key := range tool { - if key != "type" { - return nil, &responsesRequestError{ - Message: "旧版 local_shell 不支持额外配置字段", - Param: param + "." + key, Code: "unsupported_parameter", - } - } + if len(tool) > 1 { + c.addWarning("legacy_local_shell_controls_ignored") } c.legacyLocalShell = true c.changed = true @@ -45,20 +40,9 @@ func (c *responsesToolCompatibility) normalizeLegacyLocalShellTool(tool map[stri } // normalizeApplyPatchTool 将客户端执行的 apply_patch 包装为严格 function。 -func (c *responsesToolCompatibility) normalizeApplyPatchTool(tool map[string]any, namespace, param string) ([]any, error) { - if namespace != "" { - return nil, &responsesRequestError{ - Message: "namespace 内暂不支持 apply_patch", - Param: param + ".type", Code: "unsupported_parameter", - } - } - for key := range tool { - if key != "type" { - return nil, &responsesRequestError{ - Message: "apply_patch 不接受自定义字段", - Param: param + "." + key, Code: "unsupported_parameter", - } - } +func (c *responsesToolCompatibility) normalizeApplyPatchTool(tool map[string]any, param string) ([]any, error) { + if len(tool) > 1 { + c.addWarning("apply_patch_controls_ignored") } identity := responsesToolIdentity{Kind: responsesApplyPatchTool, Name: "apply_patch"} c.changed = true @@ -100,17 +84,11 @@ func (c *responsesToolCompatibility) normalizeApplyPatchCallInput(item map[strin if err != nil { return nil, err } - converted := map[string]any{ + return map[string]any{ "type": "function_call", "call_id": callID, "name": c.alias(responsesToolIdentity{Kind: responsesApplyPatchTool, Name: "apply_patch"}), "arguments": string(arguments), - } - for _, key := range []string{"id", "status"} { - if value, exists := item[key]; exists { - converted[key] = cloneJSONValue(value) - } - } - return converted, nil + }, nil } func normalizeApplyPatchOutputInput(item map[string]any, param string) (map[string]any, error) { @@ -202,7 +180,7 @@ func legacyShellAction(value any, param string) (map[string]any, error) { return nil, &responsesRequestError{Message: "local_shell_call.action 必须是对象", Param: param, Code: "invalid_parameter"} } if kind := strings.TrimSpace(stringField(action, "type")); kind != "" && kind != "exec" { - return nil, &responsesRequestError{Message: "local_shell_call.action.type 只支持 exec", Param: param + ".type", Code: "unsupported_parameter"} + return nil, &responsesRequestError{Message: "local_shell_call.action.type 必须是 exec", Param: param + ".type", Code: "invalid_parameter"} } command, err := legacyShellCommand(action, param) if err != nil { @@ -292,7 +270,7 @@ func normalizeLegacyLocalShellOutputInput(item map[string]any, param string) (ma return nil, &responsesRequestError{Message: "local_shell_call_output.output 必须是字符串或数组", Param: param + ".output", Code: "invalid_parameter"} } converted := map[string]any{"type": "shell_call_output", "call_id": callID, "output": output} - if value, exists := item["max_output_length"]; exists { + if value, exists := item["max_output_length"]; exists && value != nil { converted["max_output_length"] = cloneJSONValue(value) } return converted, nil @@ -308,7 +286,7 @@ func normalizeShellCallOutputInput(item map[string]any, param string) (map[strin return nil, err } converted := map[string]any{"type": "shell_call_output", "call_id": callID, "output": output} - if value, exists := item["max_output_length"]; exists { + if value, exists := item["max_output_length"]; exists && value != nil { converted["max_output_length"] = cloneJSONValue(value) } return converted, nil @@ -323,7 +301,7 @@ func normalizeFunctionCallOutputInput(item map[string]any, param string) (map[st if err != nil { return nil, err } - // Allowlist only. CLIProxyAPI builds function_call_output without id/status. + // 按官方 Build 回放结构重建,不携带输出态 id/status。 return map[string]any{"type": "function_call_output", "call_id": callID, "output": output}, nil } @@ -458,7 +436,7 @@ func validEnvironmentName(value string) bool { func (c *responsesToolCompatibility) normalizeAdditionalToolsInput(item map[string]any, param string) (map[string]any, []any, []any, error) { if role := strings.TrimSpace(stringField(item, "role")); role != "" && role != "developer" { - return nil, nil, nil, &responsesRequestError{Message: "additional_tools.role 只支持 developer", Param: param + ".role", Code: "unsupported_parameter"} + c.addWarning("additional_tools_role_approximated") } tools, ok := item["tools"].([]any) if !ok { diff --git a/backend/internal/infra/provider/cli/responses_codex_tools_test.go b/backend/internal/infra/provider/cli/responses_codex_tools_test.go index e536d58a..08d90be0 100644 --- a/backend/internal/infra/provider/cli/responses_codex_tools_test.go +++ b/backend/internal/infra/provider/cli/responses_codex_tools_test.go @@ -121,9 +121,10 @@ func TestFunctionCallOutputHistoryEncodesStructuredOutput(t *testing.T) { } } -func TestAssistantOutputMessageHistoryKeepsOutputText(t *testing.T) { +func TestAssistantOutputMessageHistoryUsesEasyMessageText(t *testing.T) { normalized, _, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":[ + {"type":"message","role":"system","content":"system instruction"}, {"id":"msg_1","type":"message","status":"completed","role":"assistant","content":[ {"type":"output_text","text":"Hi there","annotations":[]} ]}, @@ -138,15 +139,18 @@ func TestAssistantOutputMessageHistoryKeepsOutputText(t *testing.T) { t.Fatal(err) } items := request["input"].([]any) - first := items[0].(map[string]any) - second := items[1].(map[string]any) - firstContent := first["content"].([]any)[0].(map[string]any) - secondContent := second["content"].([]any)[0].(map[string]any) - if first["id"] != nil || first["status"] != nil || firstContent["type"] != "output_text" || firstContent["annotations"] != nil { - t.Fatalf("assistant message history = %#v", first) + system := items[0].(map[string]any) + assistant := items[1].(map[string]any) + user := items[2].(map[string]any) + userContent := user["content"].([]any)[0].(map[string]any) + if system["role"] != "system" || system["content"] != "system instruction" { + t.Fatalf("system message history = %#v", system) } - if secondContent["type"] != "input_text" { - t.Fatalf("user message history = %#v", second) + if assistant["id"] != nil || assistant["status"] != nil || assistant["content"] != "Hi there" { + t.Fatalf("assistant message history = %#v", assistant) + } + if userContent["type"] != "input_text" { + t.Fatalf("user message history = %#v", user) } } @@ -169,7 +173,7 @@ func TestRoleMissingTypeBecomesMessageAndFunctionCallIsAllowlisted(t *testing.T) user := items[0].(map[string]any) call := items[1].(map[string]any) output := items[2].(map[string]any) - if user["type"] != "message" || user["content"].([]any)[0].(map[string]any)["type"] != "input_text" { + if user["type"] != "message" || user["content"] != "hello" { t.Fatalf("user history = %#v", user) } if call["type"] != "function_call" || call["id"] != nil || call["status"] != nil || call["internal_chat_message_metadata_passthrough"] != nil { @@ -180,12 +184,13 @@ func TestRoleMissingTypeBecomesMessageAndFunctionCallIsAllowlisted(t *testing.T) } } -func TestUnsupportedResponsesHistoryItemsBecomeBoundaries(t *testing.T) { +func TestNativeBuildHistoryItemsArePreservedAndSanitized(t *testing.T) { normalized, _, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":[ - {"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"kept summary"}],"encrypted_content":"cipher"}, - {"type":"web_search_call","id":"ws_1","status":"completed"}, - {"type":"shell_call","call_id":"call_1","status":"completed","action":{"type":"exec","commands":["pwd"]}}, + {"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"Grok Build","sources":null},"phase":"commentary"}, + {"type":"shell_call","id":null,"call_id":"call_1","status":"completed","action":{"commands":["pwd"],"timeout_ms":null,"internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}}, + {"type":"shell_call_output","call_id":"call_1","output":[{"stdout":"/workspace\n","stderr":"","outcome":{"type":"exit","exit_code":0}}]}, + {"type":"code_interpreter_call","id":"ci_1","container_id":"container_1","status":"completed","code":"print(1)","outputs":null}, {"type":"message","role":"user","content":[{"type":"input_text","text":"continue"}]} ] }`), "grok-4.5") @@ -197,25 +202,28 @@ func TestUnsupportedResponsesHistoryItemsBecomeBoundaries(t *testing.T) { t.Fatal(err) } items := request["input"].([]any) - if items[0].(map[string]any)["type"] != "reasoning" || items[0].(map[string]any)["encrypted_content"] != "cipher" { - t.Fatalf("reasoning history = %#v", items[0]) + webSearch := items[0].(map[string]any) + searchAction := webSearch["action"].(map[string]any) + if webSearch["type"] != "web_search_call" || webSearch["phase"] != nil || searchAction["sources"] != nil { + t.Fatalf("web search history = %#v", webSearch) } - for index, raw := range items[1:3] { - item := raw.(map[string]any) - text := item["content"].([]any)[0].(map[string]any)["text"].(string) - if item["type"] != "message" || item["role"] != "developer" || !strings.Contains(text, "Type: ") { - t.Fatalf("item %d was not downgraded: %#v", index+1, item) - } + shellCall := items[1].(map[string]any) + shellAction := shellCall["action"].(map[string]any) + if shellCall["type"] != "shell_call" || shellCall["id"] != nil || shellAction["timeout_ms"] != nil || shellAction["internal_chat_message_metadata_passthrough"] != nil { + t.Fatalf("shell call history = %#v", shellCall) } - if items[3].(map[string]any)["role"] != "user" { - t.Fatalf("user message changed unexpectedly: %#v", items[3]) + if items[2].(map[string]any)["type"] != "shell_call_output" || items[3].(map[string]any)["type"] != "code_interpreter_call" || items[3].(map[string]any)["outputs"] != nil { + t.Fatalf("native tool history = %#v", items[2:4]) + } + if items[4].(map[string]any)["role"] != "user" { + t.Fatalf("user message changed unexpectedly: %#v", items[4]) } } -func TestNullEncryptedReasoningBecomesBoundary(t *testing.T) { +func TestReasoningWithoutEncryptedContentRemainsNative(t *testing.T) { normalized, _, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":[ - {"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"who am I"}],"content":null,"encrypted_content":null,"internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, + {"type":"reasoning","id":"rs_1","status":"completed","summary":[{"type":"summary_text","text":"who am I"}],"content":null,"encrypted_content":null,"internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, {"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}, {"type":"message","role":"user","content":[{"type":"input_text","text":"嗯"}]} ] @@ -229,22 +237,66 @@ func TestNullEncryptedReasoningBecomesBoundary(t *testing.T) { } items := request["input"].([]any) first := items[0].(map[string]any) - text := first["content"].([]any)[0].(map[string]any)["text"].(string) - if first["type"] != "message" || first["role"] != "developer" || first["encrypted_content"] != nil || first["content"] == nil { - t.Fatalf("null reasoning should become boundary: %#v", first) + if first["type"] != "reasoning" || first["status"] != nil || first["encrypted_content"] != nil || first["content"] != nil { + t.Fatalf("reasoning history = %#v", first) } - if !strings.Contains(text, "who am I") || strings.Contains(text, "null") { - t.Fatalf("boundary text = %q", text) + summary := first["summary"].([]any)[0].(map[string]any) + if summary["text"] != "who am I" { + t.Fatalf("reasoning summary = %#v", first["summary"]) } - if items[1].(map[string]any)["content"].([]any)[0].(map[string]any)["type"] != "output_text" { + if items[1].(map[string]any)["content"] != "hi" { t.Fatalf("assistant history = %#v", items[1]) } } +func TestUnsupportedResponsesHistoryItemBecomesBoundary(t *testing.T) { + normalized, _, err := normalizeResponsesRequest([]byte(`{ + "model":"public","input":[ + {"type":"future_codex_item","id":"future_1","status":"completed"}, + {"type":"message","role":"user","content":"continue"} + ] + }`), "grok-4.5") + if err != nil { + t.Fatal(err) + } + var request map[string]any + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + items := request["input"].([]any) + boundary := items[0].(map[string]any) + text := boundary["content"].([]any)[0].(map[string]any)["text"].(string) + if boundary["role"] != "developer" || !strings.Contains(text, "future_codex_item") || items[1].(map[string]any)["role"] != "user" { + t.Fatalf("normalized history = %#v", items) + } +} + +func TestMessageImageAndFileNullFieldsAreRemoved(t *testing.T) { + normalized, _, err := normalizeResponsesRequest([]byte(`{ + "model":"public","input":[{"type":"message","role":"user","content":[ + {"type":"input_image","image_url":"https://example.com/image.png","detail":null,"file_id":null}, + {"type":"input_file","file_id":"file_1","file_url":null,"filename":null} + ]}] + }`), "grok-4.5") + if err != nil { + t.Fatal(err) + } + var request map[string]any + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + content := request["input"].([]any)[0].(map[string]any)["content"].([]any) + image := content[0].(map[string]any) + file := content[1].(map[string]any) + if image["image_url"] == nil || image["detail"] != nil || image["file_id"] != nil || file["file_id"] != "file_1" || file["file_url"] != nil || file["filename"] != nil { + t.Fatalf("message content = %#v", content) + } +} + func TestCodexPrivateMetadataIsStrippedFromHistory(t *testing.T) { normalized, _, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":[ - {"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"plan"}],"encrypted_content":"cipher","internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, + {"type":"reasoning","id":"rs_1","status":"completed","summary":[{"type":"summary_text","text":"plan"}],"encrypted_content":"cipher","internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, {"type":"function_call","id":"fc_1","call_id":"call_1","name":"shell_command","arguments":"{}","internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, {"type":"function_call_output","id":"fco_1","call_id":"call_1","output":"ok","internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, {"type":"custom_tool_call","id":"ctc_1","call_id":"call_2","name":"apply_patch","input":"patch","status":"completed","internal_chat_message_metadata_passthrough":{"turn_id":"t1"}}, @@ -266,7 +318,7 @@ func TestCodexPrivateMetadataIsStrippedFromHistory(t *testing.T) { } } items := request["input"].([]any) - if items[0].(map[string]any)["type"] != "reasoning" || items[0].(map[string]any)["encrypted_content"] != "cipher" { + if items[0].(map[string]any)["type"] != "reasoning" || items[0].(map[string]any)["encrypted_content"] != "cipher" || items[0].(map[string]any)["status"] != nil { t.Fatalf("reasoning history = %#v", items[0]) } if items[1].(map[string]any)["type"] != "function_call" || items[3].(map[string]any)["type"] != "function_call" { @@ -277,107 +329,6 @@ func TestCodexPrivateMetadataIsStrippedFromHistory(t *testing.T) { } } -func TestStripExternalClientToolsKeepsFunctionBackedTools(t *testing.T) { - t.Setenv("GROK2API_STRIP_EXTERNAL_TOOLS", "true") - normalized, compatibility, err := normalizeResponsesRequest([]byte(`{ - "model":"public","input":"hello", - "tools":[ - {"type":"function","name":"read_file","parameters":{"type":"object"}}, - {"type":"apply_patch"}, - {"type":"tool_search","execution":"client"}, - {"type":"web_search","external_web_access":false}, - {"type":"local_shell"} - ], - "tool_choice":{"type":"apply_patch"} - }`), "grok-4.5") - if err != nil { - t.Fatal(err) - } - if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "external_tools_omitted") { - t.Fatalf("compatibility warnings = %#v", compatibility) - } - var request map[string]any - if err := json.Unmarshal(normalized, &request); err != nil { - t.Fatal(err) - } - tools := request["tools"].([]any) - if len(tools) != 4 { - t.Fatalf("normalized tools = %#v choice=%#v", tools, request["tool_choice"]) - } - seen := map[string]bool{} - for _, rawTool := range tools { - tool := rawTool.(map[string]any) - switch tool["type"] { - case "function": - seen[tool["name"].(string)] = true - case "shell": - seen["shell"] = true - } - if tool["type"] == "web_search" { - t.Fatalf("web_search should be omitted: %#v", tools) - } - } - choice := request["tool_choice"].(map[string]any) - if !seen["read_file"] || !seen["grok2api_apply_patch"] || !seen["grok2api_tool_search"] || !seen["shell"] || - choice["type"] != "function" || choice["name"] != "grok2api_apply_patch" { - t.Fatalf("normalized tools = %#v choice=%#v", tools, request["tool_choice"]) - } - input := request["input"].([]any) - if input[0].(map[string]any)["role"] != "developer" || input[1].(map[string]any)["role"] != "user" { - t.Fatalf("input boundary = %#v", input) - } -} - -func TestStripExternalClientToolsRemovesStringToolChoice(t *testing.T) { - t.Setenv("GROK2API_STRIP_EXTERNAL_TOOLS", "true") - normalized, _, err := normalizeResponsesRequest([]byte(`{ - "model":"public","input":"hello", - "tools":[{"type":"web_search","external_web_access":false}], - "tool_choice":"auto" - }`), "grok-4.5") - if err != nil { - t.Fatal(err) - } - var request map[string]any - if err := json.Unmarshal(normalized, &request); err != nil { - t.Fatal(err) - } - if request["tools"] != nil || request["tool_choice"] != nil { - t.Fatalf("tools/tool_choice should be omitted: %#v", request) - } -} - -func TestStripExternalClientToolHistory(t *testing.T) { - t.Setenv("GROK2API_STRIP_EXTERNAL_TOOLS", "true") - normalized, compatibility, err := normalizeResponsesRequest([]byte(`{ - "model":"public","input":[ - {"type":"web_search_call","id":"ws_1","status":"completed"}, - {"type":"function_call","call_id":"call_1","name":"read_file","arguments":"{}"}, - {"type":"function_call_output","call_id":"call_1","output":"done"}, - {"type":"message","role":"user","content":"next"} - ] - }`), "grok-4.5") - if err != nil { - t.Fatal(err) - } - if compatibility == nil || !strings.Contains(compatibility.warningHeader(), "external_tool_history_omitted") { - t.Fatalf("compatibility warnings = %#v", compatibility) - } - var request map[string]any - if err := json.Unmarshal(normalized, &request); err != nil { - t.Fatal(err) - } - items := request["input"].([]any) - if items[0].(map[string]any)["role"] != "developer" { - t.Fatalf("input[0] = %#v", items[0]) - } - if items[1].(map[string]any)["type"] != "function_call" || - items[2].(map[string]any)["type"] != "function_call_output" || - items[3].(map[string]any)["role"] != "user" { - t.Fatalf("function history should be preserved: %#v", items) - } -} - func TestRequestRejectsAmbiguousShellDeclarations(t *testing.T) { _, _, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":"hello", @@ -389,6 +340,33 @@ func TestRequestRejectsAmbiguousShellDeclarations(t *testing.T) { } } +func TestOptionalCompatibilityControlsAreIgnored(t *testing.T) { + normalized, compatibility, err := normalizeResponsesRequest([]byte(`{ + "model":"public", + "tools":[{"type":"local_shell","display_width":120},{"type":"apply_patch","mode":"auto"}], + "input":[{"type":"additional_tools","role":"user","tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}]}] + }`), "grok-4.5") + if err != nil { + t.Fatal(err) + } + if compatibility == nil { + t.Fatal("兼容字段未触发归一化") + } + warnings := compatibility.warningHeader() + for _, expected := range []string{"legacy_local_shell_controls_ignored", "apply_patch_controls_ignored", "additional_tools_role_approximated"} { + if !strings.Contains(warnings, expected) { + t.Fatalf("warnings = %q", warnings) + } + } + var request map[string]any + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + if len(request["tools"].([]any)) != 3 { + t.Fatalf("tools = %#v", request["tools"]) + } +} + func TestApplyPatchToolRequestHistoryAndJSONResponse(t *testing.T) { normalized, compatibility, err := normalizeResponsesRequest([]byte(`{ "model":"public","input":"edit file", @@ -445,7 +423,7 @@ func TestApplyPatchToolRequestHistoryAndJSONResponse(t *testing.T) { t.Fatal(err) } items := request["input"].([]any) - if items[0].(map[string]any)["type"] != "function_call" || !strings.Contains(items[0].(map[string]any)["arguments"].(string), `"delete_file"`) { + if items[0].(map[string]any)["type"] != "function_call" || items[0].(map[string]any)["id"] != nil || items[0].(map[string]any)["status"] != nil || !strings.Contains(items[0].(map[string]any)["arguments"].(string), `"delete_file"`) { t.Fatalf("apply patch call history = %#v", items[0]) } if items[1].(map[string]any)["type"] != "function_call_output" || !strings.Contains(items[1].(map[string]any)["output"].(string), "failed") { diff --git a/backend/internal/infra/provider/cli/responses_history.go b/backend/internal/infra/provider/cli/responses_history.go index fb8b13d9..555d1c4c 100644 --- a/backend/internal/infra/provider/cli/responses_history.go +++ b/backend/internal/infra/provider/cli/responses_history.go @@ -20,8 +20,8 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, [] } param := fmt.Sprintf("input[%d]", index) itemType := strings.TrimSpace(stringField(item, "type")) - // Codex/OpenAI may omit type on role-bearing message items. Force a - // known type before rewrite so untyped objects never reach ModelInput. + // Codex/OpenAI 可能省略带 role 消息的 type;在重建前补成明确消息, + // 避免无类型对象直接进入 ModelInput。 if itemType == "" && strings.TrimSpace(stringField(item, "role")) != "" { itemType = "message" } @@ -48,10 +48,15 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, [] c.changed = true rewritten = append(rewritten, converted) case "reasoning": - converted, changed := sanitizeReasoningInput(item) - if changed { - c.changed = true - } + converted := sanitizeReasoningInput(item) + c.changed = true + rewritten = append(rewritten, converted) + case "file_search_call", "web_search_call", "image_generation_call", "code_interpreter_call", + "shell_call", "mcp_list_tools", "mcp_approval_request", "mcp_approval_response", "mcp_call", "compaction": + // 这些类型已进入 Grok Build 0.2.101 的 Responses InputItem 契约。 + // 仅清理 Codex 私有字段和 null,不能把原生调用降级成文本边界。 + converted := sanitizeNativeHistoryInput(item, itemType) + c.changed = true rewritten = append(rewritten, converted) case "tool_search_call": callID := strings.TrimSpace(stringField(item, "call_id")) @@ -189,10 +194,6 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, [] rewritten = append(rewritten, marker) default: if kind := strings.TrimSpace(stringField(item, "type")); kind != "" { - if c.stripExternal { - rewritten = append(rewritten, c.externalHistoryBoundary(item, kind)) - continue - } c.changed = true c.addWarning("unsupported_input_history_omitted") rewritten = append(rewritten, unsupportedInputHistoryBoundary(item, kind)) @@ -221,8 +222,8 @@ func (c *responsesToolCompatibility) normalizeFunctionCallInput(item map[string] if namespace != "" { name = c.alias(responsesToolIdentity{Kind: responsesFunctionTool, Namespace: namespace, Name: name}) } - // CLIProxyAPI constructs function_call with only type/call_id/name/arguments. - // Extra fields (id/status/namespace/metadata) break Grok's untagged ModelInput. + // 按官方 Build 回放结构仅保留四个输入字段,避免输出态字段和私有元数据 + // 干扰 Grok 的 untagged ModelInput 反序列化。 return map[string]any{"type": "function_call", "call_id": callID, "name": name, "arguments": arguments}, nil } @@ -251,67 +252,98 @@ func (c *responsesToolCompatibility) normalizeCustomToolCallInput(item map[strin }, nil } -func sanitizeReasoningInput(item map[string]any) (map[string]any, bool) { - // Grok Build's untagged ModelInput rejects null-valued fields and Codex - // private metadata. Only keep portable non-null reasoning fields. - // - // Codex may emit reasoning items with summary text but null - // encrypted_content (common when the model returns a summary-only item). - // Replaying that shape 422s, so fall back to a developer boundary that - // preserves the visible summary without claiming encrypted state. - encrypted, hasEncrypted := nonNullJSONValue(item["encrypted_content"]) - if !hasEncrypted || strings.TrimSpace(fmt.Sprint(encrypted)) == "" { - summary := reasoningSummaryText(item["summary"]) - text := "A prior model reasoning item was omitted because it has no portable encrypted_content for Grok Build." - if summary != "" { - text += "\nSummary:\n" + summary - } - return compatibilityBoundaryMessage(text), true +func sanitizeReasoningInput(item map[string]any) map[string]any { + // 官方 Grok Build 回放 reasoning 时会删除 output-only status,但会保留 + // id、summary、content 和可选 encrypted_content。密文不是回放的前置条件。 + converted := copyNonNullHistoryFields(item, "id", "summary", "content", "encrypted_content") + converted["type"] = "reasoning" + if !hasPortableReasoningContent(converted) { + return compatibilityBoundaryMessage("A prior model reasoning item was omitted because it has no portable content for Grok Build.") } - - converted := map[string]any{"type": "reasoning", "encrypted_content": cloneJSONValue(encrypted)} - for _, key := range []string{"id", "summary", "content", "status"} { - if value, ok := nonNullJSONValue(item[key]); ok { - converted[key] = cloneJSONValue(value) - } - } - return converted, true + return converted } -func nonNullJSONValue(value any) (any, bool) { - if value == nil { - return nil, false +func hasPortableReasoningContent(item map[string]any) bool { + if encrypted, ok := item["encrypted_content"].(string); ok && strings.TrimSpace(encrypted) != "" { + return true } - return value, true -} - -func reasoningSummaryText(raw any) string { - items, ok := raw.([]any) - if !ok { - return "" - } - parts := make([]string, 0, len(items)) - for _, rawItem := range items { - item, ok := rawItem.(map[string]any) - if !ok { - continue - } - if text := strings.TrimSpace(stringField(item, "text")); text != "" { - parts = append(parts, text) - } - } - return strings.Join(parts, "\n") -} - -func hasPrivateInputFields(item map[string]any) bool { - for _, key := range []string{"internal_chat_message_metadata_passthrough", "phase"} { - if _, exists := item[key]; exists { + for _, key := range []string{"summary", "content"} { + if values, ok := item[key].([]any); ok && len(values) > 0 { return true } } return false } +// sanitizeNativeHistoryInput 按 Grok Build 0.2.101 的原生 InputItem 字段重建历史, +// 避免 Codex 扩展元数据干扰 Rust untagged enum 的反序列化。 +func sanitizeNativeHistoryInput(item map[string]any, itemType string) map[string]any { + var fields []string + switch itemType { + case "file_search_call": + fields = []string{"id", "queries", "status", "results"} + case "web_search_call": + fields = []string{"action", "id", "status"} + case "image_generation_call": + fields = []string{"id", "result", "status"} + case "code_interpreter_call": + fields = []string{"code", "container_id", "id", "outputs", "status"} + case "shell_call": + fields = []string{"id", "call_id", "action", "status", "environment"} + case "mcp_list_tools": + fields = []string{"id", "server_label", "tools", "error"} + case "mcp_approval_request": + fields = []string{"arguments", "id", "name", "server_label"} + case "mcp_approval_response": + fields = []string{"approval_request_id", "approve", "id", "reason"} + case "mcp_call": + fields = []string{"arguments", "id", "name", "server_label", "approval_request_id", "error", "output", "status"} + case "compaction": + fields = []string{"id", "encrypted_content"} + } + converted := copyNonNullHistoryFields(item, fields...) + converted["type"] = itemType + return converted +} + +func copyNonNullHistoryFields(item map[string]any, fields ...string) map[string]any { + converted := make(map[string]any, len(fields)+1) + for _, key := range fields { + if value, ok := sanitizeHistoryJSONValue(item[key]); ok { + converted[key] = value + } + } + return converted +} + +func sanitizeHistoryJSONValue(value any) (any, bool) { + switch typed := value.(type) { + case nil: + return nil, false + case map[string]any: + cleaned := make(map[string]any, len(typed)) + for key, nested := range typed { + if key == "phase" || key == "internal_chat_message_metadata_passthrough" { + continue + } + if normalized, ok := sanitizeHistoryJSONValue(nested); ok { + cleaned[key] = normalized + } + } + return cleaned, true + case []any: + cleaned := make([]any, 0, len(typed)) + for _, nested := range typed { + if normalized, ok := sanitizeHistoryJSONValue(nested); ok { + cleaned = append(cleaned, normalized) + } + } + return cleaned, true + default: + return cloneJSONValue(value), true + } +} + func unsupportedInputHistoryBoundary(item map[string]any, kind string) map[string]any { parts := []string{"A prior Responses history item was omitted because Grok Build cannot deserialize this Codex item type.", "Type: " + kind} for _, key := range []string{"id", "call_id", "name", "status"} { diff --git a/backend/internal/infra/provider/cli/responses_input.go b/backend/internal/infra/provider/cli/responses_input.go index e680177c..23e77e33 100644 --- a/backend/internal/infra/provider/cli/responses_input.go +++ b/backend/internal/infra/provider/cli/responses_input.go @@ -63,38 +63,57 @@ func normalizeMessageInput(item map[string]any, param string) (map[string]any, e if role == "" { role = "assistant" } - if role == "system" { - role = "developer" + if role == "model" { + role = "assistant" } content, err := normalizeMessageContent(item["content"], role, param+".content") if err != nil { return nil, err } - // Rebuild with an allowlist only. Codex private fields (phase, metadata - // passthrough, status/id) are intentionally dropped for Grok ModelInput. + // 仅按白名单重建,避免 Codex 的 phase、metadata、status、id 等 + // 非输入字段进入 Grok ModelInput。 return map[string]any{"type": "message", "role": role, "content": content}, nil } -func messageTextPartType(role string) string { - switch strings.ToLower(strings.TrimSpace(role)) { - case "assistant", "model": - // Match CLIProxyAPI / OpenAI Responses construction: assistant history - // uses output_text; user/developer use input_text. - return "output_text" - default: - return "input_text" - } -} - func normalizeMessageContent(value any, role, param string) (any, error) { - textPartType := messageTextPartType(role) if text, ok := value.(string); ok { - return []any{map[string]any{"type": textPartType, "text": text}}, nil + return text, nil } items, ok := value.([]any) if !ok { return nil, &responsesRequestError{Message: param + " 必须是字符串或数组", Param: param, Code: "invalid_parameter"} } + // 官方 Grok CLI 会把 assistant 的多个输出文本合并为 EasyInputMessage + // 字符串,既保留语义,也绕开 OutputMessage 对 id/status 的输入限制。 + if role == "assistant" { + texts := make([]string, 0, len(items)) + for _, raw := range items { + item, isObject := raw.(map[string]any) + if !isObject { + texts = nil + break + } + switch stringField(item, "type") { + case "text", "input_text", "output_text": + texts = append(texts, stringField(item, "text")) + case "refusal": + texts = append(texts, stringField(item, "refusal")) + default: + texts = nil + } + if texts == nil { + break + } + } + if texts != nil { + return strings.Join(texts, "\n"), nil + } + } + + textPartType := "input_text" + if role == "assistant" { + textPartType = "output_text" + } normalized := make([]any, 0, len(items)) for index, raw := range items { item, ok := raw.(map[string]any) @@ -103,7 +122,7 @@ func normalizeMessageContent(value any, role, param string) (any, error) { } switch stringField(item, "type") { case "text", "input_text", "output_text": - // Role-aware typing: do not coerce assistant output_text into input_text. + // 按角色重建文本类型,不能把 assistant 的 output_text 改成 input_text。 normalized = append(normalized, map[string]any{"type": textPartType, "text": stringField(item, "text")}) case "refusal": normalized = append(normalized, map[string]any{"type": textPartType, "text": stringField(item, "refusal")}) @@ -112,7 +131,7 @@ func normalizeMessageContent(value any, role, param string) (any, error) { case "input_file": normalized = append(normalized, normalizeInputFilePart(item)) default: - return nil, &responsesRequestError{Message: "Grok Build 0.2.99 不支持该 message.content 类型", Param: fmt.Sprintf("%s[%d].type", param, index), Code: "unsupported_parameter"} + return nil, &responsesRequestError{Message: "Grok Build 0.2.101 不支持该 message.content 类型", Param: fmt.Sprintf("%s[%d].type", param, index), Code: "unsupported_parameter"} } } return normalized, nil @@ -120,13 +139,13 @@ func normalizeMessageContent(value any, role, param string) (any, error) { func normalizeInputImagePart(item map[string]any) map[string]any { converted := map[string]any{"type": "input_image"} - if value, exists := item["image_url"]; exists { + if value, exists := item["image_url"]; exists && value != nil { converted["image_url"] = cloneJSONValue(value) - } else if value, exists := item["url"]; exists { + } else if value, exists := item["url"]; exists && value != nil { converted["image_url"] = cloneJSONValue(value) } for _, key := range []string{"detail", "file_id"} { - if value, exists := item[key]; exists { + if value, exists := item[key]; exists && value != nil { converted[key] = cloneJSONValue(value) } } @@ -136,7 +155,7 @@ func normalizeInputImagePart(item map[string]any) map[string]any { func normalizeInputFilePart(item map[string]any) map[string]any { converted := map[string]any{"type": "input_file"} for _, key := range []string{"file_data", "file_id", "filename", "file_url"} { - if value, exists := item[key]; exists { + if value, exists := item[key]; exists && value != nil { converted[key] = cloneJSONValue(value) } } diff --git a/backend/internal/infra/provider/cli/responses_tool_choice.go b/backend/internal/infra/provider/cli/responses_tool_choice.go index 94cb96d2..fbbb2492 100644 --- a/backend/internal/infra/provider/cli/responses_tool_choice.go +++ b/backend/internal/infra/provider/cli/responses_tool_choice.go @@ -11,11 +11,6 @@ func (c *responsesToolCompatibility) normalizeToolChoice(payload map[string]json if isEmptyJSON(raw) { return nil } - if c.stripExternal && len(normalizedTools) == 0 { - delete(payload, "tool_choice") - c.changed = true - return nil - } if len(normalizedTools) == 0 { delete(payload, "tool_choice") c.changed = true @@ -39,12 +34,6 @@ func (c *responsesToolCompatibility) normalizeToolChoice(payload map[string]json return nil } kind := stringField(object, "type") - if c.stripExternal && isExternalClientToolKind(kind) { - delete(payload, "tool_choice") - c.changed = true - c.addWarning("external_tool_choice_omitted") - return nil - } if c.webSearchDisabled && normalizeHostedToolChoiceKind(kind) == "web_search" && !hasToolType(normalizedTools, "web_search") { payload["tool_choice"] = mustJSON("none") c.changed = true diff --git a/backend/internal/infra/provider/cli/responses_tool_declarations.go b/backend/internal/infra/provider/cli/responses_tool_declarations.go index 49905f08..2e2e7ec5 100644 --- a/backend/internal/infra/provider/cli/responses_tool_declarations.go +++ b/backend/internal/infra/provider/cli/responses_tool_declarations.go @@ -69,9 +69,6 @@ func normalizeResponsesTools(payload map[string]json.RawMessage) (*responsesTool if err := compatibility.normalizeToolChoice(payload, normalizedTools); err != nil { return nil, err } - if err := compatibility.addDroppedToolsBoundary(payload); err != nil { - return nil, err - } if !compatibility.changed { return nil, nil } @@ -155,10 +152,6 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl return nil, &responsesRequestError{Message: param + " 必须是对象", Param: param, Code: "invalid_parameter"} } kind := strings.TrimSpace(stringField(tool, "type")) - if c.stripExternal && isExternalClientToolKind(kind) { - c.dropExternalTool(tool, namespace) - return nil, nil - } switch kind { case "function": name := strings.TrimSpace(stringField(tool, "name")) @@ -251,7 +244,7 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl case "local_shell": return c.normalizeLegacyLocalShellTool(tool, param) case "apply_patch": - return c.normalizeApplyPatchTool(tool, namespace, param) + return c.normalizeApplyPatchTool(tool, param) case "x_search", "image_generation", "collections_search", "file_search", "code_execution", "code_interpreter": return c.normalizeNativeTool(tool, param) case "computer_use_preview": @@ -311,4 +304,3 @@ func (c *responsesToolCompatibility) buildClientSearchFunction() (map[string]any "parameters": cloneJSONValue(parameters), }, nil } - diff --git a/backend/internal/infra/provider/cli/responses_tool_state.go b/backend/internal/infra/provider/cli/responses_tool_state.go index c8789199..015576d2 100644 --- a/backend/internal/infra/provider/cli/responses_tool_state.go +++ b/backend/internal/infra/provider/cli/responses_tool_state.go @@ -5,7 +5,6 @@ import ( "encoding/hex" "encoding/json" "fmt" - "os" "strings" ) @@ -49,8 +48,6 @@ type responsesToolCompatibility struct { warnings []string warningSet map[string]struct{} changed bool - stripExternal bool - droppedTools []string } // responsesRequestError 表示可直接映射为 OpenAI 错误结构的 Provider 请求错误。 @@ -68,99 +65,9 @@ func newResponsesToolCompatibility() *responsesToolCompatibility { identityAliases: make(map[string]string), streamCalls: make(map[string]*responsesStreamCall), warningSet: make(map[string]struct{}), - stripExternal: stripExternalClientTools(), } } - -func stripExternalClientTools() bool { - switch strings.ToLower(strings.TrimSpace(os.Getenv("GROK2API_STRIP_EXTERNAL_TOOLS"))) { - case "1", "true", "yes", "on": - return true - default: - return false - } -} - -func isExternalClientToolKind(kind string) bool { - switch strings.TrimSpace(kind) { - case "computer_use_preview", - "web_search", "web_search_preview", "web_search_preview_2025_03_11", "web_search_2025_08_26": - return true - default: - return false - } -} - -func (c *responsesToolCompatibility) dropExternalTool(tool map[string]any, namespace string) { - name := strings.TrimSpace(stringField(tool, "name")) - if name == "" { - name = strings.TrimSpace(stringField(tool, "server_label")) - } - if name == "" { - name = strings.TrimSpace(stringField(tool, "type")) - } - if namespace != "" && name != "" { - name = namespace + "." + name - } - if name != "" { - c.droppedTools = append(c.droppedTools, name) - } - c.changed = true - c.addWarning("external_tools_omitted") -} - -func (c *responsesToolCompatibility) externalHistoryBoundary(item map[string]any, label string) map[string]any { - c.changed = true - c.addWarning("external_tool_history_omitted") - name := strings.TrimSpace(stringField(item, "name")) - if name == "" { - name = strings.TrimSpace(stringField(item, "type")) - } - callID := strings.TrimSpace(stringField(item, "call_id")) - text := "External tool history omitted for Grok Build compatibility." - if label != "" { - text += "\nKind: " + label - } - if name != "" { - text += "\nName: " + name - } - if callID != "" { - text += "\nCall ID: " + callID - } - return compatibilityBoundaryMessage(text) -} - -func (c *responsesToolCompatibility) addDroppedToolsBoundary(payload map[string]json.RawMessage) error { - if !c.stripExternal || len(c.droppedTools) == 0 { - return nil - } - text := "Client-side external tools are not available through this Grok Build upstream. Continue without calling those tools." - boundary := compatibilityBoundaryMessage(text) - raw := payload["input"] - if isEmptyJSON(raw) { - payload["input"] = mustJSON([]any{boundary}) - return nil - } - var input any - if err := json.Unmarshal(raw, &input); err != nil { - return &responsesRequestError{Message: "input 必须是字符串或数组", Param: "input", Code: "invalid_parameter"} - } - switch typed := input.(type) { - case string: - payload["input"] = mustJSON([]any{ - boundary, - map[string]any{"type": "message", "role": "user", "content": typed}, - }) - case []any: - payload["input"] = mustJSON(append([]any{boundary}, typed...)) - default: - return &responsesRequestError{Message: "input 必须是字符串或数组", Param: "input", Code: "invalid_parameter"} - } - c.changed = true - return nil -} - func (c *responsesToolCompatibility) alias(identity responsesToolIdentity) string { key := identity.key() if alias, exists := c.identityAliases[key]; exists {