The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): keep user image parts through typed Responses preflight
kshitijk4poor23200e75e1d7
diff --git a/agent/codex_responses_adapter.py b/agent/codex_responses_adapter.pyindex 09578aa2d79..de31d2ffaf3 100644--- a/agent/codex_responses_adapter.py+++ b/agent/codex_responses_adapter.py@@ -365,28 +365,22 @@ def _normalize_responses_message_status(value: Any, *, default: str = "completeddef _message_item(- content: Any, *, status: str, item_id: Optional[str] = None, phase: Optional[str] = None,+ content: List[Dict[str, 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. ``content`` is a- list of parts, or the string a plain-text message carries."""+ """Assistant ``message`` item; ``id``/``phase`` are added only when non-empty."""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 itemdef _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.- """+ """Plain ``message`` input item for ``role``. ``type`` is required: llama.cpp's ``/v1/responses``+ parser rejects a typeless assistant item ("Cannot determine type of 'item'")."""return {"type": "message", "role": role, "content": content}def _assistant_message_item(- raw: Dict[str, Any], content: Any, *, is_github_responses: bool,+ raw: Dict[str, Any], content: List[Dict[str, 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@@ -817,43 +811,33 @@ 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]:- """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'.")+ # Only replayed assistant output (a list-content item carrying id/status/phase) takes the strict+ # path below; the converter's plain role items go through _preflight_role_message, so preflight+ # neither rejects user image parts nor synthesizes a status the converter never sent.content = item.get("content")- # 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)+ is_replayed_assistant = (+ item.get("role") == "assistant" and isinstance(content, list)+ and any(key in item for key in ("id", "status", "phase"))+ )+ if not is_replayed_assistant:+ return _preflight_role_message(item, idx, ctx)+ 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)def _preflight_role_message(item: Dict[str, Any], idx: int, ctx: _PreflightCtx) -> Dict[str, Any]:- """Untyped ``user``/``assistant`` role message — the only legal shape besides typed items."""+ """``user``/``assistant`` role message, typed or untyped; string content or Responses parts."""role = item.get("role")if role not in {"user", "assistant"}:raise ValueError(diff --git a/agent/native_compaction.py b/agent/native_compaction.pyindex e55c5566c5e..f0f44fab8ac 100644--- a/agent/native_compaction.py+++ b/agent/native_compaction.py@@ -273,7 +273,8 @@ def prune_pre_checkpoint_items(text = flatten_message_text(source.get("content"))_src_role = source.get("role")_retain_summary(text if text.strip() else None,- {"role": _src_role if _src_role in ("user", "assistant") else "assistant", "content": text})+ {"type": "message", "role": _src_role if _src_role in ("user", "assistant") else "assistant",+ "content": text})continue# Typed non-message items never carry role=user or a summary flag.if "type" in item and item.get("type") != "message":diff --git a/tests/agent/test_codex_responses_adapter.py b/tests/agent/test_codex_responses_adapter.pyindex 421dba3321c..580eb7ea693 100644--- a/tests/agent/test_codex_responses_adapter.py+++ b/tests/agent/test_codex_responses_adapter.py@@ -997,122 +997,25 @@ def test_codex_preflight_passes_text_verbosity_through():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():[email protected]("issuer", [None, "codex_backend"])+def test_converter_role_items_are_typed_and_survive_preflight(issuer):+ """llama.cpp's /v1/responses rejects typeless message items; preflight must accept every+ item the converter emits, including user image parts."""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": "user", "content": [+ {"type": "text", "text": "what is this"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},]},- {"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": "a cat"},{"role": "assistant", "content": "", "codex_reasoning_items": [- {"type": "reasoning", "encrypted_content": "opaque-carrier", "summary": []},+ {"type": "reasoning", "encrypted_content": "opaque", "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"}]},- ])+ {"role": "user", "content": "thanks"},+ ], current_issuer_kind=issuer)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}])+ role_items = [i for i in normalized if i.get("role")]+ assert role_items and all(i["type"] == "message" for i in role_items)+ assert {"type": "input_image", "image_url": "data:image/png;base64,AAAA"} in role_items[0]["content"]+ assert normalized == itemsdiff --git a/tests/agent/test_responses_empty_tool_replay.py b/tests/agent/test_responses_empty_tool_replay.pyindex 5fdeb698f38..ef6bb5d0917 100644--- a/tests/agent/test_responses_empty_tool_replay.py+++ b/tests/agent/test_responses_empty_tool_replay.py@@ -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 {"type": "message", "role": "assistant", "content": ""} not in items+ assert not any(i.get("role") == "assistant" and i.get("content") == "" for i in items)for i, item in enumerate(items):if item.get("type") == "reasoning":# Reasoning items may cluster; the next non-reasoning item after