The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: canonical model mutation runs the shared selection guards before committing
Teknium82f24b0cf01f
diff --git a/gateway/session_mutation_model.py b/gateway/session_mutation_model.pyindex 415361838d3..e2aadf1eb94 100644--- a/gateway/session_mutation_model.py+++ b/gateway/session_mutation_model.py@@ -21,6 +21,9 @@ async def prepare_model(authority, live, payload, prepared):custom_providers=get_compatible_custom_providers(config))if not result.success:raise RuntimeStoreError('model_resolution_failed')+ refusal = await _selection_guard_refusal(authority, live, payload, prepared['snapshot'], old, result, runtime)+ if refusal is not None:+ return refusalfrozen = old.config()# 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.@@ -43,3 +46,39 @@ async def prepare_model(authority, live, payload, prepared):policy = bind_launch_key(authority, prepared['snapshot']['receipt']['session_id'], policy, key,config_secrets=secrets)return dict(prepared, policy=asdict(policy))+++async def _selection_guard_refusal(authority, live, payload, snapshot, old, result, runtime):+ """The shared selection-guard registry (cost, data-policy, large-context switch) runs before the+ commit. A flagged target is refused with ``status: confirmation_required`` and a ``confirm``+ token bound to the resolved target, the selection it replaces and the session revision; nothing+ is written. Only that exact token in ``payload['confirm']`` applies it: a stale or foreign+ token (target re-resolved elsewhere, another switch landed, a turn settled) gets a fresh+ refusal, never a silent apply."""+ import hashlib+ from hermes_cli.model_selection_guards import combined_message, selection_context_for_agent, selection_warnings+ from hermes_cli.route_identity import normalize_route_base_url+ lookup = (getattr(authority.runner, '_resident_agent_for', None)+ or getattr(authority.runner, '_cached_agent_for', None))+ agent = lookup(live.route) if live is not None and callable(lookup) else None+ # Off-loop: pricing lookups may hit models.dev on a cache miss.+ warnings = await asyncio.to_thread(+ selection_warnings, result.new_model, provider=result.target_provider,+ base_url=result.base_url or old.base_url or '', api_key=result.api_key or runtime.get('api_key') or '',+ model_info=result.model_info, selection_context=selection_context_for_agent(agent))+ if not warnings:+ return None+ binding = {'target': [result.new_model, result.target_provider, normalize_route_base_url(result.base_url),+ result.api_mode or ''],+ 'current': [old.model, old.provider or '', normalize_route_base_url(old.base_url)],+ 'session': [snapshot['target'], snapshot['target_revision']],+ 'guards': sorted(w.kind for w in warnings)}+ token = hashlib.sha256(json.dumps(binding, sort_keys=True).encode()).hexdigest()+ if payload.get('confirm') == token:+ return None+ # A fresh dict: the prepared snapshot carries the frozen policy and never leaves the owner. No+ # ``model`` key: a client that predates the exchange must not paint the target as applied.+ return {'status': 'confirmation_required', 'confirm_required': True, 'confirm': token,+ 'target_model': result.new_model, 'target_provider': result.target_provider,+ 'confirm_message': combined_message(warnings),+ 'warnings': [{'kind': w.kind, 'title': w.title, 'message': w.message} for w in warnings]}diff --git a/gateway/session_mutations.py b/gateway/session_mutations.pyindex 301b1fa7b06..d224394a1b9 100644--- a/gateway/session_mutations.py+++ b/gateway/session_mutations.py@@ -129,8 +129,9 @@ async def _mutate_session(authority, actor, ref, params):prepare = {'model': prepare_model, 'compress': prepare_compress}[operation]prepared = await prepare(authority, live, params['payload'], prepared)applied = False- if prepared.get('status') == 'preview':- # ``--preview`` is a read-only report: no receipt, no publication, no eviction.+ if prepared.get('status') in {'preview', 'confirmation_required'}:+ # ``--preview`` is a read-only report and a guarded model target awaits the user's+ # confirmation: no receipt, no publication, no eviction.return {'session_id': ref.session_id, 'operation': operation, **prepared}if prepared is not None and 'snapshot' not in prepared:# Exact retry: the durable receipt is the result. Never re-prepare (compressdiff --git a/hermes_cli/gateway_mutations.py b/hermes_cli/gateway_mutations.pyindex 7c472e2e5a6..4fb4bfb80cf 100644--- a/hermes_cli/gateway_mutations.py+++ b/hermes_cli/gateway_mutations.py@@ -29,6 +29,13 @@ class PreparedMutations:'unsupported_compress_options'}:self.pending.pop(key)raise+ if entry['result'].get('status') == 'confirmation_required':+ # The owner wrote nothing: a guarded model target needs the user's confirmation+ # (payload ``confirm`` = the returned token). These surfaces cannot collect it+ # yet, so say so instead of reporting the switch as done.+ self.pending.pop(key)+ raise GatewayClientError(entry['result']['confirm_message'] + '\n\nModel not switched: '+ 'this target needs a confirmation this client cannot collect yet.')return entry['result']def acknowledge(self, session_id, operation, payload):diff --git a/hermes_state_mutations.py b/hermes_state_mutations.pyindex 05332456520..18e6bdb11e6 100644--- a/hermes_state_mutations.py+++ b/hermes_state_mutations.py@@ -8,7 +8,8 @@ METADATA_FIELDS = {'title': str, 'archived': bool, 'hidden': bool, 'pinned': boodef validate_action(operation, payload):if not isinstance(payload, dict) or not isinstance(operation, str):raise RuntimeStoreError('invalid_params')- if (operation == 'model' and 'model' in payload and not set(payload) - {'model', 'provider'}+ # ``confirm``: the owner's selection-guard token for this exact resolved target (session_mutation_model).+ if (operation == 'model' and 'model' in payload and not set(payload) - {'model', 'provider', 'confirm'}and all(isinstance(v, str) and v.strip() for v in payload.values())):returnif operation == 'branch' and (not payload or (set(payload) == {'title'} and isinstance(payload['title'], str))):diff --git a/tests/gateway/test_session_mutation_model.py b/tests/gateway/test_session_mutation_model.pyindex 5b872bc8b4f..ca018566324 100644--- a/tests/gateway/test_session_mutation_model.py+++ b/tests/gateway/test_session_mutation_model.py@@ -234,3 +234,70 @@ async def test_committed_model_selection_is_the_next_resolved_runtime(tmp_path,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')+++async def test_guarded_model_target_commits_only_with_its_confirmation_token(tmp_path, monkeypatch):+ """The shared selection guards run before the commit: an unconfirmed (or wrongly confirmed)+ guarded target writes nothing; its own token applies it exactly once; a token for another+ target or a superseded selection gets a fresh decision."""+ from types import SimpleNamespace+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import SessionAuthority+ from gateway.session_controls import AuthorityConnection+ from gateway.session_local import create_local_session+ from hermes_cli import model_cost_guard, 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(+ success=True, new_model=k['raw_input'], target_provider='custom', base_url='http://127.0.0.1:9/v1'))+ monkeypatch.setattr(model_cost_guard, 'expensive_model_warning', lambda model, **k: (+ model_cost_guard.ExpensiveModelWarning(model, 'custom', None, None, 'test', f'{model} IS EXPENSIVE')+ if model.startswith('pricey') else None))+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ db = store._db+ runner = SimpleNamespace(session_store=store, _session_db=db, adapters={}, _draining=False,+ _evict_cached_agent=lambda route: None, _cached_agent_for=lambda route: None,+ _resolve_session_agent_runtime=lambda **k: ('frozen', {}))+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)+ authority = SessionAuthority(runner, profile_id='owned', instance_id='owner', db=db,+ epoch=rt.begin_runtime_epoch(db, instance_id='owner'))+ owner = AuthorityConnection(authority, object(), {'user_id': 'human'})+ ref = create_local_session(authority, owner.actor, dict(request_id='m', source='cli', cwd=str(tmp_path),+ model='frozen', toolsets=[]))+ calls = iter(range(100))++ async def mutate(payload, retry=None):+ snap = db.get_session(ref.session_id)+ params = retry or {'session_id': ref.session_id, 'request_id': f'switch-{next(calls)}', 'operation': 'model',+ 'payload': payload, 'expected_revision': snap['runtime_revision'],+ 'expected_generation': snap['runtime_generation']}+ response = await owner.dispatch({'id': 1, 'method': 'session.mutate', 'params': params})+ assert 'result' in response, response+ return response['result'], params++ def state():+ row = db.get_session(ref.session_id)+ return row['runtime_revision'], row['runtime_generation'], row['model'], authority.sessions[ref.session_id]+ try:+ before = state()+ refused, _ = await mutate({'model': 'pricey'})+ assert refused['status'] == 'confirmation_required' and 'pricey IS EXPENSIVE' in refused['confirm_message']+ assert 'model' not in refused, 'a refusal must not read as an applied switch'+ wrong, _ = await mutate({'model': 'pricey', 'confirm': '0' * 64})+ other, _ = await mutate({'model': 'pricey-xl', 'confirm': refused['confirm']})+ assert wrong['status'] == other['status'] == 'confirmation_required'+ assert other['confirm'] != refused['confirm'], 'a token must not carry to another target'+ assert state() == before, 'an unconfirmed selection changed revision/generation/policy'+ confirmed = {'model': 'pricey', 'confirm': refused['confirm']}+ applied, params = await mutate(confirmed)+ assert applied['model'] == 'pricey' and applied['execution_generation'] == before[1] + 1+ assert (await mutate(confirmed, params))[0] == applied # exact retry: applied once+ assert db.get_session(ref.session_id)['runtime_generation'] == before[1] + 1+ stale, _ = await mutate(confirmed) # same target, but the selection it replaced is gone+ assert stale['status'] == 'confirmation_required' and stale['confirm'] != refused['confirm']+ finally:+ await owner.close()+ store.close_all_db_handles()