The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): judge a client_env retry by the rules frozen with the session
unsupportedpastels95ecdbb08939
diff --git a/agent/session_client_env.py b/agent/session_client_env.pyindex 31bb652c309..ef8b38b7cdd 100644--- a/agent/session_client_env.py+++ b/agent/session_client_env.py@@ -45,47 +45,68 @@ def configured_names(config) -> frozenset:return frozenset(name.strip() for name in raw if isinstance(name, str) and name.strip()) if isinstance(raw, list) else frozenset()-def _travels(name: str) -> bool:+def _travels(name: str, secret=None) -> bool:"""A toolchain name may travel unless it is a credential by execute_code's secret policy (even whenlisted: ``NODE_AUTH_TOKEN`` matches ``NODE_``; secrets reach tools through ``terminal.env_passthrough``)- or a Hermes control name (a delegated child's markers, Kanban pins)."""- return not is_secret_env_name(name) and not name.startswith('HERMES_')+ or a Hermes control name (a delegated child's markers, Kanban pins). ``secret``: a session's frozen+ copy of that policy's substrings."""+ hidden = is_secret_env_name(name) if secret is None else any(s in name.upper() for s in secret)+ return not hidden and not name.startswith('HERMES_')-def allowed(name: str, extra: frozenset = frozenset()) -> bool:- if name in BEHAVIOUR_ENV:- return True- return _travels(name) and (name in TOOL_ENV or name.startswith(TOOL_ENV_PREFIXES) or name in extra)+def client_env_rules(config, *, local=True) -> dict:+ """The normalisation rules (plain data) a session's map is filtered by, frozen with it: an exact retry+ is judged by these, never by the profile's allowlist or the secret policy as they are later. A client+ not proven ``local`` keeps only the values that name nothing on this host (prompt, provider request)."""+ from tools.code_execution_env import _SECRET_SUBSTRINGS+ return {'behaviour': [n for n in BEHAVIOUR_ENV if local or n not in HOST_BEHAVIOUR],+ 'names': sorted(set(TOOL_ENV) | configured_names(config)) if local else [],+ 'prefixes': list(TOOL_ENV_PREFIXES) if local else [], 'secret': list(_SECRET_SUBSTRINGS)}+++def _kept(name: str, rules: dict) -> bool:+ return name in rules['behaviour'] or (_travels(name, rules['secret']) and (+ name in rules['names'] or name.startswith(tuple(rules['prefixes']))))def collect_client_env(environ=None, config=None) -> dict[str, str]:"""Client side: this shell's allowlisted values (the profile's extra names included)."""environ = os.environ if environ is None else environ- extra = configured_names(config)- return {name: value for name, value in environ.items() if isinstance(value, str) and allowed(name, extra)}+ rules = client_env_rules(config)+ return {name: value for name, value in environ.items() if isinstance(value, str) and _kept(name, rules)}-def accept_client_env(value, config, *, local=True) -> dict[str, str]:- """Gateway side: the validated map, filtered again against the session profile's own allowlist; for a- client not proven ``local`` only the values that name nothing on this host (prompt, provider request).+def normalise_client_env(value, rules) -> dict[str, str]:+ """The validated map filtered by ``rules`` (``None``: unfiltered, for a map frozen before rules were).Raises ``ValueError`` for anything but a bounded flat string-to-string map."""if (not isinstance(value, dict) or len(value) > _MAX_NAMESor any(not isinstance(k, str) or not isinstance(v, str) for k, v in value.items())or sum(len(k) + len(v) for k, v in value.items()) > _MAX_BYTES):raise ValueError('client_env must be a map of variable names to string values')- extra = configured_names(config)- return {name: value[name] for name in sorted(value) if allowed(name, extra)- and (local or (name in BEHAVIOUR_ENV and name not in HOST_BEHAVIOUR))}---def retry_matches(committed_json, params) -> bool:- """Whether a retried ``session.create`` carries the client environment its committed session froze.- The committed (normalised) map decides, never the current allowlist: every stored name must come back- with its value; names the gateway filtered out at creation do not count, whatever the rules are now."""- if committed_json is None:- return 'client_env' not in params- value = params.get('client_env')- return isinstance(value, dict) and all(value.get(k) == v for k, v in json.loads(committed_json).items())+ return {name: value[name] for name in sorted(value) if rules is None or _kept(name, rules)}+++def accept_client_env(value, config, *, local=True) -> dict[str, str]:+ """Gateway side: the map filtered by the session profile's own current rules."""+ return normalise_client_env(value, client_env_rules(config, local=local))+++def retry_matches(committed: dict, request: dict) -> bool:+ """Whether a retried ``session.create`` (``request``: its params) carries the client environment the+ committed session (``committed``: its stored policy) froze. The complete retried map, normalised by+ the rules frozen with the session, must equal the stored one: an added name those rules keep, a+ missing stored name or a changed value is a different request; one they drop never counts. Staging+ and the transactional commit both judge by this. A session committed without a map (Desktop, one+ from before the field) still matches only a retry that sends none."""+ stored = committed.get('client_env_json')+ if stored is None or 'client_env' not in request:+ return stored is None and 'client_env' not in request+ rules = committed.get('client_env_rules_json')+ try:+ sent = normalise_client_env(request['client_env'], None if rules is None else json.loads(rules))+ except ValueError:+ return False+ return sent == json.loads(stored)@contextmanagerdiff --git a/gateway/session_local.py b/gateway/session_local.pyindex ed4f09e3815..79a21061470 100644--- a/gateway/session_local.py+++ b/gateway/session_local.py@@ -269,7 +269,7 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, trustefrom hermes_state_local import same_create_requestfrom agent.session_client_env import retry_matchesif (not same_create_request(original.request_json, policy.request_json)- or not retry_matches(original.client_env_json, params)):+ or not retry_matches(saved['policy'], params)):raise RuntimeStoreError('invalid_params', field='request_id',detail='a resumed request_id must carry the same frozen request')import hmac@@ -304,9 +304,13 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, trusteentry = SessionEntry(route, sid, now, now, origin=source, platform=Platform.LOCAL)# Prefill is read now, at creation (main's CLI: at startup), and held only if this attempt commits.from gateway.session_worker_construct import stage_session_prefill- return stage_session_prefill(authority, policy, {+ staged = stage_session_prefill(authority, policy, {'profile_id': authority.profile_id, 'principal_id': actor.subject, 'request_id': request_id,'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}+ return stageddef publish_local_policy(authority, session_id):diff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex 6f099577fb7..432f2ccf5f5 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -81,6 +81,9 @@ class LocalSessionPolicy:# The client sent one over an attach the gateway could not prove is on its host (no gateway-minted# ticket): only host-free values were kept, and its tools run with the gateway's own toolchain.client_env_remote: bool = False+ # The rules that map was normalised by (``client_env_rules``: allowlist, secret filter, locality) as+ # plain data: an exact retry is judged by them, never by the profile's current ones.+ client_env_rules_json: str | None = Nonedef client_env(self):return None if self.client_env_json is None else json.loads(self.client_env_json)@@ -355,14 +358,15 @@ def build_policy(params, config, *, private_secrets=None, profile_terminal=True,# configured cwd unless the user picked this folder for the session.if params.get('cwd_explicit') is True or terminal_uses_host_cwd(terminal):terminal['TERMINAL_CWD'] = cwd- client_env = None+ client_env = rules = Noneif 'client_env' in params:- from agent.session_client_env import accept_client_env+ from agent.session_client_env import client_env_rules, normalise_client_env+ rules = client_env_rules(config, local=client_local)try:- client_env = json.dumps(accept_client_env(params['client_env'], config, local=client_local),- sort_keys=True)+ client_env = json.dumps(normalise_client_env(params['client_env'], rules), sort_keys=True)except ValueError as exc:_refuse('client_env', str(exc))+ rules = json.dumps(rules, sort_keys=True)# Values stay out of the request: ``launch_request`` is echoed to every viewer of the session.request = {k: v for k, v in params.items() if k not in {'request_id', 'api_key', 'client_env'}}request.setdefault('source', 'cli')@@ -374,7 +378,8 @@ def build_policy(params, config, *, private_secrets=None, profile_terminal=True,json.dumps(config), json.dumps(request, sort_keys=True), json.dumps(terminal),safe_mode=safe_mode, ignore_user_config=ignore_user_config,coding_posture=coding_posture, client_env_json=client_env,- client_env_remote=client_env is not None and not client_local)+ client_env_remote=client_env is not None and not client_local,+ client_env_rules_json=rules)def terminal_uses_host_cwd(terminal):@@ -818,6 +823,7 @@ def restore_policy(data):or not isinstance(policy.skills_prompt, (str, type(None)))or type(policy.coding_posture) is not boolor not _valid_client_env(policy.client_env_json) or type(policy.client_env_remote) is not bool+ or not _valid_client_env(policy.client_env_rules_json, list)or (policy.safe_mode and not policy.ignore_user_config)):raise ValueError('invalid policy')from dataclasses import replace@@ -832,11 +838,13 @@ def restore_policy(data):raise RuntimeStoreError('storage_unavailable') from exc-def _valid_client_env(value):+def _valid_client_env(value, kind: type = str):+ """A stored client map (names to strings) or its rules (``kind=list``: rule names to string lists)."""if value is None:return Trueenv = json.loads(value) if isinstance(value, str) else None- return isinstance(env, dict) and all(isinstance(k, str) and isinstance(v, str) for k, v in env.items())+ return isinstance(env, dict) and all(isinstance(k, str) and isinstance(v, kind) and (+ kind is str or all(isinstance(item, str) for item in v)) for k, v in env.items())def policy_for_source(runner, source):diff --git a/gateway/session_policy_credentials.py b/gateway/session_policy_credentials.pyindex 1d68264a2ac..f377da7f5d9 100644--- a/gateway/session_policy_credentials.py+++ b/gateway/session_policy_credentials.py@@ -66,8 +66,9 @@ def policy_identity(policy):data.pop('editor_mcp_json', None)if not data.get('coding_posture'):data.pop('coding_posture', None)- if data.get('client_env_json') is None:- data.pop('client_env_json', None)+ for name in ('client_env_json', 'client_env_rules_json'):+ if data.get(name) is None:+ data.pop(name, None)if not data.get('client_env_remote'):data.pop('client_env_remote', None)return hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()diff --git a/gateway/session_worker_construct.py b/gateway/session_worker_construct.pyindex 2796c7b2eb2..efff49a7d7a 100644--- a/gateway/session_worker_construct.py+++ b/gateway/session_worker_construct.py@@ -71,6 +71,8 @@ class StagedReceipt(dict):"""A creation receipt plus owner memory ``commit_local_session`` publishes only from thetransaction that creates the session (never persisted: the receipt itself is the dict)."""on_create: '_PrefillPublication | None' = None+ # The request's own ``client_env`` (stage_local_session), for an overlapping create's retry check.+ client_request: 'dict | None' = Noneclass _PrefillPublication:diff --git a/hermes_state_local.py b/hermes_state_local.pyindex f4757b3accc..380ed98cd13 100644--- a/hermes_state_local.py+++ b/hermes_state_local.py@@ -14,6 +14,12 @@ def commit_local_session(db, *, epoch, receipt):``on_create`` (owner memory, never stored) is published by the transaction that creates the rowand withdrawn if that transaction fails: an exact retry, a refused or a losing attempt adds none."""on_create = getattr(receipt, 'on_create', None)+ request = getattr(receipt, 'client_request', None) # the staged request's own client_env, never stored+ if request is None:+ if receipt['policy'].get('client_env_json') is not None:+ # Lost (a copy): never judge a retry by this attempt's own filtered map instead.+ raise RuntimeStoreError('invalid_params')+ request = {}if on_create is not None:on_create.read() # its file read: in the caller's thread, outside the write transactionencoded = _json(receipt)@@ -28,8 +34,9 @@ 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_matchessame = (same and same_create_request(saved['policy']['request_json'], receipt['policy']['request_json'])- and saved['policy'].get('client_env_json') == receipt['policy'].get('client_env_json'))+ and retry_matches(saved['policy'], request))except (ValueError, TypeError, KeyError) as exc:raise RuntimeStoreError('storage_unavailable') from excif not same:diff --git a/tests/acp_adapter/test_policy_identity_compat.py b/tests/acp_adapter/test_policy_identity_compat.pyindex 289118037af..491fcb199e3 100644--- a/tests/acp_adapter/test_policy_identity_compat.py+++ b/tests/acp_adapter/test_policy_identity_compat.py@@ -15,5 +15,6 @@ def test_policy_identity_preserves_pre_editor_credential_binding(tmp_path):legacy.pop('coding_posture')legacy.pop('client_env_json')legacy.pop('client_env_remote')+ legacy.pop('client_env_rules_json')expected = hashlib.sha256(json.dumps(legacy, sort_keys=True).encode()).hexdigest()assert policy_identity(policy) == expecteddiff --git a/tests/gateway/test_session_client_env.py b/tests/gateway/test_session_client_env.pyindex fa087bfe69c..983492d1a32 100644--- a/tests/gateway/test_session_client_env.py+++ b/tests/gateway/test_session_client_env.py@@ -212,6 +212,99 @@ async def test_exact_retry_is_judged_by_the_committed_map_not_the_current_allowlowner.db.close()+async def test_exact_retry_compares_the_complete_map_under_its_committed_rules(tmp_path, monkeypatch):+ """The retry, normalised by the rules committed with its session (allowlist, secret filter, locality),+ must equal the committed map: a name those rules keep added, a stored one dropped or a value changed+ is a different request; a name they would have dropped is ignored, whatever the rules are now."""+ from gateway.session_local import create_local_session+ from hermes_state_runtime import RuntimeStoreError+ home = _home(tmp_path, _CONFIG + 'terminal: {client_env_passthrough: [GEM_HOME]}\n')+ owner, connection = await _owner(home, monkeypatch)+ base = {'source': 'cli', 'cwd': str(home), 'toolsets': []}++ def create(request_id, env, local=True):+ return create_local_session(owner, connection.actor, {**base, 'request_id': request_id, 'client_env': env},+ client_local=local)+ env = {'GEM_HOME': '/gems', 'PATH': '/client/bin'}+ try:+ ref, empty = create('x', env), create('e', {})+ remote = create('r', {'PATH': '/a', 'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'P'}, local=False)+ (home / 'config.yaml').write_text(_CONFIG + 'terminal: {client_env_passthrough: [BUNDLE_PATH]}\n')+ assert create('x', {**env, 'BUNDLE_PATH': '/b', 'NODE_AUTH_TOKEN': 't', 'HERMES_YOLO_MODE': '1'}) == ref+ for added in ({'VIRTUAL_ENV': '/venv'}, {'NVM_DIR': '/nvm'}, {'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'P'}):+ with pytest.raises(RuntimeStoreError):+ create('x', {**env, **added})+ assert create('e', {'BUNDLE_PATH': '/b'}) == empty # not allowlisted when 'e' committed+ for sent in ({'PATH': '/client/bin'}, {'GEM_HOME': '/g'}, 'PATH=/x'):+ with pytest.raises(RuntimeStoreError):+ create('e', sent)+ # Committed without the gateway's proof of locality: host values were dropped then, so they are now.+ assert create('r', {'PATH': '/b', 'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'P'}) == remote+ with pytest.raises(RuntimeStoreError):+ create('r', {'PATH': '/a', 'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'Q'})+ finally:+ await connection.close()+ owner.db.close()+++async def test_overlapping_retries_across_an_allowlist_change_agree_with_sequential_ones(tmp_path, monkeypatch):+ """Two creates of one request_id staged on either side of an allowlist edit: the transactional commit+ judges the loser by the winner's committed rules, exactly as a sequential retry would be."""+ from gateway.session_local import stage_local_session+ from hermes_state_local import commit_local_session, local_receipt+ from hermes_state_runtime import RuntimeStoreError+ home = _home(tmp_path, _CONFIG + 'terminal: {client_env_passthrough: [GEM_HOME]}\n')+ owner, connection = await _owner(home, monkeypatch)+ env = {'GEM_HOME': '/gems', 'BUNDLE_PATH': '/bundle', 'PATH': '/client/bin'}++ def stage(sent):+ return stage_local_session(owner, connection.actor, {'request_id': 'o', 'source': 'cli', 'cwd': str(home),+ 'toolsets': [], 'client_env': sent}, client_local=True)+ try:+ first = stage(env)+ (home / 'config.yaml').write_text(_CONFIG + 'terminal: {client_env_passthrough: [BUNDLE_PATH]}\n')+ same, added = stage(env), stage({**env, 'VIRTUAL_ENV': '/venv'})+ assert all(isinstance(receipt, dict) for receipt in (first, same, added)) # all staged before the row+ commit_local_session(owner.db, epoch=owner.epoch, receipt=first)+ saved = local_receipt(owner.db, first['session_id'])+ assert commit_local_session(owner.db, epoch=owner.epoch, receipt=same)['policy'] == saved['policy']+ with pytest.raises(RuntimeStoreError):+ commit_local_session(owner.db, epoch=owner.epoch, receipt=added)+ assert local_receipt(owner.db, first['session_id']) == saved+ finally:+ await connection.close()+ owner.db.close()+++async def test_a_copied_staged_receipt_is_never_judged_by_its_own_filtered_map(tmp_path, monkeypatch):+ """An overlapping create's own ``client_env`` is owner memory on its staged receipt. A plain copy has lost+ it, and its filtered map (an allowlist edit dropped GEM_HOME) equals the winner's: the commit refuses it."""+ from gateway.session_local import stage_local_session+ from hermes_state_local import commit_local_session+ from hermes_state_runtime import RuntimeStoreError+ home = _home(tmp_path, _CONFIG + 'terminal: {client_env_passthrough: [GEM_HOME]}\n')+ owner, connection = await _owner(home, monkeypatch)++ def stage(sent):+ return stage_local_session(owner, connection.actor, {'request_id': 'c', 'source': 'cli', 'cwd': str(home),+ 'toolsets': [], 'client_env': sent}, client_local=True)+ try:+ first = stage({'PATH': '/client/bin'})+ (home / 'config.yaml').write_text(_CONFIG)+ added = stage({'PATH': '/client/bin', 'GEM_HOME': '/gems'})+ commit_local_session(owner.db, epoch=owner.epoch, receipt=first)+ with pytest.raises(RuntimeStoreError):+ commit_local_session(owner.db, epoch=owner.epoch, receipt=added)+ with pytest.raises(RuntimeStoreError):+ commit_local_session(owner.db, epoch=owner.epoch, receipt=dict(added))+ finally:+ await connection.close()+ owner.db.close()++@pytest.mark.asyncioasync def test_host_values_apply_only_over_a_gateway_proven_local_attach(tmp_path, monkeypatch):"""Toolchain and path-valued values are the client's only when the gateway itself proves the attach is