The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: prefer explicit anthropic api key
kshitij0845232d7646
diff --git a/agent/anthropic_adapter.py b/agent/anthropic_adapter.pyindex 9ba37bd39b3..70a95993231 100644--- a/agent/anthropic_adapter.py+++ b/agent/anthropic_adapter.py@@ -1360,19 +1360,27 @@ def resolve_anthropic_token() -> Optional[str]:Priority:1. ANTHROPIC_TOKEN env var (OAuth/setup token saved by Hermes)2. CLAUDE_CODE_OAUTH_TOKEN env var- 3. Claude Code credentials (~/.claude.json or ~/.claude/.credentials.json)+ 3. ANTHROPIC_API_KEY env var (explicit regular API key)+ 4. Claude Code credentials (~/.claude.json or ~/.claude/.credentials.json)— with automatic refresh if expired and a refresh token is available- 4. Anthropic credential_pool OAuth entry (~/.hermes/auth.json)- 5. ANTHROPIC_API_KEY env var (regular API key, or legacy fallback)+ 5. Anthropic credential_pool OAuth entry (~/.hermes/auth.json)Returns the token string or None."""- creds = read_claude_code_credentials()+ creds: Optional[Dict[str, Any]] = None+ creds_loaded = False++ def _read_creds() -> Optional[Dict[str, Any]]:+ nonlocal creds, creds_loaded+ if not creds_loaded:+ creds = read_claude_code_credentials()+ creds_loaded = True+ return creds# 1. Hermes-managed OAuth/setup token env vartoken = _getenv("ANTHROPIC_TOKEN").strip()if token:- preferred = _prefer_refreshable_claude_code_token(token, creds)+ preferred = _prefer_refreshable_claude_code_token(token, _read_creds())if preferred:return preferredreturn token@@ -1380,27 +1388,27 @@ def resolve_anthropic_token() -> Optional[str]:# 2. CLAUDE_CODE_OAUTH_TOKEN (used by Claude Code for setup-tokens)cc_token = _getenv("CLAUDE_CODE_OAUTH_TOKEN").strip()if cc_token:- preferred = _prefer_refreshable_claude_code_token(cc_token, creds)+ preferred = _prefer_refreshable_claude_code_token(cc_token, _read_creds())if preferred:return preferredreturn cc_token- # 3. Claude Code credential file- resolved_claude_token = _resolve_claude_code_token_from_credentials(creds)+ # 3. Regular API key. An explicit user-configured key must not be shadowed+ # by auto-discovered Claude Code or credential-pool OAuth credentials.+ api_key = _getenv("ANTHROPIC_API_KEY").strip()+ if api_key:+ return api_key++ # 4. Claude Code credential file+ resolved_claude_token = _resolve_claude_code_token_from_credentials(_read_creds())if resolved_claude_token:return resolved_claude_token- # 4. Hermes credential_pool OAuth entry.+ # 5. Hermes credential_pool OAuth entry.resolved_pool_token = _resolve_anthropic_pool_token()if resolved_pool_token:return resolved_pool_token- # 5. Regular API key, or a legacy OAuth token saved in ANTHROPIC_API_KEY.- # This remains as a compatibility fallback for pre-migration Hermes configs.- api_key = _getenv("ANTHROPIC_API_KEY").strip()- if api_key:- return api_key-return Nonediff --git a/tests/agent/test_anthropic_adapter.py b/tests/agent/test_anthropic_adapter.pyindex cad2d371ab3..0b8a7b08bb7 100644--- a/tests/agent/test_anthropic_adapter.py+++ b/tests/agent/test_anthropic_adapter.py@@ -182,6 +182,9 @@ class TestIsClaudeCodeTokenValid:class TestResolveAnthropicToken:+ def _assert_not_called(*_args, **_kwargs):+ raise AssertionError("should not be called when API key is present")+def test_prefers_oauth_token_over_api_key(self, monkeypatch, tmp_path):monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-api03-mykey")monkeypatch.setenv("ANTHROPIC_TOKEN", "sk-ant-oat01-mytoken")@@ -199,14 +202,41 @@ class TestResolveAnthropicToken:assert resolve_anthropic_token() is Nonedef test_falls_back_to_api_key_when_no_oauth_sources_exist(self, monkeypatch, tmp_path):- monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-api03-mykey")+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant...ykey")monkeypatch.delenv("ANTHROPIC_TOKEN", raising=False)monkeypatch.delenv("CLAUDE_CODE_OAUTH_TOKEN", raising=False)monkeypatch.setattr("agent.anthropic_adapter.Path.home", lambda: tmp_path)- assert resolve_anthropic_token() == "sk-ant-api03-mykey"+ assert resolve_anthropic_token() == "sk-ant...ykey"+ def test_api_key_wins_over_auto_discovered_claude_code_credentials(+ self, monkeypatch, tmp_path+ ):+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant...ykey")+ monkeypatch.delenv("ANTHROPIC_TOKEN", raising=False)+ monkeypatch.delenv("CLAUDE_CODE_OAUTH_TOKEN", raising=False)+ cred_file = tmp_path / ".claude" / ".credentials.json"+ cred_file.parent.mkdir(parents=True)+ cred_file.write_text(json.dumps({+ "claudeAiOauth": {+ "accessToken": "cc-auto-token",+ "refreshToken": "refresh",+ "expiresAt": int(time.time() * 1000) + 3600_000,+ }+ }))+ monkeypatch.setattr("agent.anthropic_adapter.Path.home", lambda: tmp_path)+ assert resolve_anthropic_token() == "sk-ant...ykey"+ def test_api_key_path_does_not_read_auto_discovered_credentials(self, monkeypatch):+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant...ykey")+ monkeypatch.delenv("ANTHROPIC_TOKEN", raising=False)+ monkeypatch.delenv("CLAUDE_CODE_OAUTH_TOKEN", raising=False)+ monkeypatch.setattr(+ "agent.anthropic_adapter.read_claude_code_credentials",+ self._assert_not_called,+ )++ assert resolve_anthropic_token() == "sk-ant...ykey"def test_falls_back_to_claude_code_credentials(self, monkeypatch, tmp_path):monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)@@ -229,7 +259,7 @@ class TestResolveAnthropicToken:monkeypatch.delenv("ANTHROPIC_TOKEN", raising=False)monkeypatch.delenv("CLAUDE_CODE_OAUTH_TOKEN", raising=False)monkeypatch.setattr("agent.anthropic_adapter.Path.home", lambda: tmp_path)- # Isolate source #4 (credential_pool): ensure source #3 (Claude Code+ # Isolate source #5 (credential_pool): ensure source #4 (Claude Code# creds, incl. the macOS keychain read which Path.home does not cover)# returns nothing, mirroring a Hermes-PKCE-only setup.monkeypatch.setattr("agent.anthropic_adapter.read_claude_code_credentials", lambda: None)@@ -245,32 +275,27 @@ class TestResolveAnthropicToken:assert resolve_anthropic_token() == "pool-oauth-token"- def test_prefers_anthropic_credential_pool_oauth_over_api_key(self, monkeypatch, tmp_path):+ def test_api_key_wins_over_anthropic_credential_pool_oauth(self, monkeypatch, tmp_path):monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant...ykey")monkeypatch.delenv("ANTHROPIC_TOKEN", raising=False)monkeypatch.delenv("CLAUDE_CODE_OAUTH_TOKEN", raising=False)monkeypatch.setattr("agent.anthropic_adapter.Path.home", lambda: tmp_path)- # Pool (source #4) must win over ANTHROPIC_API_KEY (source #5); also- # isolate source #3 so a machine-local Claude Code creds / keychain- # entry can't short-circuit before the pool.- monkeypatch.setattr("agent.anthropic_adapter.read_claude_code_credentials", lambda: None)-- pool_entry = SimpleNamespace(- auth_type="oauth",- access_token="pool-oauth-token",+ monkeypatch.setattr(+ "agent.anthropic_adapter.read_claude_code_credentials",+ self._assert_not_called,)- pool = SimpleNamespace(- _available_entries=lambda **_kwargs: ([pool_entry], []),+ monkeypatch.setattr(+ "agent.credential_pool.load_pool",+ self._assert_not_called,)- monkeypatch.setattr("agent.credential_pool.load_pool", lambda provider: pool)- assert resolve_anthropic_token() == "pool-oauth-token"+ assert resolve_anthropic_token() == "sk-ant...ykey"def test_pool_entry_with_null_access_token_does_not_crash(self, monkeypatch, tmp_path):"""A persisted OAuth entry with access_token=None must not crash theresolver (None.strip() would escape the helper's try/excepts and takedown the whole resolver incl. the ANTHROPIC_API_KEY fallback). It should- be skipped and the api-key fallback (source #5) should win."""+ be skipped and the api-key fallback (source #3) should win."""monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant...ykey")monkeypatch.delenv("ANTHROPIC_TOKEN", raising=False)monkeypatch.delenv("CLAUDE_CODE_OAUTH_TOKEN", raising=False)@@ -283,7 +308,7 @@ class TestResolveAnthropicToken:)monkeypatch.setattr("agent.credential_pool.load_pool", lambda provider: pool)- # Must fall through to source #5 (ANTHROPIC_API_KEY), not raise.+ # Must fall through to source #3 (ANTHROPIC_API_KEY), not raise.assert resolve_anthropic_token() == "sk-ant...ykey"def test_pool_api_key_only_entry_is_not_returned_as_token(self, monkeypatch, tmp_path):