mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-04 07:18:50 +00:00
responses: Codex multi-agent v2 items (agent_message, multi_agent_call) are read, not refused (#4210, #5244)
Codex's multi-agent v2 sends a worker its task, and the parent the worker's answer, as `agent_message` input items on /v1/responses, and may send agent calls as `multi_agent_call` / `multi_agent_call_output`. Strata answered 400 "input items of type 'agent_message' are not supported", so every worker request failed (a Codex Security scan stopped in its first phase). One adapter in serve/responses.py (input_messages and two new helpers, _agent_message and _agent_payload; nothing in serve/server.py, the tool-call parser or the prompt-tools cache changes): - an agent_message becomes a user message: Codex's own input_text header (Message Type, Task name, Sender, Payload) and the payload part as they are; a message without that header gets one line naming its author and recipient; - an encrypted_content payload part holds plain text when the agents run here (Codex builds it): read as text; one this server sealed (the reasoning ENCRYPTED_PREFIX form) is opened; another server's ciphertext (OpenAI's Fernet tokens) or a damaged seal is named as unreadable, never passed off as text; - an agent_message that arrives between a turn's calls and their outputs is placed after those outputs, so each call's result still follows its call in the template; it is never dropped; - multi_agent_call(_output) are a call (name, or "action") and its result. Requests without these items render as before. From PR #4210 (WenyuanXu) and PR #5244 (bsorensen110), consolidated into one adapter as the review asked; neither PR's code is taken as is. Not taken: #5244's second commit (a forked sub-agent turn's prompt reusing the parent's namespace tools): a prompt-cache change, separate. Not run: a pinned Codex multi-agent client. Test: serve/test_responses_agent_message.py (9 unit cases and one live /v1/responses request on the mock engine: 8 fail or error on the base, the live one with the 400; 10 pass); serve.test_responses passes (53 in both files).
This commit is contained in:
1 parent
f513ad460d
commit
3cb933d298
2 files changed
+197
-5
No files matched your search
+81
-5
@@ -24,6 +24,7 @@ from __future__ import annotations
|
||||
import base64
|
||||
import copy
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
|
||||
@@ -125,6 +126,56 @@ def _tool_output(item, param):
|
||||
return out if isinstance(out, str) else _content(out, param + ".output")
|
||||
|
||||
|
||||
#: An encrypted payload of another server (OpenAI's are Fernet tokens: "gAAAAA" + url-safe base64) cannot be read here.
|
||||
_FOREIGN_CIPHERTEXT = re.compile(r"gAAAAA[A-Za-z0-9_\-]{60,}={0,2}")
|
||||
_UNREADABLE_PAYLOAD = "[this part was encrypted by another server and cannot be read here]"
|
||||
|
||||
|
||||
def _agent_payload(enc) -> str:
|
||||
"""One `encrypted_content` part of an agent_message -> text. Codex builds these parts itself and, with the agents
|
||||
running on this server, they hold the plain text of the task or answer; a payload sealed by this server (reasoning's
|
||||
ENCRYPTED_PREFIX form) is opened; another server's ciphertext is named as unreadable, never passed off as text."""
|
||||
if not isinstance(enc, str):
|
||||
return _UNREADABLE_PAYLOAD
|
||||
if enc.startswith(ENCRYPTED_PREFIX):
|
||||
try:
|
||||
text = json.loads(base64.b64decode(enc[len(ENCRYPTED_PREFIX):], validate=True).decode("utf-8"))["text"]
|
||||
except (ValueError, KeyError, TypeError, UnicodeError):
|
||||
return _UNREADABLE_PAYLOAD
|
||||
return text if isinstance(text, str) else _UNREADABLE_PAYLOAD
|
||||
if _FOREIGN_CIPHERTEXT.fullmatch(enc.strip()):
|
||||
return _UNREADABLE_PAYLOAD
|
||||
return enc
|
||||
|
||||
|
||||
def _agent_message(item, param) -> str:
|
||||
"""#4210 #5244: an `agent_message` item (Codex multi-agent v2: the task a parent agent sends a worker, the worker's
|
||||
answer) -> the text of a user message. Codex writes the attribution itself (an input_text header: "Message Type",
|
||||
"Task name", "Sender", "Payload:"), followed by the payload in an `encrypted_content` part; both are kept as they are.
|
||||
A message without such a header gets one line naming its author and recipient, so who said it is not lost."""
|
||||
raw = item.get("content")
|
||||
parts = [{"type": "input_text", "text": raw}] if isinstance(raw, str) else raw if isinstance(raw, list) else []
|
||||
texts = []
|
||||
for j, part in enumerate(parts):
|
||||
if not isinstance(part, dict):
|
||||
raise ResponsesError("expected a content part object", f"{param}.content[{j}]")
|
||||
kind = part.get("type")
|
||||
if kind in ("input_text", "output_text", "text"):
|
||||
text = part.get("text")
|
||||
texts.append(text if isinstance(text, str) else "")
|
||||
elif kind == "encrypted_content":
|
||||
texts.append(_agent_payload(part.get("encrypted_content")))
|
||||
else:
|
||||
raise ResponsesError(f"agent_message parts of type {kind!r} are not supported (text and encrypted_content are)",
|
||||
f"{param}.content[{j}].type", "unsupported_parameter")
|
||||
body = "".join(texts)
|
||||
if body.startswith("Message Type:"):
|
||||
return body
|
||||
author = item.get("author") if isinstance(item.get("author"), str) and item.get("author") else "another agent"
|
||||
recipient = item.get("recipient") if isinstance(item.get("recipient"), str) and item.get("recipient") else "this agent"
|
||||
return f"Message from {author} to {recipient}:\n{body}"
|
||||
|
||||
|
||||
def input_messages(req: dict) -> list[dict]:
|
||||
"""`instructions` + `input` -> the chat template's messages."""
|
||||
messages = []
|
||||
@@ -141,9 +192,18 @@ def input_messages(req: dict) -> list[dict]:
|
||||
raise ResponsesError("input must be a string or an array of input items", "input")
|
||||
thinking = [] # reasoning waiting for the assistant turn it belongs to
|
||||
open_turn = None # the assistant message the next function_call joins
|
||||
unanswered = set() # call ids of the last turn's calls whose outputs have not come yet
|
||||
held = [] # agent messages that arrived while calls were unanswered
|
||||
|
||||
def flush_held():
|
||||
# #4210 #5244: an agent_message that arrives between a turn's calls and their outputs follows those outputs,
|
||||
# so the template still sees each call's result right after the call
|
||||
messages.extend(held)
|
||||
held.clear()
|
||||
|
||||
def turn(content=""):
|
||||
nonlocal open_turn
|
||||
unanswered.clear()
|
||||
open_turn = {"role": "assistant", "content": content}
|
||||
if thinking:
|
||||
open_turn["reasoning_content"] = "".join(thinking)
|
||||
@@ -156,6 +216,9 @@ def input_messages(req: dict) -> list[dict]:
|
||||
if not isinstance(item, dict):
|
||||
raise ResponsesError("expected an input item object", param)
|
||||
kind = item.get("type") or ("message" if "role" in item else None)
|
||||
if held and kind not in ("function_call_output", "custom_tool_call_output", "multi_agent_call_output", "agent_message"):
|
||||
flush_held() # the calls' outputs stopped coming: the held messages go here
|
||||
unanswered.clear()
|
||||
if kind == "message":
|
||||
role = item.get("role")
|
||||
if role not in ("user", "assistant", "system", "developer"):
|
||||
@@ -174,23 +237,35 @@ def input_messages(req: dict) -> list[dict]:
|
||||
if open_turn is not None and (open_turn.get("tool_calls") or open_turn["content"]):
|
||||
open_turn = None # thinking starts a new model turn
|
||||
thinking.append(text)
|
||||
elif kind in ("function_call", "custom_tool_call"):
|
||||
name = item.get("name")
|
||||
elif kind in ("function_call", "custom_tool_call", "multi_agent_call"):
|
||||
# #5244: Codex multi-agent v2 also sends its agent calls as multi_agent_call items (the name may be "action")
|
||||
field = "action" if kind == "multi_agent_call" and "name" not in item else "name"
|
||||
name = item.get(field)
|
||||
if not isinstance(name, str) or not name:
|
||||
raise ResponsesError("a function_call needs a name", param + ".name")
|
||||
raise ResponsesError(f"a {kind} needs a {field}", f"{param}.{field}")
|
||||
if item.get("namespace"):
|
||||
name = f"{item['namespace']}.{name}"
|
||||
if kind == "function_call":
|
||||
if kind in ("function_call", "multi_agent_call"):
|
||||
args = _arguments(item.get("arguments"), param + ".arguments")
|
||||
else:
|
||||
args = {"input": item.get("input") if isinstance(item.get("input"), str) else ""}
|
||||
target = open_turn if open_turn is not None and not thinking else turn()
|
||||
target.setdefault("tool_calls", []).append({"function": {"name": name, "arguments": args},
|
||||
"_call_id": item.get("call_id")})
|
||||
elif kind in ("function_call_output", "custom_tool_call_output"):
|
||||
if item.get("call_id"):
|
||||
unanswered.add(item.get("call_id"))
|
||||
elif kind in ("function_call_output", "custom_tool_call_output", "multi_agent_call_output"):
|
||||
messages.append({"role": "tool", "content": _tool_output(item, param), "_call_id": item.get("call_id")})
|
||||
open_turn = None
|
||||
thinking.clear()
|
||||
unanswered.discard(item.get("call_id"))
|
||||
if held and not unanswered:
|
||||
flush_held()
|
||||
elif kind == "agent_message":
|
||||
message = {"role": "user", "content": _agent_message(item, param)}
|
||||
open_turn = None
|
||||
thinking.clear()
|
||||
(held if unanswered else messages).append(message)
|
||||
elif kind == "additional_tools":
|
||||
continue # #782 (Codex): tools the client adds as an input item; see request_tools
|
||||
elif kind == "item_reference":
|
||||
@@ -199,6 +274,7 @@ def input_messages(req: dict) -> list[dict]:
|
||||
else:
|
||||
raise ResponsesError(f"input items of type {kind!r} are not supported", param + ".type",
|
||||
"unsupported_parameter")
|
||||
flush_held()
|
||||
_order_tool_results(messages)
|
||||
# leading system/developer messages (Codex: instructions, then its developer message) become one system message
|
||||
# at the start; later ones become user messages in place, as on the chat path
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""#4210 #5244: Codex multi-agent v2 items on /v1/responses. A worker's task and its answer arrive as `agent_message` items
|
||||
(Codex's own input_text header, then the payload in an `encrypted_content` part that holds plain text when the agents run
|
||||
here); agent calls may arrive as `multi_agent_call` / `multi_agent_call_output`. They were refused with a 400 ("input items
|
||||
of type 'agent_message' are not supported"), which stopped every worker of a Codex Security scan.
|
||||
Payload shapes as in PRs #4210 (WenyuanXu) and #5244 (bsorensen110), from codex-rs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import unittest
|
||||
|
||||
from serve.responses import ENCRYPTED_PREFIX, ResponsesError, input_messages
|
||||
|
||||
|
||||
def seal(text):
|
||||
return ENCRYPTED_PREFIX + base64.b64encode(json.dumps({"text": text}).encode()).decode("ascii")
|
||||
|
||||
|
||||
HEADER_TASK = "Message Type: NEW_TASK\nTask name: /root/worker1\nSender: /root\nTrigger turn: false\nPayload:\n"
|
||||
TASK = {"type": "agent_message", "author": "/root", "recipient": "/root/worker1",
|
||||
"content": [{"type": "input_text", "text": HEADER_TASK},
|
||||
{"type": "encrypted_content", "encrypted_content": "Compute 2 + 2 and reply with the exact integer."}]}
|
||||
HEADER_ANSWER = "Message Type: FINAL_ANSWER\nTask name: /root/worker1\nSender: /root/worker1\nTrigger turn: true\nPayload:\n"
|
||||
ANSWER = {"type": "agent_message", "author": "/root/worker1", "recipient": "/root",
|
||||
"content": [{"type": "input_text", "text": HEADER_ANSWER}, {"type": "encrypted_content", "encrypted_content": seal("4")}]}
|
||||
|
||||
|
||||
class AgentMessage(unittest.TestCase):
|
||||
def test_a_task_is_a_user_message_with_codex_header_and_payload(self):
|
||||
msgs = input_messages({"instructions": "You are Codex", "input": [TASK]})
|
||||
self.assertEqual(msgs, [{"role": "system", "content": "You are Codex"},
|
||||
{"role": "user", "content": HEADER_TASK + "Compute 2 + 2 and reply with the exact integer."}])
|
||||
|
||||
def test_a_payload_this_server_sealed_is_opened(self):
|
||||
msgs = input_messages({"input": [ANSWER]})
|
||||
self.assertEqual(msgs[-1]["content"], HEADER_ANSWER + "4")
|
||||
|
||||
def test_another_servers_ciphertext_is_named_unreadable_not_passed_off_as_text(self):
|
||||
token = "gAAAAA" + "Bo" * 60 + "=="
|
||||
item = {"type": "agent_message", "content": [{"type": "input_text", "text": HEADER_ANSWER},
|
||||
{"type": "encrypted_content", "encrypted_content": token}]}
|
||||
content = input_messages({"input": [item]})[-1]["content"]
|
||||
self.assertNotIn(token, content)
|
||||
self.assertIn("encrypted by another server and cannot be read here", content)
|
||||
for broken in (ENCRYPTED_PREFIX + "!!!", seal(None), None):
|
||||
item = {"type": "agent_message", "content": [{"type": "encrypted_content", "encrypted_content": broken}]}
|
||||
self.assertIn("cannot be read here", input_messages({"input": [item]})[-1]["content"])
|
||||
|
||||
def test_a_message_without_codex_header_keeps_who_sent_it(self):
|
||||
item = {"type": "agent_message", "author": "orchestrator", "recipient": "researcher", "content": "look at x"}
|
||||
self.assertEqual(input_messages({"input": [item]})[-1]["content"], "Message from orchestrator to researcher:\nlook at x")
|
||||
|
||||
def test_an_unknown_part_is_refused_clearly(self):
|
||||
item = {"type": "agent_message", "content": [{"type": "input_audio", "data": "x"}]}
|
||||
with self.assertRaises(ResponsesError) as caught:
|
||||
input_messages({"input": [item]})
|
||||
self.assertIn("agent_message parts of type 'input_audio'", str(caught.exception))
|
||||
|
||||
def test_a_message_between_calls_and_their_outputs_follows_the_outputs(self):
|
||||
msgs = input_messages({"input": [
|
||||
{"type": "message", "role": "user", "content": "start"},
|
||||
{"type": "function_call", "name": "exec_command", "arguments": "{\"cmd\":\"a\"}", "call_id": "c1"},
|
||||
{"type": "function_call", "name": "exec_command", "arguments": "{\"cmd\":\"b\"}", "call_id": "c2"},
|
||||
TASK,
|
||||
{"type": "function_call_output", "call_id": "c2", "output": "out2"},
|
||||
{"type": "function_call_output", "call_id": "c1", "output": "out1"},
|
||||
{"type": "function_call", "name": "exec_command", "arguments": "{\"cmd\":\"c\"}", "call_id": "c3"},
|
||||
{"type": "function_call_output", "call_id": "c3", "output": "out3"},
|
||||
]})
|
||||
self.assertEqual([m["role"] for m in msgs], ["user", "assistant", "tool", "tool", "user", "assistant", "tool"])
|
||||
self.assertEqual([m["content"] for m in msgs if m["role"] == "tool"], ["out1", "out2", "out3"])
|
||||
self.assertTrue(msgs[4]["content"].startswith("Message Type: NEW_TASK"))
|
||||
self.assertEqual(len(msgs[1]["tool_calls"]), 2)
|
||||
|
||||
def test_a_held_message_is_not_lost_when_the_outputs_never_come(self):
|
||||
msgs = input_messages({"input": [
|
||||
{"type": "function_call", "name": "spawn_agent", "arguments": "{}", "call_id": "c1"}, TASK]})
|
||||
self.assertEqual([m["role"] for m in msgs], ["assistant", "user"])
|
||||
|
||||
def test_multi_agent_call_items_are_calls_and_results(self):
|
||||
msgs = input_messages({"input": [
|
||||
{"type": "message", "role": "user", "content": "go"},
|
||||
{"type": "multi_agent_call", "action": "spawn_agent", "namespace": "multi_agent_v2", "arguments": "{\"task\":\"t\"}",
|
||||
"call_id": "m1"},
|
||||
{"type": "multi_agent_call_output", "call_id": "m1", "output": "started"},
|
||||
ANSWER]})
|
||||
self.assertEqual([m["role"] for m in msgs], ["user", "assistant", "tool", "user"])
|
||||
self.assertEqual(msgs[1]["tool_calls"][0]["function"], {"name": "multi_agent_v2.spawn_agent", "arguments": {"task": "t"}})
|
||||
self.assertEqual(msgs[2]["content"], "started")
|
||||
|
||||
def test_requests_without_these_items_render_as_before(self):
|
||||
req = {"instructions": "I", "input": [{"type": "message", "role": "user", "content": "hi"},
|
||||
{"type": "function_call", "name": "f", "arguments": "{}", "call_id": "a"},
|
||||
{"type": "function_call_output", "call_id": "a", "output": "r"}]}
|
||||
self.assertEqual([m["role"] for m in input_messages(req)], ["system", "user", "assistant", "tool"])
|
||||
|
||||
|
||||
from serve.test_responses import Server # noqa: E402 (the live mock server of the Responses tests)
|
||||
|
||||
|
||||
class OverHttp(Server):
|
||||
def test_a_worker_request_is_answered_not_refused(self):
|
||||
code, r = self.post({"model": "m", "store": False, "input": [
|
||||
{"type": "message", "role": "user", "content": "scan the repo"},
|
||||
{"type": "function_call", "name": "spawn_agent", "arguments": "{}", "call_id": "c1"},
|
||||
{"type": "function_call_output", "call_id": "c1", "output": "started"},
|
||||
ANSWER]})
|
||||
self.assertEqual(code, 200, r)
|
||||
self.assertEqual(r["status"], "completed")
|
||||
|
||||
|
||||
del Server # its own tests stay in serve.test_responses
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user