Skip to content

The agent that grows with you

fix: canonical model mutation commits the route the next turn actually runs

Teknium4492d033c584
diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.py
index bcdf5c1b0aa..30ce6a80300 100644
--- a/gateway/run_turn_prepare.py
+++ b/gateway/run_turn_prepare.py
@@ -32,8 +32,8 @@ from typing import Any, Callable, Dict, List, Optional, Tuple
from utils import base_url_hostname
if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
- from gateway.run import GatewayRunner # noqa: F401
- from gateway.run_turn_runner import TurnRunner # noqa: F401
+ from gateway.run import GatewayRunner
+ from gateway.run_turn_runner import TurnRunner
# Log-record parity with the origin module.
logger = logging.getLogger("gateway.run")
@@ -52,6 +52,12 @@ def _resolve_policy_agent_runtime(runner, policy) -> tuple[str, dict]:
frozen = policy.config(authority)
key = launch_key(authority, policy)
launch_url = json.loads(policy.request_json).get('base_url')
+ if launch_url:
+ # The creation request is immutable identity, not the current selection: once a canonical
+ # model mutation moved the route off the launch endpoint, the policy's selection wins.
+ from hermes_cli.route_identity import normalize_route_base_url
+ if normalize_route_base_url(launch_url) != normalize_route_base_url(policy.base_url):
+ launch_url = None
# Every rung reads the session's FROZEN config, never live config.yaml: a later
# ``model.base_url`` edit must not carry this route's frozen credential to the new host
# (R2-M2). The auth-store pool is not config, so refresh/rotation still applies.
@@ -659,7 +665,7 @@ class GatewayTurnPrepareMixin:
# Per-turn notes ride the user message via the api_content sidecar, NOT context_prompt
# (appending to the ephemeral system prompt forced a full agent rebuild).
- turn_sidecar_notes: List[str] = []
+ turn_sidecar_notes: list[str] = []
if _was_auto_reset:
await self._hmwa_deliver_auto_reset_notice(session_entry, source, turn_sidecar_notes)
diff --git a/gateway/session_mutation_model.py b/gateway/session_mutation_model.py
index 91d93dbaab5..415361838d3 100644
--- a/gateway/session_mutation_model.py
+++ b/gateway/session_mutation_model.py
@@ -9,7 +9,7 @@ from hermes_state_runtime import RuntimeStoreError
async def prepare_model(authority, live, payload, prepared):
from gateway.session_policy import restore_policy, launch_key, bind_launch_key
from gateway.session_policy_credentials import recover_config_secrets
- from hermes_cli.model_switch import switch_model
+ from hermes_cli.model_switch import apply_model_selection, selection_route_changed, switch_model
from hermes_cli.config import get_compatible_custom_providers
old = restore_policy(prepared['snapshot']['receipt']['policy'])
config = old.config(authority)
@@ -22,15 +22,22 @@ async def prepare_model(authority, live, payload, prepared):
if not result.success:
raise RuntimeStoreError('model_resolution_failed')
frozen = old.config()
- frozen.setdefault('model', {}).update(default=result.new_model, provider=result.target_provider,
- base_url=result.base_url)
- # Creation identity remains immutable; runtime selection lives in the policy.
+ # The one selection shape config.yaml gets (#25106): api_mode follows the target, a context pin
+ # and the endpoint-bound credential fields (inline key, key_env/api_key_env) drop on a route change.
+ # Off-loop: the context-pin check can do cold-start disk I/O.
+ frozen['model'] = await asyncio.to_thread(apply_model_selection, frozen.get('model'), result)
+ # 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 {}
+ # 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'])}
# Re-fingerprint frozen config references because policy identity includes model.
- # An explicit launch key cannot silently cross into a different provider.
+ # An explicit launch key belongs to the endpoint it authenticated, not to a provider name:
+ # custom -> custom on another base_url must not carry it (same route identity as config keys).
key = launch_key(authority, old)
- if result.provider_changed:
+ current = {'provider': old.provider, 'base_url': old.base_url or runtime.get('base_url') or ''}
+ if selection_route_changed(current, result):
policy = replace(policy, credential_ref=None)
key = None
policy = bind_launch_key(authority, prepared['snapshot']['receipt']['session_id'], policy, key,
diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.py
index 2bd402c2d4f..67e4ec488c0 100644
--- a/hermes_cli/model_switch.py
+++ b/hermes_cli/model_switch.py
@@ -1790,7 +1790,7 @@ def model_selection_config_updates(result: ModelSwitchResult, current_model_cfg:
model_cfg.get("base_url"), result.base_url, model_cfg.get("provider"), result.target_provider):
updates["context_length"] = None
target = str(result.target_provider or "").strip().lower()
- route_changed = _route_changed(model_cfg, result)
+ route_changed = selection_route_changed(model_cfg, result)
stale = ["api_key", "api"] if (not target.startswith("custom") or route_changed) else []
if route_changed:
stale += ["key_env", "api_key_env"]
@@ -1800,8 +1800,9 @@ def model_selection_config_updates(result: ModelSwitchResult, current_model_cfg:
return updates
-def _route_changed(model_cfg: dict, result: ModelSwitchResult) -> bool:
- """Provider or endpoint differs between the on-disk ``model:`` block and the switch target."""
+def selection_route_changed(model_cfg: dict, result: ModelSwitchResult) -> bool:
+ """Provider or endpoint differs between a ``model:`` block and the switch target. The one
+ route-identity test for endpoint-bound credentials (inline keys, ``key_env``, launch keys)."""
from hermes_cli.route_identity import normalize_route_base_url
if str(model_cfg.get("provider") or "").strip().lower() != str(result.target_provider or "").strip().lower():
return True
diff --git a/tests/gateway/test_session_mutation_model.py b/tests/gateway/test_session_mutation_model.py
index cea358c3600..5b872bc8b4f 100644
--- a/tests/gateway/test_session_mutation_model.py
+++ b/tests/gateway/test_session_mutation_model.py
@@ -119,7 +119,7 @@ async def test_input_queued_while_a_model_receipt_commits_still_runs(tmp_path, m
from gateway.session_contract import Submission
from gateway.session_controls import AuthorityConnection
from gateway.session_local import create_local_session
- import hermes_cli.model_switch as model_switch
+ from hermes_cli import model_switch
import hermes_state_runtime as rt
monkeypatch.setattr(run, '_load_gateway_config', lambda *a: {})
monkeypatch.setattr(model_switch, 'switch_model', lambda **k: model_switch.ModelSwitchResult(
@@ -171,7 +171,7 @@ async def test_provider_change_drops_the_launch_key_and_keeps_config_secrets(tmp
from gateway.session_mutation_model import prepare_model
from gateway.session_policy import bind_launch_key, build_policy, restore_policy
from hermes_state import SessionDB
- import hermes_cli.model_switch as model_switch
+ from hermes_cli import model_switch
monkeypatch.setattr(model_switch, 'switch_model', lambda **k: model_switch.ModelSwitchResult(
success=True, new_model='b', target_provider='anthropic', provider_changed=True,
base_url='https://api.anthropic.com'))
@@ -189,3 +189,48 @@ async def test_provider_change_drops_the_launch_key_and_keeps_config_secrets(tmp
{'model': 'b', 'provider': 'anthropic'}, prepared))['policy'])
assert switched.credential_ref is None, 'the launch key crossed into another provider'
assert switched.config(authority)['providers']['mine']['api_key'] == 'sk-config-secret'
+
+
+async 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
+ endpoint, protocol and credentials. The creation request's launch URL, the old endpoint's launch
+ key, its key_env pointer, api_mode and context pin must not survive; a same-route re-pick keeps them."""
+ 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 bind_launch_key, build_policy, restore_policy
+ from hermes_state import SessionDB
+ from hermes_cli import model_switch
+ old_url, new_url = 'http://127.0.0.1:9/v1', 'http://127.0.0.2:9/v1'
+ 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, {'api_key': 'sk-endpoint-a'}))
+ authority.runner = runner
+ config = {'model': {'provider': 'custom', 'default': 'a', 'base_url': old_url, 'api_mode': 'chat_completions',
+ 'context_length': 4096, 'key_env': 'ENDPOINT_A_KEY'}}
+ private = {}
+ policy = build_policy({'cwd': str(tmp_path), 'model': 'a', 'provider': 'custom', 'base_url': old_url,
+ 'api_key': 'sk-endpoint-a'}, config, private_secrets=private)
+ policy = bind_launch_key(authority, 'sid', policy, 'sk-endpoint-a', config_secrets=private)
+ prepared = {'snapshot': {'receipt': {'session_id': 'sid', 'policy': asdict(policy)}}}
+
+ async def switch(url, mode):
+ monkeypatch.setattr(model_switch, 'switch_model', lambda **k: model_switch.ModelSwitchResult(
+ success=True, new_model='b', target_provider='custom', base_url=url, api_mode=mode))
+ switched = restore_policy((await prepare_model(authority, SimpleNamespace(source=None, route='r'),
+ {'model': 'b'}, prepared))['policy'])
+ return switched, _resolve_policy_agent_runtime(runner, switched)[1]
+
+ moved, runtime = await switch(new_url, 'anthropic_messages')
+ committed = moved.config()['model']
+ assert (committed['base_url'], committed['api_mode']) == (new_url, 'anthropic_messages')
+ assert 'context_length' not in committed and 'key_env' not in committed
+ assert moved.credential_ref is None, "endpoint A's launch key crossed to another origin"
+ assert (runtime['base_url'].rstrip('/'), runtime['api_mode']) == (new_url, 'anthropic_messages')
+ assert runtime['api_key'] != 'sk-endpoint-a'
+ same, runtime = await switch(old_url, 'chat_completions')
+ assert same.credential_ref is not None and same.config()['model']['key_env'] == 'ENDPOINT_A_KEY'
+ assert (runtime['base_url'].rstrip('/'), runtime['api_key']) == (old_url, 'sk-endpoint-a')