Skip to content

The agent that grows with you

fix(agent): stamp type=message on every Responses input message item

huanshan519540721bffe5be
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index df4bd83e3a9..0129a25755f 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -1417,6 +1417,7 @@ class _CodexCompletionsAdapter:
_chat_messages_to_responses_input,
_classify_responses_issuer,
_responses_tools,
+ _role_message_item,
_wire_model_identity,
classify_responses_route,
)
@@ -1489,7 +1490,7 @@ class _CodexCompletionsAdapter:
resp_kwargs: Dict[str, Any] = {
# Codex only knows the base slug; strip the Hermes ``-900k`` picker suffix.
"model": wire_model, "instructions": instructions,
- "input": input_items or [{"role": "user", "content": ""}], "store": False,
+ "input": input_items or [_role_message_item("user", "")], "store": False,
}
# Forward the chat.completions timeout; otherwise a Codex stream can sit behind a
# dead-looking CLI until the user force-interrupts.
diff --git a/agent/codex_responses_adapter.py b/agent/codex_responses_adapter.py
index 60e9f49ef2c..09578aa2d79 100644
--- a/agent/codex_responses_adapter.py
+++ b/agent/codex_responses_adapter.py
@@ -365,16 +365,28 @@ def _normalize_responses_message_status(value: Any, *, default: str = "completed
def _message_item(
- content: List[Dict[str, Any]], *, status: str, item_id: Optional[str] = None, phase: Optional[str] = None,
+ content: Any, *, status: str, item_id: Optional[str] = None, phase: Optional[str] = None,
) -> Dict[str, Any]:
- """Assistant ``message`` item; ``id``/``phase`` are added only when non-empty."""
+ """Assistant ``message`` item; ``id``/``phase`` are added only when non-empty. ``content`` is a
+ list of parts, or the string a plain-text message carries."""
item: Dict[str, Any] = {"type": "message", "role": "assistant", "status": status, "content": content}
item.update({k: v for k, v in (("id", item_id), ("phase", phase)) if v})
return item
+def _role_message_item(role: str, content: Any) -> Dict[str, Any]:
+ """Plain ``message`` input item for ``role``.
+
+ ``type`` is not decoration: strict ``/v1/responses`` parsers (llama.cpp ``server-chat.cpp``)
+ reject a typeless input item outright, so every emitter builds its message items here and the
+ invariant is structural rather than remembered. ``status`` is an assistant *output* field and is
+ deliberately absent — it is not valid on a user input item.
+ """
+ return {"type": "message", "role": role, "content": content}
+
+
def _assistant_message_item(
- raw: Dict[str, Any], content: List[Dict[str, Any]], *, is_github_responses: bool,
+ raw: Dict[str, Any], content: Any, *, is_github_responses: bool,
current_issuer_kind: Optional[str] = None,
) -> Dict[str, Any]:
"""Replayable assistant ``message`` item from a stored one. ``id`` is kept only when short enough and never for
@@ -614,7 +626,7 @@ def _chat_messages_to_responses_input(
def wire_content(value: Any) -> Any:
return [{"type": text_type, "text": value}] if typed_text_only and isinstance(value, str) else value
if role == "user":
- emit([{"role": role, "content": wire_content(content_parts or content_text)}], msg)
+ emit([_role_message_item(role, wire_content(content_parts or content_text))], msg)
continue
reasoning_items = [] if not replay_encrypted_reasoning else _replay_reasoning_items(
msg, seen_item_ids=seen_item_ids, current_issuer_kind=current_issuer_kind,
@@ -635,7 +647,7 @@ def _chat_messages_to_responses_input(
# non-empty: strict Responses-compatible providers reject "" with 400.
if fallback is not None and not (fallback == "" and tool_items):
follower = " " if fallback == "" else fallback
- emit([{"role": "assistant", "content": wire_content(follower)}], msg)
+ emit([_role_message_item("assistant", wire_content(follower))], msg)
emit(tool_items, msg)
# The server renders nothing placed before a compaction item, so pre-checkpoint history is
# dead weight and plaintext asks / merged summaries silently vanish. Keep the newest checkpoint
@@ -805,24 +817,39 @@ def _preflight_encrypted(item: Dict[str, Any], idx: int, ctx: _PreflightCtx) ->
def _preflight_message(item: Dict[str, Any], idx: int, ctx: _PreflightCtx) -> Dict[str, Any]:
- if item.get("role") != "assistant":
- raise ValueError(f"Codex Responses input[{idx}] message items must have role='assistant'.")
+ """Typed ``message`` item. Both roles land here now that every message item carries ``type``;
+ before, a user message reached the untyped handler and went out typeless."""
+ role = item.get("role")
+ if role not in {"assistant", "user"}:
+ raise ValueError(f"Codex Responses input[{idx}] message items must have role='assistant' or 'user'.")
content = item.get("content")
- if not isinstance(content, list):
- raise ValueError(f"Codex Responses input[{idx}] message item must have content list.")
- normalized_content = []
- for part_idx, part in enumerate(content):
- if not isinstance(part, dict):
- raise ValueError(f"Codex Responses input[{idx}] message content[{part_idx}] must be an object.")
- part_type = part.get("type")
- if part_type not in _OUTPUT_TEXT_TYPES:
- raise ValueError(
- f"Codex Responses input[{idx}] message content[{part_idx}] has unsupported type {part_type!r}."
- )
- normalized_content.append({"type": "output_text", "text": ctx.sanitize_text(_str_or_empty(part.get("text", "")))})
- if not normalized_content:
- raise ValueError(f"Codex Responses input[{idx}] message item must contain at least one text part.")
- return _assistant_message_item(item, normalized_content, is_github_responses=ctx.is_github_responses)
+ # A plain-text message converts to string content, and the required following item after a
+ # reasoning block is the empty string. List-only validation rejected exactly the items our own
+ # converter produces — which is why stamping ``type`` on them had to wait for this.
+ if isinstance(content, str):
+ normalized_content: Any = ctx.sanitize_text(content)
+ elif isinstance(content, list):
+ text_type = _text_type_for(role)
+ accepted = _OUTPUT_TEXT_TYPES if role == "assistant" else _TEXT_PART_TYPES
+ normalized_content = []
+ for part_idx, part in enumerate(content):
+ if not isinstance(part, dict):
+ raise ValueError(f"Codex Responses input[{idx}] message content[{part_idx}] must be an object.")
+ part_type = part.get("type")
+ if part_type not in accepted:
+ raise ValueError(
+ f"Codex Responses input[{idx}] message content[{part_idx}] has unsupported type {part_type!r}."
+ )
+ normalized_content.append({"type": text_type, "text": ctx.sanitize_text(_str_or_empty(part.get("text", "")))})
+ if not normalized_content:
+ raise ValueError(f"Codex Responses input[{idx}] message item must contain at least one text part.")
+ else:
+ raise ValueError(f"Codex Responses input[{idx}] message item content must be a string or a list.")
+ if role == "assistant":
+ return _assistant_message_item(item, normalized_content, is_github_responses=ctx.is_github_responses)
+ # ``id``/``phase`` are dropped for user items, as they were when these reached the untyped
+ # handler: a replayed id binds to a backend connection and 400s once it goes stale.
+ return _role_message_item(role, normalized_content)
def _preflight_role_message(item: Dict[str, Any], idx: int, ctx: _PreflightCtx) -> Dict[str, Any]:
@@ -834,7 +861,7 @@ def _preflight_role_message(item: Dict[str, Any], idx: int, ctx: _PreflightCtx)
)
content = item.get("content", "")
if not isinstance(content, list):
- return {"role": role, "content": ctx.sanitize_text(_str_or_empty(content))}
+ return _role_message_item(role, ctx.sanitize_text(_str_or_empty(content)))
# Parts are already Responses-shaped; validate and re-type text for the role.
# Unlike history conversion, empty text / empty image urls are kept, not dropped.
text_type = _text_type_for(role)
@@ -855,7 +882,7 @@ def _preflight_role_message(item: Dict[str, Any], idx: int, ctx: _PreflightCtx)
raise ValueError(
f"Codex Responses input[{idx}].content[{part_idx}] has unsupported type {part.get('type')!r}."
)
- return {"role": role, "content": validated}
+ return _role_message_item(role, validated)
_PREFLIGHT_ITEM_HANDLERS: Dict[str, Callable[..., Optional[Dict[str, Any]]]] = {
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]
new file mode 100644
index 00000000000..c3578974ad9
--- /dev/null
+++ b/contributors/emails/[email protected]
@@ -0,0 +1 @@
+huanshan5195
diff --git a/tests/agent/test_codex_responses_adapter.py b/tests/agent/test_codex_responses_adapter.py
index bb5d1fdedd4..421dba3321c 100644
--- a/tests/agent/test_codex_responses_adapter.py
+++ b/tests/agent/test_codex_responses_adapter.py
@@ -180,6 +180,7 @@ def test_preflight_rewrites_raw_assistant_images_to_text_markers():
}]
assert _preflight_codex_input_items(raw) == [{
+ "type": "message",
"role": "assistant",
"content": [{
"type": "output_text",
@@ -994,3 +995,124 @@ def test_codex_preflight_passes_text_verbosity_through():
assert _preflight_codex_api_kwargs(dict(kwargs))["text"] == {"verbosity": "low"}
# An empty block is dropped, like the other optional fields, instead of rejected.
assert "text" not in _preflight_codex_api_kwargs({**kwargs, "text": {}})
+
+
+# ---------------------------------------------------------------------------
+# Every message item on the Responses wire must carry an explicit
+# ``"type": "message"``. OpenAI tolerates typeless items; llama.cpp's
+# ``server-chat.cpp`` /v1/responses parser does not — it rejects the request,
+# so an agent turn dies with an empty "" answer as soon as multi-turn history
+# is replayed. Preflight must then also accept the items our own converter
+# produces: string content, user role, and the empty assistant "following
+# item" after a reasoning block.
+# ---------------------------------------------------------------------------
+
+
+def test_converter_stamps_message_type_on_every_role_item():
+ items = _chat_messages_to_responses_input([
+ {"role": "user", "content": "hello"},
+ {"role": "assistant", "content": "hi there"},
+ {"role": "user", "content": [{"type": "text", "text": "look at this"}]},
+ {"role": "assistant", "content": [{"type": "text", "text": "saw it"}]},
+ ])
+
+ assert [i["type"] for i in items] == ["message"] * 4
+ assert [i["role"] for i in items] == ["user", "assistant", "user", "assistant"]
+
+
+def test_converter_leaves_typed_non_message_items_alone():
+ items = _chat_messages_to_responses_input([
+ {"role": "assistant", "content": "", "tool_calls": [
+ {"call_id": "call_abc123", "function": {"name": "web_search", "arguments": "{}"}},
+ ]},
+ {"role": "tool", "tool_call_id": "call_abc123", "content": "some result"},
+ ])
+
+ assert [i["type"] for i in items] == ["function_call", "function_call_output"]
+
+
+def test_converter_stamps_the_reasoning_following_item():
+ """The assistant item that must follow a replayed reasoning block is exactly the item
+ llama.cpp rejects when it goes out typeless. Its content is the non-empty ``" "`` spacer
+ the converter mints when there is no text (strict providers reject ``""`` with 400)."""
+ items = _chat_messages_to_responses_input([
+ {"role": "user", "content": "think about this"},
+ {"role": "assistant", "content": "", "codex_reasoning_items": [
+ {"type": "reasoning", "encrypted_content": "opaque-carrier", "summary": []},
+ ]},
+ ])
+
+ assert items[0] == {"type": "message", "role": "user", "content": "think about this"}
+ assert items[1]["type"] == "reasoning"
+ assert items[2] == {"type": "message", "role": "assistant", "content": " "}
+
+
+def test_preflight_stamps_message_type_on_typeless_role_items():
+ normalized = _preflight_codex_input_items([
+ {"role": "user", "content": "ping"},
+ {"role": "assistant", "content": "pong"},
+ {"role": "user", "content": [{"type": "input_text", "text": "look"}]},
+ ])
+
+ assert [i["type"] for i in normalized] == ["message"] * 3
+ assert normalized[0]["content"] == "ping"
+ assert normalized[2]["content"] == [{"type": "input_text", "text": "look"}]
+
+
+def test_preflight_accepts_stamped_items_with_string_content():
+ """Stamping ``type`` routes plain-text messages to the typed handler, which used to accept
+ a content list only — list-only validation rejected the converter's own output."""
+ normalized = _preflight_codex_input_items([
+ {"type": "message", "role": "user", "content": "ping"},
+ {"type": "message", "role": "assistant", "content": "pong"},
+ {"type": "message", "role": "assistant", "content": ""},
+ ])
+
+ assert [i["content"] for i in normalized] == ["ping", "pong", ""]
+ assert [i["role"] for i in normalized] == ["user", "assistant", "assistant"]
+
+
+def test_converter_output_survives_preflight_unchanged():
+ """The real main-flow wire: converter → preflight, every message item still typed."""
+ items = _chat_messages_to_responses_input([
+ {"role": "user", "content": "hello"},
+ {"role": "assistant", "content": "hi there"},
+ {"role": "user", "content": [{"type": "text", "text": "look at this"}]},
+ {"role": "assistant", "content": [{"type": "text", "text": "saw it"}]},
+ ])
+
+ normalized = _preflight_codex_input_items(items)
+
+ assert [i["type"] for i in normalized] == ["message"] * 4
+ assert [i["role"] for i in normalized] == ["user", "assistant", "user", "assistant"]
+
+
+def test_preflight_user_message_keeps_input_text_parts():
+ """A user part is ``input_text`` on the wire; the typed handler used to force every part to
+ ``output_text`` because it only ever saw assistant items."""
+ normalized = _preflight_codex_input_items(
+ [{"type": "message", "role": "user", "content": [{"type": "text", "text": "look"}]}]
+ )
+
+ assert normalized[0]["content"] == [{"type": "input_text", "text": "look"}]
+
+
+def test_preflight_never_stamps_status_on_a_user_item():
+ """``status`` is an assistant-output field; assistant status still survives for replay."""
+ normalized = _preflight_codex_input_items([
+ {"type": "message", "role": "user", "content": "ping"},
+ {"type": "message", "role": "assistant", "content": "pong", "status": "in_progress"},
+ ])
+
+ assert "status" not in normalized[0]
+ assert normalized[1]["status"] == "in_progress"
+
+
+def test_preflight_rejects_a_typed_message_with_an_unsupported_role():
+ with pytest.raises(ValueError):
+ _preflight_codex_input_items([{"type": "message", "role": "system", "content": "be nice"}])
+
+
+def test_preflight_rejects_typed_message_content_that_is_neither_string_nor_list():
+ with pytest.raises(ValueError):
+ _preflight_codex_input_items([{"type": "message", "role": "assistant", "content": 42}])
diff --git a/tests/agent/test_native_compaction.py b/tests/agent/test_native_compaction.py
index a6fc0197115..bb5733a71b8 100644
--- a/tests/agent/test_native_compaction.py
+++ b/tests/agent/test_native_compaction.py
@@ -579,8 +579,8 @@ class TestPrunePreCheckpointItems:
# The checkpoint's own turn content is emitted AFTER the checkpoint
# in wire order (sidecar items lead the assistant branch), so it
# survives in the post tail — call pairing for that turn is intact.
- assert {"role": "assistant", "content": "ok"} in items
- assert items.index({"role": "assistant", "content": "ok"}) > 0
+ assert {"type": "message", "role": "assistant", "content": "ok"} in items
+ assert items.index({"type": "message", "role": "assistant", "content": "ok"}) > 0
def test_adapter_without_checkpoint_unchanged_shape(self):
from agent.codex_responses_adapter import _chat_messages_to_responses_input
@@ -647,7 +647,7 @@ class TestCheckpointGatedOnCurrentEligibility:
assert items == pre_feature
# Specifically: no checkpoint on the wire, no deleted history.
assert all(i.get("type") != "compaction" for i in items)
- assert {"role": "assistant", "content": _CODEX_ON_IT} in items
+ assert {"type": "message", "role": "assistant", "content": _CODEX_ON_IT} in items
def test_eligible_request_still_restructures(self):
from agent.codex_responses_adapter import _chat_messages_to_responses_input
@@ -665,7 +665,7 @@ class TestCheckpointGatedOnCurrentEligibility:
items = _chat_messages_to_responses_input(self._history())
assert all(i.get("type") != "compaction" for i in items)
- assert {"role": "assistant", "content": "on it"} in items
+ assert {"type": "message", "role": "assistant", "content": "on it"} in items
def test_build_kwargs_without_field_does_not_prune(self):
"""Model swapped out of the gpt-5.6 family / kill switch fired:
@@ -679,7 +679,7 @@ class TestCheckpointGatedOnCurrentEligibility:
)
assert "context_management" not in kwargs
assert all(i.get("type") != "compaction" for i in kwargs["input"])
- assert {"role": "assistant", "content": "on it"} in kwargs["input"]
+ assert {"type": "message", "role": "assistant", "content": "on it"} in kwargs["input"]
def test_build_kwargs_with_field_prunes(self):
from agent.transports.codex import ResponsesApiTransport
@@ -700,7 +700,7 @@ class TestCheckpointGatedOnCurrentEligibility:
self._history(), is_codex_backend=True
)
assert all(i.get("type") != "compaction" for i in items)
- assert {"role": "assistant", "content": _CODEX_ON_IT} in items
+ assert {"type": "message", "role": "assistant", "content": _CODEX_ON_IT} in items
def test_auxiliary_responses_adapter_never_prunes(self, monkeypatch):
"""Auxiliary calls (compression, flush_memories, MoA) replay real
@@ -738,4 +738,4 @@ class TestCheckpointGatedOnCurrentEligibility:
assert seen.get("native_compaction_eligible") is False
assert all(i.get("type") != "compaction" for i in seen["input"])
- assert {"role": "assistant", "content": _CODEX_ON_IT} in seen["input"]
+ assert {"type": "message", "role": "assistant", "content": _CODEX_ON_IT} in seen["input"]
diff --git a/tests/agent/test_native_compaction_nontext_retention.py b/tests/agent/test_native_compaction_nontext_retention.py
index 7fbf681b4cf..aa44e200b0b 100644
--- a/tests/agent/test_native_compaction_nontext_retention.py
+++ b/tests/agent/test_native_compaction_nontext_retention.py
@@ -72,9 +72,9 @@ def test_adapter_preserves_image_only_user_message_across_checkpoint():
assert converted == [
_CHECKPOINT,
- {"role": "user", "content": [_RESPONSES_IMAGE_PART]},
- {"role": "assistant", "content": "checkpoint turn"},
- {"role": "user", "content": "after checkpoint"},
+ {"type": "message", "role": "user", "content": [_RESPONSES_IMAGE_PART]},
+ {"type": "message", "role": "assistant", "content": "checkpoint turn"},
+ {"type": "message", "role": "user", "content": "after checkpoint"},
]
diff --git a/tests/agent/test_provider_parity.py b/tests/agent/test_provider_parity.py
index 672e4d93c64..710ef9954f3 100644
--- a/tests/agent/test_provider_parity.py
+++ b/tests/agent/test_provider_parity.py
@@ -454,7 +454,7 @@ class TestChatMessagesToResponsesInput:
def test_user_message_passes_through(self, monkeypatch):
messages = [{"role": "user", "content": "hello"}]
items = _chat_messages_to_responses_input(messages)
- assert items == [{"role": "user", "content": "hello"}]
+ assert items == [{"type": "message", "role": "user", "content": "hello"}]
def test_system_messages_filtered(self, monkeypatch):
messages = [
@@ -626,7 +626,7 @@ class TestChatMessagesToResponsesInputMessageItems:
{"role": "user", "content": "follow up"},
]
items = _chat_messages_to_responses_input(messages)
- msg_items = [i for i in items if i.get("type") == "message"]
+ msg_items = [i for i in items if i.get("type") == "message" and i.get("role") == "assistant"]
assert len(msg_items) == 1
assert msg_items[0]["id"] == "msg_123"
assert msg_items[0]["phase"] == "final_answer"
@@ -635,7 +635,7 @@ class TestChatMessagesToResponsesInputMessageItems:
def test_fallback_to_plain_when_no_message_items(self, monkeypatch):
messages = [{"role": "assistant", "content": "Hello world"}]
items = _chat_messages_to_responses_input(messages)
- assert items == [{"role": "assistant", "content": "Hello world"}]
+ assert items == [{"type": "message", "role": "assistant", "content": "Hello world"}]
diff --git a/tests/agent/test_responses_empty_tool_replay.py b/tests/agent/test_responses_empty_tool_replay.py
index c0482bce898..5fdeb698f38 100644
--- a/tests/agent/test_responses_empty_tool_replay.py
+++ b/tests/agent/test_responses_empty_tool_replay.py
@@ -18,7 +18,7 @@ def test_reasoning_without_tool_keeps_nonempty_following_item():
'codex_reasoning_items': [{'type': 'reasoning', 'id': 'rs_test',
'encrypted_content': 'synthetic-encrypted-fixture', 'summary': []}],
}])
- assert items[-1] == {'role': 'assistant', 'content': ' '}
+ assert items[-1] == {'type': 'message', 'role': 'assistant', 'content': ' '}
def test_failing_turn_fixture_emits_no_invented_carrier():
@@ -36,7 +36,7 @@ def test_failing_turn_fixture_emits_no_invented_carrier():
)
messages = json.loads(fixture_path.read_text(encoding="utf-8"))
items = _chat_messages_to_responses_input(messages)
- assert {"role": "assistant", "content": ""} not in items
+ assert {"type": "message", "role": "assistant", "content": ""} not in items
for i, item in enumerate(items):
if item.get("type") == "reasoning":
# Reasoning items may cluster; the next non-reasoning item after