Skip to content

The agent that grows with you

fix(auth): preserve configured provider compatibility

fangliquanflq3a7c09458227
diff --git a/hermes_cli/auth_commands.py b/hermes_cli/auth_commands.py
index b06c9a6eb19..77c867d8a76 100644
--- a/hermes_cli/auth_commands.py
+++ b/hermes_cli/auth_commands.py
@@ -38,27 +38,53 @@ from hermes_cli.secret_prompt import masked_secret_prompt
_OAUTH_CAPABLE_PROVIDERS = {"anthropic", "nous", "openai-codex", "xai-oauth", "qwen-oauth", "minimax-oauth"}
-def _get_custom_provider_names() -> list:
- """Return list of (display_name, pool_key, provider_key) tuples."""
+def _get_custom_provider_entries() -> list[dict]:
+ """Return configured provider entries with legacy and canonical pool IDs."""
try:
from hermes_cli.config import get_compatible_custom_providers, load_config
config = load_config()
except Exception:
return []
- result = []
+ result: list[dict] = []
for entry in get_compatible_custom_providers(config):
if not isinstance(entry, dict):
continue
name = entry.get("name")
if not isinstance(name, str) or not name.strip():
continue
- pool_key = f"{CUSTOM_POOL_PREFIX}{_normalize_custom_pool_name(name)}"
- provider_key = str(entry.get("provider_key", "") or "").strip()
- result.append((name.strip(), pool_key, provider_key))
+ normalized = dict(entry)
+ normalized["name"] = name.strip()
+ normalized["pool_key"] = (
+ f"{CUSTOM_POOL_PREFIX}{_normalize_custom_pool_name(name)}"
+ )
+ normalized["provider_key"] = str(
+ entry.get("provider_key", "") or ""
+ ).strip()
+ result.append(normalized)
return result
+def _get_custom_provider_names() -> list:
+ """Return list of (display_name, pool_key, provider_key) tuples."""
+ return [
+ (entry["name"], entry["pool_key"], entry["provider_key"])
+ for entry in _get_custom_provider_entries()
+ ]
+
+
+def _configured_provider_entry(provider: str) -> dict | None:
+ """Resolve a canonical ``providers.<key>`` entry."""
+ normalized = (provider or "").strip().lower()
+ if not normalized or normalized.startswith(CUSTOM_POOL_PREFIX):
+ return None
+ for entry in _get_custom_provider_entries():
+ provider_key = str(entry.get("provider_key") or "").strip().lower()
+ if provider_key and provider_key == normalized:
+ return entry
+ return None
+
+
def _resolve_custom_provider_input(raw: str) -> str | None:
"""Resolve legacy names and keyed providers to their credential-pool ID."""
normalized = (raw or "").strip().lower().replace(" ", "-")
@@ -67,7 +93,10 @@ def _resolve_custom_provider_input(raw: str) -> str | None:
# Direct match on 'custom:name' format
if normalized.startswith(CUSTOM_POOL_PREFIX):
return normalized
- for display_name, pool_key, provider_key in _get_custom_provider_names():
+ for entry in _get_custom_provider_entries():
+ display_name = entry["name"]
+ pool_key = entry["pool_key"]
+ provider_key = entry["provider_key"]
# ``providers:`` entries already have a durable runtime slug. Keep
# credentials under that slug instead of leaking the legacy
# ``custom:`` compatibility identity into auth.json and discovery.
@@ -92,9 +121,8 @@ def _normalize_provider(provider: str) -> str:
return normalized
-def _migrate_legacy_custom_pool_key(provider: str) -> None:
+def _migrate_legacy_custom_pool_key(provider: str, legacy_key: str) -> None:
"""Move a keyed provider's old ``custom:`` pool into its runtime slug."""
- legacy_key = f"{CUSTOM_POOL_PREFIX}{provider}"
with auth_mod._auth_store_lock():
auth_store = auth_mod._load_auth_store()
credential_pool = auth_store.get("credential_pool")
@@ -141,10 +169,22 @@ def _provider_base_url(provider: str) -> str:
if cp_config:
return str(cp_config.get("base_url") or "").strip()
return ""
+ configured = _configured_provider_entry(provider)
+ if configured is not None:
+ return str(configured.get("base_url") or "").strip()
pconfig = PROVIDER_REGISTRY.get(provider)
return pconfig.inference_base_url if pconfig else ""
+def _is_known_provider(provider: str, configured_provider: dict | None) -> bool:
+ return (
+ provider in PROVIDER_REGISTRY
+ or provider == "openrouter"
+ or provider.startswith(CUSTOM_POOL_PREFIX)
+ or configured_provider is not None
+ )
+
+
def _oauth_default_label(provider: str, count: int) -> str:
return f"{provider}-oauth-{count}"
@@ -207,16 +247,11 @@ def _format_exhausted_status(entry) -> str:
def auth_add_command(args) -> None:
provider = _normalize_provider(getattr(args, "provider", ""))
- configured_provider = _resolve_custom_provider_input(provider) == provider
- if (
- provider not in PROVIDER_REGISTRY
- and provider != "openrouter"
- and not provider.startswith(CUSTOM_POOL_PREFIX)
- and not configured_provider
- ):
+ configured_provider = _configured_provider_entry(provider)
+ if not _is_known_provider(provider, configured_provider):
raise SystemExit(f"Unknown provider: {provider}")
- if configured_provider and not provider.startswith(CUSTOM_POOL_PREFIX):
- _migrate_legacy_custom_pool_key(provider)
+ if configured_provider is not None:
+ _migrate_legacy_custom_pool_key(provider, configured_provider["pool_key"])
requested_type = str(getattr(args, "auth_type", "") or "").strip().lower()
if requested_type in {AUTH_TYPE_API_KEY, "api-key"}:
@@ -491,10 +526,21 @@ def auth_list_command(args) -> None:
if provider_filter:
providers = [provider_filter]
else:
+ credential_pool = auth_mod._load_auth_store().get("credential_pool")
+ persisted_providers = (
+ credential_pool.keys() if isinstance(credential_pool, dict) else ()
+ )
+ configured_providers = (
+ entry["provider_key"]
+ for entry in _get_custom_provider_entries()
+ if entry["provider_key"]
+ )
providers = sorted({
*PROVIDER_REGISTRY.keys(),
"openrouter",
*list_custom_pool_providers(),
+ *configured_providers,
+ *persisted_providers,
})
for provider in providers:
pool = load_pool(provider)
@@ -723,7 +769,8 @@ def _pick_provider(prompt: str = "Provider") -> str:
def _interactive_add() -> None:
provider = _pick_provider("Provider to add credential for")
- if provider not in PROVIDER_REGISTRY and provider != "openrouter" and not provider.startswith(CUSTOM_POOL_PREFIX):
+ configured_provider = _configured_provider_entry(provider)
+ if not _is_known_provider(provider, configured_provider):
raise SystemExit(f"Unknown provider: {provider}")
# For OAuth-capable providers, ask which type
diff --git a/tests/hermes_cli/test_auth_commands.py b/tests/hermes_cli/test_auth_commands.py
index 6ebb787959b..67bee988111 100644
--- a/tests/hermes_cli/test_auth_commands.py
+++ b/tests/hermes_cli/test_auth_commands.py
@@ -18,13 +18,16 @@ def _write_auth_store(tmp_path, payload: dict) -> None:
(hermes_home / "auth.json").write_text(json.dumps(payload, indent=2))
-def _write_groq_provider_config(tmp_path, *, name="Groq", base_url=None) -> None:
+def _write_groq_provider_config(
+ tmp_path, *, provider_key="groq", name="Groq", base_url=None
+) -> None:
hermes_home = tmp_path / "hermes"
+ hermes_home.mkdir(parents=True, exist_ok=True)
(hermes_home / "config.yaml").write_text(
yaml.safe_dump(
{
"providers": {
- "groq": {
+ provider_key: {
"name": name,
"base_url": base_url or "https://api.groq.com/openai/v1",
"key_env": "GROQ_API_KEY",
@@ -180,6 +183,137 @@ def test_auth_add_migrates_legacy_prefixed_key_for_configured_provider(
} == {"gsk-legacy", "gsk-new"}
+def test_auth_add_migrates_display_name_derived_legacy_pool_key(
+ tmp_path, monkeypatch
+):
+ hermes_home = tmp_path / "hermes"
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ monkeypatch.delenv("GROQ_API_KEY", raising=False)
+ _write_auth_store(
+ tmp_path,
+ {
+ "version": 1,
+ "providers": {},
+ "credential_pool": {
+ "custom:groq": [
+ {
+ "id": "legacy-key",
+ "label": "legacy",
+ "auth_type": "api_key",
+ "priority": 0,
+ "source": "manual",
+ "access_token": "gsk-legacy",
+ }
+ ]
+ },
+ },
+ )
+ _write_groq_provider_config(tmp_path, provider_key="groq-cloud", name="Groq")
+
+ from hermes_cli.auth_commands import auth_add_command
+
+ class _Args:
+ provider = "groq-cloud"
+ auth_type = "api-key"
+ api_key = "gsk-new"
+ label = "new"
+
+ with patch("hermes_cli.models.clear_provider_models_cache") as clear_cache:
+ auth_add_command(_Args())
+
+ payload = json.loads((hermes_home / "auth.json").read_text(encoding="utf-8"))
+ assert "custom:groq" not in payload["credential_pool"]
+ assert {
+ entry["access_token"]
+ for entry in payload["credential_pool"]["groq-cloud"]
+ } == {"gsk-legacy", "gsk-new"}
+ clear_cache.assert_called_once_with("custom:groq")
+
+
+def test_auth_add_non_registry_configured_provider_preserves_endpoint(
+ tmp_path, monkeypatch
+):
+ hermes_home = tmp_path / "hermes"
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ _write_auth_store(tmp_path, {"version": 1, "providers": {}})
+ _write_groq_provider_config(
+ tmp_path,
+ provider_key="private-groq",
+ base_url="https://private.example/v1",
+ )
+
+ from hermes_cli.auth_commands import auth_add_command
+
+ auth_add_command(
+ type(
+ "Args",
+ (),
+ {
+ "provider": "private-groq",
+ "auth_type": "api-key",
+ "api_key": "private-key",
+ "label": "private",
+ },
+ )()
+ )
+
+ payload = json.loads((hermes_home / "auth.json").read_text(encoding="utf-8"))
+ entry = payload["credential_pool"]["private-groq"][0]
+ assert entry["base_url"] == "https://private.example/v1"
+
+
+def test_auth_list_includes_non_registry_configured_provider(
+ tmp_path, monkeypatch, capsys
+):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
+ _write_groq_provider_config(tmp_path, provider_key="private-groq")
+ _write_auth_store(
+ tmp_path,
+ {
+ "version": 1,
+ "providers": {},
+ "credential_pool": {
+ "private-groq": [
+ {
+ "id": "private-key",
+ "label": "private",
+ "auth_type": "api_key",
+ "priority": 0,
+ "source": "manual",
+ "access_token": "secret",
+ }
+ ]
+ },
+ },
+ )
+
+ from hermes_cli.auth_commands import auth_list_command
+
+ auth_list_command(type("Args", (), {"provider": None})())
+
+ assert "private-groq (1 credentials):" in capsys.readouterr().out
+
+
+def test_interactive_auth_add_accepts_non_registry_configured_provider(
+ tmp_path, monkeypatch
+):
+ hermes_home = tmp_path / "hermes"
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ _write_auth_store(tmp_path, {"version": 1, "providers": {}})
+ _write_groq_provider_config(tmp_path, provider_key="private-groq")
+
+ from hermes_cli import auth_commands
+
+ monkeypatch.setattr(auth_commands, "_pick_provider", lambda _prompt: "private-groq")
+ monkeypatch.setattr(auth_commands, "line_input", lambda _prompt: "private")
+ monkeypatch.setattr(auth_commands, "masked_secret_prompt", lambda _prompt: "private-key")
+
+ auth_commands._interactive_add()
+
+ payload = json.loads((hermes_home / "auth.json").read_text(encoding="utf-8"))
+ assert payload["credential_pool"]["private-groq"][0]["access_token"] == "private-key"
+
+
def test_auth_add_explicit_custom_provider_keeps_prefixed_pool_key(
tmp_path, monkeypatch
):