The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: quota-exhausted 429 is no longer reported to chat as a sign-in failure
teknium14b0dd7e9a7f8
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 211acafaacb..b215e0f8356 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -1086,6 +1086,16 @@ class _ProviderAuthResolutionError(RuntimeError):"""Provider credential resolution failed. Typed so callers never mislabel otherRuntimeErrors from run_conversation() (e.g. a closed OpenAI client) as auth failures."""+ def user_text(self) -> str:+ """Raw-surface failure line. A quota/429 cap with valid credentials must not be labelled an+ authentication failure — the cause chain (RuntimeError -> AuthError) tells them apart (#89401)."""+ from hermes_cli.auth import is_rate_limited_auth_error++ cause = self.__cause__+ cause = getattr(cause, "__cause__", None) if isinstance(cause, RuntimeError) else cause+ label = "Provider rate-limited" if is_rate_limited_auth_error(cause) else "Provider authentication failed"+ return f"⚠️ {label}: {self}"+class _SessionEventQueue:"""Ordered SSE event queue for one /api/sessions/{id}/chat/stream run. ``payload`` stamps@@ -3820,10 +3830,10 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):except _ProviderAuthResolutionError as exc:# Typed provider-auth failure only, handled once for every caller in# run.py's response shape (text, no HTTP error).- logger.warning("Provider authentication failed for session=%s: %s",+ logger.warning("Provider resolution failed for session=%s: %s",session_id or "", exc)return (- {"final_response": f"⚠️ Provider authentication failed: {exc}", "messages": [],+ {"final_response": exc.user_text(), "messages": [],"api_calls": 0, "tools": [],**({"_notification_presentation_suppressed": True} if muted else {})},{"input_tokens": 0, "output_tokens": 0, "total_tokens": 0})diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.pyindex ea7efb7f1a3..387263912be 100644--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@ -772,8 +772,8 @@ async def _execute_run(self, run: _RunLaunch, *, _api_server) -> None:raiseexcept _api_server._ProviderAuthResolutionError as exc:# Same controlled provider-auth message the _run_agent() endpoints give.- logger.warning("Provider authentication failed for run=%s: %s", run_id, exc)- _finish("failed", error=f"⚠️ Provider authentication failed: {exc}")+ logger.warning("Provider resolution failed for run=%s: %s", run_id, exc)+ _finish("failed", error=exc.user_text())except Exception as exc:logger.exception("[api_server] run %s failed", run_id)_finish("failed", error=_redact_api_error_text(exc))diff --git a/gateway/run.py b/gateway/run.pyindex 7ed20012737..2183c65d8cf 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -374,8 +374,11 @@ _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)._GATEWAY_AUTH_ERROR_RE = re.compile(- r"(provider\s+authentication\s+failed|incorrect\s+api\s+key|invalid\s+api\s+key|\b401\b)",+ r"(provider\s+authentication\s+failed|incorrect\s+api\s+key|invalid\s+api\s+key"+ r"|(?<![\d:,.\-_])401(?![\d:,.\-_]))",re.IGNORECASE)_GATEWAY_RATE_LIMIT_RE = re.compile(@@ -579,14 +582,17 @@ def _format_exec_approval_fallback(+ ", ".join(choices[:-1]) + f", or {choices[-1]}.\n"+ format_approval_deadline_line(approval_timeout_seconds()))-# Ordered: auth beats policy beats rate-limit beats connection; first match wins. Copy names the-# slash command the chat user can run; raw provider text stays in the gateway log (`hermes logs`).+# Ordered: rate-limit beats auth beats policy beats connection; first match wins. Rate-limit goes+# first because a quota/429 envelope often also carries an auth-shaped preamble ("Provider+# authentication failed: ... quota exhausted (429) ... Credentials are still valid") and re-auth can+# never fix a quota, so text with both signals must fail safe toward the quota reply (#89401). Copy+# names the slash command the chat user can run; raw provider text stays in the gateway log._PROVIDER_ERROR_REPLIES = (+ (_GATEWAY_RATE_LIMIT_RE, "⏱️ The AI model service is rate-limiting requests. Wait a moment, then use /retry."),(_GATEWAY_AUTH_ERROR_RE, "⚠️ Sign-in to the AI model service failed. Use /login to sign in again, ""or ask whoever runs this bot to run `hermes doctor` on the host."),(_GATEWAY_PROVIDER_POLICY_RE, "⚠️ The AI model service rejected this request. Try rephrasing your ""message, or use /model to switch models."),- (_GATEWAY_RATE_LIMIT_RE, "⏱️ The AI model service is rate-limiting requests. Wait a moment, then use /retry."),(_GATEWAY_CONNECTION_ERROR_RE, "⚠️ The AI model service isn't reachable right now — the configured model ""endpoint is not running or is unreachable. Wait a moment and use /retry; ""if it persists, run `hermes doctor` on the host."))@@ -599,11 +605,27 @@ _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+ if 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}. "+ "Use /retry after that, or /model to switch models.")++def _gateway_provider_error_reply(text: str) -> str:"""Map raw provider/API errors to a short user-safe Telegram reply."""for pattern, reply in _PROVIDER_ERROR_REPLIES:if pattern.search(text):- return reply+ return _rate_limit_reply(text) if pattern is _GATEWAY_RATE_LIMIT_RE else replyreturn ("⚠️ The AI model service kept failing. Use /retry to try again, or /model to switch ""models. Details are in the gateway log (`hermes logs`).")diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 1b09f5af18a..cb8424f5e57 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -1905,6 +1905,12 @@ class TurnRunner:# Model/credential resolution failed before the turn began; the raw text (URLs, status# codes) belongs in the log, and the chat gets the commands that fix it.logger.warning("Model resolution failed for session %s: %s", ctx.session_key or "", exc)+ from hermes_cli.auth import is_rate_limited_auth_error+ if is_rate_limited_auth_error(exc.__cause__):+ # Quota cap with valid credentials: /login cannot help; name the reset window (#89401).+ from gateway.run import _gateway_provider_error_reply+ return {"final_response": _gateway_provider_error_reply(str(exc)),+ "messages": [], "api_calls": 0, "tools": []}return {"final_response": ("⚠️ I couldn't connect to the AI model service, so this message wasn't processed. "diff --git a/tests/gateway/test_local_model_connection_reply.py b/tests/gateway/test_local_model_connection_reply.pyindex cf0f64f0eda..07c34a628a8 100644--- a/tests/gateway/test_local_model_connection_reply.py+++ b/tests/gateway/test_local_model_connection_reply.py@@ -69,3 +69,40 @@ class TestGatewayConnectionErrorReply:for reply in replies:assert any(cmd in reply for cmd in ("/login", "/retry", "/model")), replyassert "provider" not in reply.lower(), reply+++class TestQuotaExhaustedIsNotAnAuthFailure:+ """A 429/quota envelope must never send the user to re-authenticate valid credentials, and a+ long reset window must be named instead of "wait a moment" (#89401)."""++ def test_quota_envelope_with_auth_preamble_names_reset_window(self):+ reply = _gateway_provider_error_reply(+ "⚠️ Provider authentication failed: Codex provider quota exhausted (429); "+ "retry after 116168s. Credentials are still valid.")+ assert "/login" not in reply and "resets in ~33h" in reply+ body_reply = _gateway_provider_error_reply(+ "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 "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+ from hermes_cli.auth import AuthError+ from hermes_cli.auth_constants import CODEX_RATE_LIMITED_CODE++ def _wrap(cause):+ 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: ")