The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(auth): each served profile home reads its own provider rows and aliases
Teknium0e389738071b
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex d11b068f766..ab25405f981 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -242,7 +242,7 @@ from hermes_cli.auth_plugin_providers import HomeScopedRegistry # mirrored rowsPROVIDER_REGISTRY: dict[str, ProviderConfig] = HomeScopedRegistry((p.id, p) for p in (r if isinstance(r, ProviderConfig) else _api_key_provider(*r) for r in _REGISTRY_ROWS))# The rows above, before any plugin touches the dict (a user plugin may override these; #48450).-BUILTIN_PROVIDER_IDS = frozenset(PROVIDER_REGISTRY)+BUILTIN_PROVIDER_IDS = frozenset(dict.keys(PROVIDER_REGISTRY))# ``hermes_cli.config`` discovers model-provider plugins while importing, and a plugin may read this# module's registry during that discovery. Keep the import below ProviderConfig / PROVIDER_REGISTRY sodiff --git a/hermes_cli/auth_plugin_providers.py b/hermes_cli/auth_plugin_providers.pyindex 6593fb22ca4..cb0c33e2778 100644--- a/hermes_cli/auth_plugin_providers.py+++ b/hermes_cli/auth_plugin_providers.py@@ -17,6 +17,7 @@ right after ``PROVIDER_REGISTRY`` exists, and by ``agent.credential_pool``."""from __future__ import annotations+import copyimport loggingfrom typing import Any, Callable, Optional@@ -35,48 +36,51 @@ PLUGIN_AUTH_ACTIONS = ("add", "status", "logout", "refresh")PLUGIN_MIRRORED_PROVIDERS: set[str] = set()-def _absent_mirrored(ids) -> set[str]:- """The plugin-mirrored ids among *ids* that the bound home has no profile for."""- mirrored = [pid for pid in ids if pid in PLUGIN_MIRRORED_PROVIDERS]- if not mirrored:- return set()- from providers import names_without_profile- return names_without_profile(mirrored)--class HomeScopedRegistry(dict):- """``PROVIDER_REGISTRY``: process-wide storage, read per profile home.-- Plugin profiles are per ``$HERMES_HOME`` but their mirrored rows (and the alias keys pointing at- them) live in one process-wide dict, and one process serves many profiles (multiplex gateway,- Desktop ``serve``). Every read hides a mirrored row whose provider has no profile in the bound- home, so a profile without the plugin never resolves, auto-detects or reads credentials for a- provider another profile installed. Built-in rows are never hidden; writes are plain dict writes.+ """``PROVIDER_REGISTRY``: process-wide storage, each row read as the bound profile home sees it.++ One process serves many profile homes (multiplex gateway, Desktop ``serve``) and each home+ installs its own provider plugins, so no read returns a row another home rewrote: a mirrored row+ is hidden from a home without that provider and built from the home's own profile when only the+ home declares it; a ``$HERMES_HOME`` plugin's declared fields (:func:`override_registry_row`) land+ on a per-home copy; an alias key follows the bound home's plugin that claims it. Built-in rows a+ home does not override are returned as stored; writes are plain dict writes."""- def _hidden(self) -> set[str]:- return _absent_mirrored({row.id for row in dict.values(self)}) if PLUGIN_MIRRORED_PROVIDERS else set()-- def _shown(self, row: Any) -> bool:- return row.id not in PLUGIN_MIRRORED_PROVIDERS or not _absent_mirrored((row.id,))+ def _view(self, key: str, row: Any, resolve: Callable[[str], tuple]) -> Any:+ """*row* (stored under *key*) for the bound home; None = hidden there."""+ if key != row.id:+ claimant = resolve(key)[0]+ if claimant is not None and claimant.name != row.id:+ row = dict.get(self, claimant.name)+ if row is None or row.id != claimant.name:+ return None+ user, shared = resolve(row.id)+ mirrored = row.id in PLUGIN_MIRRORED_PROVIDERS+ if user is None:+ return row if shared is not None or not mirrored else None+ if row.id in _REGISTRY_PLUGIN_SKIP or not (mirrored or row.id in _builtin_ids()):+ return row+ return _home_row(row, user, from_profile=mirrored and shared is None)def __getitem__(self, key: str) -> Any:- row = dict.__getitem__(self, key)- if not self._shown(row):+ row = self._view(key, dict.__getitem__(self, key), _resolver())+ if row is None:raise KeyError(key)return rowdef get(self, key: str, default: Any = None) -> Any:row = dict.get(self, key)- return row if row is not None and self._shown(row) else default+ row = None if row is None else self._view(key, row, _resolver())+ return default if row is None else rowdef __contains__(self, key: object) -> bool:- row = dict.get(self, key)- return row is not None and self._shown(row)+ return self.get(key) is not Nonedef items(self) -> list[tuple[str, Any]]:- hidden = self._hidden()- return [(key, row) for key, row in dict.items(self) if row.id not in hidden]+ resolve = _resolver()+ views = ((key, self._view(key, row, resolve)) for key, row in dict.items(self))+ return [(key, row) for key, row in views if row is not None]def keys(self) -> list[str]:return [key for key, _ in self.items()]@@ -91,6 +95,37 @@ class HomeScopedRegistry(dict):return len(self.items())+def _resolver() -> Callable[[str], tuple]:+ from providers import bound_profile_resolver+ return bound_profile_resolver()+++def _builtin_ids() -> frozenset:+ from hermes_cli.auth import BUILTIN_PROVIDER_IDS+ return BUILTIN_PROVIDER_IDS+++# (id(stored row), id(home profile)) -> (stored row, home profile, that home's row). Holding both+# keeps the ids from being reused; a re-imported plugin is a new profile object, so a new entry.+_HOME_ROWS: dict[tuple[int, int], tuple[Any, Any, Any]] = {}+++def _home_row(row: Any, pp: Any, *, from_profile: bool) -> Any:+ """The row a home whose own plugin *pp* declares *row*'s provider reads: built from *pp* when no+ process-wide profile backs the row (``from_profile``), else a copy carrying *pp*'s declared fields."""+ cached = _HOME_ROWS.get((id(row), id(pp)))+ if cached is not None:+ return cached[2]+ home = _profile_row(pp) if from_profile else None+ if home is None:+ home = copy.copy(row)+ override_registry_row(home, pp)+ if len(_HOME_ROWS) >= 512:+ _HOME_ROWS.clear()+ _HOME_ROWS[(id(row), id(pp))] = (row, pp, home)+ return home++def _api_key_env_fields(pp: Any) -> tuple[tuple, str]:"""Split a profile's ``env_vars`` into (api-key vars, base-URL var); the URL var may be ""."""is_url = lambda v: v.endswith("_BASE_URL") or v.endswith("_URL")@@ -104,23 +139,31 @@ def register_plugin_provider(pp: Any) -> None:Registering is what lets an out-of-tree provider pass ``resolve_provider()``'s known-providergate ("Unknown provider"); OAuth-shaped plugins carry their own login via ``auth_handler``."""- from hermes_cli.auth import PROVIDER_REGISTRY, ProviderConfig, _api_key_provider+ from hermes_cli.auth import PROVIDER_REGISTRY- if pp.name in _REGISTRY_PLUGIN_SKIP:+ pconfig = _profile_row(pp)+ if pconfig is None:return+ _insert_row(PROVIDER_REGISTRY, pconfig, pp.registry_after)+ PLUGIN_MIRRORED_PROVIDERS.add(pp.name)+ mirror_aliases(pconfig, pp)+++def _profile_row(pp: Any) -> Optional[Any]:+ """The registry row *pp* declares, or None (a skipped name, an api-key profile without env vars)."""+ from hermes_cli.auth import ProviderConfig, _api_key_provider++ if pp.name in _REGISTRY_PLUGIN_SKIP:+ return Noneauth_type = registry_auth_type(pp)if auth_type == "api_key":if not pp.env_vars:- return+ return Nonekey_vars, url_var = _api_key_env_fields(pp)- pconfig = _api_key_provider(pp.name, pp.display_name or pp.name, pp.base_url, key_vars,- pp.base_url_env_var or url_var)- else:- pconfig = ProviderConfig(pp.name, pp.display_name or pp.name, auth_type, inference_base_url=pp.base_url,- base_url_env_var=pp.base_url_env_var)- _insert_row(PROVIDER_REGISTRY, pconfig, pp.registry_after)- PLUGIN_MIRRORED_PROVIDERS.add(pp.name)- mirror_aliases(pconfig, pp)+ return _api_key_provider(pp.name, pp.display_name or pp.name, pp.base_url, key_vars,+ pp.base_url_env_var or url_var)+ return ProviderConfig(pp.name, pp.display_name or pp.name, auth_type, inference_base_url=pp.base_url,+ base_url_env_var=pp.base_url_env_var)def registry_auth_type(pp: Any) -> str:@@ -170,7 +213,9 @@ def override_registry_row(pconfig: Any, pp: Any) -> None:"""A ``$HERMES_HOME`` plugin re-registering a name that already has a row wins for the fieldsit declares — ``display_name``, ``base_url`` and, on api-key rows, ``env_vars`` (#48450, #116668). ``register_provider()``is last-writer-wins for the profile; without this the runtime kept reading the built-in- endpoint. In place, so alias rows sharing the object follow; idempotent, so re-sync is free.+ endpoint. A ``$HERMES_HOME`` layer plugin's fields land on that home's own copy of the row+ (:class:`HomeScopedRegistry`), so another served home keeps the built-in endpoint; a process-wide+ registration (every home reads it) rewrites the stored row in place."""if pp.display_name:pconfig.name = pp.display_name@@ -186,7 +231,7 @@ def sync_plugin_provider_registry() -> int:"""Mirror provider-plugin profiles into ``PROVIDER_REGISTRY``; return how many were added.Idempotent (existing entries are never replaced — a user plugin re-registering a bundled name- only rewrites the fields it declares, see :func:`override_registry_row`), so it is safe from+ wins for the fields it declares in its own home only, see :class:`HomeScopedRegistry`), so it is safe fromresolution paths. It runs atauth import 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: a plugin@@ -198,6 +243,7 @@ def sync_plugin_provider_registry() -> int:try:from providers import list_providers, provider_sourceprofiles = list_providers()+ home_profile = lambda name: _resolver()(name)[0]except Exception:return 0added = 0@@ -207,8 +253,10 @@ def sync_plugin_provider_registry() -> int:# own, more specific declaration and stays as written.core_row = pp.name in BUILTIN_PROVIDER_IDS or pp.name in PLUGIN_MIRRORED_PROVIDERSif core_row and pp.name not in _REGISTRY_PLUGIN_SKIP and provider_source(pp.name) == "user":- override_registry_row(PROVIDER_REGISTRY[pp.name], pp)- mirror_aliases(PROVIDER_REGISTRY[pp.name], pp)+ row = dict.__getitem__(PROVIDER_REGISTRY, pp.name)+ if home_profile(pp.name) is not pp: # registered process-wide: every home reads it+ override_registry_row(row, pp)+ mirror_aliases(row, pp)continueregister_plugin_provider(pp)added += pp.name in PROVIDER_REGISTRY@@ -228,7 +276,10 @@ def registry_lookup(provider_id: str) -> Optional[Any]:from hermes_cli.auth import PROVIDER_REGISTRYpconfig = PROVIDER_REGISTRY.get(provider_id)- if pconfig is None and sync_plugin_provider_registry():+ if pconfig is None:+ # Re-read whatever the count says: a home's first plugin scan runs inside the sync's own+ # ``list_providers()`` and mirrors its rows in that nested pass.+ sync_plugin_provider_registry()pconfig = PROVIDER_REGISTRY.get(provider_id)return pconfigdiff --git a/hermes_cli/models_catalog_static.py b/hermes_cli/models_catalog_static.pyindex da2998284ff..ec7dced0518 100644--- a/hermes_cli/models_catalog_static.py+++ b/hermes_cli/models_catalog_static.py@@ -6,7 +6,7 @@ maps. Split out of ``hermes_cli.models``.from __future__ import annotations-from typing import NamedTuple+from typing import Any, NamedTupleclass CuratedFallbackModels(list[str]):@@ -371,6 +371,7 @@ CANONICAL_PROVIDERS: list[ProviderEntry] = [ProviderEntry(*row) for row in (# through ``auth.get_auth_status`` (external_process → the binary resolves; OAuth → auth.json /# credential-pool entry), so an admitted row reads authenticated=False until the user signs in._canonical_slugs = {p.slug for p in CANONICAL_PROVIDERS}+_BUILTIN_SLUGS = frozenset(_canonical_slugs)def _plugin_provider_enters_picker(pp) -> bool:@@ -412,8 +413,8 @@ def sync_plugin_provider_catalog() -> int:def _admit_plugin_provider(pp) -> None:- """Add one plugin profile to the picker tables: row (at ``picker_after``), label, group,- catalog aliases and the aggregator set."""+ """Add one plugin profile to the picker tables: row (at ``picker_after``), label, group and the+ aggregator set. Its catalog aliases are read per home (:class:`_CatalogAliases`)."""label = pp.display_name or pp.nameentry = ProviderEntry(pp.name, label, pp.description or f"{label} (direct API)")slugs = [p.slug for p in CANONICAL_PROVIDERS]@@ -427,9 +428,6 @@ def _admit_plugin_provider(pp) -> None:if pp.name not in members:members.append(pp.name)_SLUG_TO_GROUP[pp.name] = gid- if pp.catalog_aliases:- for alias in pp.aliases:- _PROVIDER_ALIASES.setdefault(alias, pp.name)if pp.aggregator:_AGGREGATOR_PROVIDERS.add(pp.name)@@ -515,7 +513,61 @@ def group_providers(slugs):return rows-_PROVIDER_ALIASES = dict((+class _CatalogAliases(dict):+ """``_PROVIDER_ALIASES``: the built-in alias table plus the ``catalog_aliases`` of the bound home's+ plugin profiles, resolved per read and never copied in: two served homes may give one alias to+ different providers. A built-in alias always wins; among plugins the first registered does."""++ _memo: tuple[tuple, dict[str, str]] = ((), {})++ def _plugin_aliases(self) -> dict[str, str]:+ try:+ from providers import bound_registry_key, list_providers+ token = bound_registry_key()+ if self._memo[0] == token:+ return self._memo[1]+ profiles = list_providers()+ except Exception:+ return {}+ found: dict[str, str] = {}+ for pp in profiles:+ if pp.catalog_aliases and pp.name not in _BUILTIN_SLUGS:+ for alias in pp.aliases:+ if not dict.__contains__(self, alias):+ found.setdefault(alias, pp.name)+ self._memo = (token, found)+ return found++ def __getitem__(self, key: str) -> str:+ if dict.__contains__(self, key):+ return dict.__getitem__(self, key)+ return self._plugin_aliases()[key]++ def get(self, key: str, default: Any = None) -> Any:+ if dict.__contains__(self, key):+ return dict.__getitem__(self, key)+ return self._plugin_aliases().get(key, default)++ def __contains__(self, key: object) -> bool:+ return dict.__contains__(self, key) or key in self._plugin_aliases()++ def items(self) -> list[tuple[str, str]]:+ return [*dict.items(self), *self._plugin_aliases().items()]++ def keys(self) -> list[str]:+ return [key for key, _ in self.items()]++ def values(self) -> list[str]:+ return [value for _, value in self.items()]++ def __iter__(self):+ return iter(self.keys())++ def __len__(self) -> int:+ return len(self.items())+++_PROVIDER_ALIASES = _CatalogAliases((("glm", "zai"), ("z-ai", "zai"), ("z.ai", "zai"), ("zhipu", "zai"), ("google", "gemini"),("google-gemini", "gemini"), ("google-ai-studio", "gemini"), ("google-vertex", "vertex"), ("vertex-ai", "vertex"),("gcp-vertex", "vertex"), ("vertexai", "vertex"), ("kimi", "kimi-coding"), ("moonshot", "kimi-coding"),diff --git a/providers/__init__.py b/providers/__init__.pyindex 091da90dcff..e309e0b4003 100644--- a/providers/__init__.py+++ b/providers/__init__.py@@ -389,19 +389,20 @@ def unlisted_provider_names() -> set[str]:return hidden-def names_without_profile(names) -> set[str]:- """The *names* that have no profile in the bound home: neither process-wide nor its plugins.+def bound_profile_resolver():+ """``resolve(name) -> (home plugin profile, process-wide profile)`` for the home bound now.- Lets process-wide mirrors of profiles (``hermes_cli.auth.PROVIDER_REGISTRY``) hide the rows- another home's plugins put there. Cheap enough for per-lookup use: no discovery, no miss re-scan;- only the periodic plugin-dir stamp check, skipped mid-scan so a plugin reading the mirror while- it imports cannot re-enter its own scan.+ *name* may be an alias. For process-wide mirrors read per home (``hermes_cli.auth``'s+ ``PROVIDER_REGISTRY``), so cheap enough per lookup: no discovery, no miss re-scan; only the+ periodic plugin-dir stamp check, skipped mid-scan so a plugin reading the mirror while it imports+ cannot re-enter its own scan."""- rest = [name for name in names if name not in _REGISTRY]- if not rest:- return set()layer = _bound_home_layer()[0] if _discovering else _home_layer()- return {name for name in rest if name not in layer.registry}++ def resolve(name: str) -> tuple[ProviderProfile | None, ProviderProfile | None]:+ shared = _ALIASES.get(name, name)+ return layer.registry.get(layer.aliases.get(name) or shared), _REGISTRY.get(shared)+ return resolvedef _home_layer(*, force_stamp_check: bool = False) -> _HomeLayer:diff --git a/tests/hermes_cli/test_auth_registry_home_scope.py b/tests/hermes_cli/test_auth_registry_home_scope.pynew file mode 100644index 00000000000..f3c15fb7a56--- /dev/null+++ b/tests/hermes_cli/test_auth_registry_home_scope.py@@ -0,0 +1,83 @@+"""Auth registry rows and provider aliases belong to the profile home that declares them.++One process serves many profile homes. The auth registry and the catalog alias table are+process-wide, so a row rewritten for one home (endpoint, credential env names) or an alias claimed+first by one home leaked into every other home served by the same process.+"""++from __future__ import annotations++import sys+import textwrap+from pathlib import Path++import pytest++from hermes_constants import reset_hermes_home_override, set_hermes_home_override+++def _plugin(home: Path, name: str, url: str, env: tuple, aliases: tuple) -> None:+ plugin = home / "plugins" / "model-providers" / name+ plugin.mkdir(parents=True)+ (plugin / "__init__.py").write_text(textwrap.dedent(f"""+ from providers import register_provider+ from providers.base import ProviderProfile++ register_provider(ProviderProfile(+ name={name!r}, auth_type="api_key", env_vars={env!r}, base_url={url!r},+ aliases={aliases!r}, catalog_aliases=True))+ """), encoding="utf-8")+++def homes(tmp_path, monkeypatch):+ import providers+ from hermes_cli import auth_plugin_providers as app+ from hermes_cli.auth import PROVIDER_REGISTRY++ a, b, c = (tmp_path / n for n in "abc")+ _plugin(a, "acme-scope", "https://a.invalid/v1", ("ACME_SCOPE_A_KEY",), ("acs",))+ _plugin(a, "deepseek", "https://deepseek-a.invalid/v1", ("DEEPSEEK_API_KEY",), ())+ _plugin(b, "acme-scope", "https://b.invalid/v1", ("ACME_SCOPE_B_KEY",), ())+ _plugin(b, "zeta-scope", "https://z.invalid/v1", ("ZETA_SCOPE_KEY",), ("acs",))+ c.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(c))+ monkeypatch.setattr(providers, "_REGISTRY", dict(providers._REGISTRY))+ monkeypatch.setattr(providers, "_ALIASES", dict(providers._ALIASES))+ monkeypatch.setattr(providers, "_PROVIDER_LIST_CACHE", None)+ monkeypatch.setattr(providers, "_HOME_LAYERS", {})+ monkeypatch.setattr(app, "PLUGIN_MIRRORED_PROVIDERS", set(app.PLUGIN_MIRRORED_PROVIDERS))+ rows = list(dict.items(PROVIDER_REGISTRY))+ yield a, b, c+ PROVIDER_REGISTRY.clear()+ PROVIDER_REGISTRY.update(rows)+ for mod in [m for m in sys.modules if m.startswith("_hermes_user_provider")]:+ del sys.modules[mod]+++def _view(home: Path):+ from hermes_cli.auth import PROVIDER_REGISTRY+ from hermes_cli.auth_plugin_providers import registry_lookup+ from hermes_cli.models import normalize_provider++ token = set_hermes_home_override(home)+ try:+ acme = registry_lookup("acme-scope")+ alias = PROVIDER_REGISTRY.get("acs")+ return ((acme.inference_base_url, tuple(acme.api_key_env_vars)) if acme else None,+ alias.id if alias else None, normalize_provider("acs"),+ PROVIDER_REGISTRY["deepseek"].inference_base_url)+ finally:+ reset_hermes_home_override(token)+++def test_each_home_reads_its_own_provider_rows_and_aliases(homes):+ a, b, c = homes+ builtin_deepseek = _view(c)[3]+ home_a = (("https://a.invalid/v1", ("ACME_SCOPE_A_KEY",)), "acme-scope", "acme-scope",+ "https://deepseek-a.invalid/v1")+ assert _view(a) == home_a+ assert _view(b) == (("https://b.invalid/v1", ("ACME_SCOPE_B_KEY",)), "zeta-scope", "zeta-scope",+ builtin_deepseek)+ assert _view(a) == home_a+ assert _view(c) == (None, None, "acs", builtin_deepseek)diff --git a/tests/hermes_cli/test_provider_table_placement.py b/tests/hermes_cli/test_provider_table_placement.pyindex 2da0f4da72d..bbbc4912965 100644--- a/tests/hermes_cli/test_provider_table_placement.py+++ b/tests/hermes_cli/test_provider_table_placement.py@@ -20,7 +20,6 @@ def catalog(monkeypatch):monkeypatch.setattr(cat, "_PROVIDER_LABELS", dict(cat._PROVIDER_LABELS))monkeypatch.setattr(cat, "PROVIDER_GROUPS", {k: (lbl, d, list(m)) for k, (lbl, d, m) in cat.PROVIDER_GROUPS.items()})monkeypatch.setattr(cat, "_SLUG_TO_GROUP", dict(cat._SLUG_TO_GROUP))- monkeypatch.setattr(cat, "_PROVIDER_ALIASES", dict(cat._PROVIDER_ALIASES))monkeypatch.setattr(cat, "_AGGREGATOR_PROVIDERS", set(cat._AGGREGATOR_PROVIDERS))return cat@@ -29,6 +28,8 @@ def _use_profiles(monkeypatch, *profiles):import providersmonkeypatch.setattr(providers, "list_providers", lambda: list(profiles))+ # The new profile list stands for a registration, which moves the generation.+ monkeypatch.setattr(providers, "_REGISTRY_GENERATION", providers._REGISTRY_GENERATION + 1)def test_picker_fields_place_plugin_rows(catalog, monkeypatch):