The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): expand config ${VAR} refs for a new local session against the profile's current .env
unsupportedpastels556033f6560c
diff --git a/gateway/session_local.py b/gateway/session_local.pyindex b6d460e374d..e8c314b11bd 100644--- a/gateway/session_local.py+++ b/gateway/session_local.py@@ -5,6 +5,7 @@ Source and supported launch settings are frozen per route, never process env.from __future__ import annotationsimport uuid+from contextlib import contextmanagerfrom gateway.config import Platform, PlatformConfigfrom gateway.platforms.base import BasePlatformAdapter, SendResult@@ -145,6 +146,35 @@ def _bypass_policy(params, *, private_secrets):return build_policy(params, defaults, private_secrets=private_secrets, profile_terminal=False)+def load_profile_config(home=None):+ """The profile's effective config.yaml for a NEW session's policy, ``${VAR}`` refs expanded against+ the profile's CURRENT ``.env`` (the source tool env refreshes from), not the env this daemon+ started with: a single-profile owner binds no secret scope and never reloads ``.env`` for local+ turns. A bound scope (a served profile's owner scope) already is that source and is kept; a miss+ on the launch profile still falls to the process env (systemd / ``op run`` injection)."""+ from pathlib import Path+ from gateway.run import _load_gateway_config+ with profile_env_scope(home):+ return _load_gateway_config(*(() if home is None else (Path(home) / 'config.yaml',)))+++@contextmanager+def profile_env_scope(home=None):+ """Bind the profile's current ``.env`` (see ``load_profile_config``) unless a scope is bound."""+ from pathlib import Path+ from agent.secret_scope import build_profile_secret_scope, current_secret_scope, reset_secret_scope, set_secret_scope+ from gateway.run import _gateway_config_home+ if current_secret_scope() is not None:+ yield+ return+ home = Path(home) if home is not None else _gateway_config_home() # default: the active gateway home+ token = set_secret_scope(build_profile_secret_scope(home), profile_home=str(home))+ try:+ yield+ finally:+ reset_secret_scope(token)++def create_local_session(authority, actor, params, *, trusted_policy=None, trusted_secrets=None, skills_prompt=None):"""Stage, commit and publish a local session inline (synchronous callers)."""from gateway.session_local_recovery import restore_local_session@@ -165,26 +195,31 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, trusteif 'session:create' not in actor.capabilities:raise RuntimeStoreError('permission_denied')from gateway.session_policy import build_policy, BYPASS_FIELDS- from gateway.run import _load_gateway_config, _resolve_gateway_model+ from gateway.run import _resolve_gateway_modelfrom dataclasses import replaceprivate_secrets = dict(trusted_secrets or {})+ client_key = params.get('api_key') # the client's own; an alias's key is the owner's expansionif trusted_policy is not None:policy = trusted_policyelif any(params.get(name) is True for name in BYPASS_FIELDS):policy = _bypass_policy(params, private_secrets=private_secrets)else:from gateway.session_local_route import resolve_launch_route- config = _load_gateway_config()- raw_model = params.get('model')- params = resolve_launch_route(params, config)+ raw_model, sent = params.get('model'), params+ with profile_env_scope(): # an alias's ``key_env`` / ``${VAR}`` key reads the same .env+ config = load_profile_config()+ params = resolve_launch_route(params, config)# A client's session.create is the one caller whose named folder may select the coding posture.policy = build_policy(params, config, private_secrets=private_secrets, workspace_posture=True)- if isinstance(raw_model, str) and params.get('model') != raw_model:- # Owner-stamped provenance (not a create field): a remote client cannot re-resolve the- # typed `-m` alias against its own home, so resume compares a repeat against this.+ if params is not sent: # resolved, even to a model of the alias's own name+ # Owner-stamped provenance (not create fields): a remote client cannot re-resolve the typed+ # `-m` alias against its own home, so resume and an exact retry compare a repeat against the+ # name, and ``route_derived`` names the fields the route (not the client) filled.import json+ derived = sorted(key for key in ('provider', 'base_url') if key in params and key not in sent)policy = replace(policy, request_json=json.dumps(- {**json.loads(policy.request_json), 'model_requested': raw_model}, sort_keys=True))+ {**json.loads(policy.request_json), 'model_requested': raw_model, 'route_derived': derived},+ sort_keys=True))if policy.model is None:policy = replace(policy, model=_resolve_gateway_model(policy.config()))request_id = params.get('request_id', uuid.uuid4().hex)@@ -202,11 +237,18 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, trustefrom hermes_state_local import local_receiptsaved = local_receipt(authority.db, sid)original = restore_policy(saved['policy'])- if original.request_json != policy.request_json:+ from hermes_state_local import same_create_request+ if not same_create_request(original.request_json, policy.request_json):raise RuntimeStoreError('invalid_params', field='request_id',detail='a resumed request_id must carry the same frozen request')- if original.credential_ref is not None or params.get('api_key') is not None:- import hmac+ import hmac+ import json+ if 'model_requested' in json.loads(original.request_json):+ # An owner-resolved alias: its key came from the profile (a `.env` rotation is not a changed+ # request) and the client sent none, so one it sends now is a different request.+ if client_key is not None:+ raise RuntimeStoreError('admission_conflict')+ elif original.credential_ref is not None or params.get('api_key') is not None:key = launch_key(authority, original)if key is None or not hmac.compare_digest(key, params.get('api_key') or ''):raise RuntimeStoreError('admission_conflict')@@ -218,7 +260,8 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, trusteraise RuntimeStoreError('invalid_params', field='skills',detail='the caller must render -s skills before minting the session')policy = replace(policy, skills_prompt=skills_prompt)- policy = bind_launch_key(authority, sid, policy, params.get("api_key"), config_secrets=private_secrets)+ policy = bind_launch_key(authority, sid, policy, params.get("api_key"), config_secrets=private_secrets,+ owner_key=client_key is None) # an overlapping exact retry takes the held onefrom gateway.session_local_recovery import local_sourcesource = local_source(authority, sid, actor.subject)route = authority.runner.session_store._generate_session_key(source)diff --git a/gateway/session_local_route.py b/gateway/session_local_route.pyindex 408cceae380..25a3cef6763 100644--- a/gateway/session_local_route.py+++ b/gateway/session_local_route.py@@ -23,7 +23,8 @@ def resolve_launch_route(params: dict, config: dict) -> dict:route = resolve_startup_model_route(model, explicit_provider=explicit_provider,current_provider=(explicit_provider or str(model_cfg.get('provider') or '')).strip().lower(),- user_providers=config.get('providers'), custom_providers=config.get('custom_providers'))+ user_providers=config.get('providers'), custom_providers=config.get('custom_providers'),+ alias_config=config) # this snapshot's aliases, not a cache keyed on config.yaml aloneif route is None:return paramsresolved = dict(params, model=route.model)diff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex e6eda9af02c..87230e43659 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -635,11 +635,14 @@ def register_worker_hooks(policy):register_outbound_webhooks(config)-def bind_launch_key(authority, session_id, policy, api_key, *, config_secrets=None):+def bind_launch_key(authority, session_id, policy, api_key, *, config_secrets=None, owner_key=False):"""CLI keys live only in this authority lifetime, never its durable receipt.Restart deliberately revokes them. History remains readable; inference mustreport launch_credentials_unavailable, never select a profile fallback key.+ An ``owner_key`` (an alias's, expanded by the owner) of the same create request as the attempt+ holding the slot takes the held key: a ``.env`` rotation between overlapping attempts is not a+ changed request, and the policy then fingerprints the key it runs with."""from dataclasses import replaceimport hmac@@ -655,6 +658,12 @@ def bind_launch_key(authority, session_id, policy, api_key, *, config_secrets=Nokeys = authority._local_launch_keys = {}ref = f'{authority.instance_id}:{authority.epoch}:{session_id}'old = keys.get(ref)+ owners = getattr(authority, '_local_owner_key_requests', None)+ if owners is None:+ owners = authority._local_owner_key_requests = {}+ if owner_key and api_key is not None and old is not None and ref in owners:+ from hermes_state_local import same_create_request+ api_key = old if same_create_request(owners[ref], policy.request_json) else api_key# Only a key that IS being bound can conflict: binding config secrets alone (a provider# change drops the launch key) must not be refused by the key the session already holds.if api_key is not None and old is not None and not hmac.compare_digest(old, api_key):@@ -670,6 +679,8 @@ def bind_launch_key(authority, session_id, policy, api_key, *, config_secrets=Noraise RuntimeStoreError('admission_conflict')if config_secrets:configs[config_ref] = dict(config_secrets)+ if api_key is not None and old is None and owner_key:+ owners[ref] = policy.request_jsonif api_key is not None:keys[ref] = api_key# The durable ref carries the key's fingerprint (the digest config_secret_ref already@@ -731,8 +742,10 @@ def release_launch_secrets(authority, session_ids):prefix = f'{authority.instance_id}:{authority.epoch}:'keys = getattr(authority, '_local_launch_keys', None) or {}# A key re-supplied after a restart sits in the slot of the epoch that minted it.+ owners = getattr(authority, '_local_owner_key_requests', None) or {}for ref in [ref for ref in keys if ref.split(':', 2)[-1] in retired]:del keys[ref]+ owners.pop(ref, None)configs = getattr(authority, '_local_config_secrets', None) or {}for ref in list(configs):if ref.startswith(PREFIX):diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.pyindex 3cd0cba7e7e..18ac968c5dc 100644--- a/hermes_cli/model_switch.py+++ b/hermes_cli/model_switch.py@@ -200,8 +200,8 @@ def _clean(value: Any) -> str:DIRECT_ALIASES: dict[str, DirectAlias] = {}-def _load_direct_aliases() -> dict[str, DirectAlias]:- """Load direct aliases from config.yaml.+def _load_direct_aliases(cfg: Optional[dict] = None) -> dict[str, DirectAlias]:+ """Load direct aliases from config.yaml (or from the caller's *cfg* snapshot).``model_aliases:`` entries are dicts (``model``, ``provider``, ``base_url``, optional``api_key`` — literal or ``"${VAR}"`` — / ``key_env``); with neither credential field the key@@ -213,8 +213,9 @@ def _load_direct_aliases() -> dict[str, DirectAlias]:"""merged = dict(_BUILTIN_DIRECT_ALIASES)try:- from hermes_cli.config import load_config- cfg = load_config()+ if cfg is None:+ from hermes_cli.config import load_config+ cfg = load_config()user_aliases = cfg.get("model_aliases")if isinstance(user_aliases, dict):@@ -357,7 +358,7 @@ class StartupModelRoute(NamedTuple):def resolve_startup_model_route(raw_model: str, *, explicit_provider: str = "", current_provider: str = "",user_providers: Optional[dict] = None,- custom_providers: Optional[list] = None) -> Optional[StartupModelRoute]:+ custom_providers: Optional[list] = None, alias_config: Optional[dict] = None) -> Optional[StartupModelRoute]:"""Resolve aliases, ``provider:model`` and configured ``provider/model`` input at startup.``HermesCLI`` is constructed before the interactive ``/model`` pipeline runs; resolving here@@ -365,13 +366,16 @@ def resolve_startup_model_route(model. ``provider/model`` strings are consumed only for providers present in user config. When``current_provider`` is a routing aggregator and the raw string is an aggregator-native slug(``anthropic/claude-opus-4.6`` on OpenRouter) the input stays on the aggregator — a- ``providers:`` block for the same vendor must not steal the route."""+ ``providers:`` block for the same vendor must not steal the route. ``alias_config`` is a+ caller's config snapshot to read aliases from instead of the process-global cache."""raw = _clean(raw_model)if not raw:return None- _ensure_direct_aliases()- direct = DIRECT_ALIASES.get(raw.lower())+ if alias_config is None:+ _ensure_direct_aliases()+ aliases = DIRECT_ALIASES if alias_config is None else _load_direct_aliases(alias_config)+ direct = aliases.get(raw.lower())if direct is not None:if explicit_provider:# An explicit --provider wins over the alias's own label; the alias contributesdiff --git a/hermes_state_local.py b/hermes_state_local.pyindex 3ba2a5e1c10..bee2b8bdbc2 100644--- a/hermes_state_local.py+++ b/hermes_state_local.py@@ -23,7 +23,7 @@ def commit_local_session(db, *, epoch, receipt):saved = json.loads(old[0])same = all(saved[k] == receipt[k] for k in ('profile_id', 'principal_id', 'request_id', 'session_id', 'route'))- same = same and saved['policy']['request_json'] == receipt['policy']['request_json']+ same = same and same_create_request(saved['policy']['request_json'], receipt['policy']['request_json'])except (ValueError, TypeError, KeyError) as exc:raise RuntimeStoreError('storage_unavailable') from excif not same:@@ -57,6 +57,34 @@ def commit_local_session(db, *, epoch, receipt):return db._execute_write(write)+def client_request(request_json, derived=None):+ """A frozen create request as the client sent it: an owner-resolved ``-m`` route (``model_requested``)+ compares by the name the client typed, not by the model and the *derived* fields (a receipt from+ before ``route_derived``: the endpoint) its ``${VAR}`` refs expanded to at the time."""+ request = json.loads(request_json)+ if derived is None:+ request.pop('route_derived', None)+ if 'model_requested' in request:+ request.pop('model', None)+ for key in ('base_url',) if derived is None else derived:+ request.pop(key, None)+ return request+++def same_create_request(saved_json, retry_json):+ """Whether a create retry carries the frozen request it resumes: one check for a retry that finds the+ session committed and one staged before it was. The saved receipt's provenance names the owner's+ fields; one from before a same-name alias got ``model_requested`` compares exactly, as it did."""+ derived = json.loads(saved_json).get('route_derived')+ if client_request(saved_json, derived) == client_request(retry_json, derived):+ return True+ retry = json.loads(retry_json)+ if retry.get('model_requested') == retry.get('model'):+ retry.pop('model_requested', None)+ retry.pop('route_derived', None)+ return json.loads(saved_json) == retry++def _row_cwd(policy):"""The sessions-row ``cwd``: the create request's ``row_cwd`` (``""`` = none) when it sent one,else the execution cwd. Row metadata only (workspace grouping, ``-c``, cwd restore); thediff --git a/tests/gateway/test_local_create_alias_retry.py b/tests/gateway/test_local_create_alias_retry.pynew file mode 100644index 00000000000..73306889ca9--- /dev/null+++ b/tests/gateway/test_local_create_alias_retry.py@@ -0,0 +1,250 @@+"""An exact retry of an alias ``session.create`` is the same request whatever the owner's ``.env`` now+expands the alias to: retry identity is what the client sent (the alias name and its own fields),+checked the same way by a retry that sees the committed session and by one that overlaps the first+create's staging. A payload the client really changed is still refused."""+import json++import pytest+import pytest_asyncio++CONFIG = (+ 'platform_toolsets: {cli: []}\n'+ 'model: {provider: custom, default: m, base_url: http://default.invalid/v1}\n'+ 'model_aliases:\n'+ ' alias-key: {model: model-alias, provider: custom, base_url: "${P5_ENDPOINT}", api_key: "${P5_ALIAS_KEY}"}\n'+ ' twin-key: {model: model-alias, provider: custom, base_url: "${P5_ENDPOINT}", api_key: "${P5_ALIAS_KEY}"}\n'+ ' same-name: {model: same-name, provider: custom, base_url: "${P5_ENDPOINT}"}\n')+++def _env(home, n):+ (home / '.env').write_text(f'P5_ENDPOINT=http://endpoint-{n}.invalid/v1\nP5_ALIAS_KEY=alias-key-{n}\n')+++@pytest_asyncio.fixture+async def owner(tmp_path, monkeypatch):+ from hermes_cli import model_switch+ monkeypatch.setattr(model_switch, 'DIRECT_ALIASES', {})+ for name in ('P5_ENDPOINT', 'P5_ALIAS_KEY'):+ monkeypatch.delenv(name, raising=False)+ home = tmp_path / 'home'+ home.mkdir()+ (home / 'config.yaml').write_text(CONFIG)+ _env(home, 1)+ running = [home, *await _start(home, monkeypatch)]+ try:+ yield running+ finally:+ await _stop(running)+++async def _start(home, monkeypatch):+ from tests.gateway.test_local_create_env_refs import _owner+ return await _owner(home, monkeypatch)+++async def _stop(running):+ await running[2].close()+ running[1].db.close()+++def _params(home, **fields):+ return {'request_id': 'retry', 'source': 'cli', 'cwd': str(home), 'toolsets': [], **fields}+++def _create(authority, connection, params):+ from gateway.session_local import create_local_session+ return create_local_session(authority, connection.actor, dict(params))+++def _stage(authority, connection, params):+ from gateway.session_local import stage_local_session+ return stage_local_session(authority, connection.actor, dict(params))+++def _commit(authority, staged):+ from gateway.session_local_recovery import restore_local_session+ from hermes_state_local import commit_local_session+ commit_local_session(authority.db, epoch=authority.epoch, receipt=staged)+ return restore_local_session(authority, staged['session_id'])+++def _policy(authority, ref):+ from hermes_state_local import local_receipt+ return local_receipt(authority.db, ref.session_id)['policy']+++def _refusal(call, *args):+ from hermes_state_runtime import RuntimeStoreError+ with pytest.raises(RuntimeStoreError) as refused:+ call(*args)+ return refused.value.reason+++async def test_exact_alias_retry_after_an_owner_key_rotation_returns_the_original(owner):+ """``api_key: "${VAR}"`` rotated in ``.env`` between create and retry: the owner's new expansion is+ not the client's payload, so the retry returns the original session, which keeps its own key."""+ from gateway.session_policy import launch_key, restore_policy+ home, authority, connection = owner+ ref = _create(authority, connection, _params(home, model='alias-key'))+ saved = _policy(authority, ref)+ assert launch_key(authority, restore_policy(saved)) == 'alias-key-1'+ _env(home, 2)+ assert _create(authority, connection, _params(home, model='alias-key')) == ref+ assert _policy(authority, ref) == saved+ assert launch_key(authority, restore_policy(saved)) == 'alias-key-1'++[email protected]('changed', [{'api_key': 'alias-key-1'}, {'api_key': 'other'},+ {'base_url': 'http://endpoint-1.invalid/v1'}])+async def test_an_alias_retry_that_adds_a_client_route_field_is_refused(owner, changed):+ """The alias's key and endpoint were the owner's; a retry that now supplies its own is a new request,+ even when the value happens to equal what the owner expanded."""+ home, authority, connection = owner+ _create(authority, connection, _params(home, model='alias-key'))+ assert _refusal(_create, authority, connection, _params(home, model='alias-key', **changed)) in {+ 'invalid_params', 'admission_conflict'}+++async def test_a_changed_client_credential_is_still_refused(owner):+ home, authority, connection = owner+ params = _params(home, model='plain-model', base_url='http://client.invalid/v1', api_key='client-1')+ ref = _create(authority, connection, params)+ _env(home, 2)+ assert _create(authority, connection, params) == ref+ assert _refusal(_create, authority, connection, dict(params, api_key='client-2')) == 'admission_conflict'++[email protected]('alias', ['same-name', 'alias-key'])[email protected]('order', ['sequential', 'overlap-first-wins', 'overlap-second-wins'])+async def test_exact_alias_retry_after_an_endpoint_rotation_returns_the_original(owner, alias, order):+ """Same identity check whether the retry sees the committed session (sequential) or both attempts+ staged before either commits; ``same-name`` resolves to the model of its own name."""+ home, authority, connection = owner+ params = _params(home, model=alias)+ if order == 'sequential':+ ref = _create(authority, connection, params)+ saved = _policy(authority, ref)+ _env(home, 2)+ assert _create(authority, connection, params) == ref+ else:+ staged = [_stage(authority, connection, params)]+ _env(home, 2) # the alias's key rotates too: the retry takes the key its slot holds+ staged.append(_stage(authority, connection, params))+ assert json.loads(staged[0]['policy']['config_json']) != json.loads(staged[1]['policy']['config_json'])+ ordered = staged if order == 'overlap-first-wins' else staged[::-1]+ ref = _commit(authority, ordered[0])+ saved = _policy(authority, ref)+ assert _commit(authority, ordered[1]) == ref+ assert _policy(authority, ref) == saved+ assert restore_policy_url(saved) == f'http://endpoint-{1 if order != "overlap-second-wins" else 2}.invalid/v1'+++def restore_policy_url(saved):+ from gateway.session_policy import restore_policy+ return restore_policy(saved).config()['model']['base_url']++[email protected]('order', ['sequential', 'overlap'])[email protected]('first, second', [('alias-key', 'twin-key'), ('same-name', 'm'),+ ('alias-key', 'model-alias'), ('same-name', 'other-model')])+async def test_a_different_alias_or_model_under_one_request_id_is_refused(owner, order, first, second):+ """Two aliases that resolve to the same model and endpoint are still two requests, and so is an+ explicit model id in place of the alias (even the one the alias resolves to)."""+ home, authority, connection = owner+ if order == 'sequential':+ _create(authority, connection, _params(home, model=first))+ assert _refusal(_create, authority, connection, _params(home, model=second)) == 'invalid_params'+ else:+ winner = _stage(authority, connection, _params(home, model=first))+ loser = _stage(authority, connection, _params(home, model=second))+ _commit(authority, winner)+ assert _refusal(_commit, authority, loser) == 'invalid_params'++[email protected]('alias, old_shape', [+ ('alias-key', lambda request: request.pop('route_derived', None)), # stamped model_requested only+ ('same-name', lambda request: [request.pop(key, None) for key in ('model_requested', 'route_derived')]),+])+async def test_a_receipt_committed_before_this_change_still_takes_its_exact_retry(owner, monkeypatch, alias,+ old_shape):+ """Receipts written before ``route_derived`` (and, for a same-name alias, before ``model_requested``+ was stamped for it), retried after the owner restarts on this code: the unchanged retry still+ returns the original session."""+ from hermes_state_local import POLICY_PREFIX+ home, authority, connection = owner+ params = _params(home, model=alias)+ ref = _create(authority, connection, params)++ def rewrite(conn):+ key = POLICY_PREFIX + ref.session_id+ receipt = json.loads(conn.execute('SELECT value FROM state_meta WHERE key=?', (key,)).fetchone()[0])+ request = json.loads(receipt['policy']['request_json'])+ old_shape(request)+ receipt['policy']['request_json'] = json.dumps(request, sort_keys=True)+ conn.execute('UPDATE state_meta SET value=? WHERE key=?', (json.dumps(receipt), key))+ authority.db._execute_write(rewrite)+ await _stop(owner)+ owner[1:] = await _start(home, monkeypatch)+ authority, connection = owner[1:]+ saved = _policy(authority, ref)+ assert _create(authority, connection, params) == ref+ if alias == 'alias-key': # model_requested already marked the alias's key and endpoint as the owner's+ _env(home, 2)+ assert _create(authority, connection, params) == ref+ assert _policy(authority, ref) == saved+++def _attempt(call, *args):+ from hermes_state_runtime import RuntimeStoreError+ try:+ return call(*args)+ except RuntimeStoreError as exc:+ return exc.reason+++def _rotate_key(home):+ (home / '.env').write_text('P5_ENDPOINT=http://endpoint-1.invalid/v1\nP5_ALIAS_KEY=alias-key-2\n')++[email protected]('order', ['first-wins', 'second-wins'])+async def test_an_overlapping_exact_alias_retry_after_a_key_rotation_reuses_the_held_key(owner, order):+ """Both attempts share one key slot: the retry staged after ``.env`` rotated the alias's key runs with+ the key the first attempt holds, and whichever commits stores that key's fingerprint."""+ from agent.credential_persistence import fingerprint_secret_value+ from gateway.session_policy import launch_key, restore_policy+ home, authority, connection = owner+ params = _params(home, model='alias-key')+ staged = [_stage(authority, connection, params)]+ _rotate_key(home)+ staged.append(_attempt(_stage, authority, connection, params))+ assert isinstance(staged[1], dict), staged[1]+ ordered = staged if order == 'first-wins' else staged[::-1]+ ref = _commit(authority, ordered[0])+ assert _commit(authority, ordered[1]) == ref+ with authority.db._read_ctx() as conn:+ assert conn.execute('SELECT COUNT(*) FROM sessions').fetchone()[0] == 1+ policy = restore_policy(_policy(authority, ref))+ assert launch_key(authority, policy) == 'alias-key-1'+ assert policy.credential_ref.partition('#')[2] == fingerprint_secret_value('alias-key-1')++[email protected]('first, second', [+ ({'model': 'alias-key'}, {'model': 'alias-key', 'api_key': 'other'}),+ ({'model': 'alias-key'}, {'model': 'twin-key'}), # another request under the same id+ ({'model': 'plain-model', 'api_key': 'client-1'}, {'model': 'plain-model', 'api_key': 'client-2'}),+])+async def test_an_overlapping_retry_with_another_key_is_still_refused(owner, first, second):+ """Only the same request's owner-expanded key takes the held one: a key the client sends is compared+ exactly, and another request staged under the same id never inherits the slot's key."""+ home, authority, connection = owner+ _stage(authority, connection, _params(home, **first))+ _rotate_key(home)+ assert _attempt(_stage, authority, connection, _params(home, **second)) == 'admission_conflict'diff --git a/tests/gateway/test_local_create_env_refs.py b/tests/gateway/test_local_create_env_refs.pynew file mode 100644index 00000000000..13f32e2a562--- /dev/null+++ b/tests/gateway/test_local_create_env_refs.py@@ -0,0 +1,151 @@+"""A new local session expands ``config.yaml`` ``${VAR}`` refs against the profile's CURRENT ``.env``+(the source tool env already refreshes from), not the daemon's start-time ``os.environ`` (CFG-4)."""+from types import SimpleNamespace++import pytest+++async def _owner(home, monkeypatch):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_controls import AuthorityConnection+ monkeypatch.setattr(run, '_hermes_home', home)+ monkeypatch.setenv('HERMES_HOME', str(home)) # a single-profile owner: this IS the launch home+ store = SessionStore(home / 'sessions', GatewayConfig())+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,+ _cached_agent_for=lambda route: None, _adapter_for_source=lambda source: None,+ _evict_cached_agent=lambda route: None)+ owner = await initialize_session_authority(runner, profile_id=str(home), instance_id='fixture')+ return owner, AuthorityConnection(owner, object(), {'user_id': 'owner'})+++def _created_model(owner, actor, home, request_id):+ from gateway.session_local import create_local_session+ from gateway.session_policy import restore_policy+ from hermes_state_local import local_receipt+ ref = create_local_session(owner, actor, {'request_id': request_id, 'source': 'cli', 'cwd': str(home),+ 'toolsets': []})+ return restore_policy(local_receipt(owner.db, ref.session_id)['policy']).config()['model']+++async def test_new_session_expands_config_refs_against_current_profile_env(tmp_path, monkeypatch):+ from agent.secret_scope import current_secret_scope+ home = tmp_path / 'home'+ home.mkdir()+ (home / 'config.yaml').write_text(+ 'platform_toolsets: {cli: []}\n'+ 'model: {provider: custom, default: m, base_url: "${CFG4_BASE_URL}", api_mode: "${CFG4_INJECTED}"}\n')+ # Gateway-start values: CFG4_BASE_URL came from .env at boot; CFG4_INJECTED only from the+ # process env (systemd / ``op run``), which a single-profile owner must keep honouring.+ monkeypatch.setenv('CFG4_BASE_URL', 'http://boot.invalid/v1')+ monkeypatch.setenv('CFG4_INJECTED', 'chat_completions')+ (home / '.env').write_text('CFG4_BASE_URL=http://rotated.invalid/v1\n')+ owner, connection = await _owner(home, monkeypatch)+ try:+ first = _created_model(owner, connection.actor, home, 'first')+ assert first['base_url'] == 'http://rotated.invalid/v1'+ assert first['api_mode'] == 'chat_completions'+ (home / '.env').write_text('CFG4_BASE_URL=http://rotated-again.invalid/v1\n')+ assert _created_model(owner, connection.actor, home, 'second')['base_url'] == \+ 'http://rotated-again.invalid/v1'+ assert current_secret_scope() is None # the read's scope never outlives the build+ finally:+ await connection.close()+ owner.db.close()++[email protected]('model', [None, 'alias-env'])+async def test_exact_create_retry_after_an_env_rotation_returns_the_original_session(tmp_path, monkeypatch, model):+ """A session committed before this change (config expanded against the daemon's start env) and+ retried after the profile's ``.env`` rotated: the exact retry returns the original session and its+ frozen policy, never ``invalid_params`` or a re-expanded route. Also for a ``-m`` alias launch+ whose endpoint is a ``${VAR}`` ref (the resolved route rides the frozen request)."""+ from gateway import session_local+ from gateway.run import _load_gateway_config+ from gateway.session_local import create_local_session+ from gateway.session_policy import restore_policy+ from hermes_cli import model_switch+ from hermes_state_local import local_receipt+ home = tmp_path / 'home'+ home.mkdir()+ (home / 'config.yaml').write_text(+ 'platform_toolsets: {cli: []}\n'+ 'model: {provider: custom, default: m, base_url: "${CFG4_BASE_URL}"}\n'+ 'model_aliases:\n'+ ' alias-env: {model: model-alias, provider: custom, base_url: "${CFG4_BASE_URL}"}\n')+ monkeypatch.setattr(model_switch, 'DIRECT_ALIASES', {})+ monkeypatch.setenv('CFG4_BASE_URL', 'http://boot.invalid/v1')+ (home / '.env').write_text('CFG4_BASE_URL=http://boot.invalid/v1\n')+ owner, connection = await _owner(home, monkeypatch)+ params = {'request_id': 'retry', 'source': 'cli', 'cwd': str(home), 'toolsets': [],+ **({'model': model} if model else {})}+ try:+ with monkeypatch.context() as old: # the pre-change create: the daemon's start env+ old.setattr(session_local, 'load_profile_config', lambda home=None: _load_gateway_config())+ ref = create_local_session(owner, connection.actor, dict(params))+ saved = local_receipt(owner.db, ref.session_id)['policy']+ assert restore_policy(saved).config()['model']['base_url'] == 'http://boot.invalid/v1'+ (home / '.env').write_text('CFG4_BASE_URL=http://rotated.invalid/v1\n')+ model_switch.DIRECT_ALIASES.clear()+ assert create_local_session(owner, connection.actor, dict(params)) == ref+ assert local_receipt(owner.db, ref.session_id)['policy'] == saved+ finally:+ await connection.close()+ owner.db.close()+++async def test_new_alias_session_uses_the_current_profile_env(tmp_path, monkeypatch):+ """A ``-m`` alias whose endpoint is a ``${VAR}`` ref resolves from the same fresh config snapshot+ as the rest of the policy: not the daemon's start env, and not an alias cache that only notices+ ``config.yaml`` edits."""+ from gateway.session_local import create_local_session+ from gateway.session_policy import restore_policy+ from hermes_cli import model_switch+ from hermes_state_local import local_receipt+ home = tmp_path / 'home'+ home.mkdir()+ (home / 'config.yaml').write_text(+ 'platform_toolsets: {cli: []}\n'+ 'model: {provider: custom, default: m}\n'+ 'model_aliases:\n'+ ' alias-env: {model: model-alias, provider: custom, base_url: "${CFG4_BASE_URL}"}\n')+ monkeypatch.setattr(model_switch, 'DIRECT_ALIASES', {})+ monkeypatch.setattr(model_switch, '_DIRECT_ALIAS_LOADED', None)+ monkeypatch.setattr(model_switch, '_DIRECT_ALIAS_IDENTITY', None)+ monkeypatch.setenv('CFG4_BASE_URL', 'http://boot.invalid/v1')+ (home / '.env').write_text('CFG4_BASE_URL=http://rotated.invalid/v1\n')+ owner, connection = await _owner(home, monkeypatch)++ def created(request_id):+ ref = create_local_session(owner, connection.actor, {+ 'request_id': request_id, 'source': 'cli', 'cwd': str(home), 'toolsets': [], 'model': 'alias-env'})+ policy = restore_policy(local_receipt(owner.db, ref.session_id)['policy'])+ return policy.model, policy.config()['model']['base_url']+ try:+ assert created('first') == ('model-alias', 'http://rotated.invalid/v1')+ (home / '.env').write_text('CFG4_BASE_URL=http://rotated-again.invalid/v1\n')+ assert created('second') == ('model-alias', 'http://rotated-again.invalid/v1')+ finally:+ await connection.close()+ owner.db.close()+++def test_bound_scope_is_kept(tmp_path, monkeypatch):+ """A served profile's owner scope (multiplex) is already the right source: never rebuilt from+ another home."""+ from agent.secret_scope import reset_secret_scope, set_secret_scope+ from gateway.session_local import load_profile_config+ home = tmp_path / 'home'+ home.mkdir()+ (home / 'config.yaml').write_text('model: {base_url: "${CFG4_BASE_URL}"}\n')+ (home / '.env').write_text('CFG4_BASE_URL=http://file.invalid/v1\n')+ token = set_secret_scope({'CFG4_BASE_URL': 'http://scope.invalid/v1'}, profile_home=str(home))+ try:+ assert load_profile_config(home)['model']['base_url'] == 'http://scope.invalid/v1'+ finally:+ reset_secret_scope(token)