The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tools): run a CLI/TUI session's tools with its client's toolchain environment
unsupportedpastels979c08e35d69
diff --git a/agent/session_client_env.py b/agent/session_client_env.pyindex e3bc45dbd0e..083218b7f97 100644--- a/agent/session_client_env.py+++ b/agent/session_client_env.py@@ -12,10 +12,11 @@ from __future__ import annotationsimport jsonimport os-import refrom contextlib import contextmanagerfrom contextvars import ContextVar+from tools.code_execution_env import is_secret_env_name+# What main's CLI read per process and the gateway otherwise reads daemon-wide.BEHAVIOUR_ENV = ('HERMES_EPHEMERAL_SYSTEM_PROMPT', 'HERMES_PREFILL_MESSAGES_FILE', 'HERMES_INFERENCE_PROVIDER','HERMES_ENABLE_PROJECT_PLUGINS')@@ -23,9 +24,6 @@ TOOL_ENV = ('PATH', 'VIRTUAL_ENV', 'GOPATH', 'GOROOT', 'CARGO_HOME', 'RUSTUP_HOMTOOL_ENV_PREFIXES = ('CONDA_', 'NODE_', 'NVM_', 'PYENV_')# ``terminal.client_env_passthrough`` names more non-secret toolchain variables for a profile.CONFIG_KEY = 'client_env_passthrough'-# A name that looks like a credential never travels or lands in the session's stored policy, even when-# listed (``NODE_AUTH_TOKEN`` matches ``NODE_``); secrets reach tools through ``terminal.env_passthrough``.-_SECRETISH = re.compile(r'TOKEN|SECRET|PASS|KEY|AUTH|CREDENTIAL|COOKIE', re.IGNORECASE)_MAX_NAMES = 256_MAX_BYTES = 256 * 1024@@ -39,12 +37,17 @@ 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:+ """A toolchain name may travel unless it is a credential by execute_code's secret policy (even when+ listed: ``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_')++def allowed(name: str, extra: frozenset = frozenset()) -> bool:if name in BEHAVIOUR_ENV:return True- if _SECRETISH.search(name):- return False- return name in TOOL_ENV or name.startswith(TOOL_ENV_PREFIXES) or name in extra+ return _travels(name) and (name in TOOL_ENV or name.startswith(TOOL_ENV_PREFIXES) or name in extra)def collect_client_env(environ=None, config=None) -> dict[str, str]:@@ -101,4 +104,16 @@ def session_env(name: str, default: str = '') -> str:def tool_env() -> dict[str, str]:"""The toolchain values this session's tool subprocesses start with (empty when unbound)."""env = _BOUND.get() or {}- return {name: value for name, value in env.items() if name not in BEHAVIOUR_ENV}+ return {name: value for name, value in env.items() if name not in BEHAVIOUR_ENV and _travels(name)}+++def toolchain_environ(base=None) -> dict[str, str]:+ """The environment this session's tool subprocesses start from (``base``: the gateway's). Unbound+ (messaging, cron, Desktop): unchanged. A shell client's session: its toolchain replaces the gateway's,+ and a built-in toolchain name it did not export is unset, as in main's process: one client's venv+ never reaches another's session through the daemon it started."""+ env = dict(os.environ if base is None else base)+ if _BOUND.get() is None:+ return env+ kept = {k: v for k, v in env.items() if k == 'PATH' or not (k in TOOL_ENV or k.startswith(TOOL_ENV_PREFIXES))}+ return kept | tool_env()diff --git a/cli-config.yaml.example b/cli-config.yaml.exampleindex d143219bb9d..4687dc01eb9 100644--- a/cli-config.yaml.example+++ b/cli-config.yaml.example@@ -431,6 +431,12 @@ terminal:home_mode: "auto"docker_mount_cwd_to_workspace: false # SECURITY: off by default. Opt in to mount the launch cwd into Docker /workspace.lifetime_seconds: 300+ # A `hermes` / `hermes --tui` session's local tools (terminal, background processes, execute_code)+ # start with the launching shell's toolchain: PATH, VIRTUAL_ENV and CONDA_* / NODE_* / NVM_* /+ # PYENV_* (plus GOPATH, GOROOT, CARGO_HOME, RUSTUP_HOME, JAVA_HOME), for that session only.+ # List more non-secret names here; names that look like credentials (…TOKEN, …KEY, …SECRET,+ # …PASSWORD, …AUTH) are never sent: pass secrets with `env_passthrough` instead.+ # client_env_passthrough: ["GEM_HOME", "POETRY_HOME"]# sudo_password: "hunter2" # Optional: pipe a sudo password via sudo -S. SECURITY WARNING: plaintext.# sudo_password: "" # Explicit empty password: try empty and never open the interactive sudo prompt.diff --git a/tests/gateway/test_managed_worker_client_env.py b/tests/gateway/test_managed_worker_client_env.pynew file mode 100644index 00000000000..39abdaf9115--- /dev/null+++ b/tests/gateway/test_managed_worker_client_env.py@@ -0,0 +1,129 @@+"""T3 / LC-8 on a real gateway: CLI sessions attached through the gateway's own ticket run their tools in+managed workers under their client's toolchain, and the client environment never shows in a public+projection (session.info, session.list, export, search)."""+import asyncio+from contextlib import closing+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import os+from pathlib import Path+import sqlite3+import threading++import pytest++from tests.waiting import async_wait_until++ROOT = Path(__file__).resolve().parents[2]+PROBE = 'printf "%s|%s" "$NVM_DIR" "$(whichclient)"'+++class Model(BaseHTTPRequestHandler):+ """``PROBE`` runs the terminal probe; anything else ends the turn."""+ def log_message(self, *args):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ messages = body.get('messages') or [{'role': 'system'}]+ last = messages[-1]+ call = last['role'] == 'user' and last.get('content') == 'PROBE'+ message = ({'role': 'assistant', 'content': None, 'tool_calls': [{'id': f'c{len(messages)}', 'index': 0,+ 'type': 'function', 'function': {'name': 'terminal', 'arguments': json.dumps({'command': PROBE})}}]}+ if call else {'role': 'assistant', 'content': 'OK'})+ choice = {'index': 0, 'delta': message, 'finish_reason': 'tool_calls' if call else 'stop'}+ frame = {'id': 'env', 'model': 'm', 'choices': [choice], 'usage': {'prompt_tokens': 1, 'completion_tokens': 1, 'total_tokens': 2}}+ if body.get('stream'):+ payload, kind = ('data: ' + json.dumps(frame) + '\n\ndata: [DONE]\n\n').encode(), 'text/event-stream'+ else:+ choice['message'] = choice.pop('delta')+ payload, kind = json.dumps(frame).encode(), 'application/json'+ self.send_response(200)+ self.send_header('Content-Type', kind)+ self.send_header('Content-Length', str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+++def _bin(root, name):+ path = root / name / 'bin'+ path.mkdir(parents=True)+ script = path / 'whichclient'+ script.write_text(f'#!/bin/sh\necho {name}\n')+ script.chmod(0o755)+ return path++[email protected]("linux")+def test_managed_workers_run_each_sessions_tools_under_its_client_toolchain(tmp_path):+ from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir(mode=0o700)+ user.mkdir()+ (user / '.hushlogin').touch() # Ubuntu's bash.bashrc sudo hint on stdout+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ threading.Thread(target=peer.serve_forever, daemon=True).start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'multiplex_profiles': False, 'managed_workers': True},+ 'model': {'provider': 'custom', 'default': 'm', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}}, 'approvals': {'mode': 'off'},+ 'platform_toolsets': {'cli': ['terminal']}}))+ system_path = os.environ['PATH']+ bins = {name: _bin(tmp_path, name) for name in ('daemon', 'alpha', 'beta')}+ env = {k: os.environ[k] for k in ('LANG', 'TZ') if k in os.environ}+ env.update(PATH=f'{bins["daemon"]}{os.pathsep}{system_path}', HOME=str(user), USERPROFILE=str(user),+ HERMES_HOME=str(home), PYTHONPATH=str(ROOT), OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)+ # Never printed by the probe: if it shows anywhere public, the private client map leaked.+ sentinels = {name: f'--title=client-env-sentinel-{name}' for name in ('alpha', 'beta')}++ def settled(request_id):+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:+ rows = db.execute('SELECT status FROM session_admissions WHERE request_id=?', (request_id,)).fetchall()+ return rows == [('terminal',)]++ async def exercise(desc):+ outputs, public = {}, []+ async with websocket(home, desc) as ws:+ sessions = {}+ for name in ('alpha', 'beta', 'desktop'):+ client = {} if name == 'desktop' else {'client_env': {+ 'PATH': f'{bins[name]}{os.pathsep}{system_path}', 'NVM_DIR': f'/nvm/{name}',+ 'NODE_OPTIONS': sentinels[name]}}+ created = await rpc(ws, 'session.create', request_id=name, source='cli', cwd=str(home), model='m',+ provider='custom', base_url=url, api_key='loopback-only', toolsets=['terminal'],+ ignore_rules=True, **client)+ assert 'result' in created, created+ sessions[name] = created['result']['session_id']+ public.append(created['result'])+ for name, sid in sessions.items():+ assert 'result' in await rpc(ws, 'prompt.submit', session_id=sid, input_id=f'probe-{name}', text='PROBE')+ for name in sessions:+ await async_wait_until(lambda n=name: settled(f'probe-{n}'), timeout=90, interval=.1,+ what=f'{name} probe to settle')+ for name, sid in sessions.items():+ messages = (await rpc(ws, 'session.resume', session_id=sid))['result']['messages']+ outputs[name] = json.loads([m['content'] for m in messages if m['role'] == 'tool'][-1])['output']+ public.append(await rpc(ws, 'session.info', session_id=sid))+ public.append(await rpc(ws, 'session.list', limit=50))+ return outputs, sessions, public+ try:+ with daemon(ROOT, home, env, barrier=False) as (_owner, desc):+ outputs, sessions, public = asyncio.run(exercise(desc))+ finally:+ peer.shutdown()+ peer.server_close()+ assert outputs['alpha'].strip().endswith('/nvm/alpha|alpha'), outputs+ assert outputs['beta'].strip().endswith('/nvm/beta|beta'), outputs+ assert outputs['desktop'].strip().endswith('|daemon'), outputs # no client_env: the gateway's own+ from hermes_state import SessionDB+ db = SessionDB(home / 'state.db')+ try:+ public += [db.export_session(sid, include_compacted=True) for sid in sessions.values()]+ public += [db.list_sessions_rich(search_query='sentinel', order_by_last_active=True, include_archived=True),+ db.list_sessions_rich(limit=50), db.search_sessions(limit=50),+ db.search_messages('sentinel')]+ finally:+ db.close()+ text = json.dumps(public, default=str)+ assert not [s for s in sentinels.values() if s in text], 'client_env leaked into a public projection'diff --git a/tests/gateway/test_session_client_env.py b/tests/gateway/test_session_client_env.pyindex 3acb5135f4d..eb9fc69f049 100644--- a/tests/gateway/test_session_client_env.py+++ b/tests/gateway/test_session_client_env.py@@ -127,8 +127,9 @@ async def test_client_env_is_filtered_validated_and_never_echoed(tmp_path, monkeowner, connection = await _owner(home, monkeypatch)try:_, policy = _create(owner, connection.actor, home, 'f1', client_env={- 'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'P', 'OPENAI_API_KEY': 'sk-leak', 'HERMES_YOLO_MODE': '1'})- assert policy.client_env() == {'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'P'}+ 'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'P', 'OPENAI_API_KEY': 'sk-leak', 'HERMES_YOLO_MODE': '1',+ 'NODE_CREDS': 'c', 'CONDA_DSN': 'postgres://u:p@h/db', 'NVM_DIR': '/client/.nvm'})+ assert policy.client_env() == {'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'P', 'NVM_DIR': '/client/.nvm'}assert 'client_env' not in json.loads(policy.request_json) # launch_request stays value-freefor bad in ('PATH=/x', {'PATH': 1}, {1: 'x'}):with pytest.raises(RuntimeStoreError) as exc:diff --git a/tests/hermes_cli/test_gateway_client_env.py b/tests/hermes_cli/test_gateway_client_env.pyindex 4472485f85d..0621fbce577 100644--- a/tests/hermes_cli/test_gateway_client_env.py+++ b/tests/hermes_cli/test_gateway_client_env.py@@ -127,6 +127,25 @@ def test_tui_launcher_hands_the_shell_env_to_ink(monkeypatch):_expected(json.loads(captured['HERMES_TUI_CLIENT_ENV']))-def test_tui_bootstrap_keeps_the_client_env_out_of_a_daemon_it_starts():- text = (Path(__file__).resolve().parents[2] / 'ui-tui' / 'scripts' / 'gateway_bootstrap.py').read_text()- assert 'HERMES_TUI_CLIENT_ENV' in text+def test_tui_bootstrap_keeps_the_client_env_out_of_a_daemon_it_starts(monkeypatch):+ """The daemon Ink's bootstrap starts inherits the bootstrap's environment: the shell's client_env+ (and its behaviour values) are gone from it by the time the gateway is ensured."""+ import importlib.util+ import os+ from hermes_cli import gateway_runtime+ path = Path(__file__).resolve().parents[2] / 'ui-tui' / 'scripts' / 'gateway_bootstrap.py'+ spec = importlib.util.spec_from_file_location('tui_gateway_bootstrap_probe', path)+ bootstrap = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(bootstrap)+ monkeypatch.setenv('HERMES_TUI_CLIENT_ENV', json.dumps({'PATH': '/client/bin', 'HERMES_INFERENCE_PROVIDER': 'x'}))+ monkeypatch.setenv('HERMES_INFERENCE_PROVIDER', 'x')+ started = []++ def ensure(home, **kwargs):+ started.append(dict(os.environ))+ return SimpleNamespace(state='failed', reason_code='probe', endpoint=None, detail=None)+ monkeypatch.setattr(gateway_runtime, 'ensure_gateway_runtime', ensure)+ with pytest.raises(RuntimeError, match='probe'):+ bootstrap.bootstrap(True)+ assert len(started) == 1+ assert 'HERMES_TUI_CLIENT_ENV' not in started[0] and 'HERMES_INFERENCE_PROVIDER' not in started[0]diff --git a/tests/tools/test_session_tool_env.py b/tests/tools/test_session_tool_env.pynew file mode 100644index 00000000000..b1da8470995--- /dev/null+++ b/tests/tools/test_session_tool_env.py@@ -0,0 +1,201 @@+"""T3: a local session's tool subprocesses (terminal, background processes, execute_code) start with+its client's allowlisted toolchain environment (PATH, an activated venv, nvm/pyenv/conda), not the+gateway daemon's. Applied to that session only; no full shell snapshot. As on main, the activated venv+reaches terminal children through PATH: ``VIRTUAL_ENV`` itself stays a stripped runtime marker there."""+import asyncio+import os+from types import SimpleNamespace++import pytest++from tests.tools._child_env_fixtures import child_env, run_code++CLIENT = {'PATH': '/client/venv/bin:/usr/bin:/bin', 'VIRTUAL_ENV': '/client/venv', 'NVM_DIR': '/client/.nvm'}+++def daemon_env(monkeypatch):+ monkeypatch.setenv('PATH', '/daemon/bin:/usr/bin:/bin')+ monkeypatch.delenv('VIRTUAL_ENV', raising=False)+ monkeypatch.delenv('NVM_DIR', raising=False)+++def _parts(env):+ return env['PATH'].split(os.pathsep)+++def test_terminal_run_env_starts_from_the_sessions_toolchain(daemon_env):+ from agent.session_client_env import client_env_scope+ from tools.environments.local import _make_run_env+ with client_env_scope(CLIENT):+ env = _make_run_env({})+ assert '/client/venv/bin' in _parts(env) and '/daemon/bin' not in _parts(env)+ assert env['NVM_DIR'] == '/client/.nvm'+ # The backend's own terminal.env still wins over the client's.+ assert _make_run_env({'NVM_DIR': '/configured'})['NVM_DIR'] == '/configured'+ with client_env_scope({'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'p'}): # behaviour names are not tool env+ assert 'HERMES_EPHEMERAL_SYSTEM_PROMPT' not in _make_run_env({})+ env = _make_run_env({}) # messaging/cron/Desktop: the gateway's own environment+ assert '/daemon/bin' in _parts(env) and 'NVM_DIR' not in env+++def test_background_process_env_starts_from_the_sessions_toolchain(daemon_env):+ from agent.session_client_env import client_env_scope+ from tools.process_registry import ProcessRegistry+ with client_env_scope(CLIENT):+ env = ProcessRegistry._spawn_env({})+ assert '/client/venv/bin' in _parts(env) and env['NVM_DIR'] == '/client/.nvm'+ assert '/daemon/bin' in _parts(ProcessRegistry._spawn_env({}))+++def test_execute_code_child_env_starts_from_the_sessions_toolchain(daemon_env, tmp_path):+ import sys+ from agent.session_client_env import client_env_scope+ from tools.code_execution_env import _build_child_env+ kwargs = dict(rpc_endpoint='sock', rpc_token='t', tmpdir=str(tmp_path), child_python=sys.executable)+ with client_env_scope(CLIENT):+ env = _build_child_env(**kwargs)+ assert '/client/venv/bin' in _parts(env) and env['VIRTUAL_ENV'] == '/client/venv'+ assert '/daemon/bin' in _parts(_build_child_env(**kwargs))+++# execute_code's secret names (BEARER, CREDS, DSN, WEBHOOK...) and Hermes control names never travel, even+# under a built-in prefix (NODE_, CONDA_) or a profile's configured extra names.+REFUSED = {'NODE_BEARER': 'b', 'NODE_CREDS': 'c', 'CONDA_DSN': 'postgres://u:p@h/db', 'DEPLOY_WEBHOOK': 'https://h',+ 'HERMES_KANBAN_DB': '/board.db', 'HERMES_DELEGATED_CHILD_CONTEXT': '1'}+++def test_credential_and_control_names_are_refused_by_execute_codes_secret_policy():+ from agent.session_client_env import accept_client_env, collect_client_env+ config = {'terminal': {'client_env_passthrough': ['DEPLOY_WEBHOOK', 'HERMES_KANBAN_DB', 'MY_TOOLCHAIN_HOME']}}+ sent = {**REFUSED, 'NVM_DIR': '/client/.nvm', 'MY_TOOLCHAIN_HOME': '/opt/tc', 'PATH': '/client/bin'}+ kept = {'NVM_DIR': '/client/.nvm', 'MY_TOOLCHAIN_HOME': '/opt/tc', 'PATH': '/client/bin'}+ assert accept_client_env(sent, config) == kept # the gateway, before anything is stored+ assert collect_client_env(sent, config) == kept # the client, before anything is sent+++def test_execute_code_scrubs_after_merging_the_sessions_toolchain(daemon_env, tmp_path):+ """A bound map (say, one committed before this rule) still cannot carry a secret or a control marker+ into the sandbox; the client's non-secret toolchain names (NVM_DIR) do reach it."""+ import sys+ from agent.session_client_env import client_env_scope+ from tools.code_execution_env import _build_child_env+ with client_env_scope({**CLIENT, **REFUSED}):+ env = _build_child_env(rpc_endpoint='sock', rpc_token='t', tmpdir=str(tmp_path), child_python=sys.executable)+ assert env['NVM_DIR'] == '/client/.nvm' and '/client/venv/bin' in _parts(env)+ assert not set(REFUSED) & set(env)++[email protected]('linux', 'macos')[email protected]('child_env') # yields tmp_path: an isolated environment for the real kernel+def test_execute_code_runs_each_sessions_own_interpreter(tmp_path):+ """Project mode picks the interpreter from the session's toolchain: each client's venv, and for a+ client with no venv the gateway's own Python, never the venv of the client that started the daemon."""+ import sys+ import venv+ from pathlib import Path+ from agent.session_client_env import client_env_scope+ roots = {name: tmp_path / name for name in ('alpha', 'beta', 'daemon')}+ for root in roots.values():+ venv.EnvBuilder(with_pip=False, symlinks=False).create(root)+ os.environ['VIRTUAL_ENV'] = str(roots['daemon']) # inherited from whichever client started the gateway+ probe = 'import json, sys; print(json.dumps([sys.executable, sys.prefix]))'++ def child(client):+ with client_env_scope(client):+ return [Path(p) for p in run_code(probe)]+ for name in ('alpha', 'beta'):+ exe, prefix = child({'PATH': f'{roots[name] / "bin"}{os.pathsep}{os.environ["PATH"]}',+ 'VIRTUAL_ENV': str(roots[name])})+ assert exe == roots[name] / 'bin' / 'python' and prefix.resolve() == roots[name].resolve()+ exe, prefix = child({'PATH': os.environ['PATH']}) # a client with no activated venv+ assert prefix.resolve() == Path(sys.prefix).resolve()+ exe, prefix = child(None) # messaging/cron/Desktop: the gateway's own environment, as before+ assert prefix.resolve() == roots['daemon'].resolve()+++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))+ 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'})+++async def test_a_sessions_terminal_runs_with_its_clients_path(tmp_path, monkeypatch, daemon_env):+ """Two CLI sessions on one gateway: each terminal command sees its own client's PATH and venv."""+ from gateway.session_local import create_local_session+ from gateway.session_policy import restore_policy+ from hermes_state_local import local_receipt+ home = tmp_path / 'home'+ home.mkdir()+ (home / 'config.yaml').write_text(+ 'platform_toolsets: {cli: []}\nmodel: {provider: custom, default: m, base_url: http://x.invalid/v1}\n'+ 'terminal: {client_env_passthrough: [MY_TOOLCHAIN_HOME, MY_API_TOKEN]}\n')+ bins = {name: tmp_path / name / 'bin' for name in ('alpha', 'beta')}+ for path in bins.values():+ path.mkdir(parents=True)+ monkeypatch.setenv('PATH', f'/daemon/bin{os.pathsep}{os.environ["PATH"].split(os.pathsep, 1)[-1]}')+ owner, connection = await _owner(home, monkeypatch)+ try:+ policies = {}+ for name, path in bins.items():+ ref = create_local_session(owner, connection.actor, {+ 'request_id': name, 'source': 'cli', 'cwd': str(home), 'toolsets': [],+ 'client_env': {'PATH': f'{path}{os.pathsep}/usr/bin{os.pathsep}/bin', 'NVM_DIR': str(path.parent),+ 'MY_TOOLCHAIN_HOME': f'/opt/{name}', 'MY_API_TOKEN': 'secret', 'UNLISTED': 'x'}})+ policies[name] = restore_policy(local_receipt(owner.db, ref.session_id)['policy'])+ # Listed toolchain names travel; a credential-looking name never lands in the stored policy.+ assert set(policies['alpha'].client_env()) == {'PATH', 'NVM_DIR', 'MY_TOOLCHAIN_HOME'}+ outputs = await asyncio.to_thread(_overlapping_terminal_turns, owner, policies)+ for name, runs in outputs.items():+ for out in runs: # the first command, then again on the cached environment+ path, nvm, toolchain = out.strip().splitlines()[-1].split('|')+ assert str(bins[name]) in path.split(os.pathsep) and '/daemon/bin' not in path.split(os.pathsep)+ assert nvm == str(bins[name].parent) and toolchain == f'/opt/{name}'+ finally:+ from tools.terminal_tool_lifecycle import cleanup_all_environments+ cleanup_all_environments()+ await connection.close()+ owner.db.close()+++def _overlapping_terminal_turns(owner, policies):+ """Each session's turn runs the real terminal entry point (environment cache, shell snapshot)+ with the SAME task id, both turns alive at once, each twice so the second hits the cache."""+ import json+ import threading+ from gateway.session_context import clear_session_vars, set_session_vars+ from gateway.session_policy import policy_scope+ from tools.terminal_tool import terminal_tool+ barrier, outputs, errors = threading.Barrier(len(policies)), {}, []++ def turn(name, policy):+ tokens = set_session_vars(platform='local', session_key=f'agent:main:local:dm:{name}', session_id=name)+ try:+ with policy_scope(policy, authority=owner):+ command = 'echo "$PATH|$NVM_DIR|$MY_TOOLCHAIN_HOME"'+ first = json.loads(terminal_tool(command, task_id='same-task'))['output']+ barrier.wait(timeout=60) # both sessions now hold a cached environment for 'same-task'+ outputs[name] = (first, json.loads(terminal_tool(command, task_id='same-task'))['output'])+ except Exception as exc: # surfaced below: an assertion in a thread would be lost+ errors.append(exc)+ barrier.abort()+ finally:+ clear_session_vars(tokens)+ threads = [threading.Thread(target=turn, args=item) for item in policies.items()]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(timeout=120)+ assert not errors, errors+ return outputsdiff --git a/tools/code_execution_env.py b/tools/code_execution_env.pyindex c4d8ab66afc..a117a546f82 100644--- a/tools/code_execution_env.py+++ b/tools/code_execution_env.py@@ -27,7 +27,12 @@ _SAFE_ENV_PREFIXES = ("PATH", "HOME", "USER", "LANG", "LC_", "TERM", "TMPDIR", "# "PASS" is intentionally absent: it false-positives on BYPASS_CACHE /# COMPASS_DIR / PASSENGER_HOST while PASSWORD/PASSWD already cover credentials._SECRET_SUBSTRINGS = ("KEY", "TOKEN", "SECRET", "PASSWORD", "CREDENTIAL", "PASSWD", "AUTH", "DSN",- "WEBHOOK", "CREDS", "BEARER", "APIKEY")+ "WEBHOOK", "CREDS", "BEARER", "APIKEY", "COOKIE")+++def is_secret_env_name(name: str) -> bool:+ """The credential-name policy, shared with a local session's client environment (``agent.session_client_env``)."""+ return any(s in name.upper() for s in _SECRET_SUBSTRINGS)# Non-secret runtime-location flags that repo-root modules a sandbox script# imports may read at import time. HERMES_DELEGATED_CHILD_CONTEXT must ride@@ -49,12 +54,13 @@ _WINDOWS_ESSENTIAL_ENV_VARS = frozenset({})-def _scrub_child_env(source_env, is_passthrough=None, is_windows=None):+def _scrub_child_env(source_env, is_passthrough=None, is_windows=None, toolchain=frozenset()):"""Produce the scrubbed child-process env for execute_code.Rules, in order: (1) passthrough vars (skill/config-declared) resolvethrough the active profile secret scope — an absent scoped value is- omitted; (2) secret-substring names are blocked; (3) safe prefixes pass;+ omitted; (2) secret-substring names are blocked; (3) safe prefixes pass,+ as do a local session's client ``toolchain`` names (NVM_DIR, GOPATH...);(4) operational HERMES_* pass by exact name; (5) on Windows theOS-essential allowlist passes by exact name."""@@ -78,9 +84,9 @@ def _scrub_child_env(source_env, is_passthrough=None, is_windows=None):if resolved is not None:scrubbed[k] = resolvedcontinue- if any(s in k.upper() for s in _SECRET_SUBSTRINGS):+ if is_secret_env_name(k):continue- if (any(k.startswith(p) for p in _SAFE_ENV_PREFIXES)+ if (any(k.startswith(p) for p in _SAFE_ENV_PREFIXES) or k in toolchainor k in _HERMES_CHILD_ALLOWEDor (is_windows and k.upper() in _WINDOWS_ESSENTIAL_ENV_VARS)):scrubbed[k] = v@@ -117,7 +123,10 @@ def _build_child_env(*, rpc_endpoint: str, rpc_token: str, tmpdir: str,child_python: str) -> dict[str, str]:"""Build the scrubbed child environment both execution paths share."""from hermes_constants import apply_scratch_tmp_env, apply_subprocess_home_env, get_hermes_home_override- child_env = _scrub_child_env(os.environ)+ from agent.session_client_env import tool_env, toolchain_environ+ # A local session's client toolchain replaces the daemon's PATH / venv, then the whole scrub (secret+ # names, delegated-child restrictions) runs over the merged environment.+ child_env = _scrub_child_env(toolchain_environ(), toolchain=frozenset(tool_env()))child_env["HERMES_RPC_SOCKET"] = rpc_endpointchild_env["HERMES_RPC_TOKEN"] = rpc_tokenchild_env["PYTHONDONTWRITEBYTECODE"] = "1"@@ -257,9 +266,11 @@ def _resolve_child_python(mode: str) -> str:VIRTUAL_ENV/CONDA_PREFIX python if it exists and passes the 3.8+ probe, else ``sys.executable``."""if mode != "project":return sys.executable+ from agent.session_client_env import toolchain_environ+ environ = toolchain_environ() # a local session's: its client's venv/conda, not the daemon'ssubdir, exe_names = ("Scripts", ("python.exe", "python3.exe")) if _IS_WINDOWS else ("bin", ("python", "python3"))for var in ("VIRTUAL_ENV", "CONDA_PREFIX"):- root = os.environ.get(var, "").strip()+ root = environ.get(var, "").strip()for exe in exe_names if root else ():candidate = os.path.join(root, subdir, exe)if not (os.path.isfile(candidate) and os.access(candidate, os.X_OK)):diff --git a/tools/environments/local.py b/tools/environments/local.pyindex 9ac93d9b8e6..53c83db7009 100644--- a/tools/environments/local.py+++ b/tools/environments/local.py@@ -770,9 +770,12 @@ def _make_run_env(env: dict) -> dict:"""Build a run environment with a sane PATH and provider-var stripping. The process env isthe LAUNCH profile's; under a routed home override its ``.env`` residue is dropped first(``strip_launch_profile_env``, a no-op for the launch profile) so the backend's own ``env``- and the served profile's declared passthrough names are what the child sees."""+ and the served profile's declared passthrough names are what the child sees. A local session's+ client toolchain (PATH, venv, nvm/pyenv/conda: ``agent.session_client_env``) replaces the daemon's+ beneath the backend's own ``env``."""+ from agent.session_client_env import toolchain_environrun_env = _scrubbed_env(- [(dict(strip_launch_profile_env(os.environ.copy()) | env), True)],+ [(dict(toolchain_environ(strip_launch_profile_env(os.environ.copy())) | env), True)],frozenset(),lambda p: _user_tools_first(_append_missing_sane_path_entries(p)),)diff --git a/tools/process_registry.py b/tools/process_registry.pyindex 1de5ff14398..6f915c15b4b 100644--- a/tools/process_registry.py+++ b/tools/process_registry.py@@ -1128,9 +1128,9 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin, ProcessOu@staticmethoddef _spawn_env(env_vars: dict) -> dict:- """Sanitized child env; PYTHONUNBUFFERED so tqdm/datasets-style buffering- doesn't hide progress from process(action="poll")."""- env = _terminal_env(_sanitize_subprocess_env(os.environ, env_vars))+ """Sanitized child env from the session's client toolchain; PYTHONUNBUFFERED so poll sees progress."""+ from agent.session_client_env import toolchain_environ+ env = _terminal_env(_sanitize_subprocess_env(toolchain_environ(), env_vars))env["PYTHONUNBUFFERED"] = "1"return env