The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): codex app-server quota and rate-limit failures fail over to fallback_providers
teknium1d7e405ef799c
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 2343c74547f..79303c09110 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -1519,11 +1519,18 @@ def _run_conversation_turn(# Opt-in runtime: api_mode == codex_app_server hands the whole turn to the codex# app-server subprocess (see agent/transports/codex_app_server_session.py).if agent.api_mode == "codex_app_server":- return agent._run_codex_app_server_turn(+ codex_result = agent._run_codex_app_server_turn(user_message=s.user_message, original_user_message=s.original_user_message,messages=s.messages, effective_task_id=s.effective_task_id,should_review_memory=s._should_review_memory,)+ from agent.turn_recovery import activate_codex_app_server_fallback+ if not activate_codex_app_server_fallback(agent, codex_result):+ return codex_result+ # Fallback activation rewrote provider/model/api_mode: retry this same user turn on the generic+ # loop below, keeping codex's projected rows and its failed API call in the turn's accounting.+ s.api_call_count = int(codex_result.get("api_calls") or 0)+ s.active_system_prompt = _sync_failover_system_message(agent, None, s.active_system_prompt)while (s.api_call_count < agent.max_iterations and agent.iteration_budget.remaining > 0) or agent._budget_grace_call:if _run_phase(begin_iteration, agent, s).action == "break":diff --git a/agent/turn_recovery.py b/agent/turn_recovery.pyindex a52cf4bca99..3f0f45e7410 100644--- a/agent/turn_recovery.py+++ b/agent/turn_recovery.py@@ -1440,6 +1440,30 @@ def _eager_fallback_status(classified: Any, is_upstream: bool, is_transport_failreturn "⚠️ Rate limited — switching to fallback provider..."+_CODEX_APP_SERVER_FALLBACK_REASONS = frozenset({+ FailoverReason.billing, FailoverReason.rate_limit, FailoverReason.upstream_rate_limit,+})+++def activate_codex_app_server_fallback(agent: Any, result: Dict[str, Any]) -> bool:+ """The codex app-server runtime reports a failed turn as ``result["error"]`` text instead of+ raising, so the generic classify -> ``fallback_providers`` chain never saw it (#71633).+ Classify that text; on a billing / rate-limit verdict activate the configured fallback and+ return True so the caller re-runs the same user turn on the generic loop."""+ error = result.get("error")+ if not error or result.get("interrupted") or not agent._has_pending_fallback():+ return False+ from agent.error_classifier import classify_api_error+ classified = classify_api_error(+ RuntimeError(str(error)), provider=getattr(agent, "provider", "") or "", model=getattr(agent, "model", "") or "",+ )+ if classified.reason not in _CODEX_APP_SERVER_FALLBACK_REASONS:+ return False+ agent._buffer_diagnostic_status(+ _eager_fallback_status(classified, classified.reason == FailoverReason.upstream_rate_limit, False))+ return bool(agent._try_activate_fallback(reason=classified.reason))++def _is_genuine_nous_rate_limit(agent: Any, api_error: Exception, error_context: Any, classified: Any = None) -> bool:"""Record a genuine account-level Nous 429 to the cross-session breaker; upstreamcapacity 429s (no exhausted bucket in headers or last-known state) are left alone.diff --git a/tests/agent/test_codex_app_server_integration.py b/tests/agent/test_codex_app_server_integration.pyindex b0b1277c12d..d4be1d024dd 100644--- a/tests/agent/test_codex_app_server_integration.py+++ b/tests/agent/test_codex_app_server_integration.py@@ -620,6 +620,61 @@ class TestErrorHandling:assert result["error"] == "user interrupted"+class TestQuotaFailureFallsOverToConfiguredFallback:+ """A codex app-server turn that ends in a usage-limit error must hand the same user turn to the+ configured ``fallback_providers`` entry instead of failing outright (#71633). The fallback is a+ local fake OpenAI-compatible server so the real classify -> activate -> retry path runs."""++ def test_usage_limit_turn_completes_on_fallback_provider(self, monkeypatch):+ import json+ import threading+ from http.server import BaseHTTPRequestHandler, HTTPServer++ calls = []++ class _Handler(BaseHTTPRequestHandler):+ def log_message(self, *_a):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0)) or b"{}"))+ calls.append(self.path)+ chunk = {"id": "c1", "object": "chat.completion.chunk", "created": 0, "model": body.get("model"),+ "choices": [{"index": 0, "delta": {"role": "assistant", "content": "fallback answered"},+ "finish_reason": "stop"}]}+ data = f"data: {json.dumps(chunk)}\n\ndata: [DONE]\n\n".encode()+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ srv = HTTPServer(("127.0.0.1", 0), _Handler)+ threading.Thread(target=srv.serve_forever, daemon=True).start()+ try:+ def limit_turn(self, user_input, **kwargs):+ return TurnResult(final_text="", projected_messages=[], tool_iterations=0, interrupted=False,+ error="turn ended status=failed: You've hit your usage limit.",+ turn_id="t1", thread_id="th1", should_retire=True)++ monkeypatch.setattr(CodexAppServerSession, "ensure_started", lambda self: "th1")+ monkeypatch.setattr(CodexAppServerSession, "run_turn", limit_turn)+ agent = _make_codex_agent(fallback_model=[{+ "provider": "custom", "model": "fake-fb", "api_key": "fb-key",+ "base_url": f"http://127.0.0.1:{srv.server_port}/v1",+ }])+ with patch.object(agent, "_spawn_background_review", return_value=None):+ result = agent.run_conversation("hello")+ finally:+ srv.shutdown()+ srv.server_close()++ assert result["final_response"] == "fallback answered"+ assert result["completed"] is True+ assert "/v1/chat/completions" in calls+ assert agent.api_mode != "codex_app_server"++class TestSessionRetirementOnRunAgent:"""run_agent.py side: when run_turn returns should_retire=True, theAIAgent must close + null _codex_session so the next turn respawns."""