The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: resolve legacy provider picks in desktop sessions
KoNit-Ka47dcd6a1047
diff --git a/gateway/session_mutation_model.py b/gateway/session_mutation_model.pyindex ef29b6d99a8..26790b76a9e 100644--- a/gateway/session_mutation_model.py+++ b/gateway/session_mutation_model.py@@ -49,6 +49,7 @@ async def prepare_model(authority, live, payload, prepared):from hermes_cli.config import get_compatible_custom_providersold = restore_policy(prepared['snapshot']['receipt']['policy'])config, current = _current_route(authority, live, old)+ config = _provider_resolution_config(authority, config)def switch(**kwargs):result = switch_model(**kwargs)@@ -64,6 +65,7 @@ async def prepare_model(authority, live, payload, prepared):if refusal is not None:return refusalfrozen = old.config()+ provider_secrets = _freeze_selected_provider(config, frozen, result.target_provider)if old.follows_profile:# A following session switches FROM the profile's current route: measured from its creation# endpoint, a pick on the current one read as a route change and dropped its key_env pointer.@@ -101,6 +103,7 @@ async def prepare_model(authority, live, payload, prepared):# key is a private config secret at the alias entry's own path (what a restarted owner re-reads)# and the receipt keeps only a pointer to it, which config() projects into ``model.api_key``.key_env, source, alias_key = alias_credential+ key_env = key_env or _selected_provider_key_env(config, result.target_provider)if key_env:frozen['model']['key_env'] = key_envif source:@@ -110,6 +113,7 @@ async def prepare_model(authority, live, payload, prepared):# Creation identity (request_json) remains immutable; runtime selection lives in the policy.policy = replace(old, model=result.new_model, config_json=json.dumps(frozen))secrets = recover_config_secrets(authority, old) if old.config_secret_ref else {}+ secrets.update(provider_secrets)# A cleared field's private value must not be re-hydrated into the new route by config().secrets = {path: value for path, value in secrets.items()if not (len(path) == 2 and path[0] == 'model' and path[1] not in frozen['model'])}@@ -131,6 +135,84 @@ async def prepare_model(authority, live, payload, prepared):return dict(prepared, policy=asdict(policy))+def _provider_resolution_config(authority, config):+ """Supply current provider declarations to a legacy policy only for resolving a pick.++ Older local-session receipts can lack ``providers`` after their endpoint secrets were split out+ of the frozen config. The committed policy remains frozen; this read is only the same owning+ profile config that a new session would use to resolve the requested provider.+ """+ from pathlib import Path+ from gateway.run import _load_gateway_config+ current = _load_gateway_config(Path(authority.db.db_path).resolve().parent / 'config.yaml')+ if not isinstance(current, dict):+ return config+ resolved = dict(config)+ frozen_providers = config.get('providers')+ current_providers = current.get('providers')+ if isinstance(frozen_providers, dict) or isinstance(current_providers, dict):+ resolved['providers'] = {**(current_providers if isinstance(current_providers, dict) else {}),+ **(frozen_providers if isinstance(frozen_providers, dict) else {})}+ frozen_custom = config.get('custom_providers')+ current_custom = current.get('custom_providers')+ if isinstance(frozen_custom, list) or isinstance(current_custom, list):+ frozen_custom = list(frozen_custom) if isinstance(frozen_custom, list) else []+ names = {_custom_provider_name(entry) for entry in frozen_custom if isinstance(entry, dict)}+ resolved['custom_providers'] = frozen_custom + [+ entry for entry in (current_custom if isinstance(current_custom, list) else [])+ if not isinstance(entry, dict) or _custom_provider_name(entry) not in names]+ frozen_aliases = config.get('model_aliases')+ current_aliases = current.get('model_aliases')+ if isinstance(frozen_aliases, dict) or isinstance(current_aliases, dict):+ resolved['model_aliases'] = {**(current_aliases if isinstance(current_aliases, dict) else {}),+ **(frozen_aliases if isinstance(frozen_aliases, dict) else {})}+ return resolved+++def _custom_provider_name(entry):+ return str(entry.get('provider_key') or entry.get('name') or '').strip().lower()+++def _selected_provider_key_env(config, provider):+ """Return a selected ``providers.<slug>`` credential pointer, never its secret value."""+ providers = config.get('providers')+ entry = providers.get(provider) if isinstance(providers, dict) else None+ if not isinstance(entry, dict):+ return None+ return str(entry.get('key_env') or entry.get('api_key_env') or '').strip() or None+++def _freeze_selected_provider(config, frozen, provider):+ """Copy only a picked named provider's declaration into its frozen session route.++ A policy must resolve its next turn from its own configuration, not a later profile edit. Keep+ private provider fields in the policy's secret store, just as policy creation does.+ """+ from copy import deepcopy+ from gateway.session_policy import _extract_config_secrets+ from hermes_cli.runtime_provider_custom import named_custom_provider_config_path+ path = named_custom_provider_config_path(provider, config)+ if path is None:+ return {}+ section, index = path+ entries = config.get(section)+ if not isinstance(entries, (dict, list)) or not isinstance(entries[index], dict):+ return {}+ copied = deepcopy(entries[index])+ if section == 'providers':+ frozen_entries = dict(frozen.get(section) or {})+ frozen_entries[index] = copied+ frozen[section] = frozen_entries+ else:+ frozen_entries = list(frozen.get(section) or [])+ frozen_entries.append(copied)+ frozen[section] = frozen_entries+ index = len(frozen_entries) - 1+ secrets = {}+ _extract_config_secrets(frozen[section][index], secrets, (section, index))+ return secrets++def _alias_credential(authority, result):"""``(key_env, source_path, literal_key)`` the direct alias a switch resolved declares for its ownendpoint, read from THIS owner's config.yaml: the file a restarted owner re-reads, never thediff --git a/tests/gateway/test_session_mutation_model.py b/tests/gateway/test_session_mutation_model.pyindex 63b6f742c5b..2cab153c5b8 100644--- a/tests/gateway/test_session_mutation_model.py+++ b/tests/gateway/test_session_mutation_model.py@@ -226,6 +226,143 @@ async def test_provider_change_drops_the_launch_key_and_keeps_config_secrets(tmpassert switched.config(authority)['providers']['mine']['api_key'] == 'sk-config-secret'+async def test_model_pick_reads_current_provider_config_when_legacy_policy_lacks_it(tmp_path, monkeypatch):+ """Regression for #139740: a Desktop pick can outlive a policy written without ``providers``."""+ from dataclasses import asdict+ from types import SimpleNamespace+ from gateway.run_turn_prepare import _resolve_policy_agent_runtime+ from gateway.session_mutation_model import prepare_model+ from gateway.session_policy import build_policy, restore_policy+ from hermes_state import SessionDB+ from hermes_cli import model_switch++ (tmp_path / 'config.yaml').write_text(+ 'providers:\n'+ ' inkstone:\n'+ ' api: https://example.invalid/v1\n'+ ' key_env: INKSTONE_API_KEY\n'+ ' models: {glm-5.3: {context_length: 1048576}}\n')+ seen = {}++ def switch(**kwargs):+ seen.update(kwargs)+ return model_switch.ModelSwitchResult(+ success=True, new_model='glm-5.3', target_provider='inkstone',+ base_url='https://example.invalid/v1', api_mode='chat_completions')++ monkeypatch.setattr(model_switch, 'switch_model', switch)+ monkeypatch.setenv('INKSTONE_API_KEY', 'inkstone-secret')+ with SessionDB(tmp_path / 'state.db') as db:+ authority = SimpleNamespace(instance_id='i', epoch=1, profile_id='p', db=db)+ runner = SimpleNamespace(session_authority=authority,+ _resolve_session_agent_runtime=lambda **k: (None, {}))+ authority.runner = runner+ policy = build_policy({'cwd': str(tmp_path), 'model': 'old'}, {+ 'model': {'provider': 'deepseek', 'default': 'old'},+ 'providers': {'stale': {'base_url': 'https://stale.example.invalid/v1'}}})+ prepared = {'snapshot': {'receipt': {'session_id': 'sid', 'policy': asdict(policy)}}}++ committed = await prepare_model(authority, SimpleNamespace(source=None, route='r'), {+ 'model': 'glm-5.3', 'provider': 'inkstone'}, prepared)++ assert seen['user_providers']['inkstone']['key_env'] == 'INKSTONE_API_KEY'+ policy = restore_policy(committed['policy'])+ model = policy.config()['model']+ assert model['provider'] == 'inkstone'+ assert model['key_env'] == 'INKSTONE_API_KEY'+ _, runtime = _resolve_policy_agent_runtime(runner, policy)+ assert runtime['base_url'].rstrip('/') == 'https://example.invalid/v1'+ assert runtime['api_key'] == 'inkstone-secret'+++async def test_model_pick_freezes_legacy_custom_provider_for_the_next_runtime(tmp_path, monkeypatch):+ """A legacy ``custom_providers`` declaration must also survive a Desktop model pick."""+ from dataclasses import asdict+ from types import SimpleNamespace+ from gateway.run_turn_prepare import _resolve_policy_agent_runtime+ from gateway.session_mutation_model import prepare_model+ from gateway.session_policy import build_policy, restore_policy+ from hermes_state import SessionDB+ from hermes_cli import model_switch++ (tmp_path / 'config.yaml').write_text(+ 'custom_providers:\n'+ ' - name: inkstone\n'+ ' base_url: https://example.invalid/v1\n'+ ' key_env: INKSTONE_API_KEY\n', encoding='utf-8')+ seen = {}++ def switch(**kwargs):+ seen.update(kwargs)+ return model_switch.ModelSwitchResult(+ success=True, new_model='glm-5.3', target_provider='inkstone',+ base_url='https://example.invalid/v1', api_mode='chat_completions')++ monkeypatch.setattr(model_switch, 'switch_model', switch)+ monkeypatch.setenv('INKSTONE_API_KEY', 'inkstone-secret')+ with SessionDB(tmp_path / 'state.db') as db:+ authority = SimpleNamespace(instance_id='i', epoch=1, profile_id='p', db=db)+ runner = SimpleNamespace(session_authority=authority,+ _resolve_session_agent_runtime=lambda **k: (None, {}))+ authority.runner = runner+ policy = build_policy({'cwd': str(tmp_path), 'model': 'old'}, {+ 'model': {'provider': 'deepseek', 'default': 'old'}})+ prepared = {'snapshot': {'receipt': {'session_id': 'sid', 'policy': asdict(policy)}}}+ committed = await prepare_model(authority, SimpleNamespace(source=None, route='r'), {+ 'model': 'glm-5.3', 'provider': 'inkstone'}, prepared)++ assert seen['custom_providers'][0]['name'] == 'inkstone'+ _, runtime = _resolve_policy_agent_runtime(runner, restore_policy(committed['policy']))+ assert runtime['base_url'].rstrip('/') == 'https://example.invalid/v1'+ assert runtime['api_key'] == 'inkstone-secret'+++async def test_model_pick_keeps_a_nonfollowing_sessions_named_provider_frozen(tmp_path, monkeypatch):+ """A profile edit must not move an ordinary session's named endpoint on its next pick."""+ from dataclasses import asdict+ from types import SimpleNamespace+ from gateway.run_turn_prepare import _resolve_policy_agent_runtime+ from gateway.session_mutation_model import prepare_model+ from gateway.session_policy import build_policy, restore_policy+ from hermes_state import SessionDB+ from hermes_cli import model_switch++ (tmp_path / 'config.yaml').write_text(+ 'providers:\n'+ ' inkstone:\n'+ ' api: https://current.example.invalid/v1\n'+ ' key_env: CURRENT_KEY\n', encoding='utf-8')+ seen = {}++ def switch(**kwargs):+ seen.update(kwargs)+ return model_switch.ModelSwitchResult(+ success=True, new_model='new', target_provider='inkstone',+ base_url=kwargs['user_providers']['inkstone']['api'], api_mode='chat_completions')++ monkeypatch.setattr(model_switch, 'switch_model', switch)+ monkeypatch.setenv('FROZEN_KEY', 'frozen-secret')+ with SessionDB(tmp_path / 'state.db') as db:+ authority = SimpleNamespace(instance_id='i', epoch=1, profile_id='p', db=db)+ runner = SimpleNamespace(session_authority=authority,+ _resolve_session_agent_runtime=lambda **k: (None, {}))+ authority.runner = runner+ policy = build_policy({'cwd': str(tmp_path), 'model': 'old'}, {+ 'model': {'provider': 'deepseek', 'default': 'old'},+ 'providers': {'inkstone': {'api': 'https://frozen.example.invalid/v1', 'key_env': 'FROZEN_KEY'}}})+ prepared = {'snapshot': {'receipt': {'session_id': 'sid', 'policy': asdict(policy)}}}+ committed = await prepare_model(authority, SimpleNamespace(source=None, route='r'), {+ 'model': 'new', 'provider': 'inkstone'}, prepared)++ assert seen['user_providers']['inkstone']['key_env'] == 'FROZEN_KEY'+ _, runtime = _resolve_policy_agent_runtime(runner, restore_policy(committed['policy']))+ assert runtime['base_url'].rstrip('/') == 'https://frozen.example.invalid/v1'+ assert runtime['api_key'] == 'frozen-secret'++@pytest.mark.asyncioasync def test_committed_model_selection_is_the_next_resolved_runtime(tmp_path, monkeypatch):"""custom -> custom on a new origin: the committed policy and the next resolved runtime agree on