Skip to content

The agent that grows with you

fix(agent): stop the MoA prepared request reaching a swapped-in native client

Drexuxuxab879a1e2218
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py
index c05167d7685..a27fd23d6b3 100644
--- a/agent/conversation_loop.py
+++ b/agent/conversation_loop.py
@@ -211,6 +211,20 @@ _API_CALL_MODULES = frozenset({
})
+def _moa_client_consumes_prepared_request(client: Any) -> bool:
+ """True when ``client`` is the in-process MoA facade.
+
+ ``_moa_prepared_request`` is a private handshake with
+ ``MoAChatCompletions.create``, and only that facade exposes ``prepare()``.
+ Every other chat-completions object raises TypeError on the unexpected
+ keyword — including the native OpenAI client that credential rotation,
+ provider fallback and dead-connection cleanup rebuild from
+ ``_client_kwargs`` while ``agent.provider`` stays ``"moa"``.
+ """
+ completions = getattr(getattr(client, "chat", None), "completions", None)
+ return callable(getattr(completions, "prepare", None))
+
+
def _join_truncated_parts(parts: List[str]) -> str:
"""Join continuation fragments, adding a newline where two would glue together (#78577)."""
joined = ""
@@ -2710,7 +2724,24 @@ def run_conversation(
# only after middleware, hooks, and debug dumps so none of them
# attempts to serialize it as part of the provider payload.
if _moa_prepared_request is not None and agent.provider == "moa":
- api_kwargs["_moa_prepared_request"] = _moa_prepared_request
+ # Re-read the live client instead of trusting the one that
+ # prepared the request above. Credential rotation, provider
+ # fallback and dead-connection cleanup all rebuild
+ # agent.client from _client_kwargs between attempts, and
+ # pending_moa_prepared_request carries a prepared request
+ # across exactly that boundary. The rebuilt client is a
+ # native OpenAI client while provider stays "moa", so this
+ # private key would reach the SDK as an unexpected keyword
+ # — a non-retryable TypeError that kills every remaining
+ # turn on the session.
+ if _moa_client_consumes_prepared_request(agent.client):
+ api_kwargs["_moa_prepared_request"] = _moa_prepared_request
+ else:
+ logger.warning(
+ "MoA client replaced mid-turn (client=%s); sending the "
+ "prepared prompt without the MoA handshake",
+ type(agent.client).__name__,
+ )
# Always prefer the streaming path — even without stream
# consumers. Streaming gives us fine-grained health
diff --git a/tests/agent/test_moa_prepared_request_client_swap.py b/tests/agent/test_moa_prepared_request_client_swap.py
new file mode 100644
index 00000000000..0721b9f03f8
--- /dev/null
+++ b/tests/agent/test_moa_prepared_request_client_swap.py
@@ -0,0 +1,62 @@
+"""`_moa_prepared_request` must never reach a client that cannot consume it.
+
+The key is a private handshake between the conversation loop and
+``MoAChatCompletions.create``. Credential rotation, provider fallback and
+dead-connection cleanup rebuild ``agent.client`` from ``_client_kwargs``
+between attempts — and a prepared request survives that boundary via
+``pending_moa_prepared_request`` — while ``agent.provider`` stays ``"moa"``.
+Handing the key to the rebuilt native client raises a non-retryable
+``TypeError`` that kills every remaining turn on the session.
+"""
+
+import types
+
+from agent.conversation_loop import _moa_client_consumes_prepared_request
+from agent.moa_loop import MoAChatCompletions
+
+
+def _client_with(completions):
+ return types.SimpleNamespace(
+ chat=types.SimpleNamespace(completions=completions)
+ )
+
+
+class _NativeCompletions:
+ """openai.resources.chat.Completions — an explicit keyword signature."""
+
+ def create(self, *, model=None, messages=None, tools=None, stream=None):
+ return "native ok"
+
+
+def test_native_client_does_not_consume_the_prepared_request():
+ assert _moa_client_consumes_prepared_request(_client_with(_NativeCompletions())) is False
+
+
+def test_real_moa_facade_consumes_the_prepared_request():
+ facade = MoAChatCompletions.__new__(MoAChatCompletions)
+ assert _moa_client_consumes_prepared_request(_client_with(facade)) is True
+
+
+def test_client_without_a_chat_attribute_is_not_a_facade():
+ assert _moa_client_consumes_prepared_request(object()) is False
+ assert _moa_client_consumes_prepared_request(None) is False
+
+
+def test_native_client_rejects_the_key_it_must_not_receive():
+ """Why the guard exists: the kwarg is fatal to a native client."""
+ native = _NativeCompletions()
+ try:
+ native.create(
+ model="2 model",
+ messages=[{"role": "user", "content": "hi"}],
+ _moa_prepared_request={"messages": [], "layers": 3},
+ )
+ except TypeError as exc:
+ assert "_moa_prepared_request" in str(exc)
+ else: # pragma: no cover - would mean the premise no longer holds
+ raise AssertionError("native client accepted the private MoA kwarg")
+
+ # Without the key it is an ordinary call the rebuilt client can serve.
+ assert native.create(
+ model="2 model", messages=[{"role": "user", "content": "hi"}]
+ ) == "native ok"