Skip to content

The agent that grows with you

fix(azure-foundry): scope Responses reasoning suppression to post-tool turns (#84320)

Ben Barclayf52feed1efb4
diff --git a/agent/transports/codex.py b/agent/transports/codex.py
index 2676dd1fc0d..fac925fdba0 100644
--- a/agent/transports/codex.py
+++ b/agent/transports/codex.py
@@ -173,6 +173,96 @@ def _content_cache_key(
return f"pck_{digest}"
+def _is_azure_foundry_responses(params: Dict[str, Any]) -> bool:
+ """Return True for Microsoft Foundry's OpenAI-compatible Responses API.
+
+ Matched on the registered provider id first, then on the endpoint host.
+ Host matching goes through ``base_url_host_matches`` rather than a
+ substring test, so a path or query segment carrying the Foundry domain
+ (``https://proxy.example.com/.services.ai.azure.com/v1``) is not
+ misclassified as Foundry.
+ """
+ from utils import base_url_host_matches
+
+ provider = str(params.get("provider") or "").strip().lower()
+ if provider == "azure-foundry":
+ return True
+
+ return base_url_host_matches(
+ str(params.get("base_url") or ""), "services.ai.azure.com"
+ )
+
+
+def _is_post_tool_replay(messages: Optional[List[Dict[str, Any]]]) -> bool:
+ """Return True when ``messages`` end on a tool result awaiting a follow-up.
+
+ Azure Foundry only rejects the *post-tool follow-up* payload — the shape
+ where a prior assistant ``function_call`` and its ``function_call_output``
+ are replayed alongside an encrypted ``reasoning`` item (HTTP 400
+ invalid_payload). Detecting that shape here keeps reasoning suppression
+ scoped to the failing turn, so ordinary (non-tool) Foundry multi-turn
+ continuity is left unchanged.
+
+ The test is on the *trailing* messages, not on the history as a whole.
+ Scanning the whole history for any tool call plus any tool result makes
+ the predicate sticky: one tool call early in a conversation would then
+ suppress reasoning on every later turn, including plain user follow-ups
+ that Foundry accepts. The rejected payload is specifically the turn whose
+ last item is a tool result, so that is what this matches: the final
+ non-system message is a ``tool`` result, and the assistant message that
+ issued its ``tool_call_id`` is present.
+
+ Tool-call identity is resolved the same way
+ ``_chat_messages_to_responses_input`` resolves it, because the pairing
+ that matters is the one that reaches the wire. A stored tool call can
+ carry the function call id in ``call_id``, in ``id``, or in a composite
+ ``"call_x|fc_y"`` id, and a bare ``fc_``-prefixed ``id`` is a response
+ item id that the converter turns into ``call_<rest>``. Matching only
+ ``id`` would miss the ``id=fc_… / call_id=call_…`` shape that resumed
+ legacy sessions and host-fed histories still use, and let the rejected
+ payload through.
+ """
+ from agent.codex_responses_adapter import _split_responses_tool_id
+
+ def _pair_ids(raw: Any, explicit: Any = None) -> set:
+ """Every call id a stored tool id could pair on, converter-order."""
+ embedded_call_id, item_id = _split_responses_tool_id(raw)
+ ids = {embedded_call_id} if embedded_call_id else set()
+ if isinstance(explicit, str) and explicit.strip():
+ ids.add(explicit.strip())
+ if not ids and isinstance(raw, str) and raw.strip():
+ ids.add(raw.strip())
+ if isinstance(item_id, str) and item_id.startswith("fc_") and item_id[3:]:
+ ids.add(f"call_{item_id[3:]}")
+ return ids
+
+ trailing = set()
+ for msg in reversed(messages or ()):
+ if not isinstance(msg, dict):
+ return False
+ role = msg.get("role")
+ if role == "system":
+ continue
+ if role == "tool":
+ ids = _pair_ids(msg.get("tool_call_id"))
+ if not ids:
+ return False
+ trailing |= ids
+ continue
+ # First message before the trailing run of tool results. It must be
+ # the assistant turn that issued them for this to be the follow-up
+ # payload; a non-empty ``trailing`` is what proves the run existed.
+ if role != "assistant":
+ return False
+ return any(
+ trailing & _pair_ids(call.get("id"), call.get("call_id"))
+ for call in msg.get("tool_calls") or []
+ if isinstance(call, dict)
+ )
+
+ return False
+
+
class ResponsesApiTransport(ProviderTransport):
"""Transport for api_mode='codex_responses'.
@@ -271,6 +361,17 @@ class ResponsesApiTransport(ProviderTransport):
replay_encrypted_reasoning = bool(
params.get("replay_encrypted_reasoning", True)
)
+ if replay_encrypted_reasoning and _is_azure_foundry_responses(params):
+ # Microsoft Foundry accepts the initial Responses function-call
+ # request and ordinary (non-tool) multi-turn continuity, but
+ # rejects the post-tool follow-up payload that carries prior
+ # encrypted reasoning items alongside function_call /
+ # function_call_output, with HTTP 400 invalid_payload. Scope the
+ # suppression to that follow-up turn: keep function_call /
+ # function_call_output continuity intact and drop only the
+ # encrypted reasoning replay for this endpoint.
+ if _is_post_tool_replay(payload_messages):
+ replay_encrypted_reasoning = False
# Native server-side compaction (gpt-5.6 on direct OpenAI/Codex routes
# only). The caller resolves eligibility via
# agent.native_compaction.native_compaction_context_management();
diff --git a/tests/agent/transports/test_codex_transport.py b/tests/agent/transports/test_codex_transport.py
index 5041a32da3f..408b49d450b 100644
--- a/tests/agent/transports/test_codex_transport.py
+++ b/tests/agent/transports/test_codex_transport.py
@@ -250,6 +250,320 @@ class TestCodexBuildKwargs:
assert eb.get("prompt_cache_key") == "caller-override"
assert eb.get("other_field") == 42
+ # ── Azure Foundry post-tool reasoning suppression ──────────────────
+ #
+ # Foundry's Responses surface accepts the initial function-call request
+ # and ordinary multi-turn continuity, but rejects the post-tool follow-up
+ # payload when a replayed encrypted ``reasoning`` item sits alongside
+ # ``function_call`` / ``function_call_output`` (HTTP 400 invalid_payload).
+ # Suppression is scoped to that follow-up turn only.
+
+ @staticmethod
+ def _reasoning_item():
+ return {"type": "reasoning", "encrypted_content": "sealed", "summary": []}
+
+ @classmethod
+ def _post_tool_messages(cls):
+ """user → assistant(tool_calls + reasoning) → tool result."""
+ return [
+ {"role": "user", "content": "Create a marker"},
+ {
+ "role": "assistant",
+ "content": "",
+ "codex_reasoning_items": [cls._reasoning_item()],
+ "tool_calls": [
+ {
+ "id": "call_marker",
+ "type": "function",
+ "function": {"name": "write_marker", "arguments": "{}"},
+ }
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "call_marker",
+ "content": "marker written",
+ },
+ ]
+
+ AZURE_FOUNDRY_BASE_URL = (
+ "https://placeholder.services.ai.azure.com/"
+ "api/projects/placeholder/openai/v1"
+ )
+
+ def test_post_tool_replay_preserves_reasoning_for_default_responses(self, transport):
+ """Non-Azure Responses endpoints keep post-tool reasoning replay."""
+ kw = transport.build_kwargs(
+ model="gpt-5.4",
+ messages=self._post_tool_messages(),
+ tools=[],
+ replay_encrypted_reasoning=True,
+ )
+ item_types = [item.get("type") for item in kw["input"] if isinstance(item, dict)]
+ assert "reasoning" in item_types
+ assert "function_call" in item_types
+ assert "function_call_output" in item_types
+ assert kw.get("include") == ["reasoning.encrypted_content"]
+
+ def test_azure_foundry_post_tool_replay_suppresses_reasoning_items(self, transport):
+ """The rejected payload shape drops reasoning, keeps tool continuity."""
+ kw = transport.build_kwargs(
+ model="gpt-5.4",
+ messages=self._post_tool_messages(),
+ tools=[],
+ provider="azure-foundry",
+ base_url=self.AZURE_FOUNDRY_BASE_URL,
+ replay_encrypted_reasoning=True,
+ )
+ item_types = [item.get("type") for item in kw["input"] if isinstance(item, dict)]
+ assert "reasoning" not in item_types
+ assert "function_call" in item_types
+ assert "function_call_output" in item_types
+ assert kw.get("include") == []
+
+ def test_azure_foundry_detected_by_host_without_provider(self, transport):
+ """Foundry detection works on the endpoint host alone."""
+ kw = transport.build_kwargs(
+ model="gpt-5.4",
+ messages=self._post_tool_messages(),
+ tools=[],
+ base_url=self.AZURE_FOUNDRY_BASE_URL,
+ replay_encrypted_reasoning=True,
+ )
+ item_types = [item.get("type") for item in kw["input"] if isinstance(item, dict)]
+ assert "reasoning" not in item_types
+
+ @pytest.mark.parametrize(
+ "base_url",
+ [
+ "https://proxy.example.com/.services.ai.azure.com/openai/v1",
+ "https://openrouter.ai/api/v1?upstream=.services.ai.azure.com",
+ "https://services.ai.azure.com.evil.example/v1",
+ ],
+ )
+ def test_non_foundry_host_lookalikes_keep_reasoning(self, transport, base_url):
+ """A Foundry domain in a path/query/suffix is not a Foundry endpoint.
+
+ Guards against the substring-match false positive: these URLs all
+ contain the Foundry domain but are served by someone else, and
+ suppressing their reasoning replay would silently degrade
+ cross-turn coherence on an unrelated provider.
+ """
+ kw = transport.build_kwargs(
+ model="gpt-5.4",
+ messages=self._post_tool_messages(),
+ tools=[],
+ base_url=base_url,
+ replay_encrypted_reasoning=True,
+ )
+ item_types = [item.get("type") for item in kw["input"] if isinstance(item, dict)]
+ assert "reasoning" in item_types
+ assert kw.get("include") == ["reasoning.encrypted_content"]
+
+ def test_azure_foundry_non_tool_follow_up_preserves_reasoning_items(self, transport):
+ """Ordinary (non-tool) Azure Foundry continuity is unchanged.
+
+ A plain assistant reasoning turn followed by another user message has
+ no tool continuity, so the encrypted reasoning item must still be
+ replayed — Foundry only rejects the post-tool payload.
+ """
+ messages = [
+ {"role": "user", "content": "Explain recursion"},
+ {
+ "role": "assistant",
+ "content": "Recursion is when a function calls itself.",
+ "codex_reasoning_items": [self._reasoning_item()],
+ },
+ {"role": "user", "content": "Give an example"},
+ ]
+ kw = transport.build_kwargs(
+ model="gpt-5.4",
+ messages=messages,
+ tools=[],
+ provider="azure-foundry",
+ base_url=self.AZURE_FOUNDRY_BASE_URL,
+ replay_encrypted_reasoning=True,
+ )
+ item_types = [item.get("type") for item in kw["input"] if isinstance(item, dict)]
+ assert "reasoning" in item_types
+ assert "function_call" not in item_types
+ assert "function_call_output" not in item_types
+ assert kw.get("include") == ["reasoning.encrypted_content"]
+
+ def test_azure_foundry_user_turn_after_completed_tool_call_keeps_reasoning(
+ self, transport
+ ):
+ """Suppression must not stick for the rest of the conversation.
+
+ The tool call completed and the assistant already answered; this turn
+ is a plain user follow-up whose payload ends on a user message, which
+ Foundry accepts. A predicate that scanned the whole history for any
+ tool call plus any tool result would suppress reasoning here — and on
+ every later turn — which is the all-turns behavior this scoping
+ exists to avoid.
+ """
+ messages = self._post_tool_messages() + [
+ {
+ "role": "assistant",
+ "content": "Marker created.",
+ "codex_reasoning_items": [self._reasoning_item()],
+ },
+ {"role": "user", "content": "Now explain recursion"},
+ ]
+ kw = transport.build_kwargs(
+ model="gpt-5.4",
+ messages=messages,
+ tools=[],
+ provider="azure-foundry",
+ base_url=self.AZURE_FOUNDRY_BASE_URL,
+ replay_encrypted_reasoning=True,
+ )
+ item_types = [item.get("type") for item in kw["input"] if isinstance(item, dict)]
+ assert "reasoning" in item_types
+ assert "function_call" in item_types
+ assert "function_call_output" in item_types
+ assert kw.get("include") == ["reasoning.encrypted_content"]
+
+ def test_azure_foundry_parallel_tool_results_suppress_reasoning(self, transport):
+ """A trailing run of parallel tool results is still the rejected shape."""
+ messages = [
+ {"role": "user", "content": "Read both files"},
+ {
+ "role": "assistant",
+ "content": "",
+ "codex_reasoning_items": [self._reasoning_item()],
+ "tool_calls": [
+ {
+ "id": "call_a",
+ "type": "function",
+ "function": {"name": "read_file", "arguments": "{}"},
+ },
+ {
+ "id": "call_b",
+ "type": "function",
+ "function": {"name": "read_file", "arguments": "{}"},
+ },
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_a", "content": "a"},
+ {"role": "tool", "tool_call_id": "call_b", "content": "b"},
+ ]
+ kw = transport.build_kwargs(
+ model="gpt-5.4",
+ messages=messages,
+ tools=[],
+ provider="azure-foundry",
+ base_url=self.AZURE_FOUNDRY_BASE_URL,
+ replay_encrypted_reasoning=True,
+ )
+ item_types = [item.get("type") for item in kw["input"] if isinstance(item, dict)]
+ assert "reasoning" not in item_types
+ assert item_types.count("function_call_output") == 2
+
+ def test_azure_foundry_respects_caller_replay_disabled(self, transport):
+ """An explicit replay_encrypted_reasoning=False is not re-enabled."""
+ kw = transport.build_kwargs(
+ model="gpt-5.4",
+ messages=self._post_tool_messages(),
+ tools=[],
+ provider="azure-foundry",
+ base_url=self.AZURE_FOUNDRY_BASE_URL,
+ replay_encrypted_reasoning=False,
+ )
+ item_types = [item.get("type") for item in kw["input"] if isinstance(item, dict)]
+ assert "reasoning" not in item_types
+ assert kw.get("include") == []
+
+ @pytest.mark.parametrize(
+ "tool_call,tool_call_id",
+ [
+ # Responses histories carry the function call id in call_id while
+ # ``id`` holds the response item id. Resumed legacy sessions and
+ # host-fed histories still use this shape.
+ ({"id": "fc_item_a", "call_id": "call_a"}, "call_a"),
+ # Plain chat-completions shape: id IS the call id.
+ ({"id": "call_a"}, "call_a"),
+ # Bare fc_ id with no call_id — the converter derives call_<rest>.
+ ({"id": "fc_a"}, "call_a"),
+ # Composite stored id, on either side of the pairing.
+ ({"id": "call_a|fc_a"}, "call_a"),
+ ({"id": "call_a"}, "call_a|fc_a"),
+ # call_id present, no id at all.
+ ({"call_id": "call_a"}, "call_a"),
+ ],
+ )
+ def test_azure_foundry_suppresses_across_tool_call_id_shapes(
+ self, transport, tool_call, tool_call_id
+ ):
+ """Every id shape the converter can pair must be detected.
+
+ The converter resolves a function call's identity as
+ ``call_id`` -> embedded ``id`` -> derived from an ``fc_`` item id, and
+ splits composite ``"call_x|fc_y"`` ids. A predicate that matched only
+ ``tool_calls[*].id`` would miss the id=fc_ / call_id=call_ shape: the
+ converter still emits paired function_call / function_call_output, so
+ the exact payload Foundry rejects would ship with the reasoning item
+ intact.
+ """
+ messages = [
+ {"role": "user", "content": "Create a marker"},
+ {
+ "role": "assistant",
+ "content": "",
+ "codex_reasoning_items": [self._reasoning_item()],
+ "tool_calls": [
+ {**tool_call, "type": "function",
+ "function": {"name": "write_marker", "arguments": "{}"}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": tool_call_id, "content": "marker written"},
+ ]
+ kw = transport.build_kwargs(
+ model="gpt-5.4",
+ messages=messages,
+ tools=[],
+ provider="azure-foundry",
+ base_url=self.AZURE_FOUNDRY_BASE_URL,
+ replay_encrypted_reasoning=True,
+ )
+ item_types = [item.get("type") for item in kw["input"] if isinstance(item, dict)]
+ # The converter paired them, so this is the rejected shape.
+ assert "function_call" in item_types
+ assert "function_call_output" in item_types
+ assert "reasoning" not in item_types
+ assert kw.get("include") == []
+
+ def test_azure_foundry_unpaired_tool_result_keeps_reasoning(self, transport):
+ """A tool result that pairs with nothing is not the rejected shape."""
+ messages = [
+ {"role": "user", "content": "Create a marker"},
+ {
+ "role": "assistant",
+ "content": "",
+ "codex_reasoning_items": [self._reasoning_item()],
+ "tool_calls": [
+ {
+ "id": "fc_item_x",
+ "call_id": "call_x",
+ "type": "function",
+ "function": {"name": "write_marker", "arguments": "{}"},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_unrelated", "content": "?"},
+ ]
+ kw = transport.build_kwargs(
+ model="gpt-5.4",
+ messages=messages,
+ tools=[],
+ provider="azure-foundry",
+ base_url=self.AZURE_FOUNDRY_BASE_URL,
+ replay_encrypted_reasoning=True,
+ )
+ item_types = [item.get("type") for item in kw["input"] if isinstance(item, dict)]
+ assert "reasoning" in item_types
+ assert kw.get("include") == ["reasoning.encrypted_content"]
+
def test_xai_top_level_override_also_governs_extra_body(self, transport):
"""A caller's top-level request_overrides={"prompt_cache_key": ...}
must win in extra_body.prompt_cache_key too -- the field xAI actually
diff --git a/tests/run_agent/test_run_agent_codex_responses.py b/tests/run_agent/test_run_agent_codex_responses.py
index 18dc13526b7..5de3418a340 100644
--- a/tests/run_agent/test_run_agent_codex_responses.py
+++ b/tests/run_agent/test_run_agent_codex_responses.py
@@ -77,6 +77,31 @@ def _build_copilot_agent(monkeypatch, *, model="gpt-5.4"):
return agent
+AZURE_FOUNDRY_BASE_URL = (
+ "https://placeholder.services.ai.azure.com/api/projects/placeholder/openai/v1"
+)
+
+
+def _build_azure_foundry_agent(monkeypatch, *, model="gpt-5.4"):
+ _patch_agent_bootstrap(monkeypatch)
+
+ agent = run_agent.AIAgent(
+ model=model,
+ provider="azure-foundry",
+ api_mode="codex_responses",
+ base_url=AZURE_FOUNDRY_BASE_URL,
+ api_key="foundry-token",
+ quiet_mode=True,
+ max_iterations=4,
+ skip_context_files=True,
+ skip_memory=True,
+ )
+ agent._cleanup_task_resources = lambda task_id: None
+ agent._persist_session = lambda messages, history=None: None
+ agent._save_trajectory = lambda messages, user_message, completed: None
+ return agent
+
+
def _codex_message_response(text: str):
return SimpleNamespace(
output=[
@@ -325,6 +350,110 @@ def test_build_api_kwargs_mantle_sets_extended_prompt_cache_retention(monkeypatc
assert kwargs["prompt_cache_retention"] == "24h"
+def _azure_reasoning_item():
+ return {"type": "reasoning", "encrypted_content": "sealed", "summary": []}
+
+
+def _azure_post_tool_messages():
+ return [
+ {"role": "system", "content": "You are Hermes."},
+ {"role": "user", "content": "Create a marker"},
+ {
+ "role": "assistant",
+ "content": "",
+ "codex_reasoning_items": [_azure_reasoning_item()],
+ "tool_calls": [
+ {
+ "id": "call_marker",
+ "type": "function",
+ "function": {"name": "terminal", "arguments": "{}"},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_marker", "content": "marker written"},
+ ]
+
+
+def test_build_api_kwargs_azure_foundry_post_tool_suppresses_reasoning(monkeypatch):
+ """Live agent path reaches Azure Foundry detection and scopes suppression.
+
+ Exercises ``chat_completion_helpers.build_api_kwargs`` end-to-end rather
+ than the transport in isolation: the agent must forward ``provider`` and
+ ``base_url`` into ``build_kwargs`` for the Foundry detection to fire at
+ all. On the post-tool follow-up shape the encrypted reasoning item is
+ dropped while function_call / function_call_output continuity is kept.
+ """
+ agent = _build_azure_foundry_agent(monkeypatch)
+ assert agent._codex_reasoning_replay_enabled is True
+
+ kwargs = agent._build_api_kwargs(_azure_post_tool_messages())
+
+ item_types = [item.get("type") for item in kwargs["input"] if isinstance(item, dict)]
+ assert "reasoning" not in item_types
+ assert "function_call" in item_types
+ assert "function_call_output" in item_types
+ assert kwargs.get("include") == []
+
+
+def test_build_api_kwargs_azure_foundry_non_tool_preserves_reasoning(monkeypatch):
+ """Ordinary (non-tool) Azure Foundry continuity is unchanged via the live path.
+
+ Without the post-tool follow-up shape there is no evidence Foundry rejects
+ the payload, so the encrypted reasoning item must still be replayed even
+ though the agent forwards the Foundry identity fields.
+ """
+ agent = _build_azure_foundry_agent(monkeypatch)
+
+ messages = [
+ {"role": "system", "content": "You are Hermes."},
+ {"role": "user", "content": "Explain recursion"},
+ {
+ "role": "assistant",
+ "content": "Recursion is when a function calls itself.",
+ "codex_reasoning_items": [_azure_reasoning_item()],
+ },
+ {"role": "user", "content": "Give an example"},
+ ]
+
+ kwargs = agent._build_api_kwargs(messages)
+
+ item_types = [item.get("type") for item in kwargs["input"] if isinstance(item, dict)]
+ assert "reasoning" in item_types
+ assert "function_call" not in item_types
+ assert "function_call_output" not in item_types
+ assert kwargs.get("include") == ["reasoning.encrypted_content"]
+
+
+def test_build_api_kwargs_azure_foundry_user_turn_after_tool_call_keeps_reasoning(
+ monkeypatch,
+):
+ """Suppression does not stick once the tool call is answered.
+
+ Regression guard for the sticky-history shape: after the assistant has
+ replied to the tool result, a plain user follow-up is a payload Foundry
+ accepts, so reasoning replay must come back on rather than stay off for
+ the remainder of the conversation.
+ """
+ agent = _build_azure_foundry_agent(monkeypatch)
+
+ messages = _azure_post_tool_messages() + [
+ {
+ "role": "assistant",
+ "content": "Marker created.",
+ "codex_reasoning_items": [_azure_reasoning_item()],
+ },
+ {"role": "user", "content": "Now explain recursion"},
+ ]
+
+ kwargs = agent._build_api_kwargs(messages)
+
+ item_types = [item.get("type") for item in kwargs["input"] if isinstance(item, dict)]
+ assert "reasoning" in item_types
+ assert "function_call" in item_types
+ assert "function_call_output" in item_types
+ assert kwargs.get("include") == ["reasoning.encrypted_content"]
+
+