Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(backend/copilot): sync the Codex transport's tool rounds to the main turn limit (#15121)

Nicholas Tindle9506f9705b5e
diff --git a/autogpt_platform/backend/backend/copilot/config.py b/autogpt_platform/backend/backend/copilot/config.py
index c912672e00..2757b2167c 100644
--- a/autogpt_platform/backend/backend/copilot/config.py
+++ b/autogpt_platform/backend/backend/copilot/config.py
@@ -471,9 +471,11 @@ class ChatConfig(BaseSettings):
"CHAT_CLAUDE_AGENT_MAX_TURNS",
),
description="Maximum number of tool-call rounds per turn — applies to "
- "both the baseline and Claude Agent SDK paths. Prevents runaway tool "
- "loops from burning budget. Override via CHAT_AGENT_MAX_TURNS env var "
- "(legacy CHAT_CLAUDE_AGENT_MAX_TURNS still accepted).",
+ "both the baseline and Claude Agent SDK paths, including Codex models "
+ "on the SDK path, where each Codex function call counts as one round. "
+ "Prevents runaway tool loops from burning budget. Override via "
+ "CHAT_AGENT_MAX_TURNS env var (legacy CHAT_CLAUDE_AGENT_MAX_TURNS "
+ "still accepted).",
)
claude_agent_max_budget_usd: float = Field(
default=10.0,
diff --git a/autogpt_platform/backend/backend/copilot/sdk/codex_compat_gateway_test.py b/autogpt_platform/backend/backend/copilot/sdk/codex_compat_gateway_test.py
index d765835bf4..082e7bb077 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/codex_compat_gateway_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/codex_compat_gateway_test.py
@@ -792,6 +792,32 @@ async def test_completed_tool_result_cannot_start_a_new_conversation() -> None:
assert len(agent_session.requests) == 1
+async def test_closing_while_a_tool_call_is_unanswered_cancels_the_codex_turn() -> None:
+ """Codex has no round cap of its own, so this is what ends a long turn.
+
+ When the CLI reaches ``CHAT_AGENT_MAX_TURNS`` it stops answering tool
+ calls and the service closes the gateway; the Codex loop must stop too.
+ """
+ agent_session = _FakeAgentSession(use_tool=True)
+ transport = _FakeTransport(agent_session)
+ async with CodexAnthropicGateway(
+ credential_lease=_lease(),
+ model="gpt-5.6-terra",
+ transport=transport,
+ ) as gateway:
+ async with ClientSession() as client:
+ response = await client.post(
+ f"{gateway.base_url}/v1/messages",
+ headers=_headers(gateway),
+ json=_tool_request("run", stream=True),
+ )
+ _streamed_tool_use_id(_events(await response.text()))
+
+ assert agent_session.cancelled.is_set()
+ assert agent_session.tool_result is None
+
+
@pytest.mark.asyncio
async def test_rejects_missing_gateway_capability() -> None:
transport = _FakeTransport(_FakeAgentSession())
diff --git a/autogpt_platform/backend/backend/integrations/codex/http_session.py b/autogpt_platform/backend/backend/integrations/codex/http_session.py
index ba89379162..ebd894271a 100644
--- a/autogpt_platform/backend/backend/integrations/codex/http_session.py
+++ b/autogpt_platform/backend/backend/integrations/codex/http_session.py
@@ -41,10 +41,6 @@ logger = logging.getLogger(__name__)
EventHandler = Callable[[CodexStreamEvent], Awaitable[None]]
ToolHandler = Callable[[CodexDynamicToolCall], Awaitable[CodexDynamicToolResult]]
-# A turn that keeps asking for tools without converging is a bug somewhere;
-# stop rather than spending someone's quota in a loop.
-MAX_TOOL_ITERATIONS = 32
-
class CodexHttpSession:
"""One user's Codex turn, run over HTTPS."""
@@ -103,7 +99,10 @@ class CodexHttpSession:
reasoning_summary = ""
usage = _ZERO_USAGE
- for _ in range(MAX_TOOL_ITERATIONS):
+ # No round cap here: whoever runs the tools bounds the turn. On the
+ # copilot path that is the Claude CLI, which counts every call against
+ # CHAT_AGENT_MAX_TURNS; the turn and tool timeouts cover the rest.
+ while True:
turn = await self._stream_turn(request, conversation, tools, event_handler)
response_id = turn.response_id or response_id
@@ -132,10 +131,6 @@ class CodexHttpSession:
for call in turn.tool_calls:
conversation.append(await self._dispatch_tool(call, tool_handler))
- raise CodexTurnLimitError(
- f"Codex turn did not converge within {MAX_TOOL_ITERATIONS} tool rounds"
- )
-
async def _dispatch_tool(
self, call: "_ToolCall", tool_handler: ToolHandler
) -> dict[str, Any]:
@@ -267,10 +262,6 @@ class CodexInvocationTimeoutError(RuntimeError):
"""The whole turn exceeded its deadline."""
-class CodexTurnLimitError(RuntimeError):
- """The tool loop did not converge."""
-
-
class CodexTurnFailedError(RuntimeError):
"""ChatGPT reported the turn as failed."""
diff --git a/autogpt_platform/backend/backend/integrations/codex/http_session_test.py b/autogpt_platform/backend/backend/integrations/codex/http_session_test.py
index 0697de020b..b8a4a603fc 100644
--- a/autogpt_platform/backend/backend/integrations/codex/http_session_test.py
+++ b/autogpt_platform/backend/backend/integrations/codex/http_session_test.py
@@ -8,10 +8,8 @@ from pydantic import SecretStr
from backend.data.model import OAuth2Credentials
from backend.integrations.codex.http_session import (
- MAX_TOOL_ITERATIONS,
CodexHttpSession,
CodexTurnFailedError,
- CodexTurnLimitError,
_add_usage,
_parse_arguments,
)
@@ -274,12 +272,43 @@ async def test_a_tool_failure_is_returned_to_the_model_without_leaking_details()
@pytest.mark.asyncio
-async def test_a_loop_that_never_converges_stops_instead_of_spending_quota() -> None:
- turns = [_tool_turn("lookup", "{}") for _ in range(MAX_TOOL_ITERATIONS + 2)]
- session, _ = _session(turns)
+async def test_a_long_tool_loop_runs_until_the_model_stops_calling_tools() -> None:
+ """Codex has no round cap of its own; whoever runs the tools bounds the loop.
+
+ On the copilot path that is the Claude CLI, which counts every function
+ call as a turn against ``CHAT_AGENT_MAX_TURNS``.
+ """
+ rounds = 40
+ turns = [_tool_turn("lookup", "{}") for _ in range(rounds)]
+ session, client = _session([*turns, _text_turn("done")])
+ seen: list[CodexDynamicToolCall] = []
+
+ async def handler(call: CodexDynamicToolCall) -> CodexDynamicToolResult:
+ seen.append(call)
+ return CodexDynamicToolResult(content="tool output")
+
+ result = await session.invoke(_request(), [TOOL], handler)
+
+ assert result.final_response == "done"
+ assert len(seen) == rounds
+ assert len(client.responses.requests) == rounds + 1
+
+
+async def test_a_cancelled_tool_call_ends_the_turn_instead_of_reaching_the_model() -> (
+ None
+):
+ """The gateway cancels unanswered calls when the CLI stops at its turn
+ limit. With no round cap here, that cancellation is what ends the loop,
+ so it must not be reported to the model as an ordinary tool failure."""
+ session, client = _session([_tool_turn("lookup", "{}"), _text_turn("never")])
- with pytest.raises(CodexTurnLimitError):
- await session.invoke(_request(), [TOOL], _echo_tool)
+ async def abandoned(_call: CodexDynamicToolCall) -> CodexDynamicToolResult:
+ raise asyncio.CancelledError
+
+ with pytest.raises(asyncio.CancelledError):
+ await session.invoke(_request(), [TOOL], abandoned)
+ assert len(client.responses.requests) == 1
@pytest.mark.asyncio