The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): give an overlapping alias retry's held key the client_env check too
unsupportedpastels5ef2f5f98056
diff --git a/gateway/session_local.py b/gateway/session_local.pyindex 79a21061470..c7e3bdac1ab 100644--- a/gateway/session_local.py+++ b/gateway/session_local.py@@ -266,10 +266,8 @@ 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'])- from hermes_state_local import same_create_request- from agent.session_client_env import retry_matches- if (not same_create_request(original.request_json, policy.request_json)- or not retry_matches(saved['policy'], params)):+ from hermes_state_local import same_create_retry+ if not same_create_retry(saved['policy'], policy.request_json, params):raise RuntimeStoreError('invalid_params', field='request_id',detail='a resumed request_id must carry the same frozen request')import hmac@@ -293,8 +291,10 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, trustepolicy = replace(policy, skills_prompt=skills_prompt)if warning := project_plugins_warning(policy):logger.warning('session %s: %s', sid, warning)+ client_request = {k: params[k] for k in ('client_env',) if k in params}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 one+ owner_key=client_key is None, # an overlapping exact retry takes the held one+ client_request=client_request)from gateway.session_local_recovery import local_sourcesource = local_source(authority, sid, actor.subject)route = authority.runner.session_store._generate_session_key(source)@@ -309,7 +309,7 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, truste'session_id': sid, 'route': route, 'entry': entry.to_dict(), 'policy': asdict(policy)})# Owner memory, never stored: an overlapping create's commit judges this request's own map by the# winner's committed rules, as a sequential retry is.- staged.client_request = {k: params[k] for k in ('client_env',) if k in params}+ staged.client_request = client_requestreturn stageddiff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex a37c4e65123..2c6b67984d9 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -666,14 +666,16 @@ def register_worker_hooks(policy):register_outbound_webhooks(config)-def bind_launch_key(authority, session_id, policy, api_key, *, config_secrets=None, owner_key=False):+def bind_launch_key(authority, session_id, policy, api_key, *, config_secrets=None, owner_key=False,+ client_request=None):"""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.+ holding the slot (``same_create_retry``, its ``client_env`` in ``client_request``) 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@@ -693,8 +695,8 @@ def bind_launch_key(authority, session_id, policy, api_key, *, config_secrets=Noif 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+ from hermes_state_local import same_create_retry+ api_key = old if same_create_retry(owners[ref], policy.request_json, client_request or {}) 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):@@ -711,7 +713,7 @@ def bind_launch_key(authority, session_id, policy, api_key, *, config_secrets=Noif 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_json+ owners[ref] = {k: getattr(policy, k) for k in ('request_json', 'client_env_json', 'client_env_rules_json')}if api_key is not None:keys[ref] = api_key# The durable ref carries the key's fingerprint (the digest config_secret_ref alreadydiff --git a/hermes_state_local.py b/hermes_state_local.pyindex 380ed98cd13..c239a8643cb 100644--- a/hermes_state_local.py+++ b/hermes_state_local.py@@ -34,9 +34,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'))- from agent.session_client_env import retry_matches- same = (same and same_create_request(saved['policy']['request_json'], receipt['policy']['request_json'])- and retry_matches(saved['policy'], request))+ same = same and same_create_retry(saved['policy'], receipt['policy']['request_json'], request)except (ValueError, TypeError, KeyError) as exc:raise RuntimeStoreError('storage_unavailable') from excif not same:@@ -105,6 +103,15 @@ def same_create_request(saved_json, retry_json):return json.loads(saved_json) == retry+def same_create_retry(saved_policy, retry_json, client_request):+ """The one exact-retry identity of a create: ``same_create_request`` on what the client sent, and its+ ``client_env`` (``client_request``: the retry's own, never stored) judged by the rules frozen with+ *saved_policy*. Used by a retry that finds the session committed, at commit, and by one overlapping+ the attempt that holds the session's key slot."""+ from agent.session_client_env import retry_matches+ return same_create_request(saved_policy['request_json'], retry_json) and retry_matches(saved_policy, client_request)++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.pyindex 73306889ca9..2cf14a211dd 100644--- a/tests/gateway/test_local_create_alias_retry.py+++ b/tests/gateway/test_local_create_alias_retry.py@@ -248,3 +248,36 @@ async def test_an_overlapping_retry_with_another_key_is_still_refused(owner, fir_stage(authority, connection, _params(home, **first))_rotate_key(home)assert _attempt(_stage, authority, connection, _params(home, **second)) == 'admission_conflict'+++PROMPT = 'HERMES_EPHEMERAL_SYSTEM_PROMPT' # kept by the rules of a client the gateway did not prove local++[email protected]('first, second', [({PROMPT: 'P'}, {PROMPT: 'Q'}), ({PROMPT: 'P'}, None),+ (None, {PROMPT: 'P'}), ({PROMPT: 'P'}, {})])+async def test_an_overlapping_alias_retry_with_another_client_env_never_takes_the_held_key(owner, first, second):+ """The held key is for the same create request only, and a client_env the slot holder's rules tell+ apart is another request: refused at staging, so it gets neither the key nor a session, even when+ the holder never commits."""+ home, authority, connection = owner+ with_env = (lambda env: _params(home, model='alias-key', **({} if env is None else {'client_env': env})))+ _stage(authority, connection, with_env(first))+ _rotate_key(home)+ assert _attempt(_stage, authority, connection, with_env(second)) == 'admission_conflict'+ with authority.db._read_ctx() as conn:+ assert conn.execute('SELECT COUNT(*) FROM sessions').fetchone()[0] == 0+++async def test_an_overlapping_alias_retry_differing_only_in_a_dropped_name_reuses_the_held_key(owner):+ """A name the holder's rules drop (PATH from a client not proven local) does not make another request."""+ from gateway.session_policy import launch_key, restore_policy+ home, authority, connection = owner+ staged = [_stage(authority, connection, _params(home, model='alias-key', client_env={PROMPT: 'P'}))]+ _rotate_key(home)+ staged.append(_stage(authority, connection, _params(home, model='alias-key',+ client_env={PROMPT: 'P', 'PATH': '/client/bin'})))+ ref = _commit(authority, staged[1])+ assert _commit(authority, staged[0]) == ref+ assert launch_key(authority, restore_policy(_policy(authority, ref))) == 'alias-key-1'