Skip to content

The agent that grows with you

fix(terminal): review follow-ups for plugin cwd and stream hooks

unsupportedpastels71633f762d2d
diff --git a/tests/tools/test_terminal_plugin_cwd_and_streams.py b/tests/tools/test_terminal_plugin_cwd_and_streams.py
index 747e7fe55e4..4a84d0e35a7 100644
--- a/tests/tools/test_terminal_plugin_cwd_and_streams.py
+++ b/tests/tools/test_terminal_plugin_cwd_and_streams.py
@@ -64,6 +64,7 @@ def _providers(monkeypatch):
for provider in (_PlainProvider(), _SpaceProvider(), _HomeProvider()):
reg.register_provider(provider)
monkeypatch.delenv("TERMINAL_CWD", raising=False)
+ monkeypatch.setattr(file_tools_paths, "_ssh_home_failed_at", {})
yield
reg._reset_for_tests()
@@ -131,3 +132,57 @@ def test_streams_spawn_through_the_plugin_environments_exec_prefix(monkeypatch):
streams.open_stream(_SpaceEnv(), ["cua-driver", "mcp"], child_env={"DISPLAY": ":20"})
assert spawned[0][:6] == ["spacectl", "exec", "box-1", "--", "bash", "-c"]
assert "export DISPLAY=:20;" in spawned[0][6] and "exec cua-driver mcp" in spawned[0][6]
+
+
+def test_a_declared_home_is_kept_when_terminal_cwd_starts_the_sandbox_elsewhere(monkeypatch):
+ env = _create("spacebox", "t1", cwd="/workspace") # terminal.cwd picked another in-sandbox directory
+ assert env._hermes_sandbox_home == "/home/space"
+ monkeypatch.setattr(terminal_tool, "get_session_cwd", lambda _key: "/home/space/project")
+ assert terminal_tool._resolve_command_cwd(
+ workdir=None, default_cwd="/workspace", session_key="t1", env_type="spacebox", env=env) == "/home/space/project"
+
+
+def test_a_string_exec_prefix_is_refused_instead_of_split_into_characters():
+ class _StringPrefixEnv(_SpaceEnv):
+ def exec_prefix(self, *, user=None, interactive=True):
+ return "spacectl exec box-1 --"
+
+ assert streams.exec_prefix(_StringPrefixEnv()) is None
+
+
+def test_a_failed_sandbox_bring_up_is_not_retried_on_every_path_resolution(monkeypatch):
+ from tools import terminal_tool_lifecycle
+
+ attempts = []
+
+ def _unreachable(task_id="default"):
+ attempts.append(task_id)
+ raise ConnectionError("sandbox unreachable")
+
+ monkeypatch.setenv("TERMINAL_ENV", "homebox")
+ monkeypatch.setattr(terminal_tool_lifecycle, "get_active_env", lambda _task_id: None)
+ monkeypatch.setattr(file_tools, "_get_file_ops", _unreachable)
+ assert file_tools_paths._container_default_cwd("sess") is None
+ assert file_tools_paths._container_default_cwd("sess") is None
+ assert attempts == ["sess"]
+
+
+def test_desktop_scratch_dir_works_for_an_environment_without_get_temp_dir():
+ from tools.bot_desktop import sandbox_host
+
+ assert not hasattr(_SpaceEnv(), "get_temp_dir")
+ assert sandbox_host._remote_dir(_SpaceEnv(), "p1") == "/tmp/hermes-bot-desktop/p1"
+
+
+def test_missing_desktop_stack_hint_names_no_config_key_for_a_plugin_backend(monkeypatch):
+ from tools.bot_desktop import runtime, sandbox_host
+
+ monkeypatch.setattr(placement, "_setting", lambda: "auto")
+ monkeypatch.setattr(placement, "_terminal_backend", lambda: "spacebox")
+ monkeypatch.setattr(placement, "_plugin_host_isolated", lambda: False)
+ monkeypatch.setattr(placement, "terminal_environment", lambda *, create=True: _SpaceEnv())
+ monkeypatch.setattr(sandbox_host, "missing_binaries", lambda env: ["Xvnc"])
+ monkeypatch.setattr(sandbox_host, "published_env", lambda env, profile: {})
+ blocker = runtime.status().blocker
+ assert "terminal.spacebox_image" not in blocker
+ assert "spacebox plugin" in blocker and "placement: gateway" in blocker
diff --git a/tools/bot_desktop/runtime.py b/tools/bot_desktop/runtime.py
index 8107e5cc9fb..e828e592795 100644
--- a/tools/bot_desktop/runtime.py
+++ b/tools/bot_desktop/runtime.py
@@ -602,9 +602,11 @@ def _sandbox_status(profile: Optional[str], where) -> DesktopStatus:
blocker = None
image_switch = None
if missing:
- blocker = (f"The terminal backend's sandbox image lacks {', '.join(missing)}. Use "
- f"{sandbox_host.SANDBOX_IMAGE_HINT} as terminal.{where.backend}_image (the default sandbox base "
- f"plus the desktop stack), or set bot_desktop.placement: gateway.")
+ advice = sandbox_host.plugin_image_advice(where.backend) or (
+ f"use {sandbox_host.SANDBOX_IMAGE_HINT} as terminal.{where.backend}_image (the default sandbox base "
+ f"plus the desktop stack)")
+ blocker = (f"The terminal backend's sandbox image lacks {', '.join(missing)}. {advice[0].upper()}{advice[1:]}, "
+ f"or set bot_desktop.placement: gateway.")
if where.backend == "docker":
# The usual reason on an upgraded install: the persisted container predates the default
# flip and was kept on purpose. The pane offers the switch instead of a config hint.
diff --git a/tools/bot_desktop/sandbox_host.py b/tools/bot_desktop/sandbox_host.py
index f88b1bdf9c3..9b707051047 100644
--- a/tools/bot_desktop/sandbox_host.py
+++ b/tools/bot_desktop/sandbox_host.py
@@ -52,6 +52,16 @@ _RELAY = (
)
+def plugin_image_advice(backend: Optional[str]) -> Optional[str]:
+ """How to get the desktop stack into a plugin backend's sandbox, or None for a built-in backend: a plugin
+ picks its image through its own settings, so there is no ``terminal.<plugin>_image`` key to name."""
+ from tools.terminal_tool_config import _BUILTIN_BACKENDS
+ if not backend or backend in _BUILTIN_BACKENDS:
+ return None
+ return (f"give the {backend} plugin's sandbox the desktop stack through the plugin's own image setting "
+ f"({SANDBOX_IMAGE_HINT} has it)")
+
+
def _marker() -> Path:
return get_hermes_home() / "bot-desktop" / "sandbox.json"
@@ -100,7 +110,7 @@ def marker_sandbox_alive(marker: dict[str, Any]) -> bool:
def _remote_dir(env: Any, profile: str) -> str:
- return f"{env.get_temp_dir().rstrip('/')}/hermes-bot-desktop/{profile}"
+ return f"{streams.sandbox_temp_dir(env).rstrip('/')}/hermes-bot-desktop/{profile}"
def desktop_home(env: Any) -> str:
@@ -223,10 +233,12 @@ def start(env: Any, profile: str, *, geometry: str, wait_seconds: float = 20.0,
stop(env, profile) # a dead launcher may have left Xvnc holding :20; the relaunch needs it gone
missing = missing_binaries(env)
if missing:
+ advice = plugin_image_advice(getattr(env, "_hermes_backend_name", None)) or (
+ f"use {SANDBOX_IMAGE_HINT} (the default sandbox base plus the desktop stack) as "
+ f"terminal.docker_image / modal_image / singularity_image")
raise RuntimeError(
f"Bot Desktop needs {', '.join(missing)} inside the terminal backend's sandbox. The configured image "
- f"does not have them; use {SANDBOX_IMAGE_HINT} (the default sandbox base plus the desktop stack) as "
- f"terminal.docker_image / modal_image / singularity_image, or set bot_desktop.placement: gateway.")
+ f"does not have them; {advice}, or set bot_desktop.placement: gateway.")
user = _user_for(env)
launcher = (Path(__file__).with_name("launcher.sh").read_bytes())
wallpaper = Path(__file__).with_name("wallpaper.png").read_bytes()
diff --git a/tools/browser_tool_session.py b/tools/browser_tool_session.py
index 745c57d98e2..09e414471bb 100644
--- a/tools/browser_tool_session.py
+++ b/tools/browser_tool_session.py
@@ -606,7 +606,8 @@ def _sandbox_close_daemon(session_name: str) -> None:
def _sandbox_socket_dir(env) -> str:
- return f"{env.get_temp_dir().rstrip('/')}/hermes-bot-desktop/agent-browser"
+ from tools.environments import streams
+ return f"{streams.sandbox_temp_dir(env).rstrip('/')}/hermes-bot-desktop/agent-browser"
def sandbox_screenshot_path(host_path: Path) -> Optional[str]:
@@ -617,7 +618,8 @@ def sandbox_screenshot_path(host_path: Path) -> Optional[str]:
env = _bd_runtime._sandbox_env(create=False)
if env is None:
return None
- return f"{env.get_temp_dir().rstrip('/')}/hermes-bot-desktop/shots/{host_path.name}"
+ from tools.environments import streams
+ return f"{streams.sandbox_temp_dir(env).rstrip('/')}/hermes-bot-desktop/shots/{host_path.name}"
def fetch_sandbox_file(remote_path: str, local_dest: Path, *, max_bytes: int = 16 * 1024 * 1024) -> bool:
@@ -723,9 +725,9 @@ def _sandbox_wrap(cmd_parts: list[str], browser_env: dict[str, str], task_socket
remote_env["AGENT_BROWSER_SOCKET_DIR"] = _sandbox_socket_dir(env)
remote_env.pop("AGENT_BROWSER_EXECUTABLE_PATH", None) # the sandbox image's Playwright Chromium, not a host path
remote_env["AGENT_BROWSER_PROFILE"] = sandbox_host.browser_profile_dir(env) # persists with the container, not its tmpfs
- remote_env["TMPDIR"] = env.get_temp_dir()
+ remote_env["TMPDIR"] = streams.sandbox_temp_dir(env)
if not getattr(env, "_bd_browser_dirs_ready", False):
- streams.run_in(env, ["mkdir", "-p", _sandbox_socket_dir(env), f"{env.get_temp_dir().rstrip('/')}/hermes-bot-desktop/shots",
+ streams.run_in(env, ["mkdir", "-p", _sandbox_socket_dir(env), f"{remote_env['TMPDIR'].rstrip('/')}/hermes-bot-desktop/shots",
remote_env["AGENT_BROWSER_PROFILE"]], user=sandbox_host._user_for(env), timeout=15)
env._bd_browser_dirs_ready = True
remote_env["AGENT_BROWSER_ARGS"] = ",".join(CHROMIUM_SANDBOX_BYPASS_ARGS) # container: no userns for Chromium's own sandbox
diff --git a/tools/environments/streams.py b/tools/environments/streams.py
index cc5092acab5..75751c36416 100644
--- a/tools/environments/streams.py
+++ b/tools/environments/streams.py
@@ -65,7 +65,20 @@ def _plugin_exec_prefix(env: BaseEnvironment, *, user: Optional[str], interactiv
logger.warning("%s.exec_prefix() failed; treating the backend as unable to stream",
type(env).__name__, exc_info=True)
return None
- return [str(part) for part in prefix] if prefix else None
+ if not prefix:
+ return None
+ if not isinstance(prefix, (list, tuple)):
+ # A plain string would be split into one-character argv words.
+ logger.warning("%s.exec_prefix() returned %s, not a list of argv words; treating the backend as unable "
+ "to stream", type(env).__name__, type(prefix).__name__)
+ return None
+ return [str(part) for part in prefix]
+
+
+def sandbox_temp_dir(env: BaseEnvironment) -> str:
+ """``env.get_temp_dir()``, or ``/tmp`` for a plugin environment that doesn't subclass ``BaseEnvironment``."""
+ get_temp_dir = getattr(env, "get_temp_dir", None)
+ return str(get_temp_dir()) if callable(get_temp_dir) else "/tmp" # no-tmp: ok — sandbox-side temp dir
def supports_streams(env: BaseEnvironment) -> bool:
diff --git a/tools/file_tools_paths.py b/tools/file_tools_paths.py
index ebcfd1c50b8..2391b65a336 100644
--- a/tools/file_tools_paths.py
+++ b/tools/file_tools_paths.py
@@ -23,7 +23,8 @@ _TERMINAL_CWD_SENTINELS = frozenset({"", ".", "./", "auto", "cwd"})
_CONTAINER_PATH_BACKENDS_FALLBACK = frozenset({"docker", "singularity", "modal", "daytona", "vercel_sandbox"})
# Backend name inferred from the live environment's class name (first match wins).
_ENV_CLASS_NAME_HINTS = ("local", "ssh", "docker", "singularity", "modal", "daytona")
-# Container task id -> monotonic time of the last failed SSH bring-up in path resolution.
+# Container task id -> monotonic time of the last failed environment bring-up in path resolution (an SSH
+# home, or a plugin sandbox's ``~`` home).
_SSH_HOME_RETRY_AFTER = 30.0
_ssh_home_failed_at: dict[str, float] = {}
@@ -191,17 +192,10 @@ def _ssh_remote_anchor(task_id: str) -> str:
return "~"
-def _ssh_remote_home(task_id: str) -> str | None:
- """The SSH user's home as detected at connect (``echo $HOME``), else None.
-
- Brings the environment up through the file tools' own creator (same cwd
- and cache as the call that follows) when none is live: they resolve before
- touching the backend, and a first call keyed ``~/x`` while later ones key
- ``/home/u/x`` splits read tracking and staleness checks for one file. A
- failed bring-up is remembered briefly so one tool call's several
- resolutions don't each wait out the SSH connect timeout; the tool's own
- backend call reports the error.
- """
+def _live_or_started_env(task_id: str):
+ """The task's live terminal environment, else one brought up through the file tools' own creator. A failed
+ bring-up is remembered briefly, so one tool call's several path resolutions don't each wait out the
+ backend's connect timeout; the tool's own backend call reports the error."""
from tools.file_tools import _get_file_ops
from tools.terminal_tool import _resolve_container_task_id
from tools.terminal_tool_lifecycle import get_active_env
@@ -213,10 +207,27 @@ def _ssh_remote_home(task_id: str) -> str | None:
return None
try:
env = _get_file_ops(task_id).env
- except Exception:
+ except Exception: # health: allow BLE001 -- any backend's connect failure; the tool's own call reports it
_ssh_home_failed_at[key] = time.monotonic()
return None
_ssh_home_failed_at.pop(key, None)
+ return env
+
+
+def _ssh_remote_home(task_id: str) -> str | None:
+ """The SSH user's home as detected at connect (``echo $HOME``), else None.
+
+ Brings the environment up through the file tools' own creator (same cwd
+ and cache as the call that follows) when none is live: they resolve before
+ touching the backend, and a first call keyed ``~/x`` while later ones key
+ ``/home/u/x`` splits read tracking and staleness checks for one file. A
+ failed bring-up is remembered briefly so one tool call's several
+ resolutions don't each wait out the SSH connect timeout; the tool's own
+ backend call reports the error.
+ """
+ env = _live_or_started_env(task_id)
+ if env is None:
+ return None
# A guessed /home/<user> (``echo $HOME`` failed) must not stand in for the real home.
home = getattr(env, "_remote_home", None) if getattr(env, "_remote_home_detected", False) else None
return home if isinstance(home, str) and posixpath.isabs(home) else None
@@ -277,13 +288,14 @@ def _container_default_cwd(task_id: str = "default") -> str | None:
cwd = _get_env_config().get("cwd")
if cwd == "~":
- # A plugin backend's sandbox home is known once its environment connects: bring it up
- # through the file tools' own creator, as the call that follows would, and use the home
- # THAT environment resolved.
- from tools.file_tools import _get_file_ops
+ # A plugin backend's sandbox home is known once its environment connects: bring it up as the
+ # call that follows would, and use the home THAT environment resolved. When it can't connect,
+ # relative paths fall back to the process cwd below; the file operation itself then fails on
+ # the same connection, so nothing is read or written on the host.
from tools.terminal_tool_config import plugin_sandbox_home
- cwd = plugin_sandbox_home(_get_file_ops(task_id).env)
+ env = _live_or_started_env(task_id)
+ cwd = plugin_sandbox_home(env) if env is not None else None
if isinstance(cwd, str) and posixpath.isabs(cwd):
return cwd
except Exception:
diff --git a/tools/terminal_tool_backends.py b/tools/terminal_tool_backends.py
index 999b2c1e693..e8973cee0c0 100644
--- a/tools/terminal_tool_backends.py
+++ b/tools/terminal_tool_backends.py
@@ -215,9 +215,10 @@ def _build_ssh_env(*, cwd, timeout, ssh_config, probe_only=False, **_):
def _stamp_sandbox_home(env_obj, provider, cwd) -> None:
- """Record the home this environment started in when it started at the provider's ``default_cwd``: the
- path ``~`` resolved to inside THIS sandbox, or the declared absolute path. Per environment, never per
- backend, so a second sandbox with a different home gets its own."""
+ """Record the provider's declared home on this environment: a declared absolute path whatever ``cwd`` the
+ environment started in (``terminal.cwd`` may pick another directory), or, for ``~``, the path it resolved
+ to inside THIS sandbox when it started there. Per environment, never per backend, so a second sandbox
+ with a different home gets its own."""
try:
declared = provider.default_cwd
except Exception:
@@ -225,10 +226,10 @@ def _stamp_sandbox_home(env_obj, provider, cwd) -> None:
logger.warning("%s.default_cwd raised; not recording a sandbox home", type(provider).__name__,
exc_info=True)
declared = None
- if cwd == "~" and declared == "~":
- home = getattr(env_obj, "cwd", None)
+ if declared == "~":
+ home = getattr(env_obj, "cwd", None) if cwd == "~" else None
else:
- home = cwd if isinstance(declared, str) and cwd == declared else None
+ home = declared
if isinstance(home, str) and home.startswith("/") and home != "/":
try:
env_obj._hermes_sandbox_home = home
diff --git a/website/docs/developer-guide/terminal-environment-plugin.md b/website/docs/developer-guide/terminal-environment-plugin.md
index 89745d30277..de6afbe5529 100644
--- a/website/docs/developer-guide/terminal-environment-plugin.md
+++ b/website/docs/developer-guide/terminal-environment-plugin.md
@@ -182,7 +182,7 @@ stdout left open. A plugin backend can opt in the same way:
`None` when it can't right now. Hermes appends `bash -c <script>` as
separate words, so the client must pass them through unchanged and the
sandbox needs `bash`. `user` names the account to run as; ignore it if your
- backend can't switch users.
+ backend can't switch users. Return a list, not a single command string.
```python
class AcmeBoxEnvironment:
@@ -191,7 +191,10 @@ class AcmeBoxEnvironment:
```
The sandbox image still needs the desktop stack (Xvnc, Xfce, Chromium,
-`cua-driver`); `nousresearch/hermes-sandbox:desktop` has it.
+`cua-driver`); `nousresearch/hermes-sandbox:desktop` has it. Bot Desktop and
+the browser keep their scratch files under the environment's
+`get_temp_dir()`. An environment that doesn't subclass `BaseEnvironment` and
+has no such method gets the same default `BaseEnvironment` uses.
Both `exec_prefix()` and the `~` home resolution read the environment object
itself, so they work only for plugins loaded in-process. Under