The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(environments): share the unset-prelude and client-env helpers; drop test-only shape from ssh
kshitijk4poorbaf7ceeaceac
diff --git a/tests/tools/test_ssh_environment.py b/tests/tools/test_ssh_environment.pyindex 41ebf3db5e1..9c99f25cb66 100644--- a/tests/tools/test_ssh_environment.py+++ b/tests/tools/test_ssh_environment.py@@ -76,11 +76,6 @@ class TestBuildSSHCommand:env = SSHEnvironment(host="h", user="u")assert env._build_ssh_command()[-1] == "u@h"- def _bare_env(self):- env = SSHEnvironment.__new__(SSHEnvironment)- env.control_socket, env.host, env.user, env.port, env.key_path = "/tmp/hermes-ssh-test.sock", "h", "u", 22, ""- return env-def _capture_run_bash(self, monkeypatch, env, cmd="echo ok"):captured = {}@@ -97,7 +92,7 @@ class TestBuildSSHCommand:provider credentials on the allowlist stay behind; a .env value fills an unset shell var."""import tools.env_passthrough as env_passthrough- env = self._bare_env()+ env = SSHEnvironment(host="h", user="u")monkeypatch.setenv("NEXTCLOUD_URL", "https://next.example")monkeypatch.delenv("NEXTCLOUD_PASS", raising=False)monkeypatch.setenv("OPENAI_API_KEY", "sk-must-not-forward")@@ -119,7 +114,7 @@ class TestBuildSSHCommand:import tools.env_passthrough as env_passthroughmonkeypatch.setattr(env_passthrough, "get_all_passthrough", lambda: frozenset())- captured = self._capture_run_bash(monkeypatch, self._bare_env())+ captured = self._capture_run_bash(monkeypatch, SSHEnvironment(host="h", user="u"))assert not any(a.startswith("SendEnv=") for a in captured["cmd"])assert captured["env"] is Nonediff --git a/tools/environments/docker.py b/tools/environments/docker.pyindex b0407c7b476..6df975ad861 100644--- a/tools/environments/docker.py+++ b/tools/environments/docker.py@@ -28,7 +28,8 @@ from tools.environments.docker_egress import (check_forward_env_collisions, merge_egress_env,)from tools.environments.path_utils import sanitize_task_id_for_path-from tools.environments.remote_common import bash_argv, load_hermes_env_vars, resolve_passthrough_env, run_capture+from tools.environments.remote_common import (+ bash_argv, client_env_with, load_hermes_env_vars, prepend_unset, resolve_passthrough_env, run_capture)logger = logging.getLogger(__name__)@@ -760,7 +761,7 @@ class DockerEnvironment(BaseEnvironment):live in ``/proc/<pid>/environ`` instead, which is owner/root-only. Returns ``None`` (inherit asbefore) when there is nothing to add."""- return {**os.environ, **values} if values else None+ return client_env_with(values)def _build_init_env_args(self) -> list[str]:"""Name-only ``-e`` args for init_session so ``export -p`` captures docker_env@@ -778,9 +779,8 @@ class DockerEnvironment(BaseEnvironment):return _name_only_env_args(exec_env)def _resolve_passthrough_env(self) -> tuple[dict[str, str], set[str]]:- """Forwarded values plus scoped names that must be unset; explicit docker_forward_env- entries bypass the blocklist (see ``remote_common.resolve_passthrough_env``)."""- return resolve_passthrough_env(self._forward_env, hermes_env_loader=lambda: _load_hermes_env_vars())+ """See ``remote_common.resolve_passthrough_env``; explicit docker_forward_env bypasses the blocklist."""+ return resolve_passthrough_env(self._forward_env, hermes_env_loader=_load_hermes_env_vars)def _build_runtime_env_args_with_unsets(self) -> tuple[list[str], tuple[str, ...], dict[str, str]]:"""Runtime name-only forwarding args, names absent from scope, and the values@@ -815,10 +815,7 @@ class DockerEnvironment(BaseEnvironment):elif self._profile_scoped_passthrough:runtime_args, unset_names, env_values = self._build_runtime_env_args_with_unsets()cmd.extend(runtime_args)- if unset_names:- quoted_names = " ".join(shlex.quote(name) for name in unset_names)- cmd_string = f"unset {quoted_names} 2>/dev/null || true\n{cmd_string}"- cmd += [self._container_id, *bash_argv(cmd_string, login)]+ cmd += [self._container_id, *bash_argv(prepend_unset(cmd_string, unset_names), login)]client_env = self._docker_client_env(env_values)return _popen_bash(cmd, stdin_data, env=client_env) if client_env is not None else _popen_bash(cmd, stdin_data)diff --git a/tools/environments/remote_common.py b/tools/environments/remote_common.pyindex ea989502008..537cc0c5181 100644--- a/tools/environments/remote_common.py+++ b/tools/environments/remote_common.py@@ -3,6 +3,7 @@from __future__ import annotationsimport os+import shleximport subprocessfrom typing import Callable, Iterable@@ -29,7 +30,7 @@ def resolve_passthrough_env(explicit_forward: Iterable[str] = (),check; ``explicit_forward`` entries (docker_forward_env) are an operator opt-in that bypassesboth. Each value is the routed profile's secret when multiplex is active; a name the activescope lacks is returned in the unset set so a shared sandbox cannot leak another profile's- value. ``hermes_env_loader`` is a parameter so each backend keeps its own patchable seam.+ value."""passthrough_keys: set[str] = set()resolve_passthrough_value = None@@ -58,6 +59,20 @@ def resolve_passthrough_env(explicit_forward: Iterable[str] = (),return exec_env, unset_names+def prepend_unset(cmd_string: str, names: Iterable[str]) -> str:+ """Prefix ``cmd_string`` with ``unset`` of the profile-scoped names the remote shell must not see."""+ names = sorted(names)+ if not names:+ return cmd_string+ return f"unset {' '.join(shlex.quote(n) for n in names)} 2>/dev/null || true\n{cmd_string}"+++def client_env_with(values: dict[str, str]) -> dict[str, str] | None:+ """Env for the docker/ssh CLIENT subprocess: forwarded values travel here (owner-readable+ /proc/*/environ) while the argv carries names only; ``None`` = inherit when nothing to add."""+ return {**os.environ, **values} if values else None++def run_capture(cmd: list[str], *, timeout: float, check: bool = False, env: dict | None = None,) -> subprocess.CompletedProcess:"""``subprocess.run`` with the backend-standard capture settings: text mode with utf-8/replacediff --git a/tools/environments/ssh.py b/tools/environments/ssh.pyindex b967896b7b9..04f2a6e43b8 100644--- a/tools/environments/ssh.py+++ b/tools/environments/ssh.py@@ -15,7 +15,8 @@ from tools.environments.base import BaseEnvironment, EnvironmentConnectionErrorfrom tools.environments.base_output import _popen_bashfrom tools.environments.file_sync import (FileSyncManager, iter_sync_files, quoted_mkdir_command, quoted_rm_command, unique_parent_dirs)-from tools.environments.remote_common import bash_argv, load_hermes_env_vars, resolve_passthrough_env, run_capture+from tools.environments.remote_common import (+ bash_argv, client_env_with, load_hermes_env_vars, prepend_unset, resolve_passthrough_env, run_capture)logger = logging.getLogger(__name__)@@ -255,11 +256,10 @@ class SSHEnvironment(BaseEnvironment):client's env carries the values, so secrets never enter the remote ``bash -c`` argv. Theremote sshd must ``AcceptEnv`` them (#14091). Profile-scoped names missing from the activescope are unset remotely so a shared host cannot serve another profile's value."""- values, unset_names = resolve_passthrough_env(hermes_env_loader=lambda: _load_hermes_env_vars())- if unset_names:- cmd_string = f"unset {' '.join(shlex.quote(n) for n in sorted(unset_names))} 2>/dev/null || true\n{cmd_string}"- cmd = self._build_ssh_command(send_env=sorted(values)) + bash_argv(shlex.quote(cmd_string), login)- return _popen_bash(cmd, stdin_data, env={**os.environ, **values}) if values else _popen_bash(cmd, stdin_data)+ values, unset_names = resolve_passthrough_env(hermes_env_loader=_load_hermes_env_vars)+ cmd = self._build_ssh_command(send_env=values) + bash_argv(shlex.quote(prepend_unset(cmd_string, unset_names)), login)+ client_env = client_env_with(values)+ return _popen_bash(cmd, stdin_data, env=client_env) if client_env is not None else _popen_bash(cmd, stdin_data)def cleanup(self):if self._sync_manager: