Skip to content

The agent that grows with you

fix(auth): dead OAuth logins are reported once and leave rotation; hints point at hermes auth

teknium1d6add1605953
diff --git a/agent/anthropic_credentials.py b/agent/anthropic_credentials.py
index 8b579114b55..dbc54e24d33 100644
--- a/agent/anthropic_credentials.py
+++ b/agent/anthropic_credentials.py
@@ -257,10 +257,47 @@ def is_claude_code_token_valid(creds: Dict[str, Any]) -> bool:
# ── OAuth token endpoint ──
+# OAuth ``error`` codes (RFC 6749 §5.2 + the provider's reuse detection) after which replaying the
+# same refresh token can never succeed; only a fresh login recovers.
+_OAUTH_GRANT_DEAD_CODES = frozenset({"invalid_grant", "invalid_token", "refresh_token_reused"})
+
+
+class AnthropicOAuthError(ValueError):
+ """Token endpoint rejected the request. ``code`` is the OAuth ``error`` field of the response body."""
+
+ def __init__(self, status: int, code: str, description: str, *, what: str) -> None:
+ self.status = status
+ self.code = code
+ detail = f" ({description})" if description else ""
+ super().__init__(f"Anthropic token {what} failed: HTTP {status} {code or 'error'}{detail}")
+
+ @property
+ def relogin_required(self) -> bool:
+ return self.status in (400, 401) and self.code in _OAUTH_GRANT_DEAD_CODES
+
+
+def is_terminal_anthropic_refresh_error(exc: BaseException) -> bool:
+ """True when retrying the same Anthropic refresh token cannot succeed (dead grant)."""
+ return isinstance(exc, AnthropicOAuthError) and exc.relogin_required
+
+
+def _oauth_http_error(exc: Any, *, what: str) -> AnthropicOAuthError:
+ """``urllib.error.HTTPError`` -> structured error carrying the body's OAuth ``error`` code."""
+ code, description = "", ""
+ try:
+ payload = json.loads(exc.read().decode() or "{}")
+ code = str(payload.get("error") or "")
+ description = str(payload.get("error_description") or "")
+ except Exception:
+ pass
+ return AnthropicOAuthError(int(exc.code), code, description, what=what)
+
+
def _post_oauth_token(
data: bytes, *, content_type: str, timeout: int, what: str, user_agent: str = _OAUTH_TOKEN_USER_AGENT
) -> Dict[str, Any]:
"""POST to the token endpoints in order; raise the last error if all fail."""
+ import urllib.error
import urllib.request
last_error = None
for endpoint in _OAUTH_TOKEN_URLS:
@@ -270,6 +307,11 @@ def _post_oauth_token(
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
return json.loads(resp.read().decode())
+ except urllib.error.HTTPError as exc:
+ last_error = _oauth_http_error(exc, what=what)
+ logger.debug("Anthropic token %s failed at %s: %s", what, endpoint, last_error)
+ if last_error.relogin_required:
+ break # a dead grant is dead at every endpoint; do not replay it
except Exception as exc:
last_error = exc
logger.debug("Anthropic token %s failed at %s: %s", what, endpoint, exc)
@@ -331,7 +373,12 @@ def _refresh_oauth_token(creds: Dict[str, Any]) -> Optional[str]:
try:
refreshed = refresh_anthropic_oauth_pure(refresh_token, use_json=False)
except Exception as e:
- logger.debug("Failed to refresh Claude Code token: %s", e)
+ if is_terminal_anthropic_refresh_error(e):
+ logger.warning(
+ "Claude Code OAuth refresh token is terminally invalid (%s); Hermes cannot use this "
+ "login. Run 'hermes auth add anthropic' to give Hermes its own login.", e)
+ else:
+ logger.debug("Failed to refresh Claude Code token: %s", e)
return None
# The POST spent ``refresh_token``; this write is the commit step. On failure, fail closed and
# mark the pre-rotation pair as spent.
diff --git a/agent/credential_pool.py b/agent/credential_pool.py
index 97ac4f26530..ef2d9f4b520 100644
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@ -1439,6 +1439,17 @@ class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin)
if synced.refresh_token != entry.refresh_token:
logger.debug("Anthropic OAuth refresh failed but pool store has newer tokens — adopting")
return self._adopt(synced, **_MARK_OK)
+ from agent.anthropic_credentials import is_terminal_anthropic_refresh_error
+ if is_terminal_anthropic_refresh_error(exc):
+ # A dead grant is not "exhausted": benching it for a TTL replays the dead token every
+ # hour at DEBUG, so the lost login left no trace (#113023). Never touch the external
+ # CLI's credentials file here — only Hermes' own row goes DEAD.
+ logger.warning(
+ "Anthropic OAuth refresh token for %s is terminally invalid (%s); the credential "
+ "leaves rotation. Re-run 'hermes auth add anthropic' to sign in again.",
+ entry.label or entry.id[:8], exc)
+ self._mark_dead_refresh_grant(entry, exc)
+ return None
elif self.provider in _TOKENS_SINGLETON_PROVIDERS:
_, display, _, terminal_fn_name = _TOKENS_SINGLETON_PROVIDERS[self.provider]
synced = self._sync_entry_from_auth_store(entry)
@@ -1457,6 +1468,7 @@ class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin)
"Re-run 'hermes auth add %s' to sign in again.", display, exc, self.provider)
self._clear_terminal_tokens_state(entry, exc)
self._quarantine_sources(entry, {"device_code"})
+ self._mark_dead_refresh_grant(entry, exc)
return None
elif self.provider == "nous":
synced = self._sync_nous_entry_from_auth_store(entry)
@@ -1481,10 +1493,32 @@ class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin)
entry,
{auth_mod.NOUS_DEVICE_CODE_SOURCE, f"manual:{auth_mod.NOUS_DEVICE_CODE_SOURCE}"},
)
+ self._mark_dead_refresh_grant(entry, exc)
return None
self._mark_exhausted(entry, None)
return None
+ def _mark_dead_refresh_grant(self, entry: PooledCredential, exc: Exception) -> None:
+ """Mark a row whose refresh token was terminally rejected DEAD, if the quarantine kept it.
+
+ ``_quarantine_sources`` drops only singleton-seeded rows; an independent ``manual:*`` login
+ (``hermes auth add``) survives, and an unmarked survivor re-enters rotation and re-fires the
+ terminal WARNING on every later refresh attempt. DEAD leaves rotation until a write-side
+ re-auth sync clears it (never via TTL).
+ """
+ with self._lock:
+ current = next((item for item in self._entries if item.id == entry.id), None)
+ if current is None or current.last_status == STATUS_DEAD:
+ return
+ self._adopt(
+ current,
+ last_status=STATUS_DEAD,
+ last_status_at=time.time(),
+ last_error_code=None,
+ last_error_reason=str(getattr(exc, "code", None) or "invalid_grant"),
+ last_error_message=str(exc),
+ )
+
def _clear_terminal_tokens_state(self, entry: PooledCredential, exc: Exception) -> None:
"""Drop the dead Codex/xAI token pair from auth.json unless a peer already rotated it."""
display = _TOKENS_SINGLETON_PROVIDERS[self.provider][1]
diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py
index 491201d18c9..ecd557d3236 100644
--- a/agent/turn_recovery.py
+++ b/agent/turn_recovery.py
@@ -318,7 +318,8 @@ def _print_anthropic_401_diagnostics(agent: Any, key: Any) -> None:
f" • Check ANTHROPIC_TOKEN in {_dhh}/.env for Hermes-managed OAuth/setup tokens",
f" • Check ANTHROPIC_API_KEY in {_dhh}/.env for API keys or legacy token values",
" • For API keys: verify at https://platform.claude.com/settings/keys",
- " • For Claude Code: run 'claude /login' to refresh, then retry",
+ " • Hermes login (OAuth): run 'hermes auth add anthropic' to sign in again, then retry",
+ " • Inspect what Hermes holds: hermes auth list anthropic",
" • Legacy cleanup: hermes config set ANTHROPIC_TOKEN \"\"",
" • Clear stale keys: hermes config set ANTHROPIC_API_KEY \"\"",
)
diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.py
index 0659b061e77..a4c2988abd9 100644
--- a/hermes_cli/runtime_provider.py
+++ b/hermes_cli/runtime_provider.py
@@ -242,8 +242,8 @@ def _maybe_apply_codex_app_server_runtime(*, provider: str, api_mode: str, model
# ── base_url / credential helpers ──────────────────────────────────────────────────────────
_ANTHROPIC_DEFAULT_BASE_URL = "https://api.anthropic.com"
-_NO_ANTHROPIC_CREDENTIALS_MSG = ("No Anthropic credentials found. Set ANTHROPIC_TOKEN or ANTHROPIC_API_KEY, "
- "run 'claude setup-token', or authenticate with 'claude /login'.")
+_NO_ANTHROPIC_CREDENTIALS_MSG = ("No Anthropic credentials found. Run 'hermes auth add anthropic' to sign in, "
+ "or set ANTHROPIC_TOKEN / ANTHROPIC_API_KEY.")
def _runtime(provider: str, api_mode: str, base_url: Any, api_key: Any, **extra: Any) -> Dict[str, Any]:
diff --git a/tests/agent/test_anthropic_dead_grant_hints.py b/tests/agent/test_anthropic_dead_grant_hints.py
new file mode 100644
index 00000000000..bee94a3f165
--- /dev/null
+++ b/tests/agent/test_anthropic_dead_grant_hints.py
@@ -0,0 +1,70 @@
+"""Hermes credential hints and the Anthropic token-endpoint error shape (#113023).
+
+A dead Hermes login must be repaired with ``hermes auth add <provider>``; hints that send the user to
+an external CLI's login command do not touch Hermes' own credentials. The token endpoint's
+``invalid_grant`` body is surfaced as a structured, classifiable error so the pool can quarantine
+instead of benching the dead grant as transient.
+"""
+from __future__ import annotations
+
+import io
+import logging
+import urllib.error
+import urllib.request
+
+import pytest
+
+from agent import anthropic_credentials as ac
+
+
+def test_dead_grant_is_classified_and_not_replayed_at_other_endpoints(monkeypatch):
+ calls: list = []
+
+ def fake_urlopen(req, timeout=None):
+ calls.append(req.full_url)
+ raise urllib.error.HTTPError(req.full_url, 400, "Bad Request", {},
+ io.BytesIO(b'{"error":"invalid_grant","error_description":"revoked"}'))
+
+ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)
+ monkeypatch.setattr(ac, "_OAUTH_TOKEN_URLS", ["https://a.example/oauth/token", "https://b.example/oauth/token"])
+
+ with pytest.raises(ac.AnthropicOAuthError) as info:
+ ac.refresh_anthropic_oauth_pure("sk-ant-ort-dead")
+
+ assert ac.is_terminal_anthropic_refresh_error(info.value)
+ assert info.value.code == "invalid_grant" and "revoked" in str(info.value)
+ assert calls == ["https://a.example/oauth/token"] # a dead grant is not replayed at the fallback endpoint
+ assert not ac.is_terminal_anthropic_refresh_error(TimeoutError("timed out"))
+
+
+def test_claude_code_refresher_warns_on_dead_grant(monkeypatch, caplog):
+ """The auxiliary Claude Code refresher is a sibling path of the pool: same WARNING, same Hermes hint."""
+ monkeypatch.setattr(ac, "read_claude_code_credentials", lambda: {"accessToken": "old", "refreshToken": "rt", "expiresAt": 1})
+
+ def dead(refresh_token, *, use_json=False):
+ raise ac.AnthropicOAuthError(400, "invalid_grant", "", what="refresh")
+
+ monkeypatch.setattr(ac, "refresh_anthropic_oauth_pure", dead)
+ with caplog.at_level(logging.INFO, logger=ac.logger.name):
+ assert ac._refresh_oauth_token({"accessToken": "old", "refreshToken": "rt"}) is None
+ warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
+ assert len(warnings) == 1 and "hermes auth add anthropic" in warnings[0]
+
+
+def test_anthropic_401_troubleshooting_points_at_hermes_auth(capsys):
+ from agent.turn_recovery import _print_anthropic_401_diagnostics
+
+ class _Agent:
+ log_prefix = ""
+
+ _print_anthropic_401_diagnostics(_Agent(), "sk-ant-oat01-xxxxxxxxxxxx")
+ out = capsys.readouterr().out
+ assert "hermes auth add anthropic" in out and "hermes auth list anthropic" in out
+ assert "/login" not in out
+
+
+def test_no_anthropic_credentials_message_points_at_hermes_auth():
+ from hermes_cli.runtime_provider import _NO_ANTHROPIC_CREDENTIALS_MSG
+
+ assert "hermes auth add anthropic" in _NO_ANTHROPIC_CREDENTIALS_MSG
+ assert "/login" not in _NO_ANTHROPIC_CREDENTIALS_MSG
diff --git a/tests/agent/test_credential_pool_terminal_refresh_visibility.py b/tests/agent/test_credential_pool_terminal_refresh_visibility.py
index e2f874c258c..38cf0ae5a24 100644
--- a/tests/agent/test_credential_pool_terminal_refresh_visibility.py
+++ b/tests/agent/test_credential_pool_terminal_refresh_visibility.py
@@ -1,9 +1,11 @@
"""A terminally rejected OAuth refresh token must leave a trace at the default log level.
-The pool quarantines a dead ``openai-codex`` / ``xai-oauth`` / ``nous`` refresh token (clears the
-stored tokens, drops the seeded entry) — for the user this is the moment the login is lost, and a
-debug-only line made it look like "I signed in once and Hermes keeps failing" (#113023). The
-quarantine itself is unchanged; only the visibility is asserted here.
+The pool quarantines a dead ``openai-codex`` / ``xai-oauth`` / ``nous`` / ``anthropic`` refresh
+token — for the user this is the moment the login is lost, and a debug-only line made it look like
+"I signed in once and Hermes keeps failing" (#113023). Two invariants: the WARNING carries the
+``hermes auth add <provider>`` hint, and a row the quarantine does not drop (an independent
+``manual:*`` login) is marked DEAD so it leaves rotation instead of re-firing the WARNING on every
+later refresh attempt.
"""
from __future__ import annotations
@@ -12,8 +14,9 @@ import threading
import pytest
+from agent import anthropic_credentials as ac
from agent import credential_pool as cp
-from agent.credential_pool import CredentialPool, PooledCredential
+from agent.credential_pool import STATUS_DEAD, CredentialPool, PooledCredential
def _pool(provider: str) -> CredentialPool:
@@ -28,9 +31,9 @@ def _pool(provider: str) -> CredentialPool:
return pool
-def _entry(provider: str) -> PooledCredential:
+def _entry(provider: str, source: str = "device_code") -> PooledCredential:
return PooledCredential(id="e1", provider=provider, auth_type="oauth", access_token="dead-access",
- refresh_token="dead-refresh", label="e1", source="device_code", priority=0)
+ refresh_token="dead-refresh", label="e1", source=source, priority=0)
@pytest.mark.parametrize(
@@ -62,3 +65,54 @@ def test_terminal_refresh_quarantine_warns_with_reauth_hint(
assert len(warnings) == 1, [r.getMessage() for r in caplog.records]
assert expected_hint in warnings[0].getMessage()
assert "invalid_grant" in warnings[0].getMessage()
+
+
+def test_anthropic_dead_grant_warns_and_marks_dead(monkeypatch, caplog):
+ """A dead Anthropic grant is not a transient 'exhausted': WARNING with the re-auth hint, row DEAD."""
+ pool = _pool("anthropic")
+ entry = _entry("anthropic", source="manual:hermes_pkce")
+ pool._entries = [entry]
+ monkeypatch.setattr(pool, "_sync_entry_from_pool_store", lambda e: e)
+ monkeypatch.setattr(pool, "_persist", lambda *a, **k: None)
+ exc = ac.AnthropicOAuthError(400, "invalid_grant", "refresh token revoked", what="refresh")
+
+ with caplog.at_level(logging.INFO, logger=cp.logger.name):
+ result = pool._recover_failed_refresh(entry, exc)
+
+ assert result is None
+ row = pool._entries[0]
+ assert row.last_status == STATUS_DEAD and row.last_error_reason == "invalid_grant"
+ warnings = [r for r in caplog.records if r.levelno == logging.WARNING and "terminally invalid" in r.getMessage()]
+ assert len(warnings) == 1 and "hermes auth add anthropic" in warnings[0].getMessage()
+
+
+def test_anthropic_transient_refresh_failure_stays_exhausted(monkeypatch, caplog):
+ """Control: a network-shaped failure is still benched as transient, silently."""
+ pool = _pool("anthropic")
+ entry = _entry("anthropic", source="manual:hermes_pkce")
+ pool._entries = [entry]
+ monkeypatch.setattr(pool, "_sync_entry_from_pool_store", lambda e: e)
+ monkeypatch.setattr(pool, "_persist", lambda *a, **k: None)
+
+ with caplog.at_level(logging.INFO, logger=cp.logger.name):
+ assert pool._recover_failed_refresh(entry, TimeoutError("token endpoint timed out")) is None
+
+ assert pool._entries[0].last_status == cp.STATUS_EXHAUSTED
+ assert not [r for r in caplog.records if r.levelno == logging.WARNING]
+
+
+def test_surviving_manual_entry_is_marked_dead_after_terminal_refresh(monkeypatch):
+ """An independent ``manual:device_code`` login survives the singleton quarantine; it must leave
+ rotation as DEAD rather than sit unmarked and re-fire the WARNING on the next refresh."""
+ pool = _pool("openai-codex")
+ entry = _entry("openai-codex", source="manual:device_code")
+ pool._entries = [entry]
+ monkeypatch.setattr(pool, "_sync_entry_from_auth_store", lambda e: e)
+ monkeypatch.setattr(pool, "_clear_terminal_tokens_state", lambda e, exc: None)
+ monkeypatch.setattr(pool, "_persist", lambda *a, **k: None)
+ monkeypatch.setattr(cp.auth_mod, "_is_terminal_codex_oauth_refresh_error", lambda exc: True)
+
+ assert pool._recover_failed_refresh(entry, RuntimeError("invalid_grant")) is None
+
+ assert [e.id for e in pool._entries] == ["e1"] # manual rows are never dropped by the quarantine
+ assert pool._entries[0].last_status == STATUS_DEAD
diff --git a/website/docs/user-guide/features/credential-pools.md b/website/docs/user-guide/features/credential-pools.md
index f8999acc0b0..c454e120bee 100644
--- a/website/docs/user-guide/features/credential-pools.md
+++ b/website/docs/user-guide/features/credential-pools.md
@@ -183,6 +183,14 @@ one Claude model cools that credential down for *that model only* — the same k
other Claude model, and `ANTHROPIC_API_KEY` / borrowed Claude Code tokens honour the same per-model
cooldown. Billing (`402`, usage-limit) and auth (`401`) failures still bench the whole credential.
+**A dead OAuth login is reported, not benched.** When a refresh token is rejected for good
+(`invalid_grant`, `invalid_token`, `refresh_token_reused` — the token was revoked, or another program
+holding the same login rotated it first), the pool logs one WARNING naming the entry and the repair
+command (`hermes auth add <provider>`), and the credential leaves rotation — marked `dead`, or dropped
+when it only mirrored a token file the pool has just cleared — until you sign in again. This applies to Anthropic, Codex, xAI
+and Nous OAuth logins alike. A dead credential never re-enters rotation on a timer, so a lost login
+shows up once in the log instead of failing quietly every hour.
+
## Custom Endpoint Pools
Custom OpenAI-compatible endpoints (Together.ai, RunPod, local servers) get their own pools, keyed by the endpoint name from the `providers:` dict in config.yaml (or the legacy `custom_providers` list, which is auto-migrated).