From 654915f187d45c1e29e618fb419abb43adee6a5f Mon Sep 17 00:00:00 2001 From: AKAZIK-py <200184714+AKAZIK-py@users.noreply.github.com> Date: Fri, 31 Jul 2026 11:53:17 +0800 Subject: [PATCH 1/7] fix(moa): unwrap completed responses in the auxiliary streaming path --- agent/auxiliary_client.py | 1 + agent/relay_llm.py | 25 ++++++++- tests/agent/test_auxiliary_relay.py | 38 ++++++++++++++ tests/agent/test_relay_llm.py | 81 +++++++++++++++++++++++++++++ 4 files changed, 143 insertions(+), 2 deletions(-) diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py index 96dce03fae..4f8ee48de5 100644 --- a/agent/auxiliary_client.py +++ b/agent/auxiliary_client.py @@ -2664,6 +2664,7 @@ def _relay_sync_stream( model_name=str(kwargs.get("model") or fallback_model), finalizer=dict, metadata=metadata, + completed_response_predicate=lambda value: hasattr(value, "choices"), ) _RUNTIME_MAIN_COMPAT_SNAPSHOT: Tuple[Any, ...] = ("", "", "", "", "", "") _RUNTIME_MAIN_COMPAT_LOCK = threading.Lock() diff --git a/agent/relay_llm.py b/agent/relay_llm.py index 3481ca0723..2d3a2883e1 100644 --- a/agent/relay_llm.py +++ b/agent/relay_llm.py @@ -256,12 +256,23 @@ def stream_current( finalizer: Callable[[], Any], metadata: dict[str, Any] | None = None, defer_logical_completion: bool = False, + completed_response_predicate: Callable[[Any], bool] | None = None, ) -> Any: - """Run a provider stream under the inherited Hermes turn when present.""" + """Run a provider stream under the inherited Hermes turn when present. + + When ``completed_response_predicate`` is set and the stream_factory returns + a complete response instead of an iterator (e.g. AnthropicAuxiliaryClient + and other shims that ignore ``stream=True``), unwrap and return the + completed response directly. This mirrors the pre-Relay behavior where + ``call_llm(stream=True)`` returned the raw response and the consumer's + own ``hasattr(stream, "choices")`` check handled it (#11732, #55933) — + without the unwrap the response stays trapped as ``final_response`` on the + inner ManagedLlmStream and the outer consumer sees an empty stream. + """ turn = relay_runtime.active_turn() if turn is None: return stream_factory(request) - return stream( + managed = stream( request, stream_factory, session_id=turn.lease.session_id, @@ -270,7 +281,17 @@ def stream_current( finalizer=finalizer, metadata=metadata, defer_logical_completion=defer_logical_completion, + completed_response_predicate=completed_response_predicate, ) + # In the non-managed path the factory already ran eagerly during __init__, + # so a completed response is visible immediately and must surface raw. + # In the managed path the factory runs lazily on first pull, so + # final_response is still None here and the managed stream is returned. + if completed_response_predicate is not None: + completed = getattr(managed, "final_response", None) + if completed is not None: + return completed + return managed def stream( diff --git a/tests/agent/test_auxiliary_relay.py b/tests/agent/test_auxiliary_relay.py index 5d6bb629d4..dd18782f0b 100644 --- a/tests/agent/test_auxiliary_relay.py +++ b/tests/agent/test_auxiliary_relay.py @@ -260,3 +260,41 @@ def test_partial_auxiliary_stream_failure_closes_before_recovery( turn.lease.host.release_managed_execution(consumer) + + +def test_auxiliary_stream_unwraps_completed_response(relay_turn): + """MoA aggregator on an Anthropic-protocol provider: the client returns a + completed response for ``stream=True`` (the adapter ignores the flag), so + ``_relay_sync_stream`` must surface it raw for the consumer's + ``hasattr(stream, "choices")`` handling — regression of #11732/#55933 via + the Relay integration (SimpleNamespace is not iterable).""" + _relay, _turn = relay_turn + completed = SimpleNamespace( + choices=[ + SimpleNamespace( + message=SimpleNamespace(content="aggregated"), + finish_reason="stop", + ) + ], + model="kimi-k3", + ) + client = SimpleNamespace( + chat=SimpleNamespace( + completions=SimpleNamespace(create=lambda **_kwargs: completed) + ) + ) + + @auxiliary_client._relay_auxiliary_call + def run(task): + auxiliary_client._set_relay_auxiliary_route( + "kimi-coding", + "kimi-k3", + "chat_completions", + ) + return auxiliary_client._relay_sync_stream( + client, + {"model": "kimi-k3", "messages": [], "stream": True}, + ) + + assert run("moa_aggregator") is completed + diff --git a/tests/agent/test_relay_llm.py b/tests/agent/test_relay_llm.py index 67acabc7fb..e506fad1e8 100644 --- a/tests/agent/test_relay_llm.py +++ b/tests/agent/test_relay_llm.py @@ -714,3 +714,84 @@ def test_codec_baseline_failure_is_explicit(relay_turn, monkeypatch, caplog): assert "ignoring request rewrites" in caplog.text +def test_stream_current_unwraps_completed_response(tmp_path, monkeypatch): + """Auxiliary streaming (the MoA aggregator) must surface a completed + provider response raw instead of crashing when the client ignores + ``stream=True`` and returns a response object (AnthropicAuxiliaryClient + and other OpenAI-compatible shims). + + Pre-Relay, ``call_llm(stream=True)`` returned the raw response and the + consumer's ``hasattr(stream, "choices")`` check handled it (#11732, + #55933). The Relay integration wrapped the call in a ManagedLlmStream + without threading ``completed_response_predicate``, regressing that path + into ``TypeError: 'types.SimpleNamespace' object is not iterable``. + """ + monkeypatch.setenv("HERMES_HOME", str(tmp_path / "profile")) + relay_runtime._reset_for_tests() + lease = relay_runtime.SESSION_COORDINATOR.acquire_conversation( + profile_key=relay_runtime.current_profile_key(), + session_id="session-moa", + platform="cli", + ) + turn = relay_runtime.SESSION_COORDINATOR.begin_turn( + lease, + turn_id="turn-moa", + task_id="task-moa", + ) + try: + completed = SimpleNamespace( + choices=[ + SimpleNamespace( + message=SimpleNamespace(content="done"), + finish_reason="stop", + ) + ], + model="kimi-k3", + ) + result = relay_llm.stream_current( + {"model": "kimi-k3", "stream": True}, + lambda request: completed, + name="kimi-coding", + model_name="kimi-k3", + finalizer=dict, + completed_response_predicate=lambda value: hasattr(value, "choices"), + ) + # Unwrapped raw response — NOT a stream wrapper whose iteration would + # have raised TypeError pre-fix. + assert result is completed + finally: + relay_runtime.SESSION_COORDINATOR.end_turn(turn, outcome="success") + relay_runtime.SESSION_COORDINATOR.release_conversation(lease) + relay_runtime._reset_for_tests() + + +def test_stream_current_streams_iterators_with_predicate(tmp_path, monkeypatch): + """A genuine chunk iterator still flows through as a stream when the + completed-response predicate is supplied.""" + monkeypatch.setenv("HERMES_HOME", str(tmp_path / "profile")) + relay_runtime._reset_for_tests() + lease = relay_runtime.SESSION_COORDINATOR.acquire_conversation( + profile_key=relay_runtime.current_profile_key(), + session_id="session-moa", + platform="cli", + ) + turn = relay_runtime.SESSION_COORDINATOR.begin_turn( + lease, + turn_id="turn-moa", + task_id="task-moa", + ) + try: + result = relay_llm.stream_current( + {"model": "m", "stream": True}, + lambda request: iter([{"delta": "a"}, {"delta": "b"}]), + name="provider", + model_name="m", + finalizer=dict, + completed_response_predicate=lambda value: hasattr(value, "choices"), + ) + assert list(result) == [{"delta": "a"}, {"delta": "b"}] + finally: + relay_runtime.SESSION_COORDINATOR.end_turn(turn, outcome="success") + relay_runtime.SESSION_COORDINATOR.release_conversation(lease) + relay_runtime._reset_for_tests() + From 52705e496fedf54fe6de8f4f514b352e95e2e28c Mon Sep 17 00:00:00 2001 From: AKAZIK-py <200184714+AKAZIK-py@users.noreply.github.com> Date: Fri, 31 Jul 2026 11:53:17 +0800 Subject: [PATCH 2/7] test(moa): cover call_llm(stream=True) completed-response unwrap at the outermost seam --- tests/agent/test_auxiliary_relay.py | 49 +++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/tests/agent/test_auxiliary_relay.py b/tests/agent/test_auxiliary_relay.py index dd18782f0b..d2b41a82d4 100644 --- a/tests/agent/test_auxiliary_relay.py +++ b/tests/agent/test_auxiliary_relay.py @@ -298,3 +298,52 @@ def test_auxiliary_stream_unwraps_completed_response(relay_turn): assert run("moa_aggregator") is completed + + +def test_call_llm_stream_unwraps_completed_response(relay_turn, monkeypatch): + """Outermost seam: ``call_llm(stream=True)`` — decorated with + ``@_relay_auxiliary_call`` in production, so the Relay context is always + set — with an Anthropic-shaped client that ignores ``stream=True`` and + returns a completed response (the MoA aggregator on kimi-coding / + MiniMax / ZAI / any /anthropic gateway). Must return the raw response for + the consumer's ``hasattr(stream, "choices")`` handling, not crash with + ``TypeError: 'types.SimpleNamespace' object is not iterable``.""" + _relay, _turn = relay_turn + captured = {} + completed = SimpleNamespace( + choices=[ + SimpleNamespace( + message=SimpleNamespace(content="aggregated"), + finish_reason="stop", + ) + ], + model="kimi-k3", + ) + + def fake_create(**kwargs): + captured.update(kwargs) + return completed + + client = SimpleNamespace( + base_url="https://api.kimi.com/coding/v1", + chat=SimpleNamespace(completions=SimpleNamespace(create=fake_create)), + ) + monkeypatch.setattr( + auxiliary_client, + "_get_cached_client", + lambda *args, **kwargs: (client, "kimi-k3"), + ) + + result = auxiliary_client.call_llm( + "moa_aggregator", + provider="kimi-coding", + model="kimi-k3", + api_key="sk-test", + messages=[{"role": "user", "content": "q"}], + stream=True, + stream_options={"include_usage": True}, + ) + + assert result is completed + assert captured["stream"] is True + assert captured["stream_options"] == {"include_usage": True} From c23ff21d7ce80f7ec531ccbccc243236ecd89689 Mon Sep 17 00:00:00 2001 From: AKAZIK-py <200184714+AKAZIK-py@users.noreply.github.com> Date: Fri, 31 Jul 2026 11:53:17 +0800 Subject: [PATCH 3/7] fix(moa): carry completed responses through the managed Relay path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Under managed Relay execution the provider factory runs lazily inside provider_stream() on the Relay session's event loop. The MoA facade's auxiliary call_llm(stream=True) is invoked from that callback, so the eager final_response check added for the non-managed path never fires: the inner ManagedLlmStream is returned to the outer stream, which then synchronously iterates it on the same loop thread and dies with RuntimeError: Cannot run the event loop while another loop is running (the completed response effectively trapped one level deeper). stream_current() now detects a running event loop and returns the raw factory result instead of nesting a ManagedLlmStream: the outer managed stream already provides Relay tracking for the enclosing attempt, and its own completed_response_predicate traps the completed response as final_response — the same contract the main streaming worker consumes (chat_completion_helpers reads stream.final_response after the chunk loop). Nested managed streams remain supported for genuinely streaming providers via the outer stream's own iteration. Adds managed-execution regressions using the retained relay_turn fixture: direct completed-response trapping, and the nested facade-shaped stream_current call. --- agent/relay_llm.py | 19 +++++++++ tests/agent/test_relay_llm.py | 74 +++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) diff --git a/agent/relay_llm.py b/agent/relay_llm.py index 2d3a2883e1..96a98d54d2 100644 --- a/agent/relay_llm.py +++ b/agent/relay_llm.py @@ -247,6 +247,14 @@ async def execute_current_async( ) +def _has_running_event_loop() -> bool: + try: + asyncio.get_running_loop() + except RuntimeError: + return False + return True + + def stream_current( request: dict[str, Any], stream_factory: Callable[[dict[str, Any]], Any], @@ -272,6 +280,17 @@ def stream_current( turn = relay_runtime.active_turn() if turn is None: return stream_factory(request) + if _has_running_event_loop(): + # Managed provider callbacks execute on the Relay session's event + # loop. A nested ManagedLlmStream built here would be synchronously + # iterated on that same loop thread, which asyncio forbids + # ("Cannot run the event loop while another loop is running"). + # Return the raw factory result instead: the outer managed stream + # already provides Relay tracking for the enclosing attempt, and its + # own completed_response_predicate traps a completed response (e.g. + # the MoA facade's auxiliary ``call_llm(stream=True)`` returning a + # full response when an adapter ignores ``stream=True``). + return stream_factory(request) managed = stream( request, stream_factory, diff --git a/tests/agent/test_relay_llm.py b/tests/agent/test_relay_llm.py index e506fad1e8..e24897412a 100644 --- a/tests/agent/test_relay_llm.py +++ b/tests/agent/test_relay_llm.py @@ -795,3 +795,77 @@ def test_stream_current_streams_iterators_with_predicate(tmp_path, monkeypatch): relay_runtime.SESSION_COORDINATOR.release_conversation(lease) relay_runtime._reset_for_tests() + + +def _completed_response(content: str = "done") -> SimpleNamespace: + return SimpleNamespace( + model="test-model", + choices=[ + SimpleNamespace( + message=SimpleNamespace( + role="assistant", + content=content, + tool_calls=None, + ), + finish_reason="stop", + ) + ], + usage=None, + ) + + +def _choices_predicate(value) -> bool: + return hasattr(value, "choices") + + +def test_stream_managed_traps_direct_completed_response(relay_turn): + """Managed path: a factory returning a completed response (adapter + ignoring stream=True) is trapped as final_response instead of iterated.""" + relay, turn = relay_turn + del relay, turn + + stream = relay_llm.stream( + {"model": "test-model", "messages": []}, + lambda request: _completed_response(), + session_id="session-1", + name="test-provider", + model_name="test-model", + finalizer=lambda: {}, + completed_response_predicate=_choices_predicate, + ) + assert list(stream) == [] + assert stream.final_response is not None + assert stream.final_response.choices[0].message.content == "done" + + +def test_stream_current_inside_managed_callback_returns_raw(relay_turn): + """Managed path: an auxiliary stream_current() call made from inside a + managed provider callback (the MoA facade's call_llm(stream=True) shape) + must return the raw factory result; the outer stream traps a completed + response as its final_response instead of crashing on a nested event + loop or surfacing an empty stream.""" + relay, turn = relay_turn + del relay, turn + + def outer_factory(request): + return relay_llm.stream_current( + {"model": "test-model", "messages": []}, + lambda inner_request: _completed_response(), + name="moa-aggregator", + model_name="test-model", + finalizer=lambda: {}, + completed_response_predicate=_choices_predicate, + ) + + stream = relay_llm.stream( + {"model": "test-model", "messages": []}, + outer_factory, + session_id="session-1", + name="moa", + model_name="test-model", + finalizer=lambda: {}, + completed_response_predicate=_choices_predicate, + ) + assert list(stream) == [] + assert stream.final_response is not None + assert stream.final_response.choices[0].message.content == "done" From 8e191af0fb1def683f49feb40fd73149cd5750b0 Mon Sep 17 00:00:00 2001 From: knocksen <268946116+liusencomic-cyber@users.noreply.github.com> Date: Fri, 31 Jul 2026 21:50:00 -0700 Subject: [PATCH 4/7] fix(moa): stream completed aggregator responses safely Convert a completed MoA aggregator response into one valid Chat Completions delta chunk at the MoA facade boundary, normalize completed message.tool_calls into indexed stream deltas, and classify these local MoA adapter-shape errors as non-fallback format errors so a local compatibility bug cannot silently drift the user's MoA route to a single model (#55933 follow-up). Salvaged from PR #74903 by @liusencomic-cyber. --- agent/auxiliary_client.py | 8 ++++ agent/chat_completion_helpers.py | 2 +- agent/error_classifier.py | 13 +++++++ agent/moa_loop.py | 56 +++++++++++++++++++++++++++ tests/run_agent/test_moa_streaming.py | 40 +++++++++++++++++++ 5 files changed, 118 insertions(+), 1 deletion(-) diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py index 4f8ee48de5..c565628152 100644 --- a/agent/auxiliary_client.py +++ b/agent/auxiliary_client.py @@ -8110,6 +8110,14 @@ def call_llm( kwargs["stream"] = True if stream_options: kwargs["stream_options"] = stream_options + if task == "moa_aggregator": + # MoA's own facade owns the streaming contract. Routing this nested + # aggregator stream through Relay's generic stream manager can make + # Codex Responses adapters return a completed SimpleNamespace that + # the manager then tries to iterate (#55933). Return the provider + # call directly; the MoA facade converts a completed response into + # a one-chunk delta iterator at its boundary. + return client.chat.completions.create(**kwargs) return _relay_sync_stream( client, kwargs, diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py index 1c49a59e2a..d11b830fd8 100644 --- a/agent/chat_completion_helpers.py +++ b/agent/chat_completion_helpers.py @@ -3979,7 +3979,7 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= " To avoid this delay, set display.streaming: false " "in config.yaml\n" ) - logger.info( + logger.exception( "Streaming failed before delivery: %s", e, ) diff --git a/agent/error_classifier.py b/agent/error_classifier.py index 27df08f58e..8ac0b6c872 100644 --- a/agent/error_classifier.py +++ b/agent/error_classifier.py @@ -836,6 +836,19 @@ def classify_api_error( if classified is not None: return classified + # Local MoA streaming compatibility errors are adapter-shape bugs, not a + # provider outage. Falling back to another model would silently switch the + # user's selected MoA route to a single-model answer (#55933 follow-up). + if provider_lower == "moa" and ( + "'types.SimpleNamespace' object is not iterable" in str(error) + or "'types.SimpleNamespace' object has no attribute 'index'" in str(error) + ): + return _result( + FailoverReason.format_error, + retryable=False, + should_fallback=False, + ) + # Local MoA config drift is deterministic: a persisted session can retain # a preset name that was later renamed/deleted. Retrying the same lookup # cannot recover and makes a clear config error look like an API outage. diff --git a/agent/moa_loop.py b/agent/moa_loop.py index 173816c8cb..f302fe3813 100644 --- a/agent/moa_loop.py +++ b/agent/moa_loop.py @@ -13,6 +13,7 @@ import logging import re import threading from concurrent.futures import ThreadPoolExecutor, wait as _futures_wait +from types import SimpleNamespace from typing import Any from agent.auxiliary_client import call_llm @@ -1300,6 +1301,53 @@ def aggregate_moa_context( ) +def _completed_response_as_stream_chunk(response: Any) -> Any: + """Convert a completed Chat Completions response into one delta stream chunk. + + MoA's outer streaming consumer expects ``choices[0].delta`` chunks. A + completed aggregator response carries ``choices[0].message`` instead; adapt + it here, at the MoA facade boundary, so provider-specific Relay behavior and + other transports remain untouched. + """ + + choices = getattr(response, "choices", None) + first_choice = choices[0] if isinstance(choices, (list, tuple)) and choices else None + message = getattr(first_choice, "message", None) + raw_tool_calls = getattr(message, "tool_calls", None) + tool_call_deltas = None + if isinstance(raw_tool_calls, (list, tuple)) and raw_tool_calls: + tool_call_deltas = [] + for index, tc in enumerate(raw_tool_calls): + function = getattr(tc, "function", None) + tool_call_deltas.append(SimpleNamespace( + index=getattr(tc, "index", index), + id=getattr(tc, "id", None), + type=getattr(tc, "type", None) or "function", + function=SimpleNamespace( + name=getattr(function, "name", None), + arguments=getattr(function, "arguments", None), + ), + )) + delta = SimpleNamespace( + content=getattr(message, "content", None), + tool_calls=tool_call_deltas, + reasoning_content=getattr(message, "reasoning_content", None), + reasoning=getattr(message, "reasoning", None), + reasoning_details=getattr(message, "reasoning_details", None), + ) + choice = SimpleNamespace( + index=getattr(first_choice, "index", 0), + delta=delta, + finish_reason=getattr(first_choice, "finish_reason", None) or "stop", + ) + return SimpleNamespace( + id=getattr(response, "id", None), + model=getattr(response, "model", None), + choices=[choice], + usage=getattr(response, "usage", None), + ) + + def _attach_reference_guidance(agg_messages: list[dict[str, Any]], guidance: str) -> None: """Attach the per-turn reference block at the END of the aggregator prompt. @@ -1685,6 +1733,14 @@ class MoAChatCompletions: self._pending_trace["aggregator_output"] = _extract_text(_agg_response) except Exception: # pragma: no cover - defensive self._pending_trace["aggregator_output"] = None + if stream and hasattr(_agg_response, "choices"): + # Some aggregator adapters (notably openai-codex Responses) consume + # their provider stream internally and return a completed response + # object even when the acting consumer requested token streaming. + # The outer chat-completions streaming loop expects delta chunks; + # hand it a one-chunk iterator instead of letting it iterate the + # SimpleNamespace response itself (#55933). + return iter((_completed_response_as_stream_chunk(_agg_response),)) return _agg_response def create(self, **api_kwargs: Any) -> Any: diff --git a/tests/run_agent/test_moa_streaming.py b/tests/run_agent/test_moa_streaming.py index dff87c531e..f40822e2b3 100644 --- a/tests/run_agent/test_moa_streaming.py +++ b/tests/run_agent/test_moa_streaming.py @@ -90,6 +90,46 @@ def test_create_streams_aggregator_when_requested(monkeypatch, tmp_path): assert agg["tools"] is not None +def test_create_wraps_completed_aggregator_response_as_delta_chunk(monkeypatch, tmp_path): + """When an aggregator adapter returns a completed response despite + stream=True (Codex Responses compatibility shape), MoA must return a + one-chunk delta iterator for the outer streaming accumulator instead of + the raw non-iterable response object (#55933). + """ + + completed = _response("aggregator acted") + completed.choices[0].message.tool_calls = [ + SimpleNamespace( + id="call_1", + type="function", + function=SimpleNamespace(name="read_file", arguments='{"path":"x"}'), + ) + ] + + def on_call(kwargs): + if kwargs["task"] == "moa_aggregator": + return completed + return None + + facade, calls = _facade(monkeypatch, tmp_path, on_call=on_call) + stream = facade.create( + messages=[{"role": "user", "content": "q"}], + tools=[], + stream=True, + ) + + chunk = next(iter(stream)) + assert chunk.choices[0].delta.content == "aggregator acted" + assert chunk.choices[0].delta.tool_calls[0].index == 0 + assert chunk.choices[0].delta.tool_calls[0].function.name == "read_file" + assert chunk.choices[0].finish_reason == "stop" + with pytest.raises(StopIteration): + next(stream) + + agg = next(c for c in calls if c["task"] == "moa_aggregator") + assert agg["stream"] is True + + def test_create_non_stream_path_unchanged(monkeypatch, tmp_path): """Default (no stream): the aggregator call carries NO stream/stream_options keys, so the non-streaming path is byte-identical to before.""" From 716d274f5814c930d670f814de54ae21ad81cf7a Mon Sep 17 00:00:00 2001 From: knocksen <268946116+liusencomic-cyber@users.noreply.github.com> Date: Fri, 31 Jul 2026 21:51:00 -0700 Subject: [PATCH 5/7] test(moa): cover direct provider streaming for Codex-shim aggregators Narrow the moa_aggregator Relay bypass to CodexAuxiliaryClient and add coverage that call_llm(stream=True) returns the provider's direct create() result for Responses-shim clients. Salvaged from PR #74903 by @liusencomic-cyber. --- agent/auxiliary_client.py | 16 ++++++----- tests/agent/test_auxiliary_client.py | 41 ++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 7 deletions(-) diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py index c565628152..264e4c80d3 100644 --- a/agent/auxiliary_client.py +++ b/agent/auxiliary_client.py @@ -8110,13 +8110,15 @@ def call_llm( kwargs["stream"] = True if stream_options: kwargs["stream_options"] = stream_options - if task == "moa_aggregator": - # MoA's own facade owns the streaming contract. Routing this nested - # aggregator stream through Relay's generic stream manager can make - # Codex Responses adapters return a completed SimpleNamespace that - # the manager then tries to iterate (#55933). Return the provider - # call directly; the MoA facade converts a completed response into - # a one-chunk delta iterator at its boundary. + if task == "moa_aggregator" and isinstance(client, CodexAuxiliaryClient): + # CodexAuxiliaryClient (openai-codex, xai-oauth, and any other + # Responses-shim provider) consumes the provider stream internally + # and returns a completed response object. Routing that nested + # MoA stream through Relay's generic managed stream makes the + # manager iterate the completed SimpleNamespace itself (#55933). + # Return the provider call directly; the MoA facade converts a + # completed response into a one-chunk delta iterator at its + # boundary. return client.chat.completions.create(**kwargs) return _relay_sync_stream( client, diff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.py index 1ba43dd031..42afde0eea 100644 --- a/tests/agent/test_auxiliary_client.py +++ b/tests/agent/test_auxiliary_client.py @@ -11,6 +11,7 @@ import pytest from agent.auxiliary_client import ( _NOUS_MODEL, + CodexAuxiliaryClient, get_text_auxiliary_client, get_available_vision_backends, resolve_vision_provider_client, @@ -4051,3 +4052,43 @@ class TestCustomEndpointApiKeyInheritance: assert captured.get("api_key") == "no-key-required" + +class TestMoaAggregatorStreamingBypass: + def test_moa_aggregator_stream_bypasses_relay_for_codex_auxiliary_client(self, monkeypatch): + """The MoA facade owns the streaming contract. For Codex Responses-shim + clients (openai-codex, xai-oauth), call_llm must return the provider's + direct create() result instead of routing through Relay's managed + stream, which cannot iterate a completed SimpleNamespace (#74903). + """ + + completed = SimpleNamespace( + choices=[SimpleNamespace(message=SimpleNamespace(content="ok"))] + ) + + real_client = SimpleNamespace( + api_key="test-key", + base_url="https://chatgpt.com/backend-api/codex/", + close=lambda: None, + ) + client = CodexAuxiliaryClient(real_client, "gpt-5.6-sol") + direct_create = MagicMock(return_value=completed) + monkeypatch.setattr(client.chat.completions, "create", direct_create) + + monkeypatch.setattr( + "agent.auxiliary_client._get_cached_client", + lambda *args, **kwargs: (client, "gpt-5.6-sol"), + ) + relay_stream = MagicMock(side_effect=AssertionError("_relay_sync_stream must not be used")) + monkeypatch.setattr("agent.auxiliary_client._relay_sync_stream", relay_stream) + + result = call_llm( + task="moa_aggregator", + provider="openai-codex", + model="gpt-5.6-sol", + messages=[{"role": "user", "content": "只回答 OK"}], + stream=True, + ) + + assert result is completed + direct_create.assert_called_once() + relay_stream.assert_not_called() From 743c4906d928f650f367d5b8161dc2b0a3acdae1 Mon Sep 17 00:00:00 2001 From: knocksen <268946116+liusencomic-cyber@users.noreply.github.com> Date: Fri, 31 Jul 2026 21:51:17 -0700 Subject: [PATCH 6/7] fix(moa): restore a valid preset after fallback model drift build_moa_facade() reused agent.model as the preset name; a session that had drifted to a fallback model crashed on restore with MoAPresetNotFoundError. Validate the resolved preset against the configured presets and fall back to the default preset. Salvaged from PR #74903 by @liusencomic-cyber. --- agent/moa_loop.py | 18 +++++++++++++++++- tests/run_agent/test_moa_streaming.py | 23 +++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/agent/moa_loop.py b/agent/moa_loop.py index f302fe3813..42d0c29bca 100644 --- a/agent/moa_loop.py +++ b/agent/moa_loop.py @@ -2230,8 +2230,24 @@ def build_moa_facade(agent, preset_name: Any = None) -> MoAClient: except Exception: pass + resolved_preset = preset_name + if resolved_preset is None and getattr(agent, "provider", None) == "moa": + resolved_preset = getattr(agent, "model", None) + + resolved_preset = str(resolved_preset or "default") + try: + from hermes_cli.config import load_config + from hermes_cli.moa_config import normalize_moa_config + + moa_cfg = normalize_moa_config(load_config().get("moa") or {}) + presets = moa_cfg.get("presets") or {} + if resolved_preset not in presets: + resolved_preset = moa_cfg.get("default_preset") or "default" + except Exception: + resolved_preset = "default" + return MoAClient( - str(preset_name or getattr(agent, "model", None) or "default"), + resolved_preset, reference_callback=_moa_reference_relay, # Thread the agent through so the reference fan-out wait can be # aborted on a user interrupt (see _run_references_parallel). diff --git a/tests/run_agent/test_moa_streaming.py b/tests/run_agent/test_moa_streaming.py index f40822e2b3..edacc5c6ac 100644 --- a/tests/run_agent/test_moa_streaming.py +++ b/tests/run_agent/test_moa_streaming.py @@ -90,6 +90,29 @@ def test_create_streams_aggregator_when_requested(monkeypatch, tmp_path): assert agg["tools"] is not None +def test_build_moa_facade_ignores_fallback_model_name_when_restoring(monkeypatch, tmp_path): + """A fallback restore must not turn the temporary fallback model name into + a MoA preset. Sessions that drifted to e.g. deepseek-v4-flash previously + crashed on restore with MoAPresetNotFoundError because build_moa_facade() + reused agent.model as the preset (#MoA restore path). + """ + home = tmp_path / ".hermes" + _write_cfg(home) + monkeypatch.setenv("HERMES_HOME", str(home)) + + from agent.moa_loop import build_moa_facade + + agent = SimpleNamespace( + provider="moa", + model="deepseek-v4-flash", + tool_progress_callback=None, + ) + + client = build_moa_facade(agent, None) + + assert client.chat.completions.preset_name == "review" + + def test_create_wraps_completed_aggregator_response_as_delta_chunk(monkeypatch, tmp_path): """When an aggregator adapter returns a completed response despite stream=True (Codex Responses compatibility shape), MoA must return a From 48ded07155ef379d2e0d5e70b729a2943b1b4744 Mon Sep 17 00:00:00 2001 From: Kyle <9322236+DocAwk@users.noreply.github.com> Date: Wed, 29 Jul 2026 20:07:56 -0600 Subject: [PATCH 7/7] fix(codex): handle completed auxiliary responses --- agent/auxiliary_client.py | 18 ++++++++++---- tests/agent/test_auxiliary_client.py | 37 ++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py index 264e4c80d3..21649aa5bc 100644 --- a/agent/auxiliary_client.py +++ b/agent/auxiliary_client.py @@ -1226,11 +1226,19 @@ class _CodexCompletionsAdapter: event_stream = self._client.responses.create(**stream_kwargs) try: - final = _consume_codex_event_stream( - event_stream, - model=resp_kwargs.get("model"), - on_event=_on_each_event, - ) + # Some Codex-compatible hosts accept ``stream=True`` but return + # a completed Responses object instead of an SSE iterator. Do + # not hand that object to the event consumer: typed Responses + # (and compatibility shims such as SimpleNamespace) are not + # event streams and may not be iterable at all. + if hasattr(event_stream, "output"): + final = event_stream + else: + final = _consume_codex_event_stream( + event_stream, + model=str(resp_kwargs.get("model") or model), + on_event=_on_each_event, + ) finally: close_fn = getattr(event_stream, "close", None) if callable(close_fn): diff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.py index 42afde0eea..eb930eba78 100644 --- a/tests/agent/test_auxiliary_client.py +++ b/tests/agent/test_auxiliary_client.py @@ -3302,6 +3302,43 @@ class TestCodexAuxiliaryAdapterNullOutputRecovery: codex_runtime._consume_codex_event_stream = original_consume +class TestCodexAuxiliaryAdapterCompletedResponse: + def test_accepts_completed_response_when_stream_was_requested(self): + completed = SimpleNamespace( + status="completed", + id="resp_completed", + output=[SimpleNamespace( + type="message", + content=[SimpleNamespace( + type="output_text", + text="completed response", + )], + )], + usage=SimpleNamespace( + input_tokens=11, + output_tokens=3, + total_tokens=14, + ), + ) + + class FakeResponses: + def create(self, **kwargs): + assert kwargs["stream"] is True + return completed + + fake_client = SimpleNamespace(responses=FakeResponses()) + adapter = _CodexCompletionsAdapter(fake_client, "gpt-5.6-terra") + + response = adapter.create( + messages=[{"role": "user", "content": "review this"}], + ) + + assert response.choices[0].message.content == "completed response" + assert response.usage.prompt_tokens == 11 + assert response.usage.completion_tokens == 3 + assert response.usage.total_tokens == 14 + + # --------------------------------------------------------------------------- # Issue #23432 — auxiliary timeout poisons cached client; later aux calls fail # ---------------------------------------------------------------------------