The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(auxiliary): preserve Codex completion status and phase
Xipong0104b9810d62
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 75bff11af14..8b743d282dd 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -1129,26 +1129,33 @@ def _scoped_key_env(name: str) -> str:# Codex Responses → chat.completions adapter, so aux consumers need no changes.-def _parse_codex_final_response(final: Any) -> Tuple[List[str], List[Any], Any]:- """Split a completed Responses object into (text_parts, tool_calls, usage) in chat.completions shape."""- text_parts: List[str] = []- tool_calls_raw: List[Any] = []- for item in (getattr(final, "output", None) or []):- item_type = _field(item, "type")- if item_type == "message":- for part in (_field(item, "content") or []):- part_type = _field(part, "type")- if part_type in {"output_text", "text"}:- text_parts.append(_field(part, "text", ""))- elif part_type == "refusal":- # A refusal part carries the model's explanation; dropping it turns a- # refusal-only turn into an empty response that gets retried.- text_parts.append(_field(part, "refusal", ""))- elif item_type == "function_call":- tool_calls_raw.append(SimpleNamespace(- id=_field(item, "call_id", ""), type="function",- function=SimpleNamespace(- name=_field(item, "name", ""), arguments=_field(item, "arguments", "{}"))))+def _parse_codex_final_response(final: Any) -> Tuple[List[str], List[Any], Any, str]:+ """Normalize Responses output without losing phase or completion state for aux callers."""+ from agent.codex_responses_adapter import _normalize_codex_response++ # The shared normalizer reads SDK-style items. Keep support for compatible hosts+ # returning dict items, and the aux adapter's legacy empty completed response.+ output = [+ SimpleNamespace(**item) if isinstance(item, dict) else item+ for item in (getattr(final, "output", None) or [])+ ]+ normalized_final = SimpleNamespace(+ output=output or [SimpleNamespace(type="message", content=[])],+ output_text=getattr(final, "output_text", None),+ status=getattr(final, "status", None),+ incomplete_details=getattr(final, "incomplete_details", None),+ error=getattr(final, "error", None),+ )+ message, finish_reason = _normalize_codex_response(normalized_final)+ status = str(normalized_final.status or "").strip().lower()+ reason = str(_field(normalized_final.incomplete_details, "reason", "") or "").strip().lower()+ # Aux consumers speak Chat Completions: "length" activates their existing+ # partial-summary rejection/fallback, whereas Codex's "incomplete" does not.+ # A final_answer phase cannot override the provider's incomplete status.+ if finish_reason == "incomplete" or (status == "incomplete" and reason != "content_filter"):+ finish_reason = "length"+ text_parts = [message.content] if message.content else []+ tool_calls_raw = message.tool_callsusage = Noneresp_usage = getattr(final, "usage", None)if resp_usage:@@ -1157,7 +1164,7 @@ def _parse_codex_final_response(final: Any) -> Tuple[List[str], List[Any], Any]:usage = SimpleNamespace(prompt_tokens=_u("input_tokens"), completion_tokens=_u("output_tokens"),total_tokens=_u("total_tokens"))- return text_parts, tool_calls_raw, usage+ return text_parts, tool_calls_raw, usage, finish_reasondef _attempt_stream_socket(stream: Any) -> Any:@@ -1618,7 +1625,7 @@ class _CodexCompletionsAdapter:guard.release_stream(event_stream)if final is None:raise RuntimeError("Codex auxiliary Responses stream did not return a final response")- text_parts, tool_calls_raw, usage = _parse_codex_final_response(final)+ text_parts, tool_calls_raw, usage, finish_reason = _parse_codex_final_response(final)# Undo only the aliases THIS request emitted, before the call reaches Hermes dispatch.for tc in tool_calls_raw or ():if tc.function.name in wire_aliases:@@ -1635,10 +1642,11 @@ class _CodexCompletionsAdapter:role="assistant", content="".join(text_parts).strip() or None,tool_calls=tool_calls_raw or None,)- choice = SimpleNamespace(- index=0, message=message, finish_reason="stop" if not tool_calls_raw else "tool_calls"+ choice = SimpleNamespace(index=0, message=message, finish_reason=finish_reason)+ return SimpleNamespace(+ choices=[choice], model=model, usage=usage, status=getattr(final, "status", None),+ incomplete_details=getattr(final, "incomplete_details", None), error=getattr(final, "error", None),)- return SimpleNamespace(choices=[choice], model=model, usage=usage)class _ChatShim:diff --git a/tests/agent/test_auxiliary_codex_completion_status.py b/tests/agent/test_auxiliary_codex_completion_status.pynew file mode 100644index 00000000000..ac3d673d9f1--- /dev/null+++ b/tests/agent/test_auxiliary_codex_completion_status.py@@ -0,0 +1,136 @@+"""Auxiliary Responses normalization must not certify a partial checkpoint."""++from types import SimpleNamespace++import pytest++from agent.auxiliary_client import _CodexCompletionsAdapter+from agent.context_compressor import ContextCompressor+++def _message(text, *, phase: str | None = "final_answer", status="completed"):+ return SimpleNamespace(+ type="message", role="assistant", phase=phase, status=status,+ content=[SimpleNamespace(type="output_text", text=text)],+ )+++def _adapter_response(final, *, streamed):+ class FakeStream:+ def __iter__(self):+ if getattr(final, "output_text", ""):+ yield SimpleNamespace(type="response.output_text.delta", delta=final.output_text)+ for item in final.output or []:+ yield SimpleNamespace(type="response.output_item.done", item=item)+ # Cancellation is a response status, not a Responses SSE event type.+ terminal = "failed" if final.status == "cancelled" else final.status+ yield SimpleNamespace(type=f"response.{terminal}", response=final)++ def close(self):+ pass++ class FakeResponses:+ def create(self, **kwargs):+ assert kwargs["stream"] is True+ return FakeStream() if streamed else final++ return _CodexCompletionsAdapter(+ SimpleNamespace(responses=FakeResponses()), "aux-model",+ ).create(messages=[{"role": "user", "content": "Summarize the task."}])++[email protected]("fallback", [False, True], ids=["abort", "main-fallback"])+def test_compressor_rejects_actual_adapter_partial_summary(monkeypatch, fallback):+ partial = SimpleNamespace(+ status="incomplete", output=[_message("PARTIAL_CHECKPOINT")],+ incomplete_details={"reason": "max_output_tokens"}, error=None,+ usage=SimpleNamespace(input_tokens=11, output_tokens=3, total_tokens=14),+ )+ complete = SimpleNamespace(+ status="completed", output=[_message("COMPLETE_CHECKPOINT")],+ incomplete_details=None, error=None, usage=None,+ )+ calls = []++ def fake_call_llm(**kwargs):+ calls.append(kwargs.get("model"))+ return _adapter_response(partial if len(calls) == 1 else complete, streamed=True)++ monkeypatch.setattr("agent.context_compressor.call_llm", fake_call_llm)+ monkeypatch.setattr("agent.context_compressor.get_model_context_length", lambda *a, **k: 100000)+ compressor = ContextCompressor(+ model="main-model", summary_model_override="aux-model" if fallback else "",+ quiet_mode=True, tail_mode="legacy", protect_first_n=2, protect_last_n=2,+ abort_on_summary_failure=False,+ )+ messages = [+ {"role": "user" if i % 2 == 0 else "assistant", "content": f"task {i} " + "x" * 50}+ for i in range(12)+ ]+ original = [dict(message) for message in messages]+ result = compressor.compress(messages, current_tokens=999999, force=True)++ assert "PARTIAL_CHECKPOINT" not in (compressor._previous_summary or "")+ assert messages == original+ if fallback:+ assert calls == ["aux-model", None]+ assert "COMPLETE_CHECKPOINT" in (compressor._previous_summary or "")+ assert result != original+ assert compressor._last_compress_aborted is False+ else:+ assert calls == [None]+ assert result == original+ assert compressor._previous_summary is None+ assert compressor._last_summary_truncated_failure is True+ assert compressor._last_compress_aborted is True++[email protected]("streamed", [False, True], ids=["response-object", "sse"])+ "status, output, reason, output_text, expected_content, expected_finish, error",+ [+ pytest.param("completed", [_message("FINAL")], None, "", "FINAL", "stop", None, id="final-answer"),+ pytest.param("completed", [_message("LEGACY", phase=None)], None, "", "LEGACY", "stop", None, id="unphased"),+ pytest.param("completed", [_message("COMMENTARY", phase="commentary")], None, "COMMENTARY", None, "length", None, id="commentary-only"),+ pytest.param("completed", [_message("ANALYSIS", phase="analysis")], None, "ANALYSIS", None, "length", None, id="analysis-only"),+ pytest.param("completed", [_message("COMMENTARY", phase="commentary"), _message("FINAL", phase="final")], None, "COMMENTARYFINAL", "FINAL", "stop", None, id="commentary-then-final"),+ pytest.param("completed", [SimpleNamespace(type="message", status="completed", content=[{"type": "refusal", "refusal": "DECLINED"}])], None, "", "DECLINED", "stop", None, id="refusal"),+ pytest.param("completed", [SimpleNamespace(type="function_call", status="completed", call_id="call_1", name="inspect", arguments='{"path":"x"}')], None, "", None, "tool_calls", None, id="tool-call"),+ pytest.param("incomplete", [_message("PARTIAL")], "max_output_tokens", "", "PARTIAL", "length", None, id="token-cap-final-phase"),+ pytest.param("incomplete", [_message("PARTIAL", phase=None)], "other", "", "PARTIAL", "length", None, id="other-incomplete"),+ pytest.param("completed", [_message("PARTIAL", status="incomplete")], None, "", "PARTIAL", "length", None, id="incomplete-item"),+ pytest.param("completed", [SimpleNamespace(type="function_call", status="in_progress", call_id="call_1", name="inspect", arguments='{"path":')], None, "", None, "length", None, id="partial-tool-call"),+ pytest.param("incomplete", None, "content_filter", "", None, "content_filter", None, id="content-filter"),+ pytest.param("failed", [_message("NOT_A_FINAL")], None, "", None, None, {"code": "provider_error", "message": "backend failed"}, id="failed"),+ pytest.param("cancelled", [_message("NOT_A_FINAL")], None, "", None, None, {"message": "request cancelled"}, id="cancelled"),+ pytest.param("completed", None, None, "DELTA_FINAL", "DELTA_FINAL", "stop", None, id="output-text-fallback"),+ pytest.param("completed", None, None, "", None, "stop", None, id="legacy-empty"),+ ],+)+def test_actual_adapter_preserves_completion_contract(+ streamed, status, output, reason, output_text, expected_content, expected_finish, error,+):+ details = {"reason": reason} if reason else None+ final = SimpleNamespace(+ status=status, output=output, output_text=output_text,+ incomplete_details=details, error=error,+ usage={"input_tokens": 11, "output_tokens": 3, "total_tokens": 14},+ )+ if error:+ with pytest.raises(RuntimeError, match=error["message"]):+ _adapter_response(final, streamed=streamed)+ return++ response = _adapter_response(final, streamed=streamed)+ choice = response.choices[0]+ assert choice.message.content == expected_content+ assert choice.finish_reason == expected_finish+ assert getattr(response, "status", None) == status+ assert getattr(response, "incomplete_details", None) == details+ assert getattr(response, "error", None) is None+ assert (response.usage.prompt_tokens, response.usage.completion_tokens, response.usage.total_tokens) == (11, 3, 14)+ if expected_finish == "tool_calls":+ call, = choice.message.tool_calls+ assert (call.id, call.function.name, call.function.arguments) == ("call_1", "inspect", '{"path":"x"}')+ else:+ assert choice.message.tool_calls is None