The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): /model <alias> commits the alias endpoint's own credential
Tekniumdeefcd87cd74
diff --git a/gateway/session_mutation_model.py b/gateway/session_mutation_model.pyindex 8051786c4af..8250b4a60cd 100644--- a/gateway/session_mutation_model.py+++ b/gateway/session_mutation_model.py@@ -14,7 +14,12 @@ async def prepare_model(authority, live, payload, prepared):old = restore_policy(prepared['snapshot']['receipt']['policy'])config = old.config(authority)_, runtime = authority.runner._resolve_session_agent_runtime(source=live.source, session_key=live.route)- result = await asyncio.to_thread(switch_model, raw_input=payload['model'],++ def switch(**kwargs):+ # The alias table switch_model resolved against, read in the same call (process-global).+ result = switch_model(**kwargs)+ return result, _alias_credential(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', ''),is_global=False, user_providers=config.get('providers'),@@ -29,12 +34,22 @@ async def prepare_model(authority, live, payload, prepared):# 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)+ # A direct alias's own credential is part of the selection (never ``result.api_key``, which the+ # switch resolved for its probe): its env pointer is committed and re-read every turn; a literal+ # key becomes a private config secret, a null in the durable receipt like build_policy's.+ key_env, alias_key = alias_credential+ if key_env:+ frozen['model']['key_env'] = key_env+ if alias_key:+ frozen['model']['api_key'] = None# 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'])}+ if alias_key:+ secrets[('model', 'api_key')] = alias_key# Re-fingerprint frozen config references because policy identity includes model.# 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).@@ -48,6 +63,17 @@ async def prepare_model(authority, live, payload, prepared):return dict(prepared, policy=asdict(policy))+def _alias_credential(result):+ """``(key_env, literal_key)`` the direct alias a switch resolved declares for its own endpoint+ (``api_key: "${VAR}"`` is the pointer ``VAR``); ``(None, None)`` when it declares none."""+ from hermes_cli.model_switch import DIRECT_ALIASES+ alias = DIRECT_ALIASES.get(result.resolved_via_alias or '') if result.success else None+ raw = (alias.api_key or '').strip() if alias is not None else ''+ if raw.startswith('${') and raw.endswith('}'):+ return raw[2:-1].strip() or None, None+ return ((alias.key_env or '').strip() or None) if alias is not None and not raw else None, raw or None++def _persisted_selection_context(authority, snapshot, old):from agent.usage_anchor import persisted_anchor_tokensfrom hermes_cli.model_selection_guards import SelectionContextdiff --git a/tests/gateway/test_model_alias_credential.py b/tests/gateway/test_model_alias_credential.pynew file mode 100644index 00000000000..b306cdee10a--- /dev/null+++ b/tests/gateway/test_model_alias_credential.py@@ -0,0 +1,48 @@+"""``/model <alias>`` keeps the alias endpoint's own credential on the next turn."""+import pytest+++async def test_model_switch_to_a_keyed_direct_alias_runs_the_next_turn_with_its_own_key(tmp_path, monkeypatch):+ """A direct alias declares its endpoint's credential (``key_env`` or a literal ``api_key``). The+ route change drops the old endpoint's credentials; the alias's own must take their place in the+ committed selection, or the next turn sends ``no-key-required`` to the alias host."""+ 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, far_url = 'http://127.0.0.1:9/v1', 'http://127.0.0.3:9/v1'+ monkeypatch.setenv('FAR_ALIAS_KEY', 'sk-far-env')+ monkeypatch.setitem(model_switch.DIRECT_ALIASES, 'far-env', model_switch.DirectAlias(+ 'far-model', 'custom', far_url, key_env='FAR_ALIAS_KEY'))+ monkeypatch.setitem(model_switch.DIRECT_ALIASES, 'far-literal', model_switch.DirectAlias(+ 'far-model', 'custom', far_url, api_key='sk-far-literal'))+ monkeypatch.setitem(model_switch.DIRECT_ALIASES, 'far-ref', model_switch.DirectAlias(+ 'far-model', 'custom', far_url, api_key='${FAR_ALIAS_KEY}'))+ 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, '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)}}}+ # Every credential shape a direct alias can declare (DirectAlias / direct_alias_api_key).+ for alias, expected in (('far-env', 'sk-far-env'), ('far-literal', 'sk-far-literal'),+ ('far-ref', 'sk-far-env')):+ monkeypatch.setattr(model_switch, 'switch_model', lambda alias=alias, **k: model_switch.ModelSwitchResult(+ success=True, new_model='far-model', target_provider='custom', base_url=far_url,+ api_key='resolved-at-switch', resolved_via_alias=alias))+ switched = restore_policy((await prepare_model(authority, SimpleNamespace(source=None, route='r'),+ {'model': alias}, prepared))['policy'])+ assert switched.credential_ref is None, "endpoint A's launch key crossed to the alias host"+ assert 'sk-far-literal' not in switched.config_json, 'a literal alias key must stay private'+ runtime = _resolve_policy_agent_runtime(runner, switched)[1]+ assert runtime['base_url'].rstrip('/') == far_url+ assert runtime['api_key'] == expected, f'{alias}: the next turn ran without the alias key'