The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): real 401 envelopes keep the sign-in reply; quota reply reads the shared reset grammar
teknium1b2af1700f322
diff --git a/agent/retry_utils.py b/agent/retry_utils.pyindex ab28ee37a94..0cec62957d4 100644--- a/agent/retry_utils.py+++ b/agent/retry_utils.py@@ -75,6 +75,8 @@ _RESETS_IN_RE = re.compile(r"(?:(\d+(?:\.\d+)?)\s*(?:s|sec|secs|second|seconds)\b)?", re.IGNORECASE,)_RETRY_AFTER_SECONDS_RE = re.compile(r"retry\s+(?:after\s+)?(\d+(?:\.\d+)?)\s*(?:sec|secs|seconds|s\b)", re.IGNORECASE)+# The plan usage-limit body field as it appears once stringified: ``'resets_in_seconds': 30995``.+_RESETS_IN_SECONDS_FIELD_RE = re.compile(r"resets_in_seconds\W{1,4}(\d+(?:\.\d+)?)", re.IGNORECASE)def _quota_reset_seconds(m: "re.Match[str]") -> float:@@ -94,10 +96,17 @@ def _resets_in_seconds(m: "re.Match[str]") -> Optional[float]:RETRY_DELAY_PATTERNS = ((_QUOTA_RESET_DELAY_RE, _quota_reset_seconds),(_RETRY_AFTER_SECONDS_RE, lambda m: float(m.group(1))),+ (_RESETS_IN_SECONDS_FIELD_RE, lambda m: float(m.group(1))),(_RESETS_IN_RE, _resets_in_seconds),)+def format_reset_window(seconds: float) -> str:+ """``~9h`` / ``~45 min`` for chat copy naming when a quota window reopens (ceilinged)."""+ seconds = int(seconds)+ return f"~{-(-seconds // 3600)}h" if seconds >= 3600 else f"~{-(-seconds // 60)} min"++def reset_delay_from_message(message: str) -> Optional[float]:"""Seconds-until-reset parsed from free-text provider error messages, or None."""if not message:diff --git a/gateway/run.py b/gateway/run.pyindex 2183c65d8cf..c4cc9d5ddb9 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -374,11 +374,12 @@ _GATEWAY_PROVIDER_POLICY_RE = re.compile(r")",re.IGNORECASE)-# ``401`` only as a standalone status token: a bare ``\b401\b`` also hit timestamp fragments-# (``05:14:15,401``) and identifiers, mislabeling unrelated failures as sign-in problems (#89401).+# ``401`` as a status token: not glued to a digit or a timestamp/identifier separator on the left+# (``05:14:15,401``), but trailing punctuation is a real envelope (``HTTP 401: Unauthorized``,+# ``returned 401.``) and must keep matching (#89401)._GATEWAY_AUTH_ERROR_RE = re.compile(r"(provider\s+authentication\s+failed|incorrect\s+api\s+key|invalid\s+api\s+key"- r"|(?<![\d:,.\-_])401(?![\d:,.\-_]))",+ r"|(?<![\d:,.])401(?!\d))",re.IGNORECASE)_GATEWAY_RATE_LIMIT_RE = re.compile(@@ -605,19 +606,15 @@ _CONTEXT_OVERFLOW_REPLY = ("Use /compress to shorten the history, or /new to start a fresh conversation.")-# Reset window a quota 429 carries: ``resets_in_seconds`` (plan usage limit body) or the credential-# pool's ``retry after Ns``. Rendered so a weekly-quota cap is not sold as "wait a moment" (#89401).-_RATE_LIMIT_RESET_SECONDS_RE = re.compile(- r"(?:resets_in_seconds\W{1,4}|retry[\s-]+after\s+)(\d+)\s*s?\b", re.IGNORECASE)--def _rate_limit_reply(text: str) -> str:- match = _RATE_LIMIT_RESET_SECONDS_RE.search(text)- seconds = int(match.group(1)) if match else 0+ """Name the reset window a quota 429 carries (``resets_in_seconds`` body field, the credential+ pool's ``retry after Ns``, ``resets in 4hr``) so a weekly cap is not sold as "wait a moment"+ (#89401). One grammar table with the retry loop: ``agent.retry_utils.RETRY_DELAY_PATTERNS``."""+ from agent.retry_utils import format_reset_window, reset_delay_from_message+ seconds = reset_delay_from_message(text) or 0if seconds < 120:return "⏱️ The AI model service is rate-limiting requests. Wait a moment, then use /retry."- window = f"~{-(-seconds // 3600)}h" if seconds >= 3600 else f"~{-(-seconds // 60)} min"- return (f"⏱️ The AI model service's usage limit is reached; it resets in {window}. "+ return (f"⏱️ The AI model service's usage limit is reached; it resets in {format_reset_window(seconds)}. ""Use /retry after that, or /model to switch models.")diff --git a/tests/gateway/test_local_model_connection_reply.py b/tests/gateway/test_local_model_connection_reply.pyindex 07c34a628a8..5ff1bdad8c6 100644--- a/tests/gateway/test_local_model_connection_reply.py+++ b/tests/gateway/test_local_model_connection_reply.py@@ -84,25 +84,39 @@ class TestQuotaExhaustedIsNotAnAuthFailure:"API call failed after 3 retries: Error code: 429 - ""{'error': {'type': 'usage_limit_reached', 'resets_in_seconds': 30995}}")assert "resets in ~9h" in body_reply- # A bare 401 inside a timestamp is not a sign-in failure; a real 401 status still is.+ assert "resets in ~5h" in _gateway_provider_error_reply("429 weekly limit reached. Resets in 4hr 5min")+ # A bare 401 inside a timestamp is not a sign-in failure; every real 401 envelope still is,+ # including the ``HTTP 401: Unauthorized`` shape _summarize_api_error emits (control).assert "rate-limiting" in _gateway_provider_error_reply("API call failed at 05:14:15,401 status 429")- assert "/login" in _gateway_provider_error_reply("Error code: 401 - token rejected")-- def test_api_server_resolution_failure_label_follows_cause(self):- from gateway.platforms.api_server import _ProviderAuthResolutionError+ assert "/login" not in _gateway_provider_error_reply("request 05:14:15,401 failed")+ for text in ("HTTP 401: Unauthorized", "returned 401.", "HTTP 401, re-authenticate", "Error code: 401 - token rejected"):+ assert "/login" in _gateway_provider_error_reply(text), text++ def test_turn_runner_resolution_quota_failure_names_reset_window_not_login(self, monkeypatch):+ """Production entry: TurnRunner.run_sync with credential resolution raising the quota+ RuntimeError the gateway wraps around a ``codex_rate_limited`` AuthError."""+ from types import SimpleNamespace+ import gateway.run as gateway_run+ from gateway.config import Platform+ from gateway.run_turn_runner import TurnRunner+ from gateway.session import SessionSource+ from gateway.turn_context import TurnContextfrom hermes_cli.auth import AuthErrorfrom hermes_cli.auth_constants import CODEX_RATE_LIMITED_CODE- def _wrap(cause):+ def _resolve(**_kwargs):try:- raise RuntimeError(str(cause)) from cause- except RuntimeError as run_exc:- try:- raise _ProviderAuthResolutionError(str(run_exc)) from run_exc- except _ProviderAuthResolutionError as typed:- return typed-- quota = AuthError("quota exhausted (429); retry after 5s. Credentials are still valid.",- code=CODEX_RATE_LIMITED_CODE, relogin_required=False)- assert _wrap(quota).user_text().startswith("⚠️ Provider rate-limited: ")- assert _wrap(AuthError("token expired")).user_text().startswith("⚠️ Provider authentication failed: ")+ raise AuthError("Codex provider quota exhausted (429); retry after 116168s. Credentials are still valid.",+ code=CODEX_RATE_LIMITED_CODE, relogin_required=False)+ except AuthError as exc:+ raise RuntimeError(str(exc)) from exc++ monkeypatch.setattr(gateway_run, "_current_max_iterations", lambda: 30)+ runner = SimpleNamespace(_resolve_session_agent_runtime=_resolve,+ _get_system_prompt_for_channel=lambda *a, **k: "",+ _ephemeral_system_prompt="")+ ctx = TurnContext(source=SessionSource(platform=Platform.SLACK, chat_id="C1", chat_type="dm"),+ session_key="slack:C1", user_config={}, message="Hi")+ result = TurnRunner(runner, ctx).run_sync()+ reply = result["final_response"]+ assert "/login" not in reply and "resets in ~33h" in reply and result["api_calls"] == 0