Skip to content

The agent that grows with you

fix(agent): name an exhausted (402) provider pool, not "No LLM provider configured"

austinpickett516535b54275
diff --git a/agent/agent_init.py b/agent/agent_init.py
index c98d5666247..c9c140cdf03 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -887,6 +887,7 @@ def _routed_client_kwargs(agent, fallback_model, _provider_timeout) -> Optional[
# A burned credential pool (#119533) is otherwise indistinguishable from missing config,
# so name it even when no fallback entries are configured.
_pool_exhausted = False
+ _pool = None
if _explicit and _explicit != "auto":
with suppress(Exception):
from agent.credential_pool import load_pool
@@ -901,6 +902,25 @@ def _routed_client_kwargs(agent, fallback_model, _provider_timeout) -> Optional[
"credential pool exhausted" if _pool_exhausted else "no usable credentials",
"; ".join(f"{_p} ({_r})" for _p, _r in _refused_entries) or "none configured",
)
+ # A fully-exhausted pool is a billing/quota failure, NOT a config problem: name it for EVERY
+ # explicit provider. ``openrouter`` / ``custom`` have no provider-specific missing-credentials
+ # branch, so a burned override pool there fell through to the generic "No LLM provider
+ # configured" setup message even though the config default was fine (#94785). Prefer a billing
+ # verdict (402 / classifier "billing") and fall back to the existing cooldown wording (which
+ # names the 429 reset time, #56810); raise before the missing-credentials branch so a genuine
+ # 402 is never described as a missing key or a transient rate limit.
+ if _pool_exhausted:
+ from agent.auxiliary_unavailable import (
+ ProviderCredentialsExhaustedError,
+ pool_billing_message,
+ pool_cooldown_message,
+ )
+ _exhausted_message = (
+ pool_billing_message(_explicit, model=agent.model, pool=_pool)
+ or pool_cooldown_message(_explicit)
+ )
+ if _exhausted_message:
+ raise ProviderCredentialsExhaustedError(_exhausted_message, provider=_explicit)
if _explicit and _explicit not in {"auto", "openrouter", "custom"}:
# Explicit non-OpenRouter provider with no creds and no usable fallback: fail fast.
from agent.auxiliary_unavailable import missing_provider_credentials_message
diff --git a/agent/auxiliary_unavailable.py b/agent/auxiliary_unavailable.py
index bf8ee5ddbff..9eac20412de 100644
--- a/agent/auxiliary_unavailable.py
+++ b/agent/auxiliary_unavailable.py
@@ -12,7 +12,7 @@ import logging
import threading
import time
from datetime import datetime
-from typing import Optional
+from typing import Any, Optional
from hermes_time import safe_strftime
@@ -90,6 +90,93 @@ def pool_cooldown_message(provider_id: str) -> Optional[str]:
"different provider with `hermes model`.")
+class ProviderCredentialsExhaustedError(RuntimeError):
+ """An explicit provider's credential pool is fully exhausted (402 out of credits, quota bench).
+
+ Subclasses ``RuntimeError`` so every existing ``except RuntimeError`` keeps working; the distinct
+ type lets a caller (gateway, Desktop) route a billing/quota failure to billing guidance instead
+ of the provider-setup flow a plain "No LLM provider configured" would trigger (#94785).
+ """
+
+ def __init__(self, message: str, *, provider: Optional[str] = None):
+ super().__init__(message)
+ self.provider = provider
+
+
+def pool_billing_message(
+ provider_id: str,
+ *,
+ model: Optional[str] = None,
+ pool: Optional[Any] = None,
+) -> Optional[str]:
+ """The "Provider 'X' … is out of usable credentials (402)" error for a billing-burned pool.
+
+ ``resolve_provider_client()`` returns ``None`` both when no credential exists and when every
+ pool entry has been marked exhausted — a 402 out-of-credits account, a 429/quota bench. The
+ ``openrouter`` / ``custom`` branch of ``agent_init`` has no provider-specific missing-credentials
+ message, so a burned pool there fell through to the generic "No LLM provider configured" setup
+ message: actively misleading when a *different* provider is configured and working and only the
+ session's override is out of credits (#94785). Name the provider, the session's model, the last
+ error code and the provider's own message instead.
+
+ Only a genuine billing verdict — a 402, or the classifier's ``billing`` reason on a 403 spending
+ limit — is named here; a plain 429/quota bench keeps the existing cooldown wording (with its
+ reset time, #56810), which the caller falls back to when this returns ``None``.
+
+ *pool* is an already-loaded ``CredentialPool`` (preferred — it carries the live in-memory
+ exhaustion state); otherwise the persisted rows are read (no seeding, no writes, mirroring
+ ``pool_cooldown_message``). ``None`` when the pool is empty, a credential is usable, no entry is
+ currently benched, or none carries a billing verdict.
+ """
+ from agent.credential_pool import (
+ FAILURE_REASON_BILLING,
+ STATUS_DEAD,
+ STATUS_EXHAUSTED,
+ PooledCredential,
+ _exhausted_until,
+ )
+
+ entries: list = []
+ with contextlib.suppress(Exception):
+ if pool is not None:
+ entries = list(pool.entries())
+ else:
+ from hermes_cli.auth import read_credential_pool
+
+ entries = [PooledCredential.from_dict(provider_id, e)
+ for e in read_credential_pool(provider_id) if isinstance(e, dict)]
+ live = [e for e in entries if getattr(e, "last_status", None) != STATUS_DEAD]
+ if not live:
+ return None
+ now = time.time()
+ benched = [
+ e for e in live
+ if getattr(e, "last_status", None) == STATUS_EXHAUSTED
+ and (_exhausted_until(e, sole_credential=len(live) == 1) or 0) > now
+ ]
+ if len(benched) != len(live):
+ # A credential is still usable (or merely cooling down on one model): not our case.
+ return None
+ billing = [
+ e for e in benched
+ if getattr(e, "last_error_code", None) == 402
+ or getattr(e, "failure_reason", None) == FAILURE_REASON_BILLING
+ ]
+ if not billing:
+ return None
+ pick = billing[0]
+ code = getattr(pick, "last_error_code", None)
+ detail = str(getattr(pick, "last_error_message", None) or "").strip()
+ which = "its only credential is" if len(live) == 1 else f"all {len(live)} credentials are"
+ scope = f" for model '{model}'" if model else ""
+ code_text = f" (last error {code}{': ' + detail if detail else ''})" if code else ""
+ return (
+ f"Provider '{provider_id}'{scope} is out of usable credentials: {which} exhausted"
+ f"{code_text}. Add credits or update billing with that provider, then retry, or switch "
+ f"to a different provider with `hermes model`."
+ )
+
+
def missing_provider_credentials_message(provider_id: str) -> str:
"""The "Provider 'X' is set in config.yaml but …" error for an explicit provider with no credentials.
diff --git a/tests/agent/test_init_exhausted_pool_billing_error.py b/tests/agent/test_init_exhausted_pool_billing_error.py
new file mode 100644
index 00000000000..1177cf204ad
--- /dev/null
+++ b/tests/agent/test_init_exhausted_pool_billing_error.py
@@ -0,0 +1,228 @@
+"""An exhausted (402) provider pool must be named as a billing failure at init.
+
+#94785: a Desktop composer pick routed through OpenRouter while the OpenRouter account was out of
+credits hit the generic "No LLM provider configured. Run `hermes model` …" message — actively
+misleading, because a *different* provider (the config default) was configured and working and only
+the session's override pool was burned. The ``openrouter`` / ``custom`` branch of
+``_routed_client_kwargs`` has no provider-specific missing-credentials message, so it fell through to
+the setup message; named providers fell through to the "no API key was found" one. Both must instead
+name the exhausted pool, its provider and its last error code.
+"""
+
+import json
+import time
+from types import SimpleNamespace
+
+import pytest
+
+from agent.credential_pool import (
+ STATUS_EXHAUSTED,
+ STATUS_OK,
+ CredentialPool,
+ PooledCredential,
+)
+
+
+def _agent(provider="openrouter", model="z-ai/glm-5.3"):
+ return SimpleNamespace(
+ provider=provider,
+ model=model,
+ base_url=None,
+ api_key=None,
+ _fallback_activated=False,
+ )
+
+
+def _credential(provider="openrouter", **overrides):
+ fields = dict(
+ provider=provider,
+ id="e1",
+ label="test-cred",
+ auth_type="api_key",
+ priority=0,
+ source="manual",
+ access_token="sk-test-0000000000",
+ )
+ fields.update(overrides)
+ return PooledCredential(**fields)
+
+
+def _exhausted_pool(provider="openrouter"):
+ entry = _credential(
+ provider,
+ last_status=STATUS_EXHAUSTED,
+ last_status_at=time.time(),
+ last_error_code=402,
+ last_error_message="You requested up to 65536 tokens, but can only afford 4282.",
+ )
+ return CredentialPool(provider, [entry])
+
+
+def _healthy_pool(provider="openrouter"):
+ return CredentialPool(provider, [_credential(provider, last_status=STATUS_OK)])
+
+
+def _exhausted_pool_429(provider="openrouter"):
+ entry = _credential(
+ provider,
+ last_status=STATUS_EXHAUSTED,
+ last_status_at=time.time(),
+ last_error_code=429,
+ last_error_message="rate limited",
+ )
+ return CredentialPool(provider, [entry])
+
+
+def _patch_no_routed_client(monkeypatch):
+ monkeypatch.setattr(
+ "agent.auxiliary_client.resolve_provider_client", lambda *a, **k: (None, None)
+ )
+ monkeypatch.setattr(
+ "hermes_cli.fallback_config.resolve_entry_api_key", lambda entry: None
+ )
+
+
+ "provider, model",
+ [
+ ("openrouter", "z-ai/glm-5.3"),
+ ("custom", "qwen3.5:4b"),
+ ("zai", "glm-5.3"),
+ ],
+)
+def test_exhausted_pool_raises_typed_billing_error(monkeypatch, provider, model):
+ """Every provider with a fully burned pool names the billing failure, not setup/missing-key."""
+ from agent import agent_init
+ from agent.auxiliary_unavailable import ProviderCredentialsExhaustedError
+
+ _patch_no_routed_client(monkeypatch)
+ monkeypatch.setattr(
+ "agent.credential_pool.load_pool", lambda p: _exhausted_pool(provider)
+ )
+
+ with pytest.raises(ProviderCredentialsExhaustedError) as excinfo:
+ agent_init._routed_client_kwargs(_agent(provider, model), None, 60)
+
+ message = str(excinfo.value)
+ assert excinfo.value.provider == provider
+ assert f"'{provider}'" in message
+ assert model in message
+ assert "402" in message
+ assert "exhausted" in message
+ # The whole point of #94785: the setup / missing-key sentence must NOT be what the user sees.
+ assert "No LLM provider configured" not in message
+ assert "no API key was found" not in message
+
+
+def test_healthy_pool_keeps_the_existing_diagnostic(monkeypatch):
+ """A usable credential must not be misreported as exhausted."""
+ from agent import agent_init
+
+ _patch_no_routed_client(monkeypatch)
+ monkeypatch.setattr(
+ "agent.credential_pool.load_pool", lambda p: _healthy_pool("openrouter")
+ )
+
+ with pytest.raises(RuntimeError, match="No LLM provider configured"):
+ agent_init._routed_client_kwargs(_agent("openrouter"), None, 60)
+
+
+def test_empty_pool_keeps_the_existing_diagnostic(monkeypatch):
+ """No read of the pool (empty / unreadable) must not invent an exhaustion verdict."""
+ from agent import agent_init
+
+ _patch_no_routed_client(monkeypatch)
+ monkeypatch.setattr(
+ "agent.credential_pool.load_pool", lambda p: CredentialPool("openrouter", [])
+ )
+
+ with pytest.raises(RuntimeError, match="No LLM provider configured"):
+ agent_init._routed_client_kwargs(_agent("openrouter"), None, 60)
+
+
+def test_pool_billing_message_names_billing_entry():
+ from agent.auxiliary_unavailable import pool_billing_message
+
+ message = pool_billing_message(
+ "openrouter", model="z-ai/glm-5.3", pool=_exhausted_pool("openrouter")
+ )
+ assert message is not None
+ assert "'openrouter'" in message
+ assert "z-ai/glm-5.3" in message
+ assert "402" in message
+ assert "can only afford 4282" in message
+
+
+def test_pool_billing_message_none_when_pool_is_usable():
+ from agent.auxiliary_unavailable import pool_billing_message
+
+ assert pool_billing_message("openrouter", pool=_healthy_pool()) is None
+ assert pool_billing_message("openrouter", pool=CredentialPool("openrouter", [])) is None
+
+
+def test_pool_billing_message_defers_non_billing_cooldown():
+ """A plain 429/quota bench is not billing: the caller keeps the cooldown wording (#56810)."""
+ from agent.auxiliary_unavailable import pool_billing_message
+
+ entry = _credential(
+ "openrouter",
+ last_status=STATUS_EXHAUSTED,
+ last_status_at=time.time(),
+ last_error_code=429,
+ last_error_message="rate limited",
+ )
+ pool = CredentialPool("openrouter", [entry])
+ assert pool_billing_message("openrouter", pool=pool) is None
+
+
+def test_openrouter_quota_cooldown_still_reports_the_cooldown(monkeypatch, tmp_path):
+ """openrouter 429 pool: the cooldown wording (with reset time) survives, not the setup message.
+
+ Regression guard for the openrouter/custom fall-through this fix widens: previously only named
+ providers reached ``pool_cooldown_message``.
+ """
+ from agent import agent_init
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)
+ reset_at = time.time() + 3 * 3600
+ (tmp_path / "auth.json").write_text(
+ json.dumps(
+ {
+ "credential_pool": {
+ "openrouter": [
+ {
+ "provider": "openrouter",
+ "id": "or1",
+ "label": "or1",
+ "auth_type": "api_key",
+ "priority": 0,
+ "source": "manual",
+ "access_token": "sk-test-0000000000",
+ "last_status": STATUS_EXHAUSTED,
+ "last_status_at": time.time(),
+ "last_error_code": 429,
+ "last_error_reset_at": reset_at,
+ }
+ ]
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ (tmp_path / "config.yaml").write_text(
+ "model:\n provider: openrouter\n default: z-ai/glm-5.3\n",
+ encoding="utf-8",
+ )
+
+ _patch_no_routed_client(monkeypatch)
+ monkeypatch.setattr(
+ "agent.credential_pool.load_pool", lambda p: _exhausted_pool_429("openrouter")
+ )
+
+ with pytest.raises(RuntimeError) as excinfo:
+ agent_init._routed_client_kwargs(_agent("openrouter", "z-ai/glm-5.3"), None, 60)
+
+ message = str(excinfo.value)
+ assert "cooling down" in message
+ assert "No LLM provider configured" not in message