The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a pick's displaced legacy entry keeps its own secrets
Tekniuma84f1f9e724a
diff --git a/gateway/session_mutation_model.py b/gateway/session_mutation_model.pyindex 52d1b2b05a2..2a95acc8020 100644--- a/gateway/session_mutation_model.py+++ b/gateway/session_mutation_model.py@@ -70,7 +70,7 @@ async def prepare_model(authority, live, payload, prepared):return refusalfrozen = old.config()# The committed selection freezes the ONE picked endpoint (its key stays a private secret).- provider_secrets, retired = ({}, ()) if old.follows_profile else _freeze_selected_provider(+ provider_secrets, retired, moved = ({}, (), {}) if old.follows_profile else _freeze_selected_provider(resolution, frozen, result.target_provider)if old.follows_profile:# A following session switches FROM the profile's current route: measured from its creation@@ -121,6 +121,8 @@ async def prepare_model(authority, live, payload, prepared):secrets = recover_config_secrets(authority, old) if old.config_secret_ref else {}# The picked entry's private subtree is replaced whole: a key or header its current declaration# withdrew must not follow it to the new endpoint.+ # An unrelated entry the pick displaced carries its own secrets to its new index.+ secrets = {moved.get(path[:2], path[:2]) + path[2:]: value for path, value in secrets.items()}secrets = {path: value for path, value in secrets.items() if path[:2] not in retired}secrets.update(provider_secrets)# A cleared field's private value must not be re-hydrated into the new route by config().@@ -194,21 +196,22 @@ def _freeze_selected_provider(config, frozen, provider):The next turn resolves from the session's own configuration, not a later profile edit. Privatefields move to the policy's secret store, as policy creation does; nothing else moves. Returns``(secrets, retired)``: the entry's private values and every ``(section, key)`` whose previous- private subtree they replace. A legacy entry from the profile is frozen at its profile index (the- path cold recovery re-reads); an equivalent earlier spelling is blanked, never left to win.+ private subtree they replace, plus ``moved``: ``{old (section, index): new}`` for an unrelated entry+ the pick displaced. A legacy entry from the profile is frozen at its profile index (the path cold+ recovery re-reads); an equivalent earlier spelling is blanked, never left to win."""from copy import deepcopyfrom gateway.session_policy import _extract_config_secretsfrom hermes_cli.runtime_provider_custom import named_custom_provider_config_pathpath = named_custom_provider_config_path(provider, config)if path is None:- return {}, ()+ return {}, (), {}section, index = pathentries = config.get(section)if not isinstance(entries, (dict, list)) or not isinstance(entries[index], dict):- return {}, ()+ return {}, (), {}copied = deepcopy(entries[index])- retired = {(section, index)}+ retired, moved = {(section, index)}, {}if section == 'providers':frozen[section] = {**(frozen.get(section) if isinstance(frozen.get(section), dict) else {}), index: copied}else:@@ -221,7 +224,8 @@ def _freeze_selected_provider(config, frozen, provider):frozen_entries += [{}] * (index + 1 - len(frozen_entries))displaced = frozen_entries[index]if isinstance(displaced, dict) and displaced and _custom_provider_name(displaced) != name:- frozen_entries.append(displaced) # still resolvable by name; its index-bound secrets retire+ moved[(section, index)] = (section, len(frozen_entries))+ frozen_entries.append(displaced) # still resolvable by name, with its own secretsfor i in same:frozen_entries[i] = {}frozen_entries[index] = copied@@ -229,7 +233,7 @@ def _freeze_selected_provider(config, frozen, provider):frozen[section] = frozen_entriessecrets = {}_extract_config_secrets(frozen[section][index], secrets, (section, index))- return secrets, retired+ return secrets, retired, moveddef _alias_credential(authority, result):diff --git a/tests/gateway/test_session_mutation_model_provider_identity.py b/tests/gateway/test_session_mutation_model_provider_identity.pynew file mode 100644index 00000000000..abf3ca72a99--- /dev/null+++ b/tests/gateway/test_session_mutation_model_provider_identity.py@@ -0,0 +1,58 @@+"""A model pick freezes only the picked provider: an unrelated legacy entry it displaces keeps its+own secret (real policy/resolver, warm and cold)."""+from copy import deepcopy+from dataclasses import asdict+import json+from types import SimpleNamespace++import pytest+++async def _pick(tmp_path, monkeypatch, before, after, provider):+ """``(warm_config, warm_runtime, cold_config, cold_runtime, frozen_config_json)``."""+ from gateway.session_mutation_model import prepare_model+ from gateway.session_policy import build_policy, bind_launch_key, restore_policy+ from gateway.run_turn_prepare import _resolve_policy_agent_runtime+ from hermes_state import SessionDB+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ (tmp_path / 'config.yaml').write_text(json.dumps(before))+ private = {}+ policy = build_policy({'cwd': str(tmp_path), 'model': 'original'}, deepcopy(before), private_secrets=private)+ with SessionDB(tmp_path / 'state.db') as db:+ authority = SimpleNamespace(instance_id='review', epoch=1, profile_id='review', db=db)+ runner = SimpleNamespace(session_authority=authority)+ authority.runner = runner+ policy = bind_launch_key(authority, 'sid', policy, None, config_secrets=private)+ runner._resolve_session_agent_runtime = lambda **k: _resolve_policy_agent_runtime(runner, policy, fallback=False)+ (tmp_path / 'config.yaml').write_text(json.dumps(after))+ prepared = {'snapshot': {'receipt': {'session_id': 'sid', 'policy': asdict(policy)}}}+ committed = await prepare_model(authority, SimpleNamespace(source=None, route='r'),+ {'model': 'switched', 'provider': provider}, prepared)+ new = restore_policy(committed['policy'])+ warm_cfg = new.config(authority)+ _, warm = _resolve_policy_agent_runtime(runner, new, fallback=False)+ authority._local_config_secrets = {} # a cold owner re-reads the profile's own paths+ cold_cfg = new.config(authority)+ _, cold = _resolve_policy_agent_runtime(runner, new, fallback=False)+ return warm_cfg, warm, cold_cfg, cold, json.loads(new.config_json)+++def _entry(cfg, name):+ return next(e for e in cfg['custom_providers'] if isinstance(e, dict) and e.get('name') == name)+++async def test_displaced_unchanged_legacy_entry_keeps_its_key(tmp_path, monkeypatch):+ """Frozen [X]; the profile inserts Y before an unchanged X and the user picks Y: X (still a+ fallback) keeps its own key warm and cold, and Y runs with Y's key."""+ x = {'name': 'x-prov', 'base_url': 'http://127.0.0.1:9/x', 'api_key': 'x-review-key'}+ y = {'name': 'y-prov', 'base_url': 'http://127.0.0.1:9/y', 'api_key': 'y-review-key'}+ before = {'model': {'provider': 'custom:x-prov', 'default': 'original'}, 'custom_providers': [x],+ 'fallback_providers': [{'provider': 'custom:x-prov', 'model': 'original'}]}+ after = {**before, 'custom_providers': [y, x]}+ warm_cfg, warm, cold_cfg, cold, _ = await _pick(tmp_path, monkeypatch, before, after, 'custom:y-prov')+ assert (warm['base_url'], warm['api_key']) == (y['base_url'], 'y-review-key')+ assert (cold['base_url'], cold['api_key']) == (y['base_url'], 'y-review-key')+ assert _entry(warm_cfg, 'x-prov')['api_key'] == 'x-review-key'+ assert _entry(cold_cfg, 'x-prov')['api_key'] == 'x-review-key'+