The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): keep a local session's endpoint and key together on a model pick
David Dudok de Wit4dad395c27f8
diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.pyindex e780514c6e3..664a5264f99 100644--- a/gateway/run_turn_prepare.py+++ b/gateway/run_turn_prepare.py@@ -39,19 +39,21 @@ if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)logger = logging.getLogger("gateway.run")-def _resolve_policy_agent_runtime(runner, policy) -> tuple[str, dict]:+def _resolve_policy_agent_runtime(runner, policy, *, fallback=True) -> tuple[str, dict]:"""``_resolve_session_agent_runtime`` for a session bound to a launch policy: the route's FROZEN- config and launch credential, walking its own fallback chain on an AuthError. Module-level so- tests that bind the method onto bare namespaces still reach it."""+ config and launch credential, walking its own fallback chain on an AuthError unless+ ``fallback=False`` (a session control asking which route the session itself runs). Module-level+ so tests that bind the method onto bare namespaces still reach it."""from gateway.run import _runtime_agent_kwargs- from gateway.session_policy import launch_key+ from gateway.session_policy import route_launch_keyfrom gateway.session_worker_construct import route_runtimefrom gateway.session_authorities import active_authorityauthority = active_authority(runner)# A follow_profile_config session's route is the profile's current one, model and endpoint from one read.frozen, model = policy.effective(authority)provider = (frozen.get('model') or {}).get('provider')- runtime, fallback_entry = route_runtime(policy, frozen, model, launch_key(authority, policy))+ runtime, fallback_entry = route_runtime(policy, frozen, model, route_launch_key(authority, policy, frozen),+ fallback=fallback)if fallback_entry is not None:from hermes_cli.fallback_config import pre_agent_fallback_noticerunner._pre_agent_fallback_notice = pre_agent_fallback_notice(@@ -91,12 +93,13 @@ def _recover_or_remember_model(runner, skey, model):class GatewayTurnPrepareMixin:def _resolve_session_agent_runtime(self, *, source: Optional[SessionSource] = None, session_key: Optional[str] = None,- user_config: Optional[dict] = None,+ user_config: Optional[dict] = None, fallback: bool = True,) -> tuple[str, dict]:"""Resolve model/runtime for a session.Priority (highest first): session ``/model`` → ``channel_overrides`` → global config/env- (``_resolve_gateway_model(user_config)`` and default provider resolution)."""+ (``_resolve_gateway_model(user_config)`` and default provider resolution). ``fallback=False``+ keeps a launch-policy session on its own route (see ``_resolve_policy_agent_runtime``)."""from gateway.run import (_credential_pool_for_provider, _get_channel_override, _resolve_gateway_model,_resolve_runtime_agent_kwargs, _resolve_runtime_agent_kwargs_for_provider,@@ -107,7 +110,7 @@ class GatewayTurnPrepareMixin:self._pre_agent_fallback_notice = Nonepolicy = policy_for_source(self, source) if source is not None else Noneif policy is not None:- return _resolve_policy_agent_runtime(self, policy)+ return _resolve_policy_agent_runtime(self, policy, fallback=fallback)skey = self._resolve_session_key_or_none(source, session_key)model = _resolve_gateway_model(user_config)if skey:diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.pyindex 6c99f05d989..587071d9eb2 100644--- a/gateway/session_managed_worker.py+++ b/gateway/session_managed_worker.py@@ -55,7 +55,7 @@ def managed_policy(authority, ref):def _bootstrap(authority, ref, row, policy, scope, text=None):from gateway.session_ingress import row_turn_author- from gateway.session_policy import launch_key+ from gateway.session_policy import route_launch_keyfrom gateway.session_policy_credentials import recover_config_secretsterminal = json.loads(policy.terminal_json)if policy.config_secret_ref:@@ -73,10 +73,11 @@ def _bootstrap(authority, ref, row, policy, scope, text=None):**({'display_v1': row['payload']['display_v1']} if row['payload'].get('display_v1') else {})})from gateway.session_worker_construct import construct_inputsrequest['construct_v1'] = construct_inputs(authority, policy, live.source.chat_id)- hydrated = replace(policy, config_json=json.dumps(_worker_config(authority, policy)), request_json=json.dumps(request),+ config = _worker_config(authority, policy)+ hydrated = replace(policy, config_json=json.dumps(config), request_json=json.dumps(request),terminal_json=json.dumps(terminal), credential_ref=None, config_secret_ref=None)return {'version': 1, 'home': authority.profile_id, 'scope': scope,- 'policy': asdict(hydrated), 'api_key': launch_key(authority, policy),+ 'policy': asdict(hydrated), 'api_key': route_launch_key(authority, policy, config),'text': row['payload']['text'] if text is None else text, 'route': live.route,**({'attachments_v1': row['payload']['attachments_v1']} if 'attachments_v1' in row['payload'] else {}),'user_id': live.source.user_id, 'chat_id': live.source.chat_id,diff --git a/gateway/session_mutation_model.py b/gateway/session_mutation_model.pyindex 1d1c24ef339..6a1a0bd0934 100644--- a/gateway/session_mutation_model.py+++ b/gateway/session_mutation_model.py@@ -2,30 +2,64 @@import asyncioimport jsonfrom dataclasses import asdict, replace+from typing import NamedTuplefrom hermes_state_runtime import RuntimeStoreError+class _Route(NamedTuple):+ provider: str+ model: str+ base_url: str+ api_key: object # a callable bearer (Azure Entra) stays callable+++def _current_route(authority, live, old):+ """``(config, route)`` the session runs now, both from ONE read of the owning profile.++ A following session runs the profile's current route, so its frozen creation endpoint beside+ the current key would send that key to a host the profile left. Main switched from the live+ runtime's whole tuple (``tui_gateway.model_switch._current_model_runtime``). The provider is+ the configured name: a named ``providers:`` entry resolves to the bare ``custom`` class, and a+ pick on the same entry must not read as a route change. Only the session's own route counts:+ a fallback is where a turn lands, not what the user switches from. A route that cannot+ authenticate here must not block leaving it: like main's agent-less ``--provider`` path, the+ pick then switches from the configured provider alone and resolves its own target.+ """+ from gateway.session_policy import profile_read_scope+ from hermes_cli.auth import AuthError+ with profile_read_scope(old, authority):+ config = old.config(authority)+ block = config.get('model') or {}+ try:+ model, runtime = authority.runner._resolve_session_agent_runtime(+ source=live.source, session_key=live.route, fallback=False)+ except AuthError:+ return config, _Route(block.get('provider') or '', old.current_model(authority) or '',+ block.get('base_url') or '', '')+ return config, _Route(block.get('provider') or runtime.get('provider') or '', model or '',+ runtime.get('base_url') or '', runtime.get('api_key') or '')++async def prepare_model(authority, live, payload, prepared):from gateway.session_policy import restore_policy, launch_key, bind_launch_keyfrom gateway.session_policy_credentials import recover_config_secretsfrom hermes_cli.model_switch import apply_model_selection, selection_route_changed, switch_modelfrom hermes_cli.config import get_compatible_custom_providersold = restore_policy(prepared['snapshot']['receipt']['policy'])- config = old.config(authority)- _, runtime = authority.runner._resolve_session_agent_runtime(source=live.source, session_key=live.route)+ config, current = _current_route(authority, live, old)def switch(**kwargs):result = switch_model(**kwargs)return result, _alias_credential(authority, result)result, alias_credential = await asyncio.to_thread(switch, raw_input=payload['model'],- current_provider=old.provider, current_model=old.model, current_base_url=old.base_url or '',- current_api_key=runtime.get('api_key') or '', explicit_provider=payload.get('provider', ''),+ current_provider=current.provider, current_model=current.model, current_base_url=current.base_url,+ current_api_key=current.api_key, explicit_provider=payload.get('provider', ''),is_global=False, user_providers=config.get('providers'),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)+ refusal = await _selection_guard_refusal(authority, live, payload, prepared['snapshot'], current, result)if refusal is not None:return refusalfrozen = old.config()@@ -66,8 +100,7 @@ async def prepare_model(authority, live, payload, prepared):# 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)- current = {'provider': old.provider, 'base_url': old.base_url or runtime.get('base_url') or ''}- if selection_route_changed(current, result):+ if selection_route_changed({'provider': old.provider, 'base_url': old.base_url or current.base_url}, result):policy = replace(policy, credential_ref=None)key = Nonepolicy = bind_launch_key(authority, prepared['snapshot']['receipt']['session_id'], policy, key,@@ -107,15 +140,15 @@ def _alias_credential(authority, result):return None, None, None-def _persisted_selection_context(authority, snapshot, old):+def _persisted_selection_context(authority, snapshot, current):from agent.usage_anchor import persisted_anchor_tokensfrom hermes_cli.model_selection_guards import SelectionContexttarget = snapshot.get('target') or snapshot['receipt']['session_id']tokens = persisted_anchor_tokens(authority.db, target, authority.db.get_messages_as_conversation(target))- return SelectionContext(context_tokens=tokens, current_model=old.model or None) if tokens else None+ return SelectionContext(context_tokens=tokens, current_model=current.model or None) if tokens else None-async def _selection_guard_refusal(authority, live, payload, snapshot, old, result, runtime):+async def _selection_guard_refusal(authority, live, payload, snapshot, current, result):"""The shared selection-guard registry (cost, data-policy, large-context switch) runs before thecommit. 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@@ -133,17 +166,17 @@ async def _selection_guard_refusal(authority, live, payload, snapshot, old, resu# No resident agent (evicted by the previous switch, or an owner restart): the session's# persisted usage anchor still measures the context at stake, so the large-context guard# does not go quiet on exactly the switch that follows another one.- context = await asyncio.to_thread(_persisted_selection_context, authority, snapshot, old)+ context = await asyncio.to_thread(_persisted_selection_context, authority, snapshot, current)# 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 '',+ base_url=result.base_url or current.base_url, api_key=result.api_key or current.api_key,model_info=result.model_info, selection_context=context)if not warnings:return Nonebinding = {'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)],+ 'current': [current.model, current.provider, normalize_route_base_url(current.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()diff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex f0f7df3fa66..03b329d7a22 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -241,14 +241,17 @@ def profile_target(config):return (model.strip() if isinstance(model, str) else ''), ''+def model_route(block):+ """``(provider, endpoint)`` identity of a ``model:`` block: what an endpoint-bound credential belongs to."""+ from hermes_cli.route_identity import normalize_route_base_url+ block = block if isinstance(block, dict) else {}+ return str(block.get('provider') or '').strip().lower(), normalize_route_base_url(block.get('base_url'))++def _held_pick(frozen, live):"""A pick that still holds keeps its selection; on the profile's own endpoint the rest of the``model:`` block (a rotated key included) is the profile's. Another endpoint never gets it."""- from hermes_cli.route_identity import normalize_route_base_url-- def route(block):- return str(block.get('provider') or '').strip().lower(), normalize_route_base_url(block.get('base_url'))- if route(frozen) != route(live):+ if model_route(frozen) != model_route(live):return frozenreturn {**{k: v for k, v in live.items() if k not in SELECTION_KEYS},**{k: frozen[k] for k in SELECTION_KEYS if k in frozen}}@@ -692,6 +695,15 @@ def launch_key(authority, policy):return value+def route_launch_key(authority, policy, config):+ """The launch key a turn on *config* (the route it runs, a followed profile's included) sends.+ A launch key authenticates the frozen route it was bound with: once the followed profile+ supersedes that pick and moves to another endpoint, the key stays behind with its route."""+ if model_route(policy.config().get('model')) != model_route(config.get('model')):+ return None+ return launch_key(authority, policy)++def restore_policy(data):"""Reject incomplete private policy rather than rebuilding from current defaults."""try:@@ -775,6 +787,18 @@ def policy_scope(policy, *, authority=None):_TURN_PROFILE.reset(profile_token)+@contextmanager+def profile_read_scope(policy, authority):+ """Hold ONE read of a following session's profile for every resolution inside, as a turn's+ ``policy_scope`` does, without that scope's workspace and terminal setup (a session control+ reads the route, it runs nothing)."""+ token = _TURN_PROFILE.set((policy, policy.read_profile(authority)))+ try:+ yield+ finally:+ _TURN_PROFILE.reset(token)++def active_policy():"""The frozen launch policy of the turn executing in this context, or ``None`` (standaloneserve / messaging turns). Consumers read it instead of re-deriving from live config."""diff --git a/gateway/session_worker_construct.py b/gateway/session_worker_construct.pyindex ff353fdd2f4..7b065260f37 100644--- a/gateway/session_worker_construct.py+++ b/gateway/session_worker_construct.py@@ -70,11 +70,14 @@ def _dict_list(value):return value is None or (isinstance(value, list) and all(isinstance(e, dict) for e in value))-def route_runtime(policy, frozen, model, key):+def route_runtime(policy, frozen, model, key, *, fallback=True):"""``(runtime, fallback_entry)`` for a launch-policy route: the session's FROZEN config and launch- credential, walking its own fallback chain on an AuthError. The one resolver an in-process turn+ credential, walking its own fallback chain on an AuthError unless ``fallback=False`` (a session+ control asking which route the session itself runs). The one resolver an in-process turn(``_resolve_policy_agent_runtime``) and a key-less managed worker (``worker_api_key``) share."""- from hermes_cli.runtime_provider import frozen_runtime_config, resolve_runtime_with_fallback+ from hermes_cli.runtime_provider import (+ frozen_runtime_config, resolve_runtime_provider, resolve_runtime_with_fallback,+ )from hermes_cli.runtime_provider_custom import _resolve_named_custom_runtimeprovider = (frozen.get('model') or {}).get('provider')launch_url = json.loads(policy.request_json).get('base_url')@@ -101,6 +104,9 @@ def route_runtime(policy, frozen, model, key):# route's own ``fallback_providers`` before the turn is refused. Only a launch URL is# explicit (classic one-shot parity): the frozen ``model.base_url`` is resolved by# the provider chain, which keeps the credential pool an explicit URL would drop.+ if not fallback:+ return resolve_runtime_provider(requested=provider, target_model=model,+ explicit_base_url=launch_url, explicit_api_key=key), Nonereturn resolve_runtime_with_fallback(frozen, requested=provider,explicit_api_key=key, explicit_base_url=launch_url, target_model=model)diff --git a/tests/gateway/test_session_mutation_model_route.py b/tests/gateway/test_session_mutation_model_route.pynew file mode 100644index 00000000000..af4051173b0--- /dev/null+++ b/tests/gateway/test_session_mutation_model_route.py@@ -0,0 +1,215 @@+"""A canonical model pick switches FROM the route the session runs now, as one tuple.++Main's switch read provider, model, endpoint and key together from the live runtime. A following+session's route is the profile's current one, so pairing its frozen creation endpoint with the+current key sends that key to a host the profile left. Real SessionStore/SessionAuthority, a real+config.yaml and loopback catalog endpoints; only models.dev metadata is held offline.+"""+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import threading++import pytest++from tests.gateway.test_session_follow_profile_config import _create, _owner, _route++MODELS = ('original', 'current', 'picked')+++class _Catalog(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_GET(self):+ self.server.received.append(self.headers.get('Authorization'))+ raw = json.dumps({'data': [{'id': name} for name in MODELS]}).encode()+ self.send_response(200)+ self.send_header('Content-Type', 'application/json')+ self.send_header('Content-Length', str(len(raw)))+ self.end_headers()+ self.wfile.write(raw)+++def endpoints():+ servers = [ThreadingHTTPServer(('127.0.0.1', 0), _Catalog) for _ in range(2)]+ for server in servers:+ server.received = []+ threading.Thread(target=server.serve_forever, daemon=True).start()+ yield [(server, f'http://127.0.0.1:{server.server_port}/v1') for server in servers]+ for server in servers:+ server.shutdown()+ server.server_close()+++def home(monkeypatch):+ from agent import models_dev+ from gateway import run+ from hermes_constants import get_hermes_home+ home = get_hermes_home()+ home.mkdir(parents=True, exist_ok=True)+ # gateway.run binds its home at first import; the loader itself is real.+ monkeypatch.setattr(run, '_hermes_home', home)+ catalog = {'custom': {'id': 'custom', 'models': {+ name: {'id': name, 'name': name, 'tool_call': True, 'cost': {'input': 0, 'output': 0},+ 'limit': {'context': 100000, 'output': 4000}} for name in MODELS}}}+ monkeypatch.setattr(models_dev, 'fetch_models_dev', lambda *args, **kwargs: catalog)+ return home+++def _configure(home, model, url, key):+ (home / 'config.yaml').write_text(json.dumps({'model': {+ 'provider': 'custom', 'default': model, 'base_url': url, 'api_key': key}}), encoding='utf-8')+++async def _pick(owner, authority, sid, payload):+ row = authority.db.get_session(sid)+ return await owner.dispatch({'id': 'pick', 'method': 'session.mutate', 'params': {+ 'session_id': sid, 'request_id': 'model-pick', 'expected_revision': row['runtime_revision'],+ 'expected_generation': row['runtime_generation'], 'operation': 'model', 'payload': payload}})+++def _bind_resolver(runner):+ from gateway.run_turn_prepare import GatewayTurnPrepareMixin+ runner._peek_session_state = lambda key: None+ runner._resolve_session_agent_runtime = GatewayTurnPrepareMixin._resolve_session_agent_runtime.__get__(runner)++[email protected]('rotate', [False, True])+async def test_following_pick_validates_on_the_current_endpoint_with_its_own_key(home, endpoints, rotate):+ (a, url_a), (b, url_b) = endpoints+ _configure(home, 'original', url_a, 'key-a')+ store, runner, authority, owner = _owner(home)+ _bind_resolver(runner)+ try:+ live = await _create(owner, authority, home, 'follow')+ sid = next(sid for sid, value in authority.sessions.items() if value is live)+ url, key = (url_b, 'key-b') if rotate else (url_a, 'key-a')+ _configure(home, 'current', url, key)+ assert _route(runner, live) == ('current', url, key)+ a.received.clear()+ b.received.clear()++ response = await _pick(owner, authority, sid, {'model': 'picked', 'provider': 'custom'})++ assert 'result' in response, response+ if rotate:+ # The retired endpoint never sees the current endpoint's credential.+ assert a.received == []+ assert b.received and set(b.received) == {'Bearer key-b'}+ assert _route(runner, live) == ('picked', url, key)+ finally:+ await owner.close()+ store.close_all_db_handles()+++async def test_a_superseded_pick_takes_its_launch_key_with_it(home):+ """The key a keyed alias pick bound authenticates the alias's endpoint. Once a profile change+ supersedes the pick and the followed route moves to another endpoint, that endpoint gets its own+ configured key, never the alias's."""+ def profile(model, port, key):+ (home / 'config.yaml').write_text(json.dumps({+ 'model': {'provider': 'custom', 'default': model, 'base_url': f'http://127.0.0.1:{port}/v1',+ 'api_key': key},+ 'model_aliases': {'picked': {'model': 'alias-model', 'provider': 'custom',+ 'base_url': 'http://127.0.0.1:2/v1', 'api_key': 'key-alias'}},+ }), encoding='utf-8')+ profile('original', 1, 'key-a')+ store, runner, authority, owner = _owner(home)+ try:+ live = await _create(owner, authority, home, 'picked', model='picked')+ assert _route(runner, live) == ('alias-model', 'http://127.0.0.1:2/v1', 'key-alias')++ profile('current', 3, 'key-b')++ assert _route(runner, live) == ('current', 'http://127.0.0.1:3/v1', 'key-b')+ finally:+ await owner.close()+ store.close_all_db_handles()+++async def test_a_bare_pick_on_a_named_provider_keeps_its_launch_key(home, endpoints):+ """A named ``providers:`` entry resolves to the bare ``custom`` class; switching from that class+ read a same-endpoint pick as a route change and dropped the key the session was launched with."""+ (_, url), _ = endpoints+ (home / 'config.yaml').write_text(json.dumps({+ 'model': {'provider': 'loopback', 'default': 'original'},+ 'providers': {'loopback': {'name': 'loopback', 'base_url': url}},+ }), encoding='utf-8')+ store, runner, authority, owner = _owner(home)+ _bind_resolver(runner)+ try:+ created = await owner.dispatch({'id': 'create', 'method': 'session.create', 'params': {+ 'request_id': 'launch', 'source': 'cli', 'cwd': str(home), 'toolsets': [],+ 'provider': 'loopback', 'api_key': 'key-launch'}})+ assert 'result' in created, created+ sid = created['result']['session_id']+ live = authority.sessions[sid]+ assert _route(runner, live) == ('original', url, 'key-launch')++ response = await _pick(owner, authority, sid, {'model': 'picked'})++ assert 'result' in response, response+ assert _route(runner, live) == ('picked', url, 'key-launch')+ finally:+ await owner.close()+ store.close_all_db_handles()+++async def test_a_pick_never_switches_from_the_fallback_route(home, endpoints):+ """While the session's own route cannot authenticate, a turn lands on its fallback; a pick still+ switches from the session's own route, so it never commits the fallback's endpoint."""+ _, (fallback, url) = endpoints+ (home / 'config.yaml').write_text(json.dumps({+ 'model': {'provider': 'custom', 'default': 'original'},+ 'fallback_providers': [{'provider': 'custom', 'model': 'current', 'base_url': url, 'api_key': 'key-fallback'}],+ }), encoding='utf-8')+ store, runner, authority, owner = _owner(home)+ _bind_resolver(runner)+ try:+ live = await _create(owner, authority, home, 'bare-with-fallback')+ sid = next(sid for sid, value in authority.sessions.items() if value is live)+ assert _route(runner, live) == ('current', url, 'key-fallback')+ fallback.received.clear()++ response = await _pick(owner, authority, sid, {'model': 'picked', 'provider': 'custom'})++ assert response.get('error', {}).get('message') == 'model_resolution_failed', response+ assert fallback.received == []+ assert _route(runner, live) == ('current', url, 'key-fallback')+ finally:+ await owner.close()+ store.close_all_db_handles()+++async def test_a_route_that_cannot_authenticate_does_not_block_switching_away(home, endpoints):+ """#138879: resolving the route being replaced raised AuthError out of ``session.mutate``, so the+ client got ``internal error`` and could never leave a route it cannot use."""+ (_, url), _ = endpoints+ (home / 'config.yaml').write_text(json.dumps({+ 'model': {'provider': 'custom', 'default': 'original'},+ 'providers': {'loopback': {'name': 'loopback', 'base_url': url, 'api_key': 'key-loopback'}},+ }), encoding='utf-8')+ store, runner, authority, owner = _owner(home)+ _bind_resolver(runner)+ try:+ live = await _create(owner, authority, home, 'bare')+ sid = next(sid for sid, value in authority.sessions.items() if value is live)+ from hermes_cli.auth_constants import AuthError+ with pytest.raises(AuthError):+ _route(runner, live)++ response = await _pick(owner, authority, sid, {'model': 'picked', 'provider': 'loopback'})++ assert 'result' in response, response+ model, base_url, key = _route(runner, live)+ assert (model, base_url, key) == ('picked', url, 'key-loopback')+ finally:+ await owner.close()+ store.close_all_db_handles()