The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a frozen session's route is the entry the runtime selects
Teknium79672209a4b9
diff --git a/gateway/session_policy_credentials.py b/gateway/session_policy_credentials.pyindex 14f99003a6a..ad640f96926 100644--- a/gateway/session_policy_credentials.py+++ b/gateway/session_policy_credentials.py@@ -29,25 +29,18 @@ def _defined(root, path):def _route_paths(policy):"""Secret paths the session's own route authenticates with: its ``model:`` block, a direct alias's- key (``api_key_from``) and the ``providers:`` / ``custom_providers:`` entry its provider names."""+ key (``api_key_from``) and the one ``providers:`` / ``custom_providers:`` entry the runtime's own+ named-provider selection routes its provider through."""+ from hermes_cli.runtime_provider_custom import named_custom_provider_config_pathconfig = json.loads(policy.config_json)model = config.get('model') if isinstance(config.get('model'), dict) else {}paths = {('model', key) for key in model}if isinstance(model.get('api_key_from'), list):paths.add(tuple(model['api_key_from']))- name = str(model.get('provider') or '').strip().lower()- name = name.removeprefix('custom:')-- def named(value):- return str(value or '').strip().lower().replace(' ', '-') == name.replace(' ', '-')- providers = config.get('providers')- for key, entry in (providers.items() if isinstance(providers, dict) and name else ()):- if named(key) or isinstance(entry, dict) and named(entry.get('name')):- paths |= {('providers', key, field) for field in (entry if isinstance(entry, dict) else ())}- custom = config.get('custom_providers')- for index, entry in (enumerate(custom) if isinstance(custom, list) and name else ()):- if isinstance(entry, dict) and named(entry.get('name')):- paths |= {('custom_providers', index, field) for field in entry}+ selected = named_custom_provider_config_path(str(model.get('provider') or ''), config)+ entry = _defined(config, selected) if selected else _ABSENT+ if isinstance(entry, dict):+ paths |= {selected + (field,) for field in entry}return pathsdiff --git a/hermes_cli/runtime_provider_custom.py b/hermes_cli/runtime_provider_custom.pyindex 3bfe977514e..d65e60e3247 100644--- a/hermes_cli/runtime_provider_custom.py+++ b/hermes_cli/runtime_provider_custom.py@@ -138,8 +138,8 @@ def _shadowed_by_builtin(requested_norm: str) -> bool:def _match_new_style_provider(requested_norm: str, providers: dict[str, Any], *, resolve_credentials: bool = True,-) -> Optional[dict[str, Any]]:- """Scan ``providers:`` (new-style, keyed) for ``requested_norm``."""+) -> Optional[tuple[dict[str, Any], Any]]:+ """Scan ``providers:`` (new-style, keyed) for ``requested_norm``; ``(entry, config key)``."""from hermes_cli.config import is_provider_enabledrp = _rp()for ep_name, entry in providers.items():@@ -167,12 +167,12 @@ def _match_new_style_provider(entry, result, provider_key=_clean(ep_name), key_env=key_env,api_mode=rp._parse_api_mode(entry.get("api_mode") or entry.get("transport")),)- return result+ return result, ep_namereturn None-def _match_legacy_custom_provider(requested_norm: str, custom_providers) -> Optional[dict[str, Any]]:- """Scan the legacy ``custom_providers:`` list for ``requested_norm``."""+def _match_legacy_custom_provider(requested_norm: str, custom_providers) -> Optional[tuple[dict[str, Any], dict]]:+ """Scan the legacy ``custom_providers:`` list for ``requested_norm``; ``(result, matched entry)``."""for entry in custom_providers:name, base_url = (entry.get("name"), entry.get("base_url")) if isinstance(entry, dict) else (None, None)if not isinstance(name, str) or not isinstance(base_url, str):@@ -186,7 +186,7 @@ def _match_legacy_custom_provider(requested_norm: str, custom_providers) -> Optiresult["model"] = model_name_lift_common_custom_fields(entry, result, provider_key=provider_key, key_env=_clean(entry.get("key_env", "")),api_mode=_rp()._parse_api_mode(entry.get("api_mode")))- return result+ return result, entryreturn None@@ -196,6 +196,22 @@ def _get_named_custom_provider() -> Optional[dict[str, Any]]:"""Resolve a named endpoint. Creation-time config copying supplies its own config snapshotand skips credential reads; ordinary runtime callers keep their existing scoped resolution."""+ found = _select_named_custom_provider(requested_provider, config=config, resolve_credentials=resolve_credentials)+ return found[0] if found else None+++def named_custom_provider_config_path(requested_provider: str, config: dict[str, Any]) -> Optional[tuple]:+ """The config path (``("providers", key)`` / ``("custom_providers", index)``) of the ONE entry+ the runtime routes *requested_provider* through, else None. Reads no credential."""+ found = _select_named_custom_provider(requested_provider, config=config, resolve_credentials=False)+ return found[1] if found else None+++def _select_named_custom_provider(+ requested_provider: str, *, config: Optional[dict[str, Any]], resolve_credentials: bool,+) -> Optional[tuple[dict[str, Any], Optional[tuple]]]:+ """``(resolved entry, its config path)`` for the first usable match: ``providers:`` first,+ then the legacy list view."""requested_norm = _normalize_custom_provider_name(requested_provider or "")if not requested_norm or requested_norm == "auto" or _shadowed_by_builtin(requested_norm):return None@@ -208,14 +224,28 @@ def _get_named_custom_provider(if isinstance(providers, dict) else None)if found:- return found+ return found[0], ("providers", found[1])if isinstance(config.get("custom_providers"), dict):logger.warning("custom_providers in config.yaml is a dict, not a list. ""Each entry must be prefixed with '-' in YAML. ""Run 'hermes doctor' for details.")return Nonecustom_providers = rp.get_compatible_custom_providers(config)- return _match_legacy_custom_provider(requested_norm, custom_providers) if custom_providers else None+ found = _match_legacy_custom_provider(requested_norm, custom_providers) if custom_providers else None+ return (found[0], _compatible_entry_path(config, found[1])) if found else None+++def _compatible_entry_path(config: dict[str, Any], entry: dict[str, Any]) -> Optional[tuple]:+ """Where a ``get_compatible_custom_providers`` entry lives in *config*. The view keeps the first+ of identical legacy entries, so the first raw entry normalizing to it is its source."""+ from hermes_cli.config_providers import _normalize_custom_provider_entry+ providers = config.get("providers")+ key = entry.get("provider_key")+ if key and isinstance(providers, dict):+ return next((("providers", k) for k in providers if str(k).strip() == key), None)+ legacy = config.get("custom_providers")+ return next((("custom_providers", i) for i, raw in enumerate(legacy if isinstance(legacy, list) else ())+ if _normalize_custom_provider_entry(raw) == entry), None)def has_named_custom_provider(requested_provider: str) -> bool:diff --git a/tests/gateway/test_config_policy_recovery.py b/tests/gateway/test_config_policy_recovery.pyindex 88b66b97c9f..b5ef66b26c2 100644--- a/tests/gateway/test_config_policy_recovery.py+++ b/tests/gateway/test_config_policy_recovery.py@@ -174,3 +174,43 @@ def test_an_unchanged_custom_providers_key_survives_a_restart(tmp_path, monkeypapolicy.config(owner())assert refused.value.field == 'custom_providers.0.api_key'assert 'changed in' in refused.value.detail+++def test_only_the_entry_the_runtime_selects_is_the_route(tmp_path, monkeypatch):+ """Two ``custom_providers`` entries share a name: the runtime routes through the FIRST, so+ rotating the unused second key leaves the session running (that key is simply not supplied);+ rotating the selected one refuses and names it."""+ from hermes_state_runtime import RuntimeStoreError+ cfg = {'model': {'provider': 'custom:shared', 'default': 'm'},+ 'custom_providers': [+ {'name': 'Shared', 'base_url': 'http://127.0.0.1:1111/v1', 'api_key': 'first-token'},+ {'name': 'Shared', 'base_url': 'http://127.0.0.1:2222/v1', 'api_key': 'second-token'}]}+ policy, owner, config_path = _bound_session(tmp_path, monkeypatch, cfg)++ cfg['custom_providers'][1]['api_key'] = 'rotated-second'+ config_path.write_text(json.dumps(cfg))+ config = policy.config(owner())+ assert config['custom_providers'][0]['api_key'] == 'first-token'+ assert config['custom_providers'][1]['api_key'] is None++ cfg['custom_providers'][0]['api_key'] = 'rotated-first'+ config_path.write_text(json.dumps(cfg))+ with pytest.raises(RuntimeStoreError) as refused:+ policy.config(owner())+ assert refused.value.field == 'custom_providers.0.api_key'+++def test_a_custom_prefixed_providers_key_is_the_route(tmp_path, monkeypatch):+ """``providers['custom:foo']`` is what ``model.provider: custom:foo`` resolves to at runtime; a+ rotated key there refuses by name instead of being silently dropped."""+ from hermes_state_runtime import RuntimeStoreError+ cfg = {'model': {'provider': 'custom:foo', 'default': 'm'},+ 'providers': {'custom:foo': {'base_url': 'http://127.0.0.1:1234/v1', 'api_key': 'foo-token'}}}+ policy, owner, config_path = _bound_session(tmp_path, monkeypatch, cfg)+ assert policy.config(owner())['providers']['custom:foo']['api_key'] == 'foo-token'++ cfg['providers']['custom:foo']['api_key'] = 'rotated-foo'+ config_path.write_text(json.dumps(cfg))+ with pytest.raises(RuntimeStoreError) as refused:+ policy.config(owner())+ assert refused.value.field == 'providers.custom:foo.api_key'