The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): label a callable API key by its credential source, not by "is it callable"
Tekniume7a81e7520f4
diff --git a/agent/agent_init.py b/agent/agent_init.pyindex 2c6c3ab0197..0a573e7ac05 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -729,11 +729,11 @@ def _setup_logging(agent):def _print_key_banner(key, label: str, warn_missing: bool = False) -> None:- """Masked credential line. ``key`` may be a callable Entra ID bearer provider (Azure- Foundry) — never invoke or inspect it. Keys ≤ 12 chars (incl. "dummy-key") are not shown."""- from agent.azure_identity_adapter import is_token_provider- if is_token_provider(key):- print("🔑 Using credentials: Microsoft Entra ID")+ """Masked credential line. A callable ``key`` (Entra ID, Vertex OAuth, key_cmd, ...) is labelled+ by its tagged source and never invoked. Keys ≤ 12 chars (incl. "dummy-key") are not shown."""+ from agent.credential_source import credential_label+ if source_label := credential_label(key):+ print(f"🔑 Using credentials: {source_label}")elif isinstance(key, str) and len(key) > 12:print(f"🔑 Using {label}: {key[:8]}...{key[-4:]}")elif warn_missing:diff --git a/agent/azure_identity_adapter.py b/agent/azure_identity_adapter.pyindex 0200d712dcd..5276856856a 100644--- a/agent/azure_identity_adapter.py+++ b/agent/azure_identity_adapter.py@@ -184,7 +184,8 @@ def build_token_provider(scope: Optional[str] = None, *, config: Optional[EntraIin the worker."""ai = _require_azure_identity()config = _resolve_config(config, scope, exclude_interactive_browser=exclude_interactive_browser)- return ai.get_bearer_token_provider(build_credential(config), config.scope)+ from agent.credential_source import ENTRA_ID, tag_credential_source+ return tag_credential_source(ai.get_bearer_token_provider(build_credential(config), config.scope), ENTRA_ID)def _probe_token(config: EntraIdentityConfig, timeout_seconds: float) -> Optional[dict[str, Any]]:diff --git a/agent/command_token_source.py b/agent/command_token_source.pyindex 604eac0c1d2..1cf4f45a021 100644--- a/agent/command_token_source.py+++ b/agent/command_token_source.py@@ -18,6 +18,8 @@ import threadingimport timefrom typing import Optional+from agent.credential_source import KEY_CMD+logger = logging.getLogger(__name__)# Treat a token as spent slightly before expiry so a request can't be signed with one that dies in@@ -115,6 +117,8 @@ def _mint(command: str, label: str) -> tuple[str, Optional[float]]:class CommandTokenSource:"""Callable returning a bearer token, cached until shortly before expiry."""+ hermes_credential_source = KEY_CMD # display label source; read without calling (agent.credential_source)+def __init__(self, command: str, label: str = "custom") -> None:self._command = commandself._label = label or "custom"diff --git a/agent/credential_source.py b/agent/credential_source.pynew file mode 100644index 00000000000..d63ba26c3a5--- /dev/null+++ b/agent/credential_source.py@@ -0,0 +1,57 @@+"""Name a callable API key's credential source without calling it.++A callable ``api_key`` mints a bearer on first use (Entra ID, Vertex OAuth, a custom provider's+``key_cmd``, MiniMax OAuth). Display paths (``/config``, the agent's key banner) must say which+kind it is, but calling it would mint a token just to mask it. Each builder tags the callable it+returns with a source; display reads the tag through one source-to-label table. An untagged+callable gets a neutral label, never another vendor's name.+"""++from __future__ import annotations++from typing import Any, Callable, Optional, TypeVar++ENTRA_ID = "entra-id"+VERTEX_OAUTH = "vertex-oauth"+KEY_CMD = "key-cmd"+MINIMAX_OAUTH = "minimax-oauth"++# Attribute read with getattr only: reading it never invokes the callable.+SOURCE_ATTR = "hermes_credential_source"++# Credential source -> i18n key. Both display surfaces resolve labels here.+SOURCE_LABEL_KEYS = {+ ENTRA_ID: "cli.config.microsoft_entra_id",+ VERTEX_OAUTH: "cli.config.google_vertex_oauth",+ KEY_CMD: "cli.config.key_cmd_token",+ MINIMAX_OAUTH: "cli.config.minimax_oauth",+}+UNKNOWN_LABEL_KEY = "cli.config.token_provider"++_F = TypeVar("_F", bound=Callable[..., Any])+++def tag_credential_source(provider: _F, source: str) -> _F:+ """Record *source* on *provider* and return it (a no-op for objects that refuse attributes)."""+ try:+ setattr(provider, SOURCE_ATTR, source)+ except (AttributeError, TypeError):+ pass+ return provider+++def credential_source(key: Any) -> Optional[str]:+ """The source tag of a callable key, or None (string keys and untagged callables)."""+ if isinstance(key, str) or not callable(key):+ return None+ source = getattr(key, SOURCE_ATTR, None)+ return source if isinstance(source, str) else None+++def credential_label(key: Any) -> Optional[str]:+ """Translated label for a callable key's source (neutral when untagged); None for a non-callable."""+ if isinstance(key, str) or not callable(key):+ return None+ from agent.i18n import t++ return t(SOURCE_LABEL_KEYS.get(credential_source(key) or "", UNKNOWN_LABEL_KEY))diff --git a/agent/vertex_adapter.py b/agent/vertex_adapter.pyindex 26c4851860c..212e498bbfa 100644--- a/agent/vertex_adapter.py+++ b/agent/vertex_adapter.py@@ -13,6 +13,7 @@ import osimport timefrom typing import Any, Optional, Tuple+from agent.credential_source import VERTEX_OAUTH, tag_credential_sourcefrom agent.secret_scope import get_secret as _get_secret, is_multiplex_activetry:@@ -232,6 +233,9 @@ def vertex_access_token() -> str:return token+tag_credential_source(vertex_access_token, VERTEX_OAUTH)++def has_vertex_credentials() -> bool:"""Fast check (no network): a resolvable SA JSON path, or an explicit project ID (implies ADC)."""return bool(_resolve_credentials_path(None) or _resolve_project_override())diff --git a/cli.py b/cli.pyindex 37581631e2f..61b31129e64 100644--- a/cli.py+++ b/cli.py@@ -1049,20 +1049,17 @@ class HermesCLI(CLIInitMixin, CLITuiRuntimeMixin, CLIProcessNotificationsMixin,config_path = Path(__file__).parent / 'cli-config.yaml'config_status = _t("cli.config.loaded") if config_path.exists() else _t("cli.config.not_found")- # ``api_key`` may be a callable (Entra ID bearer provider): never invoke it. Prefer the- # LIVE agent's key: the constructor seeds self.api_key from env before provider- # resolution, so on non-OpenAI providers it can be another vendor's key.- from agent.azure_identity_adapter import is_token_provider+ # ``api_key`` may be a callable bearer provider (Entra ID, Vertex OAuth, key_cmd, ...):+ # label it by its tagged source and never invoke it (that would mint a token just to mask+ # it). Prefer the LIVE agent's key: the constructor seeds self.api_key from env before+ # provider resolution, so on non-OpenAI providers it can be another vendor's key.+ from agent.credential_source import credential_labeldisplay_key = self.api_keyif self.agent is not None and getattr(self.agent, "api_key", None):display_key = self.agent.api_key- if is_token_provider(display_key) and getattr(display_key, "__module__", "") == "agent.vertex_adapter":- # Vertex's callable mints a Google OAuth token on first use (the gateway mints its own- # for the turn); never mint one just to mask it here.- api_key_display = _t("cli.config.google_vertex_oauth")- elif is_token_provider(display_key):- api_key_display = _t("cli.config.microsoft_entra_id")+ if label := credential_label(display_key):+ api_key_display = labelelif isinstance(display_key, str) and len(display_key) > 12:api_key_display = f"{display_key[:8]}...{display_key[-4:]}"else:diff --git a/hermes_cli/auth_minimax.py b/hermes_cli/auth_minimax.pyindex ca7cbf185c8..085ac1270f7 100644--- a/hermes_cli/auth_minimax.py+++ b/hermes_cli/auth_minimax.py@@ -331,7 +331,8 @@ def build_minimax_oauth_token_provider() -> Callable[[], str]:raise _minimax_err("MiniMax OAuth state has no access_token after refresh.", "no_access_token", relogin=True)return token- return _provide+ from agent.credential_source import MINIMAX_OAUTH, tag_credential_source+ return tag_credential_source(_provide, MINIMAX_OAUTH)def resolve_minimax_oauth_runtime_credentials(diff --git a/locales/af.yaml b/locales/af.yamlindex 809d0c9d1b6..d341d51cb08 100644--- a/locales/af.yaml+++ b/locales/af.yaml@@ -3113,6 +3113,9 @@ cli:not_found: "(nie gevind nie)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "Nie gestel nie!"value_not_set: "nie gestel nie"section_model: "Model"diff --git a/locales/ar.yaml b/locales/ar.yamlindex 76476cf4d0f..a039eb9f82a 100644--- a/locales/ar.yaml+++ b/locales/ar.yaml@@ -3113,6 +3113,9 @@ cli:not_found: "(غير موجود)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "غير معيّن!"value_not_set: "غير معيّن"section_model: "النموذج"diff --git a/locales/de.yaml b/locales/de.yamlindex 6d92356e98f..6bebe47ccd8 100644--- a/locales/de.yaml+++ b/locales/de.yaml@@ -3113,6 +3113,9 @@ cli:not_found: "(nicht gefunden)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "Nicht gesetzt!"value_not_set: "nicht gesetzt"section_model: "Modell"diff --git a/locales/en.yaml b/locales/en.yamlindex 066d35d9a83..24933d5b0ef 100644--- a/locales/en.yaml+++ b/locales/en.yaml@@ -3213,6 +3213,9 @@ cli:not_found: "(not found)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "Not set!"value_not_set: "not set"section_model: "Model"diff --git a/locales/es.yaml b/locales/es.yamlindex e686f2c1ef9..8ec065cc0dc 100644--- a/locales/es.yaml+++ b/locales/es.yaml@@ -3113,6 +3113,9 @@ cli:not_found: "(no encontrado)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "¡Sin definir!"value_not_set: "sin definir"section_model: "Modelo"diff --git a/locales/fr.yaml b/locales/fr.yamlindex 8513846efe2..73dd83005ba 100644--- a/locales/fr.yaml+++ b/locales/fr.yaml@@ -3420,6 +3420,9 @@ cli:not_found: "(introuvable)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "Non définie !"value_not_set: "non défini"section_model: "Modèle"diff --git a/locales/ga.yaml b/locales/ga.yamlindex 8967ab6669a..1e5291e5a7b 100644--- a/locales/ga.yaml+++ b/locales/ga.yaml@@ -3113,6 +3113,9 @@ cli:not_found: "(gan aimsiú)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "Gan socrú!"value_not_set: "gan socrú"section_model: "Samhail"diff --git a/locales/hu.yaml b/locales/hu.yamlindex 4543fcf0573..112e9fefcc6 100644--- a/locales/hu.yaml+++ b/locales/hu.yaml@@ -3130,6 +3130,9 @@ cli:not_found: "(nem található)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "Nincs beállítva!"value_not_set: "nincs beállítva"section_model: "Modell"diff --git a/locales/it.yaml b/locales/it.yamlindex 1d452e2f4f1..599d1806933 100644--- a/locales/it.yaml+++ b/locales/it.yaml@@ -3113,6 +3113,9 @@ cli:not_found: "(non trovato)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "Non impostata!"value_not_set: "non impostato"section_model: "Modello"diff --git a/locales/ja.yaml b/locales/ja.yamlindex f532c41654d..3842ae2e594 100644--- a/locales/ja.yaml+++ b/locales/ja.yaml@@ -3113,6 +3113,9 @@ cli:not_found: "(見つかりません)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "未設定!"value_not_set: "未設定"section_model: "モデル"diff --git a/locales/ko.yaml b/locales/ko.yamlindex 7d224a7fe03..75a774d7fc4 100644--- a/locales/ko.yaml+++ b/locales/ko.yaml@@ -3113,6 +3113,9 @@ cli:not_found: "(찾을 수 없음)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "설정되지 않음!"value_not_set: "설정되지 않음"section_model: "모델"diff --git a/locales/pt.yaml b/locales/pt.yamlindex 6478c8ed017..29f29addb18 100644--- a/locales/pt.yaml+++ b/locales/pt.yaml@@ -3113,6 +3113,9 @@ cli:not_found: "(não encontrado)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "Não definida!"value_not_set: "não definido"section_model: "Modelo"diff --git a/locales/ru.yaml b/locales/ru.yamlindex e62a458996f..af83a2770ef 100644--- a/locales/ru.yaml+++ b/locales/ru.yaml@@ -3113,6 +3113,9 @@ cli:not_found: "(не найдено)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "Не задан!"value_not_set: "не задано"section_model: "Модель"diff --git a/locales/tr.yaml b/locales/tr.yamlindex b7b1becfba1..c99b4e7e5c3 100644--- a/locales/tr.yaml+++ b/locales/tr.yaml@@ -3113,6 +3113,9 @@ cli:not_found: "(bulunamadı)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "Ayarlanmamış!"value_not_set: "ayarlanmamış"section_model: "Model"diff --git a/locales/uk.yaml b/locales/uk.yamlindex 4802789cbc4..f9e45452656 100644--- a/locales/uk.yaml+++ b/locales/uk.yaml@@ -3113,6 +3113,9 @@ cli:not_found: "(не знайдено)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "Не задано!"value_not_set: "не задано"section_model: "Модель"diff --git a/locales/zh-hant.yaml b/locales/zh-hant.yamlindex e944af93539..a559c1abc31 100644--- a/locales/zh-hant.yaml+++ b/locales/zh-hant.yaml@@ -3113,6 +3113,9 @@ cli:not_found: "(找不到)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "未設定!"value_not_set: "未設定"section_model: "模型"diff --git a/locales/zh.yaml b/locales/zh.yamlindex bc7faca7b2b..78d91b242a2 100644--- a/locales/zh.yaml+++ b/locales/zh.yaml@@ -3113,6 +3113,9 @@ cli:not_found: "(未找到)"microsoft_entra_id: "Microsoft Entra ID"google_vertex_oauth: "Google OAuth (Vertex AI)"+ key_cmd_token: "key_cmd token (command)"+ minimax_oauth: "MiniMax OAuth"+ token_provider: "Token provider"api_key_not_set: "未设置!"value_not_set: "未设置"section_model: "模型"diff --git a/tests/agent/test_credential_source_labels.py b/tests/agent/test_credential_source_labels.pynew file mode 100644index 00000000000..318a947cb33--- /dev/null+++ b/tests/agent/test_credential_source_labels.py@@ -0,0 +1,118 @@+"""A callable API key is labelled by its credential source, never by "is it callable".++``/config`` (``cli.py`` ``show_config``) and the agent's key banner (``_print_key_banner``) printed+"Microsoft Entra ID" for every callable key, so a custom provider's ``key_cmd`` bearer or MiniMax+OAuth read as Azure. Each builder now tags its callable with a source, and both surfaces resolve the+label through one table in ``agent.credential_source``. An untagged callable gets a neutral label.+No test may let the display path call the callable: that would mint a token just to mask it.+"""++from __future__ import annotations++import sys+from datetime import datetime+from types import SimpleNamespace++import pytest++from agent.i18n import t+++def _never_called() -> str:+ raise AssertionError("a display path invoked the credential callable")+++def _config_api_line(capsys, api_key) -> str:+ from cli import HermesCLI++ cli = HermesCLI.__new__(HermesCLI)+ cli.api_key, cli.agent = api_key, None+ cli.model, cli.base_url = "m", "https://example.invalid/v1"+ cli.max_turns, cli.enabled_toolsets, cli.verbose = 10, [], False+ cli.session_start = datetime(2031, 1, 1)+ cli.show_config()+ out = capsys.readouterr().out+ return next(line for line in out.splitlines() if t("cli.config.label_api_key") in line)+++def _banner(capsys, key) -> str:+ from agent.agent_init import _print_key_banner++ _print_key_banner(key, "API key")+ return capsys.readouterr().out+++def _entra_provider(monkeypatch):+ from agent import azure_identity_adapter as adapter++ fake = SimpleNamespace(get_bearer_token_provider=lambda credential, scope: (lambda: _never_called()))+ monkeypatch.setitem(sys.modules, "azure", SimpleNamespace(identity=fake))+ monkeypatch.setitem(sys.modules, "azure.identity", fake)+ monkeypatch.setattr(adapter, "_require_azure_identity", lambda: fake)+ monkeypatch.setattr(adapter, "build_credential", lambda config: object())+ return adapter.build_token_provider()+++def _vertex_provider(monkeypatch):+ import agent.vertex_adapter as va++ monkeypatch.setattr(va, "get_vertex_credentials", lambda *_a, **_k: _never_called())+ return va.vertex_access_token+++def _key_cmd_provider(monkeypatch):+ import agent.command_token_source as cts++ monkeypatch.setattr(cts, "_mint", lambda *_a, **_k: _never_called())+ return cts.build_command_token_provider("print-token", "corp")+++def _minimax_provider(monkeypatch):+ import hermes_cli.auth_minimax as mm++ monkeypatch.setattr(mm, "_minimax_fresh_state", lambda: _never_called())+ return mm.build_minimax_oauth_token_provider()+++def _untagged_provider(monkeypatch):+ def some_plugin_token_provider() -> str:+ return _never_called()++ return some_plugin_token_provider+++CASES = [+ pytest.param(_entra_provider, "cli.config.microsoft_entra_id", id="entra"),+ pytest.param(_vertex_provider, "cli.config.google_vertex_oauth", id="vertex"),+ pytest.param(_key_cmd_provider, "cli.config.key_cmd_token", id="key_cmd"),+ pytest.param(_minimax_provider, "cli.config.minimax_oauth", id="minimax"),+ pytest.param(_untagged_provider, "cli.config.token_provider", id="unknown"),+]++[email protected](("build", "label_key"), CASES)+def test_config_labels_a_callable_key_by_its_source(capsys, monkeypatch, build, label_key):+ line = _config_api_line(capsys, build(monkeypatch))+ assert t(label_key) in line, line+ if label_key != "cli.config.microsoft_entra_id":+ assert t("cli.config.microsoft_entra_id") not in line, line++[email protected](("build", "label_key"), CASES)+def test_key_banner_labels_a_callable_key_by_its_source(capsys, monkeypatch, build, label_key):+ out = _banner(capsys, build(monkeypatch))+ assert t(label_key) in out, out+ if label_key != "cli.config.microsoft_entra_id":+ assert "Microsoft Entra ID" not in out, out+++def test_both_surfaces_share_one_source_table():+ from agent import credential_source as cs++ labels = {cs.credential_label(cs.tag_credential_source(lambda: "", s)) for s in cs.SOURCE_LABEL_KEYS}+ assert labels == {t(k) for k in cs.SOURCE_LABEL_KEYS.values()}+ assert t(cs.UNKNOWN_LABEL_KEY) not in labels, "the neutral label must not collide with a vendor label"+++def test_string_keys_keep_the_masked_form(capsys):+ assert _banner(capsys, "sk-live-abcdefghijklmnop3456").strip() == "🔑 Using API key: sk-live-...3456"diff --git a/tests/hermes_cli/test_cli_config_vertex_label.py b/tests/hermes_cli/test_cli_config_vertex_label.pyindex c94e2bfc126..78ef5416069 100644--- a/tests/hermes_cli/test_cli_config_vertex_label.py+++ b/tests/hermes_cli/test_cli_config_vertex_label.py@@ -39,9 +39,13 @@ def test_config_labels_vertex_callable_as_google_oauth_without_minting(capsys, massert mints == [], "/config minted a Vertex token just to display it"-def test_config_keeps_entra_label_for_other_token_providers(capsys):+def test_config_keeps_entra_label_for_entra_token_providers(capsys):+ from agent.credential_source import ENTRA_ID, tag_credential_source+def entra_bearer_provider() -> str:raise AssertionError("never invoked")- out = _config_text(capsys, entra_bearer_provider)+ # Only a provider tagged as Entra gets the Entra label; an untagged callable gets the neutral+ # label (tests/agent/test_credential_source_labels.py).+ out = _config_text(capsys, tag_credential_source(entra_bearer_provider, ENTRA_ID))assert t("cli.config.microsoft_entra_id") in out, out