Skip to content

The agent that grows with you

fix(agent): a credit-limited 402 retries once with the affordable output cap instead of failing as billing

kshitijk4pooree8dd6c88632
diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py
index 95442a89b86..201d08c737e 100644
--- a/agent/turn_recovery.py
+++ b/agent/turn_recovery.py
@@ -640,6 +640,27 @@ def _recover_welcome_tier(agent: Any, classified: Any, _retry: TurnRetryState) -
return False
+def _clamp_to_affordable_budget(agent: Any, api_error: Exception, classified: Any, _retry: TurnRetryState) -> bool:
+ """A credit-limited 402 (OpenRouter: "...requested up to 65536 tokens, but can only afford
+ 56272") means the account has credit and the output cap was too large: retry ONCE with the
+ cap lowered to the affordable budget instead of abandoning the provider as billing (#49769).
+ Same budget parse as the auxiliary client's retry. The 402 itself says the request's cap
+ exceeded the budget (which may be a boosted continuation cap above ``agent.max_tokens``),
+ so a second credit-limited 402 on this call is genuine exhaustion."""
+ if classified.reason != FailoverReason.billing or _retry.affordable_402_clamp_attempted:
+ return False
+ from agent.auxiliary_client import _affordable_max_tokens_from_error
+
+ affordable = _affordable_max_tokens_from_error(api_error)
+ if affordable is None:
+ return False
+ _retry.affordable_402_clamp_attempted = True
+ agent._ephemeral_max_output_tokens = affordable
+ _vlines(agent, f"πŸ’³ Credit balance covers fewer output tokens β€” retrying with max_tokens={affordable:,}...")
+ logger.info("%sCredit-limited 402: retrying once with max_tokens=%d", agent.log_prefix, affordable)
+ return True
+
+
def recover_after_classification(
agent: Any, api_error: Exception, classified: Any, _retry: TurnRetryState, *,
status_code: Optional[int], error_context: Any, messages: List[Dict[str, Any]],
@@ -647,14 +668,18 @@ def recover_after_classification(
) -> Tuple[bool, bool]:
"""One-shot recovery chain that runs AFTER ``classify_api_error`` and before the
generic retry path. Order is load-bearing (each branch may ``return`` early):
- Nous paid-entitlement refresh β†’ Codex stale-reasoning strip on 401 ``token_expired`` β†’
- credential-pool rotation β†’ image shrink β†’ multimodal-tool-content strip β†’ corrupt-image
+ welcome-tier repair β†’ credit-limited 402 output-cap clamp β†’ Nous paid-entitlement refresh β†’
+ Codex stale-reasoning strip on 401 ``token_expired`` β†’ credential-pool rotation β†’ image shrink β†’ multimodal-tool-content strip β†’ corrupt-image
strip β†’ Anthropic OAuth 1M-beta disable β†’ per-provider 401 credential refresh β†’
format-recovery strips.
Returns ``(retry_now, recovered_with_pool)``; the latter feeds the Nous rate-limit guard."""
from agent.conversation_loop import _is_nous_inference_route
- if _recover_welcome_tier(agent, classified, _retry):
+ # The credit-limited 402 clamp runs before pool rotation, which would bench a credential
+ # that still has credit.
+ if _recover_welcome_tier(agent, classified, _retry) or _clamp_to_affordable_budget(
+ agent, api_error, classified, _retry
+ ):
return True, False
# 401 ``token_expired`` while the transcript still carries ``codex_reasoning_items`` is a
diff --git a/agent/turn_retry_state.py b/agent/turn_retry_state.py
index 76752ae61cd..e00297d095c 100644
--- a/agent/turn_retry_state.py
+++ b/agent/turn_retry_state.py
@@ -42,6 +42,8 @@ class TurnRetryState:
# Transport / rate-limit recovery
primary_recovery_attempted: bool = False
has_retried_429: bool = False
+ # Credit-limited 402 ("can only afford N tokens") already retried with a lowered output cap.
+ affordable_402_clamp_attempted: bool = False
# Persistent 401/403 already escalated to the fallback chain once this attempt.
auth_failover_attempted: bool = False
# Post-exhaustion auto-recovery cycles spent on this API call (agent.auto_recovery_cycles caps it).
diff --git a/tests/agent/test_affordable_402_main_loop.py b/tests/agent/test_affordable_402_main_loop.py
new file mode 100644
index 00000000000..f8b50d6ec99
--- /dev/null
+++ b/tests/agent/test_affordable_402_main_loop.py
@@ -0,0 +1,53 @@
+"""Main-loop credit-limited 402: retry once with the affordable output cap (#49769).
+
+OpenRouter answers a request whose ``max_tokens`` exceeds the remaining balance with
+``402 ... You requested up to 65536 tokens, but can only afford 56272``. The account has
+credit; the cap was too large. A real ``AIAgent`` turn against a recording fake provider must
+retry the same provider once with the cap lowered to the affordable budget (the auxiliary
+client's ``_affordable_max_tokens_from_error`` parse) and answer β€” and a second 402 must
+still end the turn as billing, without a retry loop.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import pytest
+
+from tests.e2e.core.history._helpers import NO_BACKGROUND_REVIEW, OFFLINE_CONFIG
+from tests.fakes.fake_llm_provider import Error, FakeLLMServer, Text, write_hermes_home
+
+_CREDIT_LIMITED_402 = (
+ "This request requires more credits, or fewer max_tokens. You requested up to 65536 tokens, "
+ "but can only afford 56272. To increase, visit https://openrouter.ai/settings/credits and add more credits"
+)
+
+
+def _turn(script):
+ from run_agent import AIAgent
+
+ home = Path(os.environ["HERMES_HOME"])
+ with FakeLLMServer(script) as srv:
+ write_hermes_home(home, srv.base_url, extra_config=OFFLINE_CONFIG + NO_BACKGROUND_REVIEW)
+ agent = AIAgent(provider="custom", base_url=srv.base_url, api_key="sk-fake", model="fake-model",
+ session_id="affordable-402", quiet_mode=True, platform="cli", skip_memory=True,
+ max_tokens=65536)
+ try:
+ result = agent.run_conversation("hi", conversation_history=[], task_id="t")
+ finally:
+ agent.close()
+ caps = [r.get("max_tokens") or r.get("max_completion_tokens") for r in srv.main_requests()]
+ return result, caps
+
+
[email protected]("repeat_402", [False, True], ids=["retry-answers", "second-402-is-billing"])
+def test_credit_limited_402_retries_once_with_the_affordable_cap(repeat_402):
+ script = [Error(402, _CREDIT_LIMITED_402)] * (2 if repeat_402 else 1) + [Text("answered")]
+ result, caps = _turn(script)
+
+ assert caps == [65536, 56272 - 64]
+ if repeat_402:
+ assert result.get("failed") and "Billing" in (result.get("final_response") or ""), result
+ else:
+ assert result.get("completed") and result.get("final_response") == "answered", result