The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tools): sanitize cwd overrides written into live container envs
kokhlob911b9794ed1
diff --git a/tests/tools/test_live_env_cwd_override_sanitize.py b/tests/tools/test_live_env_cwd_override_sanitize.pynew file mode 100644index 00000000000..800a63151bd--- /dev/null+++ b/tests/tools/test_live_env_cwd_override_sanitize.py@@ -0,0 +1,127 @@+"""Regression tests for cwd-override sanitization on LIVE cached envs.++``register_task_env_overrides`` applies a ``cwd`` override to the cached live+environment directly. On container backends a raw host path (a desktop/TUI+session registering its workspace) can never be the in-sandbox workdir: every+file-tools ``_exec`` wrapper does ``builtin cd -- <env.cwd> || exit 126``, so a+host cwd poisoned all later file operations with an unrelated ``cd:`` error+while terminal commands kept working (their per-command resolver sanitizes).+These tests pin the live-env write so a host cwd is either remapped to the+in-container view of the same mounted directory or not applied at all.+"""++import pytest++import tools.terminal_tool as tt+++class _FakeEnv:+ def __init__(self, env_type, cwd, host_cwd=None):+ self.env_type = env_type+ self.cwd = cwd+ self.host_cwd = host_cwd++ def execute(self, *a, **k):+ return {"output": "", "returncode": 0}++[email protected](autouse=True)+def _clean_state(monkeypatch):+ monkeypatch.setattr(tt, "_session_cwd", {})+ monkeypatch.setattr(tt, "_task_env_overrides", {})+ monkeypatch.setattr(tt, "_active_environments", {})+ monkeypatch.setattr(tt, "_creation_locks", {})+ monkeypatch.setattr(tt, "_container_aliases", {})+++class TestLiveEnvCwdSanitized:+ def test_windows_host_cwd_not_applied_to_docker_env(self):+ # The reported bug: a desktop session registers its Windows workspace,+ # env.cwd becomes C:\... and every file op dies on `cd: C:\...`.+ env = _FakeEnv("docker", "/workspace")+ tt._active_environments["default"] = env+ tt.register_task_env_overrides(+ "default", {"cwd": r"C:\Users\rashi\ai_workspace"}+ )+ assert env.cwd == "/workspace"++ def test_posix_host_cwd_not_applied_to_docker_env(self):+ env = _FakeEnv("docker", "/root")+ tt._active_environments["default"] = env+ tt.register_task_env_overrides("default", {"cwd": "/Users/me/workspace"})+ assert env.cwd == "/root"++ def test_mounted_host_cwd_remaps_to_workspace(self):+ # Docker cwd passthrough: the host dir IS mounted at /workspace, so the+ # session's directory stays reachable — remap instead of discarding.+ env = _FakeEnv("docker", "/workspace", host_cwd="/Users/me/ws")+ tt._active_environments["default"] = env+ tt.register_task_env_overrides("default", {"cwd": "/Users/me/ws"})+ assert env.cwd == "/workspace"++ def test_mounted_windows_host_cwd_remaps_to_workspace(self):+ # The exact reported shape: a Windows host cwd with docker cwd+ # passthrough mounted at /workspace.+ env = _FakeEnv("docker", "/workspace", host_cwd=r"C:\Users\rashi\ai_workspace")+ tt._active_environments["default"] = env+ tt.register_task_env_overrides(+ "default", {"cwd": r"C:\Users\rashi\ai_workspace"}+ )+ assert env.cwd == "/workspace"++ def test_host_cwd_not_applied_on_singularity(self):+ env = _FakeEnv("singularity", "/root")+ tt._active_environments["default"] = env+ tt.register_task_env_overrides("default", {"cwd": "/Users/me/workspace"})+ assert env.cwd == "/root"++ def test_in_container_override_applied_verbatim(self):+ env = _FakeEnv("docker", "/root")+ tt._active_environments["default"] = env+ tt.register_task_env_overrides("default", {"cwd": "/workspace/task42"})+ assert env.cwd == "/workspace/task42"++ def test_local_env_applies_override_verbatim(self):+ # Non-container backends must keep applying overrides raw: ACP+ # session/load project-root switching relies on it.+ env = _FakeEnv("local", "/start")+ tt._active_environments["default"] = env+ tt.register_task_env_overrides("default", {"cwd": "/proj/two"})+ assert env.cwd == "/proj/two"++ def test_session_record_keeps_raw_host_path(self):+ # The record is the tracking surface for host workspaces; only the+ # live-env write is sanitized.+ tt.register_task_env_overrides("default", {"cwd": "/Users/me/workspace"})+ assert tt.get_session_cwd("default") == "/Users/me/workspace"++ def test_env_found_under_collapsed_container_id(self):+ # CWD-only overrides collapse to "default": the env may be cached under+ # the collapsed key, not the raw task id.+ env = _FakeEnv("docker", "/workspace")+ tt._active_environments["default"] = env+ tt.register_task_env_overrides(+ "sess-abc", {"cwd": r"C:\Users\rashi\ai_workspace"}+ )+ assert env.cwd == "/workspace"+++class TestSanitizerUnit:+ def test_none_env_type_returns_cwd(self):+ # Env without the backend tag (pre-existing instances, __slots__ plugin+ # providers): do not guess, apply verbatim like before the tag existed.+ env = _FakeEnv(None, "/root")+ assert tt._sanitize_cwd_for_live_env(env, "/any/path") == "/any/path"++ def test_docker_env_mounted_remap(self, monkeypatch):+ monkeypatch.setattr("os.path.isdir", lambda p: True)+ env = _FakeEnv("docker", "/workspace", host_cwd="/Users/me/ws")+ assert tt._sanitize_cwd_for_live_env(env, "/Users/me/ws") == "/workspace"++ def test_docker_env_unmounted_host_path_returns_none(self):+ env = _FakeEnv("docker", "/root", host_cwd=None)+ assert tt._sanitize_cwd_for_live_env(env, "/Users/me/ws") is None++ def test_relative_cwd_not_applied_to_docker_env(self):+ env = _FakeEnv("docker", "/root")+ assert tt._sanitize_cwd_for_live_env(env, "relative/dir") is Nonediff --git a/tools/environments/docker.py b/tools/environments/docker.pyindex 45e9524c5c7..204088ed279 100644--- a/tools/environments/docker.py+++ b/tools/environments/docker.py@@ -702,6 +702,10 @@ class DockerEnvironment(BaseEnvironment):and not workspace_explicitly_mounted)if auto_mount_cwd and host_cwd and not os.path.isdir(host_cwd_abs):logger.debug("Skipping docker cwd mount: host_cwd is not a valid directory: %s", host_cwd)+ # The host directory actually bound at /workspace, if any. Readers that+ # only hold the env instance (cwd remapping on live envs) use it to+ # recognize a session workspace registered as a raw host path.+ self.host_cwd = host_cwd_abs if bind_host_cwd else Nonemount_workspace = not bind_host_cwd and not workspace_explicitly_mountedwritable_args: list[str] = []diff --git a/tools/terminal_tool.py b/tools/terminal_tool.pyindex 3ab015c4f38..a8f354bc19a 100644--- a/tools/terminal_tool.py+++ b/tools/terminal_tool.py@@ -273,6 +273,35 @@ def clear_session_cwd(session_key: str) -> None:_session_cwd.pop(session_key, None)+def _sanitize_cwd_for_live_env(env: Any, new_cwd: str) -> Optional[str]:+ """Cwd to write into a LIVE cached env, or None to leave it untouched.++ On container backends a raw host path (a desktop/TUI session registering its+ 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+ 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"+ return None++def register_task_env_overrides(task_id: str, overrides: Dict[str, Any]):"""Register per-task sandbox overrides (``docker_image``/``modal_image``/``singularity_image``/``daytona_image``, ``env_type``, ``cwd``) before the@@ -281,7 +310,9 @@ def register_task_env_overrides(task_id: str, overrides: Dict[str, Any]):A ``cwd`` override takes effect immediately: it becomes the session'srecorded cwd (until a ``cd`` changes it) and any live env's cwd is updatedtoo, so env-side seeding stays consistent (ACP switching project root- mid-session via ``session/load``).+ mid-session via ``session/load``). The session record keeps the RAW path+ (host workspaces are tracked there on purpose); only the live-env write is+ sanitized, since a host cwd can never be a container workdir."""_task_env_overrides[task_id] = overrides@@ -295,7 +326,9 @@ def register_task_env_overrides(task_id: str, overrides: Dict[str, Any]):with _env_lock:env = _active_environments.get(task_id) or _active_environments.get(container_id)if env is not None and getattr(env, "cwd", None) is not None:- env.cwd = new_cwd+ sanitized = _sanitize_cwd_for_live_env(env, new_cwd)+ if sanitized is not None:+ env.cwd = sanitizeddef clear_task_env_overrides(task_id: str):diff --git a/tools/terminal_tool_backends.py b/tools/terminal_tool_backends.pyindex 0ee50256893..ae6a9204ebe 100644--- a/tools/terminal_tool_backends.py+++ b/tools/terminal_tool_backends.py@@ -245,8 +245,16 @@ def _create_environment(env_type: str, image: str, cwd: str, timeout: int,kwargs = dict(image=image, cwd=cwd, timeout=timeout, cc=container_config or {}, task_id=task_id,ssh_config=ssh_config, host_cwd=host_cwd, probe_only=probe_only)if builder is not None:- return builder(**kwargs)- return _build_plugin_env(env_type=env_type, **kwargs)+ env = builder(**kwargs)+ else:+ env = _build_plugin_env(env_type=env_type, **kwargs)+ # Backend tag for consumers that only hold the instance (cwd sanitizers on+ # live cached envs); __slots__ plugin providers simply keep going untagged.+ try:+ env.env_type = env_type+ except Exception:+ pass+ return env# --- Requirement checkers: one generic path driven by _BACKEND_SPECS; optional fields, checked in order: