The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge remote-tracking branch 'origin/main' into HEAD
joaomarcosb0785fc1a19a
diff --cc tests/run_agent/test_run_agent_codex_responses.pyindex 1df2addcfff,f4a0515910b..b10d324f5a1--- a/tests/run_agent/test_run_agent_codex_responses.py+++ b/tests/run_agent/test_run_agent_codex_responses.py@@@ -857,339 -603,43 +603,105 @@@ def test_run_codex_stream_delivers_redaassert len(delivered) == 1- def test_run_codex_stream_multiple_commentary_items_are_not_reemitted(monkeypatch):- from agent.codex_responses_adapter import _normalize_codex_response-- agent = _build_agent(monkeypatch)- delivered = []- agent.interim_assistant_callback = (- lambda text, *, already_streamed=False: delivered.append(text)- )- commentary_a = SimpleNamespace(- type="message",- phase="commentary",- status="completed",- content=[SimpleNamespace(type="output_text", text="First update.")],- )- commentary_b = SimpleNamespace(- type="message",- phase="commentary",- status="completed",- content=[SimpleNamespace(type="output_text", text="Second update.")],- )- function_item = SimpleNamespace(- type="function_call",- id="fc_1",- call_id="call_1",- name="terminal",- arguments="{}",- )-- def _fake_create(**kwargs):- return _FakeCreateStream([- SimpleNamespace(- type="response.output_item.added",- item=SimpleNamespace(type="message", phase="commentary"),- ),- SimpleNamespace(type="response.output_text.delta", delta="First update."),- SimpleNamespace(type="response.output_item.done", item=commentary_a),- SimpleNamespace(- type="response.output_item.added",- item=SimpleNamespace(type="message", phase="commentary"),- ),- SimpleNamespace(type="response.output_text.delta", delta="Second update."),- SimpleNamespace(type="response.output_item.done", item=commentary_b),- SimpleNamespace(- type="response.output_item.added",- item=SimpleNamespace(type="function_call"),- ),- SimpleNamespace(type="response.output_item.done", item=function_item),- SimpleNamespace(- type="response.completed",- response=SimpleNamespace(status="completed"),- ),- ])-- agent.client = SimpleNamespace(responses=SimpleNamespace(create=_fake_create))- response = agent._run_codex_stream(_codex_request_kwargs())- normalized, finish_reason = _normalize_codex_response(response)- agent._emit_interim_assistant_message(- agent._build_assistant_message(normalized, finish_reason)- )-- assert delivered == ["First update.", "Second update."]--- def test_run_codex_stream_retry_deduplicates_multiple_commentary_items(monkeypatch):- import httpx-- agent = _build_agent(monkeypatch)- delivered = []- agent.interim_assistant_callback = (- lambda text, *, already_streamed=False: delivered.append(text)- )- commentary_a = SimpleNamespace(- type="message",- phase="commentary",- status="completed",- content=[SimpleNamespace(type="output_text", text="First update.")],- )- commentary_b = SimpleNamespace(- type="message",- phase="commentary",- status="completed",- content=[SimpleNamespace(type="output_text", text="Second update.")],- )-- class _DroppingStream(_FakeCreateStream):- def __iter__(self):- yield from super().__iter__()- raise httpx.RemoteProtocolError("connection dropped")-- commentary_events = [- SimpleNamespace(- type="response.output_item.added",- item=SimpleNamespace(type="message", phase="commentary"),- ),- SimpleNamespace(type="response.output_text.delta", delta="First update."),- SimpleNamespace(type="response.output_item.done", item=commentary_a),- SimpleNamespace(- type="response.output_item.added",- item=SimpleNamespace(type="message", phase="commentary"),- ),- SimpleNamespace(type="response.output_text.delta", delta="Second update."),- SimpleNamespace(type="response.output_item.done", item=commentary_b),- ]- calls = {"count": 0}-- def _fake_create(**kwargs):- calls["count"] += 1- if calls["count"] == 1:- return _DroppingStream(commentary_events)- return _FakeCreateStream([- *commentary_events,- SimpleNamespace(- type="response.completed",- response=SimpleNamespace(status="completed"),- ),- ])-- agent.client = SimpleNamespace(responses=SimpleNamespace(create=_fake_create))- response = agent._run_codex_stream(_codex_request_kwargs())- assert response.status == "completed"- assert calls["count"] == 2- assert delivered == ["First update.", "Second update."]+def test_run_codex_stream_returns_terminal_response_when_post_terminal_drain_fails(+ monkeypatch, caplog+):+ """Regression test for issue #74310.++ A transport error while draining the SSE iterator *after* a valid+ ``response.completed`` has already been observed (and the response+ object fully assembled) must NOT discard that response and retry with+ a brand-new physical request -- that would silently duplicate an+ already-billed inference. Only errors that occur BEFORE a terminal+ event is captured should trigger the retry-with-new-request path.+ """+ import logging++ import httpx+ agent = _build_agent(monkeypatch)+ message_item = SimpleNamespace(+ type="message",+ status="completed",+ content=[SimpleNamespace(type="output_text", text="All done.")],+ )+ usage = SimpleNamespace(input_tokens=10, output_tokens=6, total_tokens=16)++ class _PostTerminalDroppingStream(_FakeCreateStream):+ """Yields events normally, then raises only on the *next* pull --+ i.e. after ``response.completed`` has already been consumed and the+ event-driven parser has broken out of its loop."""++ def __iter__(self):+ yield from super().__iter__()+ raise httpx.RemoteProtocolError("connection dropped during drain")++ events = [+ SimpleNamespace(type="response.output_item.done", item=message_item),+ SimpleNamespace(+ type="response.completed",+ response=SimpleNamespace(+ status="completed",+ usage=usage,+ id="resp_post_terminal_1",+ ),+ ),+ ]+ calls = {"count": 0}+ def _fake_create(**kwargs):+ calls["count"] += 1+ return _PostTerminalDroppingStream(events)++ agent.client = SimpleNamespace(responses=SimpleNamespace(create=_fake_create))++ with caplog.at_level(logging.WARNING, logger="agent.codex_runtime"):+ response = agent._run_codex_stream(_codex_request_kwargs())++ # Only ONE physical request was ever opened -- the drain failure did not+ # trigger a second call to responses.create(stream=True).+ assert calls["count"] == 1+ assert response.status == "completed"+ assert response.usage is usage+ assert response.id == "resp_post_terminal_1"+ assert any(+ "finalization" in record.message for record in caplog.records+ )- def test_run_codex_stream_surfaces_failed_status_in_final_response(monkeypatch):- """A ``response.failed`` terminal event is reflected on the returned object."""+ def test_run_conversation_codex_plain_text(monkeypatch):agent = _build_agent(monkeypatch)- error_payload = {"message": "model overloaded", "code": "overloaded"}- failed_event = SimpleNamespace(- type="response.failed",- response=SimpleNamespace(- status="failed",- error=error_payload,- id="resp_failed_1",- usage=None,- ),- )-- def _fake_create(**kwargs):- return _FakeCreateStream([- SimpleNamespace(type="response.created"),- failed_event,- ])+ monkeypatch.setattr(agent, "_interruptible_api_call", lambda api_kwargs: _codex_message_response("OK"))- agent.client = SimpleNamespace(- responses=SimpleNamespace(create=_fake_create),- )+ result = agent.run_conversation("Say OK")- response = agent._run_codex_stream(_codex_request_kwargs())- assert response.status == "failed"- assert response.error == error_payload+ assert result["completed"] is True+ assert result["final_response"] == "OK"+ assert result["messages"][-1]["role"] == "assistant"+ assert result["messages"][-1]["content"] == "OK"- def test_run_codex_stream_parses_create_stream_events(monkeypatch):- """The primary path consumes ``responses.create(stream=True)`` events directly."""- agent = _build_agent(monkeypatch)- calls = {"create": 0}- create_stream = _FakeCreateStream(- [- SimpleNamespace(type="response.created"),- SimpleNamespace(type="response.in_progress"),- SimpleNamespace(type="response.completed", response=_codex_message_response("streamed create ok")),- ]- )+ def test_copilot_final_preflight_sanitizes_both_middleware_layers(monkeypatch):+ """The dispatch chokepoint must sanitize after every mutable layer."""+ agent = _build_copilot_agent(monkeypatch)+ setattr(agent, "_disable_streaming", True)+ captured = {}- def _fake_create(**kwargs):- calls["create"] += 1- assert kwargs.get("stream") is True- return create_stream-- agent.client = SimpleNamespace(- responses=SimpleNamespace(create=_fake_create),- )-- response = agent._run_codex_stream(_codex_request_kwargs())- assert calls["create"] == 1- assert create_stream.closed is True- # The wire's response.completed.response.output is a list with the message item,- # but the event-driven path reconstructs from response.output_item.done.- # _codex_message_response returns a SimpleNamespace whose .output is a list of- # items — we don't read those directly, we read the items via output_item.done,- # but this fixture doesn't emit output_item.done. So the consumer assembles a- # message from streamed text deltas if present, or returns the items it has.- # For backward compatibility with the helper that builds _codex_message_response,- # we just assert status is completed and id propagated.- assert response.status == "completed"--- def test_run_codex_stream_ignores_completed_response_with_null_output(monkeypatch):- """Regression: Codex may send response.completed.response.output=null.-- The SDK's high-level ``responses.stream(...)`` helper used to reconstruct- the final Response from that terminal field and raised ``TypeError:- 'NoneType' object is not iterable``. The Hermes runtime consumes raw- ``response.output_item.done`` events instead, so a null terminal ``output``- must not affect the returned assistant/function-call items.- """- agent = _build_agent(monkeypatch)- output_item = SimpleNamespace(- type="message",- status="completed",- content=[SimpleNamespace(type="output_text", text="terminal output was null")],- )- create_stream = _FakeCreateStream(- [- SimpleNamespace(type="response.created"),- SimpleNamespace(type="response.output_item.done", item=output_item),- SimpleNamespace(- type="response.completed",- response=SimpleNamespace(- id="resp_null_output",- status="completed",- output=None,- usage=SimpleNamespace(input_tokens=7, output_tokens=4, total_tokens=11),- ),- ),- ]- )-- def _fake_create(**kwargs):- assert kwargs.get("stream") is True- return create_stream-- agent.client = SimpleNamespace(- responses=SimpleNamespace(create=_fake_create),- )-- response = agent._run_codex_stream(_codex_request_kwargs())- assert response is not None- assert create_stream.closed is True- assert response.id == "resp_null_output"- assert response.status == "completed"- assert response.output == [output_item]- assert response.usage.total_tokens == 11--- def test_run_conversation_codex_plain_text(monkeypatch):- agent = _build_agent(monkeypatch)- monkeypatch.setattr(agent, "_interruptible_api_call", lambda api_kwargs: _codex_message_response("OK"))-- result = agent.run_conversation("Say OK")-- assert result["completed"] is True- assert result["final_response"] == "OK"- assert result["messages"][-1]["role"] == "assistant"- assert result["messages"][-1]["content"] == "OK"--- def test_copilot_final_preflight_sanitizes_both_middleware_layers(monkeypatch):- """The dispatch chokepoint must sanitize after every mutable layer."""- agent = _build_copilot_agent(monkeypatch)- setattr(agent, "_disable_streaming", True)- captured = {}-- def _message_item(item_id, *, text, phase, status):- return {- "type": "message",- "role": "assistant",- "status": status,- "content": [{"type": "output_text", "text": text}],- "id": item_id,- "phase": phase,- }+ def _message_item(item_id, *, text, phase, status):+ return {+ "type": "message",+ "role": "assistant",+ "status": status,+ "content": [{"type": "output_text", "text": text}],+ "id": item_id,+ "phase": phase,+ }def _request_middleware(request, **_context):replacement = dict(request)