Skip to content

The agent that grows with you

fix(gateway): /model <alias> commits a reference to the alias's own literal key

Teknium1a74bb74cba4
diff --git a/gateway/session_mutation_model.py b/gateway/session_mutation_model.py
index 8250b4a60cd..6fa3f3ca5f0 100644
--- a/gateway/session_mutation_model.py
+++ b/gateway/session_mutation_model.py
@@ -16,9 +16,8 @@ async def prepare_model(authority, live, payload, prepared):
_, runtime = authority.runner._resolve_session_agent_runtime(source=live.source, session_key=live.route)
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)
+ 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', ''),
@@ -36,20 +35,24 @@ async def prepare_model(authority, live, payload, prepared):
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
+ # key is a private config secret at the alias entry's own path (what a restarted owner re-reads)
+ # and the receipt keeps only a pointer to it, which config() projects into ``model.api_key``.
+ key_env, source, alias_key = alias_credential
if key_env:
frozen['model']['key_env'] = key_env
- if alias_key:
- frozen['model']['api_key'] = None
+ if source:
+ frozen['model'].update(api_key=None, api_key_from=list(source))
+ elif 'api_key' not in frozen['model']:
+ frozen['model'].pop('api_key_from', 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
+ if source:
+ secrets.pop(('model', 'api_key'), None)
+ secrets[source] = 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).
@@ -63,15 +66,35 @@ 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 _alias_credential(authority, result):
+ """``(key_env, source_path, literal_key)`` the direct alias a switch resolved declares for its own
+ endpoint, read from THIS owner's config.yaml: the file a restarted owner re-reads, never the
+ process-global alias cache another served profile may refill after the switch. A raw
+ ``api_key: "${VAR}"`` is the pointer ``VAR``; ``(None, None, None)`` when it declares none."""
+ from pathlib import Path
+ from gateway.run import _load_gateway_config
+ from hermes_cli.config import _env_ref_var_name, read_user_config_raw
+ name = result.resolved_via_alias if result.success else ''
+ path = Path(authority.db.db_path).resolve().parent / 'config.yaml'
+ raw = read_user_config_raw(path) if name else {}
+ for section in (('model_aliases',), ('model', 'aliases')):
+ entries = raw.get(section[0]) if len(section) == 1 else (raw.get('model') or {}).get('aliases')
+ for written, entry in (entries.items() if isinstance(entries, dict) else ()):
+ if not isinstance(entry, dict) or not entry.get('model') or str(written).strip().lower() != name:
+ continue
+ key = str(entry.get('api_key') or '').strip()
+ pointer = _env_ref_var_name(key[2:-1]) if key.startswith('${') and key.endswith('}') else None
+ if pointer:
+ return pointer, None, None
+ if not key:
+ return str(entry.get('key_env') or '').strip() or None, None, None
+ value = _load_gateway_config(path)
+ for part in (*section, written, 'api_key'):
+ value = value.get(part) if isinstance(value, dict) else None
+ if not value:
+ raise RuntimeStoreError('model_resolution_failed')
+ return None, (*section, written, 'api_key'), value
+ return None, None, None
def _persisted_selection_context(authority, snapshot, old):
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index bb36837b292..6a1547072ec 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -51,8 +51,13 @@ class LocalSessionPolicy:
continue
target = config
for key in path[:-1]:
- target = target[key]
+ # An alias entry added after creation is absent from the frozen tree.
+ target = target.setdefault(key, {}) if isinstance(target, dict) else target[key]
target[path[-1]] = value
+ model = config.get('model')
+ # ``/model <alias>`` with a literal key: the receipt points at the alias entry's secret.
+ if isinstance(model, dict) and model.get('api_key_from') and 'api_key' in model:
+ model['api_key'] = secrets.get(tuple(model['api_key_from']))
return config
@property
diff --git a/tests/gateway/test_model_alias_credential.py b/tests/gateway/test_model_alias_credential.py
index b306cdee10a..47e557f5ffa 100644
--- a/tests/gateway/test_model_alias_credential.py
+++ b/tests/gateway/test_model_alias_credential.py
@@ -22,6 +22,12 @@ async def test_model_switch_to_a_keyed_direct_alias_runs_the_next_turn_with_its_
'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}'))
+ # The owner reads the alias credential from its own profile's config.yaml (N48).
+ (tmp_path / 'config.yaml').write_text(
+ 'model_aliases:\n'
+ f' far-env: {{model: far-model, provider: custom, base_url: "{far_url}", key_env: FAR_ALIAS_KEY}}\n'
+ f' far-literal: {{model: far-model, provider: custom, base_url: "{far_url}", api_key: sk-far-literal}}\n'
+ f' far-ref: {{model: far-model, provider: custom, base_url: "{far_url}", api_key: "${{FAR_ALIAS_KEY}}"}}\n')
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,
diff --git a/tests/gateway/test_model_alias_credential_restart.py b/tests/gateway/test_model_alias_credential_restart.py
new file mode 100644
index 00000000000..6ad7e85ae6b
--- /dev/null
+++ b/tests/gateway/test_model_alias_credential_restart.py
@@ -0,0 +1,54 @@
+"""N48/N30/E02: ``/model <alias>`` with a LITERAL alias key commits a reference to the alias entry,
+so a restarted owner re-derives it (no ``launch_credentials_unavailable`` wedge), and the key is
+read from this owner's profile, never from the process-global alias cache another served profile
+may have refilled."""
+from dataclasses import asdict
+from types import SimpleNamespace
+
+import pytest
+
+
+async def test_literal_alias_key_survives_owner_restart_and_stays_in_profile(tmp_path, monkeypatch):
+ 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_cli import model_switch
+ old_url, far_url = 'http://127.0.0.1:9/v1', 'http://127.0.0.3:9/v1'
+ (tmp_path / 'config.yaml').write_text(
+ f'model_aliases:\n Far: {{model: far-model, provider: custom, base_url: "{far_url}", api_key: sk-far-literal}}\n')
+ # What another served profile's own /model left in the process-global cache.
+ monkeypatch.setitem(model_switch.DIRECT_ALIASES, 'far', model_switch.DirectAlias(
+ 'far-model', 'custom', far_url, api_key='sk-other-profile'))
+
+ def owner(db):
+ 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
+
+ def switch(alias, base_url):
+ monkeypatch.setattr(model_switch, 'switch_model', lambda **k: model_switch.ModelSwitchResult(
+ success=True, new_model=alias + '-model', target_provider='custom', base_url=base_url,
+ api_key='resolved-at-switch', resolved_via_alias=alias))
+
+ with SessionDB(tmp_path / 'state.db') as db:
+ first = owner(db)
+ policy = build_policy({'cwd': str(tmp_path), 'model': 'a', 'provider': 'custom', 'base_url': old_url},
+ {'model': {'provider': 'custom', 'default': 'a', 'base_url': old_url}})
+ prepared = {'snapshot': {'receipt': {'session_id': 'sid', 'policy': asdict(policy)}}}
+ switch('far', far_url)
+ committed = (await prepare_model(first, SimpleNamespace(source=None, route='r'), {'model': 'far'},
+ prepared))['policy']
+ assert 'sk-far-literal' not in str(committed) and 'sk-other-profile' not in str(committed)
+ switched = restore_policy(committed)
+ assert _resolve_policy_agent_runtime(first.runner, switched)[1]['api_key'] == 'sk-far-literal'
+ # Owner restart: a fresh authority over the same durable receipt, nothing in memory.
+ restarted = owner(db)
+ assert _resolve_policy_agent_runtime(restarted.runner, switched)[1]['api_key'] == 'sk-far-literal'
+ switch('back', old_url)
+ again = await prepare_model(restarted, SimpleNamespace(source=None, route='r'), {'model': 'back'},
+ {'snapshot': {'receipt': {'session_id': 'sid', 'policy': committed}}})
+ back = restore_policy(again['policy'])
+ assert back.base_url == old_url and 'api_key_from' not in back.config()['model']