The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): rate-limit retry status names the provider's reset window
teknium11e8219fe18b9
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 02f298bcde3..4a8744fe40e 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -3228,6 +3228,9 @@ def extract_api_error_context(error: Exception) -> Dict[str, Any]:reset = next((payload.get(k) for k in ("resets_at", "reset_at") if payload.get(k) not in {None, ""}), None)if reset is not None:context["reset_at"] = reset+ elif isinstance(payload.get("resets_in_seconds"), (int, float)):+ # Codex/ChatGPT usage-limit bodies carry a relative window beside (or instead of) the epoch.+ context["reset_at"] = time.time() + float(payload["resets_in_seconds"])_set_reset_from_retry_after(context, payload.get("retry_after"))headers = getattr(getattr(error, "response", None), "headers", None)if headers:diff --git a/agent/turn_recovery.py b/agent/turn_recovery.pyindex 008b3b3649f..921f208300b 100644--- a/agent/turn_recovery.py+++ b/agent/turn_recovery.py@@ -959,7 +959,11 @@ def max_retries_exhausted_result(_billing_guidance = _billing_or_entitlement_message(**_billing_kw)_print_billing_or_entitlement_guidance(agent, **_billing_kw)elif is_rate_limited:- agent._emit_diagnostic_status(f"❌ Rate limited after {max_retries} retries — {_final_summary}")+ _reset = reset_hint(api_error)+ agent._emit_diagnostic_status(+ f"❌ Rate limited after {max_retries} retries — {_final_summary}"+ f"{f' (resets in {_reset})' if _reset else ''}"+ )else:agent._emit_diagnostic_status(f"❌ API failed after {max_retries} retries — {_final_summary}")_vlines(agent, f" 💀 Final error: {_final_summary}")@@ -1159,6 +1163,21 @@ _ZAI_POLICY_NOTES = {}+def reset_hint(api_error: Exception) -> str:+ """``"~13m"`` until the ``reset_at`` parsed from *api_error* (epoch s/ms or ISO-8601), else ``""``.++ A bare "Rate limited. Waiting 60s" hides the one fact that decides whether to wait or switch+ models (#26889): a per-minute throttle and a 13-minute plan window look identical without it."""+ from agent.agent_runtime_helpers import extract_api_error_context+ from agent.credential_pool import _parse_absolute_timestamp+ from agent.usage_pricing import format_duration_compact+ reset_at = extract_api_error_context(api_error).get("reset_at")+ if reset_at is None:+ return ""+ remaining = (_parse_absolute_timestamp(reset_at) or 0.0) - time.time()+ return f"~{format_duration_compact(remaining)}" if remaining >= 1 else ""++def compute_error_backoff(agent: Any, api_error: Exception, *, retry_count: int, max_retries: int, is_rate_limited: bool,is_zai_coding_overload: bool, base_url: Any, model: Any,@@ -1207,7 +1226,11 @@ def compute_error_backoff(if _adaptive:_policy_note = _ZAI_POLICY_NOTES.get(_backoff_policy or "", "")_wait_reason = "Provider overloaded" if is_zai_coding_overload and not is_rate_limited else "Rate limited"- _rate_limit_status = f"⏱️ {_wait_reason}. Waiting {wait_time:.1f}s (attempt {retry_count + 1}/{max_retries}){_policy_note}..."+ _reset = reset_hint(api_error)+ _rate_limit_status = (+ f"⏱️ {_wait_reason}.{f' Resets in {_reset}.' if _reset else ''} Waiting {wait_time:.1f}s "+ f"(attempt {retry_count + 1}/{max_retries}){_policy_note}..."+ )if _backoff_policy == "zai_coding_overload_long":agent._emit_diagnostic_status(_rate_limit_status)else:diff --git a/tests/agent/test_rate_limit_reset_hint.py b/tests/agent/test_rate_limit_reset_hint.pynew file mode 100644index 00000000000..dc062307fe8--- /dev/null+++ b/tests/agent/test_rate_limit_reset_hint.py@@ -0,0 +1,49 @@+"""A rate-limit retry names the provider's reset window on the status line (#26889).++"Rate limited. Waiting 60s" hides the one fact that decides whether to wait or+switch models: a per-minute throttle and a 13-minute plan window look identical+without it. The hint is derived from the same ``reset_at`` the credential pool+uses, so the relative ``resets_in_seconds`` a Codex/ChatGPT usage-limit body+carries must land there too.+"""++import time+from unittest.mock import MagicMock++import pytest++from agent.agent_runtime_helpers import extract_api_error_context+from agent.turn_recovery import compute_error_backoff, reset_hint+++def _codex_429(**fields):+ err = Exception("HTTP 429: The usage limit has been reached")+ err.body = {"error": {"type": "usage_limit_reached", "message": "The usage limit has been reached", **fields}}+ return err+++def test_relative_resets_in_seconds_becomes_reset_at_when_no_epoch_is_given():+ ctx = extract_api_error_context(_codex_429(resets_in_seconds=756))+ assert abs(ctx["reset_at"] - (time.time() + 756)) < 5+ # An explicit epoch wins over the relative field (same precedence as the credential pool).+ ctx = extract_api_error_context(_codex_429(resets_at=1_900_000_000, resets_in_seconds=756))+ assert ctx["reset_at"] == 1_900_000_000+ # No signal at all → no hint, not a crash.+ assert reset_hint(Exception("HTTP 429")) == "" and reset_hint(_codex_429(resets_in_seconds=-5)) == ""+++def test_rate_limit_retry_status_names_the_reset_window():+ agent = MagicMock()+ from agent.status_output import StatusOutputMixin+ for name in ("_emit_diagnostic_wait", "_buffer_diagnostic_status"):+ setattr(agent, name, getattr(StatusOutputMixin, name).__get__(agent))+ agent._client_log_context.return_value = ""++ compute_error_backoff(+ agent, _codex_429(resets_in_seconds=756), retry_count=1, max_retries=3,+ is_rate_limited=True, is_zai_coding_overload=False,+ base_url="https://example.test/v1", model="test/model",+ )++ text = agent._buffer_status.call_args.args[0]+ assert text.startswith("⏱️ Rate limited. Resets in ~13m. Waiting ")