AIStudio2API icon indicating copy to clipboard operation
AIStudio2API copied to clipboard

[Feature/Bug] /v1/responses 接口不支持 Codex 多智能体通信类型 "agent_message" 导致 400 报错

Open altiar1233 opened this issue 3 weeks ago • 2 comments

问题描述

在将 AIStudio2API 作为 Codex(OpenAI 官方客户端,版本 0.166+)的自定义 responses 提供方使用时,如果触发了 Codex 的多智能体协作或跨 Agent 委派任务(inter_agent_communication),请求会被反代服务拒绝并报错:

HTTP 400 Bad Request
{
  "error": {
    "message": "unsupported input item type \"agent_message\"",
    "type": "invalid_request_error",
    "param": null,
    "code": "invalid_request"
  }
}
复现环境
AIStudio2API 版本:v0.3.3 / v0.3.4
客户端:Codex Desktop / Codex CLI
接口协议:wire_api = "responses" (/v1/responses)
模型:gemini-4-argon / gemini-3.8-flash 等
报错日志与原因定位
查看 Codex 客户端本地跟踪日志(logs_2.sqlite):

text

submission_dispatch{operation="inter_agent_communication"}
Turn error: {"error":{"message":"unsupported input item type \"agent_message\"","type":"invalid_request_error"}}
在服务端处理 /v1/responses 的 input 数组转换时,Codex 提交的智能体间通信项类型为 "type": "agent_message"。
目前反代在解析 input item 时只包含 message、function_call_output、computer_screenshot 等白名单,遇到 "agent_message" 时会进入 default 分支直接抛出:
unsupported input item type "agent_message"。
非常感谢大佬带来这么出色的项目!

altiar1233 avatar Nov 10 '26 03:11 altiar1233

Cause: responsesContents in internal/api/responses.go has no case for agent_message, so the item falls through to the default branch (responses.go#L999-L1000 at v0.3.4) and handleResponses returns that error as the 400 you see. Codex sends agent_message items for messages between agents in its path-based multi-agent mode (/root, /root/worker, ...): spawned tasks, follow-up tasks and completion notices.

What I ran: I copied the item shapes Codex builds in InterAgentCommunication::to_model_input_item (protocol.rs#L1074) into a test in internal/api at v0.3.4 (a4092efc), built with the SpiderMonkey and libwebp archives the Dockerfile uses:

go test -tags netgo,osusergo ./internal/api -run TestCodexAgentMessage -v -count=1

Unpatched:

=== RUN   TestCodexAgentMessageHTTP
agent_message_repro_test.go:41: HTTP 400 {"error":{"message":"unsupported input item type \"agent_message\"","type":"invalid_request_error","param":null,"code":"invalid_request"}}
--- PASS: TestCodexAgentMessageHTTP (0.00s)
=== RUN   TestCodexAgentMessagePrepare
agent_message_repro_test.go:50: prepareResponses: unsupported input item type "agent_message"
--- FAIL: TestCodexAgentMessagePrepare (0.00s)
FAIL
FAIL	github.com/Mag1cFall/AIStudio2API/internal/api	0.027s
FAIL

With the patch below:

=== RUN   TestCodexAgentMessageHTTP
agent_message_repro_test.go:37: input accepted; stopped at github.com/Mag1cFall/AIStudio2API/internal/api.(*server).handleResponses(0x36ad46d9b1e0, {0x2be4610, 0x36ad47213100}, 0x36ad47096640) (no generation service in this harness)
--- PASS: TestCodexAgentMessageHTTP (0.00s)
=== RUN   TestCodexAgentMessagePrepare
agent_message_repro_test.go:54: contents[0] role=user text="review the DNS code"
agent_message_repro_test.go:54: contents[1] role=user text="Agent message from /root/reviewer to /root:\nFound the bug in resolver.go:42"
agent_message_repro_test.go:54: contents[2] role=user text="Agent message from /root to /root/worker:\nMessage Type: NEW_TASK\nTask name: /root/worker\nSender: /root\nPayload:\ncheck UDP listener reuse"
--- PASS: TestCodexAgentMessagePrepare (0.00s)
PASS
ok  	github.com/Mag1cFall/AIStudio2API/internal/api	0.019s

Whole package with the patch (go test ./internal/api):

ok  	github.com/Mag1cFall/AIStudio2API/internal/api	0.055s

One detail the fix has to get right: through this proxy, Codex puts the message text in an encrypted_content part, not in input_text. Codex treats a spawn_agent / send_message / followup_task call as plaintext only when the function_call item carries "encrypted_function_args": [] (router.rs#L70). responseFunctionCall here never emits that field, so agent_message_from_tool wraps the text as AgentMessage::Encrypted, and the next request carries {"type":"input_text","text":"Message Type: NEW_TASK\nTask name: ...\nPayload:\n"} plus {"type":"encrypted_content","encrypted_content":"<the text Gemini wrote>"}. Nothing is really encrypted; Codex does not strip that part for non-OpenAI providers. A fix that skipped encrypted_content (which is what Codex's own plaintext_agent_message_content does locally) would hand the sub-agent a task with an empty payload. So the patch reads it as text.

Fix: turn each agent_message into one user turn. User role because it is input the receiving agent has to act on (a NEW_TASK starts that agent's turn); a model turn would read as the agent's own earlier words.

diff --git a/internal/api/responses.go b/internal/api/responses.go
index ae30710..bfd780c 100644
--- a/internal/api/responses.go
+++ b/internal/api/responses.go
@@ -904,6 +904,14 @@ func responsesContents(raw json.RawMessage) ([]aistudio.Content, []string, error
 			continue
 		case "additional_tools", "configuration_update":
 			continue
+		case "agent_message":
+			pendingSignature = ""
+			content, err := responsesAgentMessage(rawItem)
+			if err != nil {
+				return nil, nil, fmt.Errorf("agent_message: %w", err)
+			}
+			contents = append(contents, content)
+			continue
 		case "web_search_call", "code_interpreter_call", "image_generation_call", "file_search_call",
 			"mcp_call", "mcp_list_tools", "mcp_approval_request", "mcp_approval_response", "tool_search_call", "tool_search_output", "program", "program_output":
 			pendingSignature = ""
@@ -1005,6 +1013,35 @@ func responsesContents(raw json.RawMessage) ([]aistudio.Content, []string, error
 	return prependSystemMedia(contents, systemMedia), instructions, nil
 }
 
+// responsesAgentMessage 把 Codex 智能体间消息转成一条 user 文本,encrypted_content 里是本服务模型写出的消息原文
+func responsesAgentMessage(raw json.RawMessage) (aistudio.Content, error) {
+	var item struct {
+		Author    string `json:"author"`
+		Recipient string `json:"recipient"`
+		Content   []struct {
+			Type             string `json:"type"`
+			Text             string `json:"text"`
+			EncryptedContent string `json:"encrypted_content"`
+		} `json:"content"`
+	}
+	if err := json.Unmarshal(raw, &item); err != nil {
+		return aistudio.Content{}, err
+	}
+	var text strings.Builder
+	fmt.Fprintf(&text, "Agent message from %s to %s:\n", item.Author, item.Recipient)
+	for _, part := range item.Content {
+		switch part.Type {
+		case "input_text":
+			text.WriteString(part.Text)
+		case "encrypted_content":
+			text.WriteString(part.EncryptedContent)
+		default:
+			return aistudio.Content{}, fmt.Errorf("unsupported content type %q", part.Type)
+		}
+	}
+	return aistudio.Content{Role: aistudio.RoleUser, Parts: []aistudio.Part{{Text: text.String()}}}, nil
+}
+
 // responsesInputConfig 返回输入项中 additional_tools 提供的工具与最后一个 configuration_update 的推理强度
 func responsesInputConfig(raw json.RawMessage) ([]responsesTool, string) {
 	var items []struct {

A matching row in the docs/protocol.md input-item table would go with it (agent_message → user text Agent message from <author> to <recipient>: followed by the input_text and encrypted_content parts).

Not tested: a live Gemini call or a real Codex session through the proxy (I have no AI Studio account here), so the HTTP-level test stops at the generation service once the input is accepted. Codex source read at 551fc719.

aron-intframe avatar Nov 10 '26 03:11 aron-intframe

Huge thanks to @aron-intframe for such an incredible, in-depth investigation and detailed patch! Really appreciate the effort and time you put into this. Sincerely hope @Mag1cFall can review and consider merging this patch into the upcoming release. Thank you both so much for maintaining such an awesome project and community! ❤️

altiar1233 avatar Nov 10 '26 04:11 altiar1233