The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(auth): re-sync plugin providers into PROVIDER_REGISTRY after discovery
zihaofeng200104f80dba0d2e
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex 8cbe8576a16..8a8c2bfce9f 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -276,13 +276,41 @@ def _register_plugin_provider(pp: Any) -> None:PROVIDER_REGISTRY.setdefault(alias, pconfig)-try:- from providers import list_providers as _list_providers_for_registry- for _pp in _list_providers_for_registry():- if _pp.name not in PROVIDER_REGISTRY:- _register_plugin_provider(_pp)-except Exception:- pass+def sync_plugin_provider_registry() -> int:+ """Mirror provider-plugin profiles into ``PROVIDER_REGISTRY``; return how many were added.++ Idempotent and cheap (only missing names are registered, existing entries are never replaced),+ so it is safe from resolution paths. It runs once at import below and again whenever a name is+ missing (:func:`_registry_lookup`) or when ``providers`` finishes discovery, because the+ import-time pass can observe a *partial* profile list: if a plugin's own imports pull this+ module in while ``providers._discover_providers()`` is still iterating the plugin directories,+ ``list_providers()`` returns only what has been registered so far (the discovery guard is+ already set) and every plugin discovered after that point would otherwise be invisible to+ ``resolve_provider()`` and fail with "Unknown provider". See #102123."""+ try:+ from providers import list_providers as _list_providers_for_registry+ profiles = _list_providers_for_registry()+ except Exception:+ return 0+ added = 0+ for pp in profiles:+ if pp.name in PROVIDER_REGISTRY:+ continue+ _register_plugin_provider(pp)+ if pp.name in PROVIDER_REGISTRY:+ added += 1+ return added+++def _registry_lookup(provider_id: str) -> Optional[ProviderConfig]:+ """``PROVIDER_REGISTRY.get`` that re-syncs plugin profiles on a miss."""+ pconfig = PROVIDER_REGISTRY.get(provider_id)+ if pconfig is None and sync_plugin_provider_registry():+ pconfig = PROVIDER_REGISTRY.get(provider_id)+ return pconfig+++sync_plugin_provider_registry()def get_anthropic_key() -> str:@@ -739,7 +767,7 @@ def mark_provider_active_if_unset(provider_id: str) -> None:def is_known_auth_provider(provider_id: str) -> bool:normalized = (provider_id or "").strip().lower()- return normalized in PROVIDER_REGISTRY or normalized in SERVICE_PROVIDER_NAMES+ return _registry_lookup(normalized) is not None or normalized in SERVICE_PROVIDER_NAMESdef get_auth_provider_display_name(provider_id: str) -> str:@@ -1357,7 +1385,7 @@ def resolve_provider(normalized = (requested or "auto").strip().lower()normalized = _plugin_aliases().get(normalized, normalized)- if normalized in ("openrouter", "custom") or normalized in PROVIDER_REGISTRY:+ if normalized in ("openrouter", "custom") or _registry_lookup(normalized) is not None:return normalizedif normalized != "auto":hint = _get_config_hint_for_unknown_provider(normalized)@@ -1766,7 +1794,7 @@ def _provider_env_base_url(pconfig: ProviderConfig) -> str:def get_api_key_provider_status(provider_id: str) -> Dict[str, Any]:"""Status snapshot for API-key providers (z.ai, Kimi, MiniMax)."""- pconfig = PROVIDER_REGISTRY.get(provider_id)+ pconfig = _registry_lookup(provider_id)if not pconfig or pconfig.auth_type != "api_key":return {"configured": False}api_key, key_source = _resolve_api_key_provider_secret(provider_id, pconfig)@@ -1854,7 +1882,7 @@ def get_external_process_provider_status(provider_id: str) -> Dict[str, Any]:``configured``/``logged_in`` are structural (executable resolves or TCP endpoint set): thesubprocess owns real auth. ``auth_verified``/``auth_source`` carry positive evidence only."""- pconfig = PROVIDER_REGISTRY.get(provider_id)+ pconfig = _registry_lookup(provider_id)if not pconfig or pconfig.auth_type != "external_process":return {"configured": False}command, args, base_url, resolved_command, _ = _external_process_spec(pconfig)@@ -1886,7 +1914,7 @@ def get_auth_status(provider_id: Optional[str] = None) -> Dict[str, Any]:status_fn_name = _BESPOKE_STATUS_FUNCTIONS.get(target)if status_fn_name:return globals()[status_fn_name]()- pconfig = PROVIDER_REGISTRY.get(target)+ pconfig = _registry_lookup(target)if pconfig and pconfig.auth_type in _STATUS_BY_AUTH_TYPE:return globals()[_STATUS_BY_AUTH_TYPE[pconfig.auth_type]](target)return {"logged_in": False}@@ -1986,7 +2014,7 @@ _API_KEY_BASE_URL_RESOLVERS: Dict[str, Callable[[str, str, str], str]] = {def resolve_api_key_provider_credentials(provider_id: str) -> Dict[str, Any]:"""Resolve API key and base URL for an API-key provider."""- pconfig = PROVIDER_REGISTRY.get(provider_id)+ pconfig = _registry_lookup(provider_id)if not pconfig or pconfig.auth_type != "api_key":raise AuthError(f"Provider '{provider_id}' is not an API-key provider.",@@ -2017,7 +2045,7 @@ def resolve_api_key_provider_credentials(provider_id: str) -> Dict[str, Any]:def resolve_external_process_provider_credentials(provider_id: str) -> Dict[str, Any]:"""Resolve runtime details for local subprocess-backed providers."""- pconfig = PROVIDER_REGISTRY.get(provider_id)+ pconfig = _registry_lookup(provider_id)if not pconfig or pconfig.auth_type != "external_process":raise AuthError(f"Provider '{provider_id}' is not an external-process provider.",diff --git a/providers/__init__.py b/providers/__init__.pyindex a8f8a777a86..884fec08516 100644--- a/providers/__init__.py+++ b/providers/__init__.py@@ -46,6 +46,7 @@ _REGISTRY: dict[str, ProviderProfile] = {}_ALIASES: dict[str, str] = {}_PROVIDER_LIST_CACHE: list[ProviderProfile] | None = None_discovered = False+_discovering = False# Repo-root ``plugins/model-providers/`` — populated at discovery time._BUNDLED_PLUGINS_DIR = (@@ -53,6 +54,26 @@ _BUNDLED_PLUGINS_DIR = ()+def _sync_auth_registry() -> None:+ """Mirror profiles into ``hermes_cli.auth.PROVIDER_REGISTRY`` if that module is loaded.++ ``hermes_cli.auth`` takes its own snapshot of ``list_providers()`` when it is imported. If a+ plugin's imports pull that module in while :func:`_discover_providers` is still running, the+ snapshot is partial and later plugins never reach the auth registry ("Unknown provider",+ #102123). Calling back into auth once discovery is complete closes that window. Looked up via+ ``sys.modules`` on purpose: this layer must never import ``hermes_cli`` (that would run auth's+ top-level code mid-scan and risk a circular import). Never raises: registration must not fail+ because of the auth mirror.+ """+ sync = getattr(sys.modules.get("hermes_cli.auth"), "sync_plugin_provider_registry", None)+ if sync is None:+ return+ try:+ sync()+ except Exception as exc: # pragma: no cover — never break discovery+ logger.debug("auth registry sync skipped: %s", exc)++def register_provider(profile: ProviderProfile) -> None:"""Register a provider profile by name and aliases.@@ -65,6 +86,8 @@ def register_provider(profile: ProviderProfile) -> None:for alias in profile.aliases:_ALIASES[alias] = profile.name_PROVIDER_LIST_CACHE = None+ if _discovered and not _discovering: # post-discovery registration: mirror it immediately+ _sync_auth_registry()def get_provider_profile(name: str) -> ProviderProfile | None:@@ -364,11 +387,22 @@ def _discover_providers() -> None:Each step imports its plugins, which call ``register_provider()`` atmodule-level. Later steps win on name collision."""- global _discovered+ global _discovered, _discoveringif _discovered:return_discovered = True+ _discovering = True+ try:+ _run_discovery_steps()+ finally:+ _discovering = False+ # hermes_cli.auth may have been imported by a plugin during discovery and snapshotted a+ # partial profile list — hand it the complete one (no-op unless auth is already loaded).+ _sync_auth_registry()++def _run_discovery_steps() -> None:+ """The discovery passes, in precedence order (see :func:`_discover_providers`)."""# 0. Pip-installed plugins — entry points in the ``hermes_agent.plugins``# group (the same group the general PluginManager uses). The manager# records model-provider manifests for introspection but deliberatelydiff --git a/tests/providers/test_auth_registry_mid_discovery.py b/tests/providers/test_auth_registry_mid_discovery.pynew file mode 100644index 00000000000..bca66d5dde0--- /dev/null+++ b/tests/providers/test_auth_registry_mid_discovery.py@@ -0,0 +1,243 @@+"""Regression tests for #102123: plugins discovered after ``hermes_cli.auth`` is+first imported must still reach ``PROVIDER_REGISTRY``.++``hermes_cli.auth`` mirrors provider-plugin profiles into ``PROVIDER_REGISTRY``+when it is imported. If a plugin's own imports pull ``hermes_cli.auth`` in+while ``providers._discover_providers()`` is still iterating the plugin+directories, that mirror runs against a partial profile list (the discovery+guard is already set, so ``list_providers()`` returns whatever has been+registered so far). Every plugin discovered afterwards was invisible to+``resolve_provider()`` and failed with "Unknown provider".+"""++from __future__ import annotations++import os+import subprocess+import sys+from pathlib import Path++import pytest++import providers+import hermes_cli.auth as auth_mod+from providers.base import ProviderProfile++REPO_ROOT = Path(__file__).resolve().parents[2]++_PLAIN_PROFILE = (+ "from providers import register_provider\n"+ "from providers.base import ProviderProfile\n"+ "register_provider(ProviderProfile(\n"+ " name={name!r},\n"+ " aliases=({alias!r},),\n"+ " env_vars=('{env}',),\n"+ " base_url='https://{name}.example/v1',\n"+ " auth_type='api_key',\n"+ "))\n"+)+++# ---------------------------------------------------------------------------+# End-to-end: a real plugin tree, a fresh interpreter, the public CLI gate.+# ---------------------------------------------------------------------------++def _write_plugin(root: Path, name: str, body: str) -> None:+ plugin_dir = root / "plugins" / "model-providers" / name+ plugin_dir.mkdir(parents=True)+ (plugin_dir / "__init__.py").write_text(body, encoding="utf-8")+ (plugin_dir / "plugin.yaml").write_text(+ f"name: {name}\nkind: model-provider\nversion: 0.0.1\ndescription: probe\n",+ encoding="utf-8",+ )+++def _run_probe(hermes_home: Path, code: str) -> subprocess.CompletedProcess:+ env = os.environ.copy()+ env["HERMES_HOME"] = str(hermes_home)+ env.pop("HERMES_PROFILE", None)+ env["PYTHONPATH"] = os.pathsep.join(+ [str(REPO_ROOT), env.get("PYTHONPATH", "")]+ ).rstrip(os.pathsep)+ return subprocess.run(+ [sys.executable, "-c", code],+ cwd=REPO_ROOT,+ env=env,+ stdin=subprocess.DEVNULL,+ capture_output=True,+ text=True,+ timeout=60,+ )+++def test_plugins_discovered_after_auth_import_resolve(tmp_path):+ hermes_home = tmp_path / ".hermes"+ # Sorted first: a plugin whose imports drag hermes_cli.auth in mid-discovery+ # (any plugin importing agent.credential_pool or similar does this).+ _write_plugin(+ hermes_home,+ "aaa-early-probe",+ "import hermes_cli.auth # noqa: F401 — simulate a core-importing plugin\n"+ + _PLAIN_PROFILE.format(+ name="aaa-early-probe", alias="aaa-alias", env="AAA_EARLY_PROBE_KEY"+ ),+ )+ # Sorted last: an ordinary plugin discovered after that import.+ _write_plugin(+ hermes_home,+ "zzz-late-probe",+ _PLAIN_PROFILE.format(+ name="zzz-late-probe", alias="zzz-alias", env="ZZZ_LATE_PROBE_KEY"+ ),+ )++ probe = _run_probe(+ hermes_home,+ "import providers\n"+ "names = {p.name for p in providers.list_providers()}\n"+ "assert {'aaa-early-probe', 'zzz-late-probe'} <= names, names\n"+ "from hermes_cli.auth import PROVIDER_REGISTRY, resolve_provider\n"+ # Discovery completion must have mirrored the late plugin already;+ # consumers that read PROVIDER_REGISTRY directly rely on this.+ "assert 'zzz-late-probe' in PROVIDER_REGISTRY, sorted(PROVIDER_REGISTRY)\n"+ "assert resolve_provider('aaa-early-probe') == 'aaa-early-probe'\n"+ "assert resolve_provider('zzz-late-probe') == 'zzz-late-probe'\n"+ "assert resolve_provider('zzz-alias') == 'zzz-late-probe'\n"+ "cfg = PROVIDER_REGISTRY['zzz-late-probe']\n"+ "assert cfg.api_key_env_vars == ('ZZZ_LATE_PROBE_KEY',), cfg\n"+ "assert cfg.inference_base_url == 'https://zzz-late-probe.example/v1', cfg\n",+ )+ assert probe.returncode == 0, probe.stdout + probe.stderr+++# ---------------------------------------------------------------------------+# In-process: the sync hook's contract (partial snapshot reconciled, idempotent,+# never imports hermes_cli.auth on its own).+# ---------------------------------------------------------------------------++EARLY = "probe-102123-early"+LATE = "probe-102123-late"+LATE_ALIAS = "probe-102123-late-alias"+++def _isolated_registries():+ """Snapshot both registries; restore on teardown so nothing leaks."""+ saved_registry = dict(providers._REGISTRY)+ saved_aliases = dict(providers._ALIASES)+ saved_discovered = providers._discovered+ saved_auth_keys = set(auth_mod.PROVIDER_REGISTRY)+ saved_plugin_modules = {+ m for m in sys.modules if m.startswith("plugins.model_providers")+ }+ providers._REGISTRY.clear()+ providers._ALIASES.clear()+ providers._PROVIDER_LIST_CACHE = None+ providers._discovered = False+ providers._discovering = False+ yield+ for key in set(auth_mod.PROVIDER_REGISTRY) - saved_auth_keys:+ del auth_mod.PROVIDER_REGISTRY[key]+ for mod in [+ m+ for m in sys.modules+ if m.startswith("plugins.model_providers")+ and m not in saved_plugin_modules+ ]:+ del sys.modules[mod]+ providers._REGISTRY.clear()+ providers._REGISTRY.update(saved_registry)+ providers._ALIASES.clear()+ providers._ALIASES.update(saved_aliases)+ providers._PROVIDER_LIST_CACHE = None+ providers._discovered = saved_discovered+ providers._discovering = False+++def test_mid_discovery_auth_import_reconciled(+ _isolated_registries, monkeypatch, tmp_path+):+ """Mid-discovery auth snapshot + late provider -> REGISTRY finally complete."""++ def fake_entry_point_step():+ # Reproduce a mid-discovery `import hermes_cli.auth`: its module+ # top-level snapshots list_providers() exactly like this, and at this+ # point nothing has been registered yet, so the snapshot is partial.+ auth_mod.sync_plugin_provider_registry()+ providers.register_provider(+ ProviderProfile(+ name=EARLY,+ display_name="Early",+ base_url="https://early.example/v1",+ env_vars=("PROBE_102123_EARLY_KEY",),+ )+ )+ # Registration during discovery must NOT sync eagerly (that would be+ # one sync per plugin); the hazard is still live at this point.+ assert LATE not in auth_mod.PROVIDER_REGISTRY++ late_plugin = tmp_path / "zzz_probe_102123"+ late_plugin.mkdir()+ (late_plugin / "__init__.py").write_text(+ "from providers import register_provider\n"+ "from providers.base import ProviderProfile\n"+ "register_provider(ProviderProfile(\n"+ f" name={LATE!r}, display_name='Late',\n"+ " base_url='https://late.example/v1',\n"+ f" env_vars=('PROBE_102123_LATE_KEY',), aliases=({LATE_ALIAS!r},)))\n",+ encoding="utf-8",+ )+ sys.modules.pop("plugins.model_providers.zzz_probe_102123", None)+ monkeypatch.setattr(+ providers, "_discover_entry_point_providers", fake_entry_point_step+ )+ monkeypatch.setattr(providers, "_BUNDLED_PLUGINS_DIR", tmp_path)+ monkeypatch.setattr(providers, "_user_plugins_dir", lambda: None)+ monkeypatch.setattr(providers, "_installed_plugins_dir", lambda: None)++ providers._discover_providers()++ assert providers.get_provider_profile(LATE) is not None+ assert LATE in auth_mod.PROVIDER_REGISTRY+ assert LATE_ALIAS in auth_mod.PROVIDER_REGISTRY+ assert EARLY in auth_mod.PROVIDER_REGISTRY+ assert providers._discovering is False+++def test_post_discovery_registration_is_mirrored(_isolated_registries, monkeypatch, tmp_path):+ """A register_provider() call after discovery finished reaches the auth registry at once."""+ monkeypatch.setattr(providers, "_discover_entry_point_providers", lambda: None)+ monkeypatch.setattr(providers, "_BUNDLED_PLUGINS_DIR", tmp_path)+ monkeypatch.setattr(providers, "_user_plugins_dir", lambda: None)+ monkeypatch.setattr(providers, "_installed_plugins_dir", lambda: None)+ providers._discover_providers()++ providers.register_provider(+ ProviderProfile(+ name=LATE,+ display_name="Late",+ base_url="https://late.example/v1",+ env_vars=("PROBE_102123_LATE_KEY",),+ aliases=(LATE_ALIAS,),+ )+ )+ assert LATE in auth_mod.PROVIDER_REGISTRY+ assert auth_mod.PROVIDER_REGISTRY[LATE_ALIAS] is auth_mod.PROVIDER_REGISTRY[LATE]+++def test_sync_idempotent_and_no_clobber(_isolated_registries):+ """Repeated syncs add nothing new and never replace existing entries."""+ snapshot = dict(auth_mod.PROVIDER_REGISTRY)+ auth_mod.sync_plugin_provider_registry()+ for key, config in snapshot.items():+ assert auth_mod.PROVIDER_REGISTRY[key] is config+ after = dict(auth_mod.PROVIDER_REGISTRY)+ assert auth_mod.sync_plugin_provider_registry() == 0+ assert dict(auth_mod.PROVIDER_REGISTRY) == after+++def test_sync_noop_when_auth_never_imported(monkeypatch):+ """The providers-side hook must not import hermes_cli.auth by itself."""+ monkeypatch.delitem(sys.modules, "hermes_cli.auth", raising=False)+ providers._sync_auth_registry()+ assert "hermes_cli.auth" not in sys.modules