The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: prefer owned Anthropic grants and bind auxiliary refresh to request credentials
Tekniumbdf45abd7c4b
diff --git a/agent/anthropic_credentials.py b/agent/anthropic_credentials.pyindex ed3f57f0ac9..14bd6eaab5c 100644--- a/agent/anthropic_credentials.py+++ b/agent/anthropic_credentials.py@@ -1,8 +1,9 @@"""Anthropic credential sources, OAuth flows, and token resolution.``resolve_anthropic_token()`` order: ``ANTHROPIC_TOKEN`` / ``CLAUDE_CODE_OAUTH_TOKEN``,-``ANTHROPIC_API_KEY``, ``~/.claude/.credentials.json`` / macOS Keychain, then the-``auth.json`` credential pool. ``~/.hermes/.anthropic_oauth.json`` (Hermes PKCE) and+``ANTHROPIC_API_KEY``, Hermes-owned OAuth grants in the ``auth.json`` credential+pool, then ``~/.claude/.credentials.json`` / macOS Keychain as a borrowed fallback.+``~/.hermes/.anthropic_oauth.json`` (Hermes PKCE) andthe Claude Code file are *singletons*: ``credential_pool._seed_from_singletons()``re-reads them on every ``load_pool()``, so a failed write here is a failed refresh(``CredentialPersistError``), not a cache miss.@@ -424,7 +425,7 @@ def _prefer_refreshable_claude_code_token(env_token: str, creds: Optional[Dict[sreturn None-def _resolve_anthropic_pool_token() -> Optional[str]:+def _resolve_anthropic_pool_token(*, skip_borrowed: bool = False) -> Optional[str]:"""First available Anthropic OAuth token from credential_pool, read-only: enumerates with ``clear_expired=False,refresh=False`` (never ``select()``) so diagnostic call sites (account_usage, ``hermes models``) never mutateauth.json or hit the network; refresh-on-expiry belongs to the API call path's pool recovery."""@@ -435,6 +436,8 @@ def _resolve_anthropic_pool_token() -> Optional[str]:logger.debug("Failed to read Anthropic credential_pool", exc_info=True)return Nonefor entry in entries:+ if skip_borrowed and entry.source == "claude_code":+ continue# access_token may be an explicit null on a persisted entry; None.strip() would crash the resolver.token = (getattr(entry, "access_token", None) or "").strip()if getattr(entry, "auth_type", None) != AUTH_TYPE_OAUTH or not token:@@ -461,7 +464,8 @@ def resolve_anthropic_token() -> Optional[str]:api_key = _first_env("ANTHROPIC_API_KEY") # an explicit API key must not be shadowed by discovered OAuth credsif api_key:return api_key- return _resolve_claude_code_token_from_credentials(_read_creds()) or _resolve_anthropic_pool_token()+ # The pool's claude_code row mirrors the same externally owned refresh grant.+ return _resolve_anthropic_pool_token(skip_borrowed=True) or _resolve_claude_code_token_from_credentials(_read_creds())def run_oauth_setup_token() -> Optional[str]:diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 51ff1daedd2..fd6ecd4672a 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -3425,13 +3425,19 @@ def _refresh_nous_credentials() -> bool:))-def _refresh_anthropic_credentials() -> bool:- from agent.anthropic_credentials import read_claude_code_credentials, _refresh_oauth_token, resolve_anthropic_token+def _refresh_anthropic_credentials(failed_api_key: str = "") -> bool:+ from agent.anthropic_credentials import read_claude_code_credentials, _refresh_oauth_token+ token = failed_api_key+ if not token:+ return False+ pool = load_pool("anthropic")+ if pool.entry_id_for_api_key(token):+ return pool.try_refresh_matching(api_key_hint=token) is not Nonecreds = read_claude_code_credentials()- token = _refresh_oauth_token(creds) if isinstance(creds, dict) and creds.get("refreshToken") else None- if not str(token or "").strip():- token = resolve_anthropic_token()- return bool(str(token or "").strip())+ # Never spend an ambient login's refresh rotation for another request's key.+ if isinstance(creds, dict) and creds.get("accessToken") == token and creds.get("refreshToken"):+ return bool(_refresh_oauth_token(creds))+ return Falsedef _refresh_xai_oauth_credentials() -> bool:@@ -3455,21 +3461,21 @@ def _refresh_vertex_credentials() -> bool:# Each refresher returns True when a usable credential exists; the caller then evicts cached clients.-_CREDENTIAL_REFRESHERS: Dict[str, Callable[[], bool]] = {+_CREDENTIAL_REFRESHERS: Dict[str, Callable[..., bool]] = {"copilot": _refresh_copilot_credentials, "openai-codex": _refresh_codex_credentials,"nous": _refresh_nous_credentials, "anthropic": _refresh_anthropic_credentials,"xai-oauth": _refresh_xai_oauth_credentials, "vertex": _refresh_vertex_credentials,}-def _refresh_provider_credentials(provider: str) -> bool:+def _refresh_provider_credentials(provider: str, *, failed_api_key: str = "") -> bool:"""Refresh short-lived credentials for OAuth-backed auxiliary providers."""normalized = _normalize_aux_provider(provider)refresher = _CREDENTIAL_REFRESHERS.get(normalized)if refresher is None:return Falsetry:- if not refresher():+ if not (refresher(failed_api_key) if normalized == "anthropic" else refresher()):return False_evict_cached_clients(normalized)return True@@ -3663,11 +3669,13 @@ def _plan_fallback_auth_retry(destination: _FallbackDestination,rebuild: Callable[[str, Any, Optional[str]], Tuple[_FallbackDestination, Dict[str, Any]]], *,async_mode: bool,+ failed_api_key: str = "",) -> Tuple[str, Optional[Tuple[Any, Dict[str, Any], _FallbackDestination]]]:"""After an auth error on a fallback candidate: refresh credentials and rebuild the request.Returns ``(refresh_provider, retry)``; ``retry`` = ``(client, kwargs, destination)`` or None."""fb_provider = _auth_refresh_provider_for_route(destination.provider, destination.base_url)- if fb_provider not in {"auto", "", None} and _refresh_provider_credentials(fb_provider):+ refresh_kwargs = {"failed_api_key": failed_api_key} if fb_provider == "anthropic" else {}+ if fb_provider not in {"auto", "", None} and _refresh_provider_credentials(fb_provider, **refresh_kwargs):retry_client, retry_model = _get_cached_client(fb_provider, destination.model, **({"async_mode": True} if async_mode else {}),base_url=destination.base_url or None, api_mode=destination.api_mode,@@ -3714,7 +3722,8 @@ def _call_fallback_candidate_sync(except Exception as fb_err:if not _is_auth_error(fb_err):raise- fb_provider, retry = _plan_fallback_auth_retry(destination, rebuild, async_mode=False)+ fb_provider, retry = _plan_fallback_auth_retry(+ destination, rebuild, async_mode=False, failed_api_key=getattr(fb_client, "api_key", ""))failed_destination = destinationif retry is not None:failed_destination = retry[2]@@ -3752,7 +3761,8 @@ async def _call_fallback_candidate_async(except Exception as fb_err:if not _is_auth_error(fb_err):raise- fb_provider, retry = _plan_fallback_auth_retry(destination, rebuild, async_mode=True)+ fb_provider, retry = _plan_fallback_auth_retry(+ destination, rebuild, async_mode=True, failed_api_key=getattr(fb_client, "api_key", ""))failed_destination = destinationif retry is not None:failed_destination = retry[2]@@ -6767,7 +6777,9 @@ def _ladder_credential_rungs(auth_refresh_provider = _auth_refresh_provider_for_route(resolved_provider, route.base_info)if (_is_auth_error(first_err) and auth_refresh_provider not in {"auto", "", None}and not client_is_nous):- if _refresh_provider_credentials(auth_refresh_provider):+ refresh_kwargs = ({"failed_api_key": getattr(client, "api_key", "")}+ if auth_refresh_provider == "anthropic" else {})+ if _refresh_provider_credentials(auth_refresh_provider, **refresh_kwargs):if auth_refresh_provider != _normalize_aux_provider(resolved_provider):# The stale client is cached under the route label (e.g. "auto"), not the# concrete backend we refreshed.diff --git a/tests/agent/test_anthropic_owned_routing.py b/tests/agent/test_anthropic_owned_routing.pynew file mode 100644index 00000000000..8d17ac62738--- /dev/null+++ b/tests/agent/test_anthropic_owned_routing.py@@ -0,0 +1,50 @@+"""Owned OAuth must win without rotating an unrelated borrowed grant."""+import json+import time++import pytest++from agent import anthropic_credentials as ac+from agent import auxiliary_client as aux+++def _seed(tmp_path, monkeypatch):+ monkeypatch.setattr(ac.Path, "home", lambda: tmp_path)+ monkeypatch.setattr(ac, "_first_env", lambda *names: "")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ borrowed = tmp_path / ".claude" / ".credentials.json"+ borrowed.parent.mkdir()+ borrowed.write_text(json.dumps({"claudeAiOauth": {+ "accessToken": "borrowed-token", "refreshToken": "borrowed-refresh", "expiresAt": 1,+ }}))+ (tmp_path / "auth.json").write_text(json.dumps({"credential_pool": {"anthropic": [{+ "id": "owned", "source": "manual:hermes_pkce", "auth_type": "oauth",+ "access_token": "owned-token", "refresh_token": "owned-refresh",+ "expires_at": int(time.time()*1000)+3600000, "priority": 0,+ }]}}))+ return borrowed+++def test_owned_pool_precedes_expired_borrowed_login(tmp_path, monkeypatch):+ borrowed = _seed(tmp_path, monkeypatch)+ before = borrowed.read_bytes()+ def forbidden(*args, **kwargs):+ pytest.fail("Borrowed refresh was consumed despite owned grant")+ monkeypatch.setattr(ac, "_refresh_oauth_token", forbidden)+ assert ac.resolve_anthropic_token() == "owned-token"+ assert borrowed.read_bytes() == before+++def test_auxiliary_owned_refresh_does_not_spend_borrowed_rotation(tmp_path, monkeypatch):+ borrowed = _seed(tmp_path, monkeypatch)+ before = borrowed.read_bytes()+ def refresh(refresh_token, **kwargs):+ assert refresh_token == "owned-refresh"+ return {"access_token": "owned-new-token", "refresh_token": "owned-new-refresh",+ "expires_at_ms": int(time.time()*1000)+3600000}+ def forbidden(*args, **kwargs):+ pytest.fail("Auxiliary refreshed an unrelated borrowed grant")+ monkeypatch.setattr(ac, "refresh_anthropic_oauth_pure", refresh)+ monkeypatch.setattr(ac, "_refresh_oauth_token", forbidden)+ assert aux._refresh_anthropic_credentials("owned-token")+ assert borrowed.read_bytes() == beforediff --git a/tests/agent/test_anthropic_spent_rotation_verdict.py b/tests/agent/test_anthropic_spent_rotation_verdict.pyindex 88f73de7713..998b101445b 100644--- a/tests/agent/test_anthropic_spent_rotation_verdict.py+++ b/tests/agent/test_anthropic_spent_rotation_verdict.py@@ -226,7 +226,7 @@ def test_auxiliary_refresh_reports_failure_for_a_lost_commit(monkeypatch.setattr(AA, "refresh_anthropic_oauth_pure", _rotating_refresh)_break_durable_write(monkeypatch)- assert _refresh_provider_credentials("anthropic") is False+ assert _refresh_provider_credentials("anthropic", failed_api_key=_STALE_ACCESS) is Falsedef test_independent_pool_credential_stays_eligible(diff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.pyindex 3e0b30b7d7a..c88f2473633 100644--- a/tests/agent/test_auxiliary_client.py+++ b/tests/agent/test_auxiliary_client.py@@ -2772,7 +2772,7 @@ class TestAuxiliaryAuthRefreshRetry:):from agent.auxiliary_client import _refresh_provider_credentials- assert _refresh_provider_credentials("anthropic") is True+ assert _refresh_provider_credentials("anthropic", failed_api_key="expired-token") is Truemock_refresh_oauth.assert_called_once_with("refresh-token", use_json=False)mock_write.assert_called_once_with("fresh-token", "refresh-token-2", 9999999999999)diff --git a/website/docs/integrations/providers.md b/website/docs/integrations/providers.mdindex ad6d55efb39..293f3c34914 100644--- a/website/docs/integrations/providers.md+++ b/website/docs/integrations/providers.md@@ -145,6 +145,13 @@ If you'd rather not track per-provider plan semantics at all, [Nous Portal](#nouUse Claude models directly through the Anthropic API — no OpenRouter proxy needed. Supports three auth methods:+When no explicit environment credential is selected, Hermes-owned OAuth grants+in the credential pool take precedence over a borrowed Claude Code login. The+borrowed login remains the fallback when no owned OAuth grant is available.+Auxiliary authentication recovery refreshes the credential used by the failed+request, not an unrelated ambient login; rotating a borrowed login can otherwise+invalidate its owner's refresh token.+:::caution Requires Claude Max "extra usage" creditsWhen you authenticate via `hermes model` → Anthropic OAuth (or via `hermes auth add anthropic --type oauth`), Hermes routes as Claude Code against your Anthropic account. **It only works if you're on a Claude Max plan and have purchased extra usage credits.** The base Max plan allowance (the usage included in Claude Code by default) is not consumed by Hermes — only the extra/overage credits you've added on top are. Claude Pro subscribers cannot use this path.