Skip to content

The agent that grows with you

fix(docker): remap a mounted host session cwd to /workspace

brooklyn!b9d5e4d17f11
diff --git a/tests/tools/test_docker_mounted_host_session_cwd.py b/tests/tools/test_docker_mounted_host_session_cwd.py
new file mode 100644
index 00000000000..db26415aee3
--- /dev/null
+++ b/tests/tools/test_docker_mounted_host_session_cwd.py
@@ -0,0 +1,176 @@
+"""A session cwd that IS the directory mounted at /workspace must not be a container cd.
+
+``_is_unusable_container_cwd`` only treats ``/Users``, ``/home``, drive letters,
+and relative paths as host paths. An absolute checkout such as ``/mnt/d/...`` or
+``/srv/...`` is ``os.path.isabs`` and skips that heuristic, so the mount-equality
+check — which runs only after the heuristic says "unusable" — never fires.
+
+Two sites then wrap that host path as ``builtin cd`` inside the container:
+
+ * the live-env write (``register_task_env_overrides`` → ``env.cwd``, which
+ file tools exec with ``cd <env.cwd> || exit 126``)
+ * the per-command resolver (``_resolve_command_cwd`` → ``env.execute(cwd=...)``,
+ which the session wrapper turns into ``builtin cd -- <cwd> || exit 126``)
+
+When the registered cwd is the mounted host directory, both must land on
+``/workspace`` instead. In-container paths and an explicit workdir stay as-is.
+"""
+
+import pytest
+
+import tools.terminal_tool as tt
+from tools.environments.base import BaseEnvironment
+from tools.environments.base_session_env import _wrap_command_script
+
+
+MNT = "/mnt/d/projects/app"
+SRV = "/srv/projects/app"
+
+
+class _FakeEnv:
+ def __init__(self, cwd, host_cwd):
+ self.env_type = "docker"
+ self.cwd = cwd
+ self.host_cwd = host_cwd
+ self.execute_cwds = []
+
+ def execute(self, command, **kwargs):
+ self.execute_cwds.append(kwargs.get("cwd"))
+ return {"output": "", "exit_code": 0, "returncode": 0}
+
+
+def _cd_line(cwd: str) -> str:
+ """The ``builtin cd`` line the container wrapper would run for *cwd*."""
+ quoted = BaseEnvironment._quote_cwd_for_cd(cwd)
+ script = _wrap_command_script(
+ "pwd",
+ quoted_cwd=quoted,
+ quoted_snap="'/tmp/snap'",
+ snap_tmp_template="'/tmp/snap.XXXXXX'",
+ passthrough_names=(),
+ snapshot_ready=False,
+ cwd_marker="__HERMES_CWD__",
+ )
+ return next(line for line in script.splitlines() if line.startswith("builtin cd -- "))
+
+
+def _config(host_cwd):
+ return {
+ "env_type": "docker",
+ "docker_image": "nikolaik/python-nodejs:python3.11-nodejs20",
+ "cwd": "/workspace",
+ "host_cwd": host_cwd,
+ "timeout": 180,
+ "lifetime_seconds": 300,
+ "container_cpu": 1,
+ "container_memory": 5120,
+ "container_disk": 51200,
+ "container_persistent": True,
+ "docker_volumes": [],
+ "docker_env": {},
+ "docker_extra_args": [],
+ "docker_mount_cwd_to_workspace": True,
+ "docker_run_as_host_user": False,
+ "docker_forward_env": [],
+ "modal_mode": "auto",
+ }
+
+
+def docker_session(monkeypatch):
+ """Docker backend with a live env whose host dir is mounted at /workspace."""
+ monkeypatch.setattr(tt, "_session_cwd", {})
+ monkeypatch.setattr(tt, "_task_env_overrides", {})
+ monkeypatch.setattr(tt, "_active_environments", {})
+ monkeypatch.setattr(tt, "_last_activity", {})
+ monkeypatch.setattr(tt, "_creation_locks", {})
+ monkeypatch.setattr(tt, "_container_aliases", {})
+ monkeypatch.setattr(tt, "_start_cleanup_thread", lambda: None)
+ monkeypatch.setattr(tt, "_check_all_guards", lambda *a, **k: {"approved": True})
+
+ state = {"host": MNT}
+
+ def config():
+ return _config(state["host"])
+
+ monkeypatch.setattr(tt, "_get_env_config", config)
+
+ def bind(host):
+ state["host"] = host
+ env = _FakeEnv("/workspace", host)
+ # CWD-only overrides collapse to "default"; the live env is cached there.
+ tt._active_environments["default"] = env
+ return env
+
+ return bind
+
+
+class TestMountedHostSessionCwd:
+ @pytest.mark.parametrize("host", [MNT, SRV])
+ def test_live_env_write_remaps_mounted_host_dir(self, docker_session, host):
+ env = docker_session(host)
+ tt.register_task_env_overrides("desktop-sess", {"cwd": host, "cwd_source": "session"})
+ assert env.cwd == "/workspace"
+ # Host surfaces still track the raw workspace; only the container cwd changes.
+ assert tt.get_session_cwd("desktop-sess") == host
+
+ @pytest.mark.parametrize("host", [MNT, SRV])
+ def test_command_cwd_is_not_the_mounted_host_dir(self, docker_session, host):
+ env = docker_session(host)
+ task_id = "desktop-sess"
+ tt.register_task_env_overrides(task_id, {"cwd": host, "cwd_source": "session"})
+ try:
+ tt.terminal_tool(command="pwd", task_id=task_id)
+ finally:
+ tt.clear_task_env_overrides(task_id)
+ assert env.execute_cwds, "terminal command never reached env.execute"
+ command_cwd = env.execute_cwds[-1]
+ cd = _cd_line(command_cwd)
+ assert command_cwd == "/workspace"
+ assert host not in cd
+ assert cd == "builtin cd -- /workspace || exit 126"
+
+ def test_background_command_uses_the_same_remap(self, docker_session, monkeypatch):
+ host = MNT
+ docker_session(host)
+ captured = {}
+
+ def fake_spawn(process_registry, *, env, env_type, command, cwd, **kwargs):
+ captured["cwd"] = cwd
+
+ class _Session:
+ id = "bg-1"
+ pid = 1
+
+ return _Session()
+
+ monkeypatch.setattr("tools.terminal_tool_background._spawn", fake_spawn)
+ task_id = "desktop-sess"
+ tt.register_task_env_overrides(task_id, {"cwd": host, "cwd_source": "session"})
+ try:
+ tt.terminal_tool(command="pwd", task_id=task_id, background=True)
+ finally:
+ tt.clear_task_env_overrides(task_id)
+ assert captured["cwd"] == "/workspace"
+ assert host not in _cd_line(captured["cwd"])
+
+ def test_in_container_session_cwd_is_preserved(self, docker_session):
+ env = docker_session(MNT)
+ task_id = "desktop-sess"
+ tt.register_task_env_overrides(task_id, {"cwd": "/workspace/task42"})
+ try:
+ tt.terminal_tool(command="pwd", task_id=task_id)
+ finally:
+ tt.clear_task_env_overrides(task_id)
+ assert env.cwd == "/workspace/task42"
+ assert env.execute_cwds[-1] == "/workspace/task42"
+
+ def test_explicit_workdir_still_wins(self, docker_session):
+ env = docker_session(MNT)
+ task_id = "desktop-sess"
+ tt.register_task_env_overrides(task_id, {"cwd": MNT, "cwd_source": "session"})
+ try:
+ tt.terminal_tool(command="pwd", task_id=task_id, workdir="/workspace/sub")
+ finally:
+ tt.clear_task_env_overrides(task_id)
+ assert env.execute_cwds[-1] == "/workspace/sub"
diff --git a/tools/file_tools.py b/tools/file_tools.py
index c598df17b41..9e5b7452433 100644
--- a/tools/file_tools.py
+++ b/tools/file_tools.py
@@ -271,7 +271,7 @@ def _create_terminal_env_for_file_ops(raw_task_id: str, task_id: str):
so a file tool that runs before any terminal command still gets the configured backend."""
from tools.terminal_tool_config import _is_container_backend, coerce_ssh_remote_cwd
from tools.terminal_tool import (
- _create_configured_env, _get_env_config, _is_unusable_container_cwd,
+ _create_configured_env, _get_env_config, _is_mounted_host_cwd, _is_unusable_container_cwd,
_resolve_task_host_cwd, _select_image, get_session_cwd, resolve_task_overrides)
config = _get_env_config()
@@ -291,18 +291,20 @@ def _create_terminal_env_for_file_ops(raw_task_id: str, task_id: str):
# reaches ``docker run -w <host-path>`` and the container starts in a directory that doesn't exist
# inside the sandbox, so search_files and friends silently return empty results (#54447). Sanitize it
# back to the already-validated config["cwd"] so the override can't bypass the guard.
- if _is_container_backend(env_type) and _is_unusable_container_cwd(cwd):
- if cwd != config["cwd"]:
+ host_cwd = _resolve_task_host_cwd(config, raw_task_id)
+ if _is_container_backend(env_type) and _is_unusable_container_cwd(cwd, mounted_host=host_cwd):
+ fallback = "/workspace" if _is_mounted_host_cwd(cwd, host_cwd) else config["cwd"]
+ if cwd != fallback:
logger.info(
"Ignoring host/relative cwd override %r for %s backend "
"(won't exist in sandbox). Using %r instead.",
- cwd, env_type, config["cwd"])
- cwd = config["cwd"]
+ cwd, env_type, fallback)
+ cwd = fallback
logger.info("Creating new %s environment for task %s...", env_type, task_id[:8])
terminal_env = _create_configured_env(
config, env_type, image=_select_image(env_type, overrides, config), cwd=cwd,
timeout=config["timeout"], task_id=task_id,
- host_cwd=_resolve_task_host_cwd(config, raw_task_id),
+ host_cwd=host_cwd,
local_config={"persistent": config.get("local_persistent", False)} if env_type == "local" else None,
)
return env_type, terminal_env
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index 21d89110542..d3b8226266b 100644
--- a/tools/terminal_tool.py
+++ b/tools/terminal_tool.py
@@ -44,7 +44,7 @@ from tools.terminal_tool_lifecycle import (
_evict_environment_for_task, cleanup_all_environments, ensure_task_env,
)
from tools.terminal_tool_config import (
- _is_container_backend, _is_host_cwd, _is_unusable_container_cwd, _parse_env_var,
+ _is_container_backend, _is_host_cwd, _is_mounted_host_cwd, _is_unusable_container_cwd, _parse_env_var,
coerce_ssh_remote_cwd,
_plugin_env_flag, _quiet, _safe_getcwd, _tenv, _tenv_bool,
)
@@ -282,25 +282,25 @@ def _sanitize_cwd_for_live_env(env: Any, new_cwd: str) -> Optional[str]:
workspace, e.g. ``C:\\Users\\me`` or ``/Users/me/workspace``) cannot be the
in-sandbox workdir: every file-tools ``_exec`` wrapper does
``builtin cd -- <env.cwd> || exit 126``, so a host cwd poisons all later
- file operations with an unrelated ``cd:`` error. The creation paths already
- sanitize this (``_is_unusable_container_cwd`` guards); the live-env write
- here is the one remaining unsanitized site. When the host path is the one
- mounted at ``/workspace`` (docker cwd passthrough), the session's directory
- is still reachable — remap instead of discarding, mirroring the env-creation
- remap in ``terminal_tool()``. Non-container backends apply the override
+ file operations with an unrelated ``cd:`` error. Prefix-shaped host paths
+ are already rejected on the creation paths. This write classifies the
+ directory mounted at ``/workspace`` as unusable before that prefix
+ heuristic, then remaps the match to ``/workspace`` instead of storing the
+ host path. Non-container backends apply the override
verbatim (ACP project-root switching must keep working).
"""
env_type = getattr(env, "env_type", None)
if not env_type or not _is_container_backend(env_type):
return new_cwd
- if not _is_unusable_container_cwd(new_cwd):
- return new_cwd
host_mount = getattr(env, "host_cwd", None)
- if isinstance(host_mount, str) and host_mount:
- candidate = os.path.abspath(os.path.expanduser(new_cwd))
- mounted = os.path.abspath(os.path.expanduser(host_mount))
- if candidate == mounted:
- return "/workspace"
+ mounted = host_mount if isinstance(host_mount, str) and host_mount else None
+ # Mount equality before the prefix heuristic. /mnt and /srv are absolute,
+ # so the heuristic alone would write the host path through as env.cwd and
+ # every later file-tools exec would `cd` to it (exit 126).
+ if not _is_unusable_container_cwd(new_cwd, mounted_host=mounted):
+ return new_cwd
+ if _is_mounted_host_cwd(new_cwd, mounted):
+ return "/workspace"
return None
@@ -833,6 +833,7 @@ def _resolve_command_cwd(
default_cwd: str,
session_key: Optional[str] = None,
env_type: Optional[str] = None,
+ mounted_host: Optional[str] = None,
) -> str:
"""cwd for a command: explicit ``workdir`` > the session's own cwd record >
``default_cwd``.
@@ -843,12 +844,26 @@ def _resolve_command_cwd(
its workspace) is unusable in the sandbox — ``cd <host path>`` fails with
exit 126 — so it is discarded in favor of ``default_cwd``.
+ A recorded cwd that IS the host directory mounted at ``/workspace`` is
+ classified unusable before the ``/Users`` / ``/home`` / drive-letter
+ heuristic (``/mnt/...``, ``/srv/...`` are absolute and miss that heuristic)
+ and remapped to ``/workspace`` so the session wrapper does not ``cd`` to it.
+
Same guard class as the env-creation sanitizers (#50636, #54447); this is the per-command sibling site.
"""
if workdir:
return coerce_ssh_remote_cwd(workdir, env_type)
recorded = get_session_cwd(session_key)
- if recorded and _is_container_backend(env_type) and _is_unusable_container_cwd(recorded):
+ if recorded and _is_container_backend(env_type) and _is_unusable_container_cwd(
+ recorded, mounted_host=mounted_host
+ ):
+ if _is_mounted_host_cwd(recorded, mounted_host):
+ logger.info(
+ "Remapping recorded session cwd %r for %s backend "
+ "(mounted host directory). Using '/workspace' instead.",
+ recorded, env_type,
+ )
+ return "/workspace"
logger.info(
"Ignoring recorded session cwd %r for %s backend "
"(host/relative path won't work in sandbox). Using %r instead.",
@@ -1014,8 +1029,9 @@ def _plan_execution(
# but an override / session record is raw: a host path would reach
# `docker run -w` and fail with exit 125. Re-apply the guard to the
# resolved cwd; when the host path IS this session's mounted workspace,
- # remap to /workspace instead of discarding it.
- if _is_container_backend(env_type) and _is_unusable_container_cwd(cwd):
+ # remap to /workspace instead of discarding it. Mount equality is part of
+ # the unusable check so /mnt and /srv are not left as the container cwd.
+ if _is_container_backend(env_type) and _is_unusable_container_cwd(cwd, mounted_host=host_cwd):
remapped = "/workspace" if host_cwd else config["cwd"]
if cwd != remapped:
logger.info(
@@ -1151,6 +1167,7 @@ def _run_foreground(
try:
command_cwd = _resolve_command_cwd(
workdir=workdir, default_cwd=plan.cwd, session_key=session_key, env_type=env_type,
+ mounted_host=getattr(env, "host_cwd", None) or plan.host_cwd,
)
# bounded_capture: model-facing output keeps a head/tail window
# while streaming so a verbose command can't OOM the gateway;
@@ -1344,6 +1361,7 @@ def terminal_tool(
result = spawn_background_process(
command=command, env=env, env_type=env_type, effective_task_id=effective_task_id,
task_id=task_id, session_key=session_key, workdir=workdir, cwd=cwd,
+ mounted_host=getattr(env, "host_cwd", None) or plan.host_cwd,
effective_pty=pty and not pty_disabled, notify_on_complete=notify_on_complete,
watch_patterns=watch_patterns, approval_note=verdict.note,
pty_disabled_reason=_PTY_DISABLED_REASON if pty_disabled else None,
diff --git a/tools/terminal_tool_background.py b/tools/terminal_tool_background.py
index 0ee535c5f25..a2146a65116 100644
--- a/tools/terminal_tool_background.py
+++ b/tools/terminal_tool_background.py
@@ -147,6 +147,7 @@ def spawn_background_process(
pty_disabled_reason: Optional[str],
heartbeat_seconds: int = 0,
persist_on_release: bool = False,
+ mounted_host: Optional[str] = None,
) -> str:
"""Spawn *command* as a tracked background process and return the JSON result.
@@ -160,6 +161,7 @@ def spawn_background_process(
effective_cwd = _resolve_command_cwd(
workdir=workdir, default_cwd=cwd, session_key=session_key, env_type=env_type,
+ mounted_host=mounted_host if mounted_host is not None else getattr(env, "host_cwd", None),
)
try:
proc_session = _spawn(
diff --git a/tools/terminal_tool_config.py b/tools/terminal_tool_config.py
index a4ce13537a8..1505b8bc4fc 100644
--- a/tools/terminal_tool_config.py
+++ b/tools/terminal_tool_config.py
@@ -127,12 +127,38 @@ def coerce_ssh_remote_cwd(cwd: str | None, env_type: str | None) -> str | None:
return text if rel == ".." or rel.startswith("../") else f"~/{rel}"
-def _is_unusable_container_cwd(cwd: str) -> bool:
+def _is_mounted_host_cwd(cwd: str, mounted_host: str | None) -> bool:
+ """True when *cwd* is the host directory mounted at ``/workspace``.
+
+ Checked before the ``/Users`` / ``/home`` / drive-letter heuristic: a WSL
+ checkout under ``/mnt/...`` or an absolute path under ``/srv/...`` is
+ ``os.path.isabs`` and would otherwise look like a valid container workdir.
+ """
+ if not cwd or not isinstance(mounted_host, str) or not mounted_host:
+ return False
+ try:
+ left = os.path.normpath(os.path.abspath(os.path.expanduser(cwd)))
+ right = os.path.normpath(os.path.abspath(os.path.expanduser(mounted_host)))
+ except (OSError, ValueError):
+ return False
+ return left == right
+
+
+def _is_unusable_container_cwd(cwd: str, *, mounted_host: str | None = None) -> bool:
"""True if *cwd* is a host or relative path that can't be a container
workdir: ``docker run -w`` needs an absolute in-sandbox path, otherwise the
container fails to start (exit 125). Windows drive paths aren't ``isabs``
- on POSIX, so they're caught by the prefix check."""
- return bool(cwd) and (_is_host_cwd(cwd) or not os.path.isabs(cwd))
+ on POSIX, so they're caught by the prefix check.
+
+ The directory mounted at ``/workspace`` is unusable inside the container
+ even when it matches none of those prefixes. That equality check runs
+ first so ``/mnt/...`` and ``/srv/...`` are not wrapped as ``cd`` targets.
+ """
+ if not cwd:
+ return False
+ if _is_mounted_host_cwd(cwd, mounted_host):
+ return True
+ return _is_host_cwd(cwd) or not os.path.isabs(cwd)
def _tenv(name: str, default: str = "") -> str:
diff --git a/tools/terminal_tool_guards.py b/tools/terminal_tool_guards.py
index de19c23a1c2..18db120f4d0 100644
--- a/tools/terminal_tool_guards.py
+++ b/tools/terminal_tool_guards.py
@@ -228,6 +228,7 @@ def gateway_lifecycle_block(
guard_cwd_base = getattr(env, "cwd", None) or cwd
guard_cwd = _resolve_command_cwd(
workdir=workdir, default_cwd=guard_cwd_base, session_key=session_key, env_type=env_type,
+ mounted_host=getattr(env, "host_cwd", None),
)
unsafe, refusal = scan_gateway_lifecycle(
command,