Skip to content

The agent that grows with you

fix(agent): live retry wait line and vendor reset headers carry the reset window

teknium1664f37dd688c
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 4a8744fe40e..26bc422ba42 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -24,7 +24,7 @@ from agent.tool_dispatch_helpers import _trajectory_normalize_msg, make_tool_res
from agent.think_scrubber import THINK_TAG_NAMES
from agent.trajectory import convert_scratchpad_to_think
from agent.credential_pool import (
- STATUS_EXHAUSTED, credential_pool_matches_provider, resolve_runtime_pool_key
+ STATUS_EXHAUSTED, _parse_absolute_timestamp, credential_pool_matches_provider, resolve_runtime_pool_key
)
from agent.error_classifier import FailoverReason
from agent.retry_utils import parse_retry_after_seconds, reset_delay_from_message
@@ -3210,6 +3210,46 @@ def _set_reset_from_retry_after(context: Dict[str, Any], retry_after: Any) -> No
context["reset_at"] = time.time() + seconds
+# OpenAI-style relative windows: "6m0s", "1.5s", "20ms", "1h2m3s" (also a bare number of seconds).
+_DURATION_COMPONENT_RE = re.compile(r"(\d+(?:\.\d+)?)(ms|h|m|s)")
+_DURATION_UNIT_SECONDS = {"h": 3600.0, "m": 60.0, "s": 1.0, "ms": 0.001}
+# Lowest-priority reset sources, after Retry-After and x-ratelimit-reset: OpenAI's per-bucket
+# durations and Anthropic's per-bucket ISO-8601 timestamps. Plain OpenAI/Anthropic 429s often
+# carry only these, and without them the retry status never names the reset window.
+_VENDOR_RESET_HEADERS = (
+ "x-ratelimit-reset-requests", "x-ratelimit-reset-tokens",
+ "anthropic-ratelimit-requests-reset", "anthropic-ratelimit-tokens-reset",
+)
+
+
+def _duration_string_seconds(text: str) -> Optional[float]:
+ raw = text.strip().lower()
+ if not raw:
+ return None
+ try:
+ return float(raw)
+ except ValueError:
+ pass
+ parts = _DURATION_COMPONENT_RE.findall(raw)
+ if not parts or "".join(n + u for n, u in parts) != raw:
+ return None
+ return sum(float(n) * _DURATION_UNIT_SECONDS[u] for n, u in parts)
+
+
+def _set_reset_from_vendor_headers(context: Dict[str, Any], headers: Any) -> None:
+ for name in _VENDOR_RESET_HEADERS:
+ value = headers.get(name)
+ if not isinstance(value, str) or not value.strip():
+ continue
+ seconds = _duration_string_seconds(value)
+ if seconds is None:
+ absolute = _parse_absolute_timestamp(value)
+ seconds = None if absolute is None else absolute - time.time()
+ if seconds is not None and seconds > 0:
+ context["reset_at"] = time.time() + seconds
+ return
+
+
def extract_api_error_context(error: Exception) -> Dict[str, Any]:
"""Extract structured rate-limit details from provider errors."""
context: Dict[str, Any] = {}
@@ -3238,6 +3278,8 @@ def extract_api_error_context(error: Exception) -> Dict[str, Any]:
ratelimit_reset = headers.get("x-ratelimit-reset")
if ratelimit_reset and "reset_at" not in context:
context["reset_at"] = ratelimit_reset
+ if "reset_at" not in context:
+ _set_reset_from_vendor_headers(context, headers)
if "message" not in context and str(error).strip():
context["message"] = str(error).strip()[:500]
if "reset_at" not in context and isinstance(context.get("message") or "", str):
diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py
index 921f208300b..00fbb38f4f6 100644
--- a/agent/turn_recovery.py
+++ b/agent/turn_recovery.py
@@ -1223,10 +1223,10 @@ def compute_error_backoff(
wait_time, _backoff_policy = adaptive_rate_limit_backoff(
retry_count, base_url=str(base_url), model=model, error=api_error, default_wait=wait_time,
)
+ _reset = reset_hint(api_error) if _adaptive else ""
+ _wait_reason = "Provider overloaded" if is_zai_coding_overload and not is_rate_limited else "Rate limited"
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"
- _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}..."
@@ -1250,9 +1250,12 @@ def compute_error_backoff(
# line is the one thing the user sees meanwhile. Name the wait there so a
# 60s backoff after a 5xx is not an anonymous spinner — this is transient
# (rewritten by the next frame, cleared on recovery), so it does not add
- # the transcript chatter the buffer exists to avoid.
+ # the transcript chatter the buffer exists to avoid. The reset window
+ # belongs here too: during the wait this line is the only place the user
+ # can learn whether to sit it out or switch models.
+ _live_reason = f"{_wait_reason.lower()} — resets in {_reset}," if _reset else "waiting on provider —"
agent._emit_diagnostic_wait(
- f"⏳ waiting on provider — retrying in {wait_time:.0f}s (attempt {retry_count}/{max_retries})"
+ f"⏳ {_live_reason} retrying in {wait_time:.0f}s (attempt {retry_count}/{max_retries})"
)
logger.warning(
"Retrying API call in %ss (attempt %s/%s) %s policy=%s error=%s",
diff --git a/tests/agent/test_rate_limit_reset_hint.py b/tests/agent/test_rate_limit_reset_hint.py
index dc062307fe8..754297ded20 100644
--- a/tests/agent/test_rate_limit_reset_hint.py
+++ b/tests/agent/test_rate_limit_reset_hint.py
@@ -47,3 +47,46 @@ def test_rate_limit_retry_status_names_the_reset_window():
text = agent._buffer_status.call_args.args[0]
assert text.startswith("⏱️ Rate limited. Resets in ~13m. Waiting ")
+
+
+def test_live_wait_line_names_the_reset_window_too():
+ """The buffered line replays only if every retry fails; the line rendered during the wait is
+ ``_emit_diagnostic_wait`` → ``_emit_wait_notice``, and it must carry the same hint."""
+ 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 = ""
+
+ def run(err):
+ compute_error_backoff(
+ agent, err, retry_count=1, max_retries=3, is_rate_limited=True, is_zai_coding_overload=False,
+ base_url="https://example.test/v1", model="test/model",
+ )
+ return agent._emit_wait_notice.call_args.args[0]
+
+ live = run(_codex_429(resets_in_seconds=756))
+ assert live.startswith("⏳ rate limited — resets in ~13m, retrying in ") and "(attempt 1/3)" in live
+ # No reset known → the existing anonymous-wait wording is unchanged.
+ assert run(Exception("HTTP 429")).startswith("⏳ waiting on provider — retrying in ")
+
+
[email protected]("headers, expected_seconds", [
+ ({"x-ratelimit-reset-requests": "6m0s"}, 360),
+ ({"x-ratelimit-reset-tokens": "1.5s"}, 1.5),
+ ({"x-ratelimit-reset-requests": "20ms"}, 0.02),
+ ({"anthropic-ratelimit-requests-reset": None}, 900), # filled below with now+900 ISO-8601 'Z'
+ ({"retry-after": "30", "x-ratelimit-reset-requests": "6m0s"}, 30), # Retry-After still wins
+])
+def test_vendor_reset_headers_feed_reset_at(headers, expected_seconds):
+ from datetime import datetime, timedelta, timezone
+ if "anthropic-ratelimit-requests-reset" in headers:
+ when = datetime.now(timezone.utc) + timedelta(seconds=900)
+ headers["anthropic-ratelimit-requests-reset"] = when.strftime("%Y-%m-%dT%H:%M:%SZ")
+ err = Exception("HTTP 429: rate limit")
+ err.response = MagicMock(headers=headers)
+ assert abs(extract_api_error_context(err)["reset_at"] - (time.time() + expected_seconds)) < 5
+ # A reset already in the past is ignored rather than reported as "resets in ~0s".
+ past = Exception("HTTP 429")
+ past.response = MagicMock(headers={"anthropic-ratelimit-tokens-reset": "2020-01-01T00:00:00Z"})
+ assert "reset_at" not in extract_api_error_context(past)