The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(responses): one role-item constructor carries a validated phase
kshitijk4poor07ab19b0a399
diff --git a/agent/codex_responses_adapter.py b/agent/codex_responses_adapter.pyindex 736745e8116..d4a630929d5 100644--- a/agent/codex_responses_adapter.py+++ b/agent/codex_responses_adapter.py@@ -364,18 +364,6 @@ def _normalize_responses_message_status(value: Any, *, default: str = "completedreturn status if status in _RESPONSE_MESSAGE_STATUSES else default-def _role_message_with_phase(role: str, content: Any, phase: Any = None) -> Dict[str, Any]:- """Preserve an explicitly supplied assistant phase without inventing output status or IDs.-- Ordinary role messages and exact output-item replay must agree on phase; user inputs- never inherit assistant-only metadata. Keep absent/invalid phase absent.- """- item = _role_message_item(role, content)- if role == "assistant" and _nonblank(phase):- item["phase"] = phase.strip()- return item--def _message_item(content: List[Dict[str, Any]], *, status: str, item_id: Optional[str] = None, phase: Optional[str] = None,) -> Dict[str, Any]:@@ -385,10 +373,17 @@ def _message_item(return item-def _role_message_item(role: str, content: Any) -> Dict[str, Any]:+_ROLE_MESSAGE_PHASES = frozenset({"commentary", "final_answer"})+++def _role_message_item(role: str, content: Any, phase: Any = None) -> Dict[str, Any]:"""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}+ parser rejects a typeless assistant item ("Cannot determine type of 'item'"). Assistant ``phase``+ is forwarded only for values the API accepts on input messages; others would 400."""+ item = {"type": "message", "role": role, "content": content}+ if role == "assistant" and (cleaned := _lower_or_none(phase)) in _ROLE_MESSAGE_PHASES:+ item["phase"] = cleaned+ return itemdef _assistant_message_item(@@ -653,7 +648,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_message_with_phase("assistant", wire_content(follower), msg.get("phase"))], msg)+ emit([_role_message_item("assistant", wire_content(follower), msg.get("phase"))], 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@@ -824,9 +819,8 @@ 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]:# Only replayed assistant output (a list-content item carrying id/status) takes the strict path- # below; the converter's plain role items, which may carry a phase, go through- # _preflight_role_message, so preflight neither rejects user image parts nor synthesizes a- # status the converter never sent.+ # below. Phase alone is no replay marker: the converter's plain role items carry it too, and+ # preflight must not synthesize a status or reject user image parts for them.content = item.get("content")is_replayed_assistant = (item.get("role") == "assistant" and isinstance(content, list)@@ -858,7 +852,7 @@ def _preflight_role_message(item: Dict[str, Any], idx: int, ctx: _PreflightCtx))content = item.get("content", "")if not isinstance(content, list):- return _role_message_with_phase(role, ctx.sanitize_text(_str_or_empty(content)), item.get("phase"))+ return _role_message_item(role, ctx.sanitize_text(_str_or_empty(content)), item.get("phase"))# 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)@@ -879,7 +873,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_message_with_phase(role, validated, item.get("phase"))+ return _role_message_item(role, validated, item.get("phase"))_PREFLIGHT_ITEM_HANDLERS: Dict[str, Callable[..., Optional[Dict[str, Any]]]] = {diff --git a/tests/agent/test_codex_responses_adapter.py b/tests/agent/test_codex_responses_adapter.pyindex 580eb7ea693..9febf15acba 100644--- a/tests/agent/test_codex_responses_adapter.py+++ b/tests/agent/test_codex_responses_adapter.py@@ -1019,3 +1019,31 @@ def test_converter_role_items_are_typed_and_survive_preflight(issuer):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 == items++[email protected]("issuer", [None, "codex_backend"])[email protected]("structured", [False, True])+def test_role_message_phase_survives_conversion_and_preflight(issuer, structured):+ """Assistant phase is resent through conversion and preflight, per OpenAI's replay guidance."""+ content = [{"type": "text", "text": "Checking."}] if structured else "Checking."+ history = [+ {"role": "user", "content": "audit"},+ {"role": "assistant", "content": content, "phase": " Commentary "},+ ]+ converted = _chat_messages_to_responses_input(history, current_issuer_kind=issuer)++ normalized = _preflight_codex_api_kwargs({"model": "m", "instructions": "i", "input": converted, "store": False})++ assert converted[-1]["phase"] == "commentary"+ assert normalized["input"] == converted+++def test_role_message_phase_is_kept_only_for_assistant_values_the_api_accepts():+ wire = _preflight_codex_input_items([+ {"role": "assistant", "content": "a", "phase": "final_answer"},+ {"role": "assistant", "content": "b", "phase": "analysis"},+ {"role": "assistant", "content": "c", "phase": 42},+ {"role": "user", "content": "d", "phase": "commentary"},+ ])++ assert [item.get("phase") for item in wire] == ["final_answer", None, None, None]diff --git a/tests/agent/test_responses_replay_phase_regression.py b/tests/agent/test_responses_replay_phase_regression.pydeleted file mode 100644index 9ce46c1431e..00000000000--- a/tests/agent/test_responses_replay_phase_regression.py+++ /dev/null@@ -1,71 +0,0 @@-"""Assistant phase must survive ordinary replay and both preflight passes."""-from copy import deepcopy--import pytest--from agent.codex_responses_adapter import (- _chat_messages_to_responses_input,- _preflight_codex_api_kwargs,- _preflight_codex_input_items,-)--[email protected]("phase", ["commentary", "final_answer", "analysis", " Commentary "])[email protected]("content", ["Checking the next file.", [{"type": "output_text", "text": "Checking the next file."}]])-def test_untyped_preflight_keeps_explicit_assistant_phase(phase, content):- raw = [{"role": "assistant", "phase": phase, "content": content, "id": "must-not-be-replayed", "extra": "omit"}]- original = deepcopy(raw)- wire = _preflight_codex_input_items(raw)- assert wire[0]["phase"] == phase.strip()- assert set(wire[0]) == {"type", "role", "content", "phase"}- assert raw == original- assert _preflight_codex_input_items(wire) == wire--[email protected]("issuer", [None, "codex_backend", "github_responses", "xai_responses"])[email protected]("structured", [False, True])-def test_history_fallback_and_final_request_preflight_retain_phase(issuer, structured):- text = "Продолжаю проверку."- content = [{"type": "text", "text": text}] if structured else text- history = [{"role": "user", "content": "audit"}, {"role": "assistant", "content": content, "phase": "commentary"}]- original = deepcopy(history)- converted = _chat_messages_to_responses_input(history, current_issuer_kind=issuer, is_github_responses=issuer == "github_responses")- assert converted[-1]["phase"] == "commentary"- request = {"model": "test-model", "instructions": "test", "input": converted, "store": False}- first = _preflight_codex_api_kwargs(request, is_github_responses=issuer == "github_responses")- second = _preflight_codex_api_kwargs(first, is_github_responses=issuer == "github_responses")- assert second["input"][-1]["phase"] == "commentary"- assert second["input"][-1]["content"] == converted[-1]["content"]- assert first == second- assert history == original--[email protected]("phase", [None, "", " ", 42, False, {}, []])-def test_absent_or_invalid_phase_is_not_invented(phase):- raw = [{"role": "assistant", "content": "Answer", "phase": phase}]- assert "phase" not in _preflight_codex_input_items(raw)[0]- assert "phase" not in _chat_messages_to_responses_input(raw)[0]---def test_user_phase_is_not_forwarded_and_typed_sidecar_remains_authoritative():- history = [- {"role": "user", "content": "audit", "phase": "commentary"},- {"role": "assistant", "content": "stale fallback", "phase": "final_answer", "codex_message_items": [- {"type": "message", "role": "assistant", "status": "completed", "id": "msg_original", "phase": "commentary", "content": [{"type": "output_text", "text": "Checking."}]},- ]},- ]- original = deepcopy(history)- wire = _preflight_codex_input_items(_chat_messages_to_responses_input(history))- assert "phase" not in wire[0]- assert wire[1]["phase"] == "commentary"- assert wire[1]["id"] == "msg_original"- assert wire[1]["content"][0]["text"] == "Checking."- assert history == original---def test_phase_and_text_sanitization_are_independent():- raw = [{"role": "assistant", "phase": "commentary", "content": "Reading <|start|> safely."}]- wire = _preflight_codex_input_items(raw, sanitize_harmony_tokens=True)- assert wire[0]["phase"] == "commentary"- assert "<|start|>" not in wire[0]["content"]- assert raw[0]["content"] == "Reading <|start|> safely."