Skip to content

The agent that grows with you

fix(gateway): a picked legacy custom provider survives a profile reorder on cold start

Tekniume4e8f9bbc92d
diff --git a/gateway/session_policy_credentials.py b/gateway/session_policy_credentials.py
index 2b5f2a9b816..555f0cdfd05 100644
--- a/gateway/session_policy_credentials.py
+++ b/gateway/session_policy_credentials.py
@@ -266,8 +266,12 @@ def recover_config_secrets(authority, policy, skip=None):
config = _load_gateway_config(home / 'config.yaml') if any(path[0] is not None for path, _ in entries) else {}
route = None # computed on the first mismatch only: an unchanged source never needs it
values, dropped = RecoveredSecrets(), []
+ frozen = None # parsed on the first legacy entry only
for path, fingerprint in entries:
value, lookup = config, path
+ if path[0] == 'custom_providers' and len(path) > 2 and type(path[1]) is int:
+ frozen = json.loads(policy.config_json) if frozen is None else frozen
+ lookup = _current_custom_path(frozen, config, path)
if path[0] is None:
from tools.terminal_scope import build_profile_terminal_scope
value, lookup = build_profile_terminal_scope(home), path[1:]
@@ -297,6 +301,31 @@ def recover_config_secrets(authority, policy, skip=None):
detail=f'unreadable ({type(exc).__name__})') from exc
+def _current_custom_path(frozen, config, path):
+ """*path* (``custom_providers[i]...``, an index into the frozen list) re-pointed at the profile's
+ entry of the SAME canonical identity (``custom_provider_slug``), wherever a reorder moved it.
+ An entry the profile no longer declares maps to no index (absent), never to whatever entry now
+ sits at ``i``. A frozen entry with no name has no identity: its index is all there is."""
+ from hermes_cli.providers import custom_provider_slug
+
+ def identity(entry):
+ if not isinstance(entry, dict) or not (entry.get('name') or entry.get('provider_key')):
+ return None
+ return custom_provider_slug(str(entry.get('name') or ''), str(entry.get('provider_key') or ''))
+
+ held = frozen.get('custom_providers')
+ mine = identity(held[path[1]]) if isinstance(held, list) and 0 <= path[1] < len(held) else None
+ current = config.get('custom_providers')
+ if mine is None or not isinstance(current, list):
+ return path
+ if 0 <= path[1] < len(current) and identity(current[path[1]]) == mine:
+ return path # unmoved (also keeps a duplicate-named later entry on its own index)
+ for index, entry in enumerate(current):
+ if identity(entry) == mine: # the first match, as the runtime's own name lookup takes
+ return (path[0], index, *path[2:])
+ return (path[0], len(current), *path[2:]) # gone: past the end reads as absent
+
+
def _entry_owner_path(entry, config):
"""The ``providers:`` / ``custom_providers:`` entry a fallback entry authenticates through."""
from hermes_cli.runtime_provider_custom import (custom_provider_config_path_for_url,
diff --git a/tests/gateway/test_session_mutation_model.py b/tests/gateway/test_session_mutation_model.py
index bb3f7394991..9b2d871324b 100644
--- a/tests/gateway/test_session_mutation_model.py
+++ b/tests/gateway/test_session_mutation_model.py
@@ -433,6 +433,54 @@ async def test_model_pick_freezes_legacy_custom_provider_for_the_next_runtime(tm
assert runtime['api_key'] == 'inkstone-secret'
+async def test_picked_legacy_custom_provider_survives_a_profile_reorder_on_cold_start(tmp_path, monkeypatch):
+ """MP-17: the picked ``custom_providers`` entry's key is recovered on a cold start by the entry's
+ canonical identity, not its list index. A reorder (or a respelled name) still runs with the picked
+ entry's own key; a deleted entry refuses by name and never borrows the entry now at that index."""
+ 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_state_runtime import RuntimeStoreError
+ from hermes_cli import model_switch
+
+ other = ' - name: other\n base_url: https://other.example.invalid/v1\n api_key: sk-other\n'
+ picked = ' - name: {name}\n base_url: https://inkstone.example.invalid/v1\n api_key: sk-inkstone\n'
+ config = tmp_path / 'config.yaml'
+ config.write_text('custom_providers:\n' + other + picked.format(name='inkstone'), encoding='utf-8')
+ monkeypatch.setattr(model_switch, 'switch_model', lambda **k: model_switch.ModelSwitchResult(
+ success=True, new_model='glm-5.3', target_provider='inkstone',
+ base_url='https://inkstone.example.invalid/v1', api_mode='chat_completions'))
+ with SessionDB(tmp_path / 'state.db') as db:
+ def owner(): # a fresh owner: no in-memory secrets, everything re-read from config.yaml
+ authority = SimpleNamespace(instance_id='i', epoch=1, profile_id='p', db=db)
+ authority.runner = SimpleNamespace(session_authority=authority,
+ _resolve_session_agent_runtime=lambda **k: (None, {}))
+ return authority
+ authority = owner()
+ policy = build_policy({'cwd': str(tmp_path), 'model': 'old'}, {
+ 'model': {'provider': 'deepseek', 'default': 'old'}})
+ prepared = {'snapshot': {'receipt': {'session_id': 'sid', 'policy': asdict(policy)}}}
+ switched = restore_policy((await prepare_model(authority, SimpleNamespace(source=None, route='r'), {
+ 'model': 'glm-5.3', 'provider': 'inkstone'}, prepared))['policy'])
+ assert switched.config_secret_ref.startswith('profile-config-v1:')
+
+ for spelling in ('inkstone', 'Inkstone'):
+ config.write_text('custom_providers:\n' + picked.format(name=spelling) + other, encoding='utf-8')
+ cold = owner()
+ _, runtime = _resolve_policy_agent_runtime(cold.runner, switched)
+ assert runtime['base_url'].rstrip('/') == 'https://inkstone.example.invalid/v1', spelling
+ assert runtime['api_key'] == 'sk-inkstone', spelling
+
+ config.write_text('custom_providers:\n' + other + other.replace('other', 'third'), encoding='utf-8')
+ with pytest.raises(RuntimeStoreError) as refused:
+ switched.config(owner())
+ assert refused.value.reason == 'launch_credentials_unavailable'
+
+
@pytest.mark.asyncio
async def test_model_pick_resolves_the_profiles_current_entry_over_a_frozen_one(tmp_path, monkeypatch):
"""A pick is an explicit user action: a slug the session froze earlier resolves to the profile's