Skip to content

The agent that grows with you

fix(responses): preserve explicit assistant phase in role-message replay

Xiponge19de264c5ac
diff --git a/agent/codex_responses_adapter.py b/agent/codex_responses_adapter.py
index de31d2ffaf3..736745e8116 100644
--- a/agent/codex_responses_adapter.py
+++ b/agent/codex_responses_adapter.py
@@ -364,6 +364,18 @@ def _normalize_responses_message_status(value: Any, *, default: str = "completed
return 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]:
@@ -641,7 +653,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_item("assistant", wire_content(follower))], msg)
+ emit([_role_message_with_phase("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
@@ -811,13 +823,14 @@ 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/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.
+ # 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.
content = item.get("content")
is_replayed_assistant = (
item.get("role") == "assistant" and isinstance(content, list)
- and any(key in item for key in ("id", "status", "phase"))
+ and any(key in item for key in ("id", "status"))
)
if not is_replayed_assistant:
return _preflight_role_message(item, idx, ctx)
@@ -845,7 +858,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_item(role, ctx.sanitize_text(_str_or_empty(content)))
+ return _role_message_with_phase(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)
@@ -866,7 +879,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_item(role, validated)
+ return _role_message_with_phase(role, validated, item.get("phase"))
_PREFLIGHT_ITEM_HANDLERS: Dict[str, Callable[..., Optional[Dict[str, Any]]]] = {
diff --git a/tests/agent/test_responses_replay_phase_regression.py b/tests/agent/test_responses_replay_phase_regression.py
new file mode 100644
index 00000000000..9ce46c1431e
--- /dev/null
+++ b/tests/agent/test_responses_replay_phase_regression.py
@@ -0,0 +1,71 @@
+"""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."