The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(ssh): isolate prompt backend probes from file sync
Ruichen Zhou50b54bb18f0f
diff --git a/agent/prompt_builder.py b/agent/prompt_builder.pyindex 69c7a729068..eb65ad35639 100644--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@ -876,19 +876,20 @@ def _run_backend_probe(env_type: str, terminal_tool) -> str:container_config=(_container_config_from_config(config)if terminal_tool._is_container_backend(env_type) else None),task_id="prompt-backend-probe", host_cwd=config.get("host_cwd"),+ # ssh: an isolated ControlMaster socket and no remote dir setup / file sync / snapshot —+ # a normal SSHEnvironment would upload the whole ~/.hermes tree just to run `uname`, and+ # its later __del__ would sync_back() and close the master shared with the agent's own env.+ probe_only=env_type == "ssh",)try:result = env.execute(_BACKEND_PROBE_CMD, timeout=4)finally:# One-shot `uname`; without teardown the backend leaves a second idle sandbox# (task_id="prompt-backend-probe") running for the whole process next to the agent's own.- # ssh is left alone: no task-scoped sandbox, and its cleanup() closes a ControlMaster socket- # (keyed by user@host:port) shared with the agent's real environment; ControlPersist expires it.- if env_type != "ssh":- try:- _cleanup_env(env, force_remove=True)- except Exception:- logger.debug("Backend probe cleanup failed", exc_info=True)+ try:+ _cleanup_env(env, force_remove=True)+ except Exception:+ logger.debug("Backend probe cleanup failed", exc_info=True)if result.get("returncode") != 0:logger.debug("Backend probe returned non-zero: %r", result)return ""diff --git a/tests/agent/test_prompt_builder.py b/tests/agent/test_prompt_builder.pyindex 0e23a752577..a3dd7becc7a 100644--- a/tests/agent/test_prompt_builder.py+++ b/tests/agent/test_prompt_builder.py@@ -932,18 +932,20 @@ class TestEnvironmentHints:assert _pb._probe_remote_backend("singularity") is not Noneassert calls == ["bare"]- def test_probe_remote_backend_does_not_tear_down_ssh(self, monkeypatch):- """SSH has no task-scoped sandbox: its cleanup() closes a ControlMaster- socket shared with the agent's real environment, so the probe must- leave it alone (nothing leaks — ControlPersist expires the master)."""+ def test_probe_remote_backend_ssh_is_probe_only_and_torn_down(self, monkeypatch):+ """SSH probe: a normal SSHEnvironment would create remote dirs, force-upload+ ~/.hermes and snapshot a session just to run `uname`, and its __del__ would+ later sync_back() and close the ControlMaster shared with the agent's real+ environment. The probe must request a probe-only instance (own socket, no+ setup/sync) and tear it down itself."""import agent.prompt_builder as _pbmonkeypatch.setenv("TERMINAL_ENV", "ssh")_pb._clear_backend_probe_cache()- calls = []+ created, calls = {}, []- class _SharedSshEnv:+ class _ProbeSshEnv:def execute(self, cmd, timeout=None):return {"returncode": 0,@@ -957,10 +959,36 @@ class TestEnvironmentHints:calls.append("cleanup")import tools.terminal_tool_backends as _tt- monkeypatch.setattr(_tt, "_create_environment", lambda **kw: _SharedSshEnv())++ def _fake_create(**kw):+ created.update(kw)+ return _ProbeSshEnv()++ monkeypatch.setattr(_tt, "_create_environment", _fake_create)assert _pb._probe_remote_backend("ssh") is not None- assert calls == []+ assert created["probe_only"] is True+ assert calls == ["cleanup"]++ def test_probe_remote_backend_ssh_cleanup_error_keeps_result(self, monkeypatch):+ """A failing teardown of the throwaway probe connection must not discard the+ metadata the probe already collected."""+ import agent.prompt_builder as _pb++ monkeypatch.setenv("TERMINAL_ENV", "ssh")+ _pb._clear_backend_probe_cache()++ class _Env:+ def execute(self, cmd, timeout=None):+ return {"returncode": 0, "output": "os=Linux\nkernel=6.8.0\nhome=/h\ncwd=/h\nuser=u\n"}++ def cleanup(self):+ raise RuntimeError("cleanup failed")++ import tools.terminal_tool_backends as _tt+ monkeypatch.setattr(_tt, "_create_environment", lambda **kw: _Env())++ assert "Linux 6.8.0" in _pb._probe_remote_backend("ssh")def test_environment_hint_from_env_var_is_appended(self, monkeypatch):diff --git a/tests/tools/test_ssh_environment.py b/tests/tools/test_ssh_environment.pyindex 9c99f25cb66..a05975429c0 100644--- a/tests/tools/test_ssh_environment.py+++ b/tests/tools/test_ssh_environment.py@@ -233,6 +233,64 @@ class TestSSHPreflight:assert env.user == "alice"+def _mock_ssh_runtime(monkeypatch, tmp_path):+ hooks = {+ "_establish_connection": MagicMock(),+ "_detect_remote_home": MagicMock(return_value="/home/alice"),+ "_ensure_remote_dirs": MagicMock(),+ "init_session": MagicMock(),+ }+ monkeypatch.setattr(ssh_env.tempfile, "gettempdir", lambda: str(tmp_path))+ monkeypatch.setattr(ssh_env.shutil, "which", lambda _name: "/usr/bin/ssh")+ for name, hook in hooks.items():+ monkeypatch.setattr(ssh_env.SSHEnvironment, name, hook)+ hooks["sync_factory"] = MagicMock(return_value=MagicMock())+ monkeypatch.setattr(ssh_env, "FileSyncManager", hooks["sync_factory"])+ return hooks+++class TestSSHProbeOnly:+ def test_probe_only_skips_state_sync_and_session_setup(self, _mock_ssh_runtime):+ env = ssh_env.SSHEnvironment(host="example.com", user="alice", probe_only=True)+ env._before_execute()+ env.cleanup()++ _mock_ssh_runtime["_establish_connection"].assert_called_once_with()+ _mock_ssh_runtime["_detect_remote_home"].assert_not_called()+ _mock_ssh_runtime["_ensure_remote_dirs"].assert_not_called()+ _mock_ssh_runtime["sync_factory"].assert_not_called()+ _mock_ssh_runtime["init_session"].assert_not_called()+ assert env._sync_manager is None++ def test_probe_only_control_socket_is_isolated(self, monkeypatch, _mock_ssh_runtime):+ control_exit_calls = []++ def _fake_run(*args, **kwargs):+ control_exit_calls.append(args[0])+ return subprocess.CompletedProcess([], 0)++ monkeypatch.setattr(ssh_env.subprocess, "run", _fake_run)++ normal = ssh_env.SSHEnvironment(host="example.com", user="alice")+ first_probe = ssh_env.SSHEnvironment(host="example.com", user="alice", probe_only=True)+ second_probe = ssh_env.SSHEnvironment(host="example.com", user="alice", probe_only=True)++ assert first_probe.control_socket != normal.control_socket+ assert second_probe.control_socket != first_probe.control_socket+ assert len(first_probe.control_socket.name) == len(normal.control_socket.name)++ normal.control_socket.touch()+ first_probe.control_socket.touch()+ first_probe.cleanup()+ first_probe.cleanup()++ assert normal.control_socket.exists()+ assert not first_probe.control_socket.exists()+ assert len(control_exit_calls) == 1+ normal.cleanup()++def _setup_ssh_env(monkeypatch, persistent: bool):monkeypatch.setenv("TERMINAL_ENV", "ssh")monkeypatch.setenv("TERMINAL_SSH_HOST", _SSH_HOST)diff --git a/tools/environments/ssh.py b/tools/environments/ssh.pyindex 04f2a6e43b8..3c97735df26 100644--- a/tools/environments/ssh.py+++ b/tools/environments/ssh.py@@ -48,6 +48,7 @@ class SSHEnvironment(BaseEnvironment):Spawn-per-call: every execute() spawns a fresh ``ssh ... bash -c`` process.Session snapshot preserves env vars across calls; CWD persists via in-bandstdout markers. Uses SSH ControlMaster for connection reuse.+ Probe-only instances use an isolated connection without sync or session state."""# Passthrough values are re-forwarded on every command (see _run_bash), so like docker/local@@ -55,18 +56,29 @@ class SSHEnvironment(BaseEnvironment):_profile_scoped_passthrough = Truedef __init__(self, host: str, user: str, cwd: str = "~",- timeout: int = 60, port: int = 22, key_path: str = ""):+ timeout: int = 60, port: int = 22, key_path: str = "",+ probe_only: bool = False):super().__init__(cwd=cwd, timeout=timeout)self.host, self.user, self.port, self.key_path = host, user, port, key_path+ self._probe_only = probe_only+ self._sync_manager = Noneself.control_dir = Path(tempfile.gettempdir()) / "hermes-ssh"self.control_dir.mkdir(parents=True, exist_ok=True)# Short, deterministic socket name: the path must stay under macOS's 104-byte sun_path# limit (raw user@host:port + SSH's 16-byte suffix under a deep $TMPDIR exceeds it), and- # stability across reconnects keeps ControlMaster reuse working.- _socket_id = hashlib.sha256(f"{user}@{host}:{port}".encode()).hexdigest()[:16]+ # stability across reconnects keeps ControlMaster reuse working. A probe gets its own+ # per-instance socket so its cleanup() can never close the agent's shared master.+ socket_key = f"{user}@{host}:{port}"+ if self._probe_only:+ socket_key = f"{socket_key}:probe:{self._session_id}"+ _socket_id = hashlib.sha256(socket_key.encode()).hexdigest()[:16]self.control_socket = self.control_dir / f"{_socket_id}.sock"_ensure_ssh_available()self._establish_connection()+ if self._probe_only:+ self._remote_home = ""+ return+self._remote_home = self._detect_remote_home()self._ensure_remote_dirs()self._sync_manager = FileSyncManager(@@ -247,7 +259,8 @@ class SSHEnvironment(BaseEnvironment):f"Remote file cleanup on {self.host}")def _before_execute(self) -> None:- self._sync_manager.sync() # rate-limited internally+ if self._sync_manager is not None:+ self._sync_manager.sync() # rate-limited internallydef _run_bash(self, cmd_string: str, *, login: bool = False, timeout: int = 120,stdin_data: str | None = None) -> subprocess.Popen:diff --git a/tools/terminal_tool_backends.py b/tools/terminal_tool_backends.pyindex 63a3dd19256..335bb1c3048 100644--- a/tools/terminal_tool_backends.py+++ b/tools/terminal_tool_backends.py@@ -173,11 +173,11 @@ _build_daytona_env = functools.partial(_build_sandbox_env, "daytona")_build_vercel_env = functools.partial(_build_sandbox_env, "vercel_sandbox")-def _build_ssh_env(*, cwd, timeout, ssh_config, **_):+def _build_ssh_env(*, cwd, timeout, ssh_config, probe_only=False, **_):if not ssh_config or not ssh_config.get("host") or not ssh_config.get("user"):raise ValueError("SSH environment requires ssh_host and ssh_user to be configured")return _SSHEnvironment(host=ssh_config["host"], user=ssh_config["user"], port=ssh_config.get("port", 22),- key_path=ssh_config.get("key", ""), cwd=cwd, timeout=timeout)+ key_path=ssh_config.get("key", ""), cwd=cwd, timeout=timeout, probe_only=probe_only)def _build_plugin_env(*, env_type, image, cwd, timeout, cc, task_id, **_):@@ -210,13 +210,14 @@ _ENV_BUILDERS = {"local": _build_local_env, "docker": _build_docker_env, "singuldef _create_environment(env_type: str, image: str, cwd: str, timeout: int,ssh_config: dict = None, container_config: dict = None,local_config: dict = None, task_id: str = "default",- host_cwd: Optional[str] = None):+ host_cwd: Optional[str] = None, probe_only: bool = False):"""Create an execution environment (instance with ``execute()``) for *env_type*. ``image`` is ignoredfor local/ssh/vercel; ``container_config`` carries the container_*/docker_* resource keys; ``host_cwd`` is- the host dir bound into Docker when cwd mounting is enabled. Unknown types fall through to plugin backends."""+ the host dir bound into Docker when cwd mounting is enabled. ``probe_only`` asks ssh for a throwaway+ connection with no remote setup/sync (the prompt-time probe). Unknown types fall through to plugin backends."""builder = _ENV_BUILDERS.get(env_type, _build_plugin_env)return builder(env_type=env_type, image=image, cwd=cwd, timeout=timeout, cc=container_config or {},- task_id=task_id, ssh_config=ssh_config, host_cwd=host_cwd)+ task_id=task_id, ssh_config=ssh_config, host_cwd=host_cwd, probe_only=probe_only)# --- Requirement checkers: one generic path driven by _BACKEND_SPECS; optional fields, checked in order: