fix(sandbox): build the bash cwd prefix for the shell that runs it (#8323)

* fix(sandbox): build the bash cwd prefix for the shell that runs it

* fix(sandbox): stop when the shell cannot enter the workspace

`Set-Location` reports a missing directory as a non-terminating error, so the
semicolon-separated command still ran — from whatever directory the gateway was
started in. Add `-ErrorAction Stop` so a vanished workspace aborts execution the
way the POSIX `&&` form does, and add a regression test that also proves the
command runs when the workspace exists.

Pin the shell in the remaining POSIX-only prefix assertion so the test no longer
depends on the host shell.

* fix(sandbox): preserve Windows workspace paths at launch

---------

Co-authored-by: huyengiang101086-spec <270684046+huyengiang101086-spec@users.noreply.github.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
huyengiang101086-spec 2026-11-22 20:57:56 +08:00 committed by GitHub
parent 9bd2bfa859
commit 25a59aa5c7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 213 additions and 16 deletions

View File

@ -111,7 +111,7 @@ Each guide is the full reference for its topic. Open the one you need.
| Models, providers, `config.yaml`, environment variables | [Configuration](docs/guide/configuration.md) |
| DeepSeek web search, thinking mode and citation excerpts | [DeepSeek Web Search](backend/docs/CONFIGURATION.md#deepseek-web-search) |
| Docker, local development, upgrades, production deployment | [Running the Application](docs/guide/deployment.md) |
| Sandbox modes, file system, uploads and outputs | [Sandbox](docs/guide/sandbox.md) |
| Sandbox modes, Windows local execution, file system, uploads and outputs | [Sandbox](docs/guide/sandbox.md) |
| boxd machines, bounded output copies and cleanup retries | [boxd sandbox provider](backend/packages/harness/deerflow/community/boxd_sandbox/README.md) |
| Skills, built-in tools, script workflows, Claude Code integration | [Skills & Tools](docs/guide/skills-and-tools.md) |
| MCP servers | [MCP Server](docs/guide/mcp.md) |

View File

@ -72,6 +72,9 @@ Windows. The portable string assertions do not replace it.
- Tool execution depends on operational arguments only. The `description`
argument is a progress label and may be empty.
- Pass the local `cmd.exe` workspace as the subprocess working directory. For
PowerShell, share the single-quote escaping rule with path mapping and stop
execution if `Set-Location` fails.
- Local writes publish a new file revision atomically and keep symlink targets and
file metadata. Check write access without truncating the file.
- Line endings are data. Full reads return the stored endings, and `str_replace`

View File

@ -285,6 +285,11 @@ class ResolvedPath(NamedTuple):
_POWERSHELL_QUOTE_TRANSLATION = str.maketrans("\u2018\u2019\u201c\u201d", "''\"\"")
def escape_powershell_single_quoted(value: str) -> str:
"""Escape text inside a PowerShell single-quoted string."""
return re.sub(r"['\u2018\u2019]", lambda char: char.group() * 2, value)
def escape_powershell_path(match: re.Match[str], path: str) -> str:
"""Keep mapped paths literal in the caller's quote context, preserving wildcards."""
quote = None
@ -330,7 +335,7 @@ def escape_powershell_path(match: re.Match[str], path: str) -> str:
if closing_quote:
path = path[:-1]
if quote == "'":
return re.sub(r"['\u2018\u2019]", lambda char: char.group() * 2, path) + closing_quote
return escape_powershell_single_quoted(path) + closing_quote
characters = r'[`$"\u201c\u201d]' if quote is not None else r"[ \t`$'\";&,()@{}#\u2018\u2019\u201c\u201d]"
return re.sub(characters, lambda char: "`" + char.group(), path) + closing_quote
@ -872,6 +877,8 @@ class LocalSandbox(Sandbox):
command: str,
env: dict[str, str] | None = None,
timeout: float | None = None,
*,
cwd: str | None = None,
) -> CommandOutput:
# Validate ``env`` keys against the POSIX env-var rule. Defense in
# depth: ``subprocess.run(env=...)`` does not go through a shell so a
@ -883,6 +890,8 @@ class LocalSandbox(Sandbox):
_validate_extra_env(env)
# Resolve container paths in command before execution
shell = self._get_shell()
if cwd is not None and (os.name != "nt" or not self._is_cmd_shell(shell)):
raise ValueError("A process working directory is only supported for the cmd.exe fallback")
resolved_command = self._resolve_paths_in_command(command, shell=shell)
if timeout is None:
timeout = DEFAULT_COMMAND_TIMEOUT_SECONDS
@ -904,6 +913,12 @@ class LocalSandbox(Sandbox):
args = [shell, "-NoProfile", "-Command", utf8_preamble + resolved_command]
elif self._is_cmd_shell(shell):
args = [shell, "/c", resolved_command]
if cwd is not None:
if ntpath.splitdrive(cwd)[0].startswith(("\\\\", "//")):
raise ValueError("cmd.exe requires a workspace on a local or mapped drive")
# /d disables AutoRun (which could change cwd). /s strips
# the outer quotes and preserves the command's own quotes.
args = f'{subprocess.list2cmdline([shell])} /d /s /c "{resolved_command}"'
else:
args = [shell, "-c", resolved_command]
if self._is_msys_shell(shell):
@ -965,6 +980,7 @@ class LocalSandbox(Sandbox):
timeout,
sandbox_env,
encoding=self._get_cmd_output_encoding(),
cwd=cwd,
)
else:
stdout, stderr, returncode, timed_out = self._run_windows_command(args, timeout, sandbox_env)
@ -991,12 +1007,13 @@ class LocalSandbox(Sandbox):
@staticmethod
def _run_windows_command(
args: list[str],
args: list[str] | str,
timeout: float,
env: dict[str, str] | None = None,
*,
encoding: str | None = None,
fallback_encoding: str | None = None,
cwd: str | None = None,
) -> tuple[str, str, int, bool]:
"""Run with bounded capture, a process-tree timeout, and locale decoding unless overridden."""
timed_out = False
@ -1012,6 +1029,7 @@ class LocalSandbox(Sandbox):
stderr=stderr_write_fd,
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP,
env=env,
cwd=cwd,
)
except BaseException:
# Include interruptions during and after Popen; the read ends have

View File

@ -45,7 +45,7 @@ from deerflow.sandbox.lease import (
sandbox_command_scope,
sandbox_lease_owner,
)
from deerflow.sandbox.local.local_sandbox import LocalSandbox, escape_powershell_path
from deerflow.sandbox.local.local_sandbox import LocalSandbox, escape_powershell_path, escape_powershell_single_quoted
from deerflow.sandbox.overwrite import unwrap_sandbox
from deerflow.sandbox.path_patterns import PATH_START_BOUNDARY, build_output_mask_pattern, normalize_mask_tail, replace_output_path_matches
from deerflow.sandbox.prewarm import claim_sandbox_prewarm
@ -2050,20 +2050,45 @@ def replace_virtual_paths_in_command(command: str, thread_data: ThreadDataState
return result
def _apply_cwd_prefix(command: str, thread_data: ThreadDataState | None) -> str:
"""Prepend 'cd <workspace> &&' so relative paths are anchored to the thread workspace.
def _apply_cwd_prefix(command: str, thread_data: ThreadDataState | None, *, shell: str | None = None) -> str:
"""Anchor relative paths to the thread workspace with a shell-appropriate prefix.
The syntax has to follow the shell that will actually run the command, not
the POSIX one this used to assume unconditionally. ``LocalSandbox._get_shell``
falls back to ``powershell.exe`` and then ``cmd.exe`` on Windows, and a
``cd '<path>' && ...`` prefix is unparseable in both: Windows PowerShell
before 7 rejects ``&&`` ("not a valid statement separator in this version",
surfaced as ``InvalidEndOfLine``), and cmd.exe does not strip single quotes,
so it looks for a directory literally named ``'<path>'``. Either way every
``bash`` call fails before the command runs.
Each form keeps the fail-closed behaviour of ``&&``: the PowerShell variant
uses ``-ErrorAction Stop`` because ``Set-Location`` otherwise reports a
missing workspace as a non-terminating error and lets the command run from
the inherited working directory.
Args:
command: The bash command to execute.
thread_data: The thread data containing the workspace path.
shell: The shell executable that will run the command. Defaults to the
one ``LocalSandbox`` resolves.
Returns:
The command prefixed with 'cd <workspace> &&' if workspace_path is available,
The command prefixed with a cwd change if workspace_path is available,
otherwise the original command unchanged.
"""
if thread_data and (workspace := thread_data.get("workspace_path")):
return f"cd {shlex.quote(workspace)} && {command}"
return command
if not (thread_data and (workspace := thread_data.get("workspace_path"))):
return command
resolved_shell = shell or LocalSandbox._get_shell()
if LocalSandbox._is_powershell(resolved_shell):
# ``-ErrorAction Stop`` keeps the stop-on-failure semantics ``&&`` gives
# the POSIX form: ``Set-Location`` reports a missing directory as a
# non-terminating error, which would let the ``;``-separated command run
# from the gateway's inherited cwd.
return f"Set-Location -LiteralPath '{escape_powershell_single_quoted(workspace)}' -ErrorAction Stop; {command}"
if LocalSandbox._is_cmd_shell(resolved_shell):
return f'cd /d "{workspace}" && {command}'
return f"cd {shlex.quote(workspace)} && {command}"
def get_thread_data(runtime: Runtime | None) -> ThreadDataState | None:
@ -2454,9 +2479,12 @@ def _execute_bash_command(
runtime: Runtime,
env: dict[str, str] | None,
timeout: float | None = None,
cwd: str | None = None,
) -> str:
"""Route subagent bash calls through their isolated shell-session scope."""
with command_owner(sandbox, sandbox_lease_owner(runtime.context)):
if cwd is not None and isinstance(sandbox, LocalSandbox):
return sandbox.execute_command(command, env=env, timeout=timeout, cwd=cwd)
scope_id = sandbox_command_scope(runtime.context)
scoped_execute = getattr(sandbox, "execute_command_in_scope", None)
if scope_id is not None and callable(scoped_execute):
@ -2937,7 +2965,12 @@ def bash_tool(runtime: Runtime, command: str, description: str = "") -> str | To
thread_data = get_thread_data(runtime)
validate_local_bash_command_paths(command, thread_data)
command = replace_virtual_paths_in_command(command, thread_data)
command = _apply_cwd_prefix(command, thread_data)
workspace = thread_data.get("workspace_path") if thread_data else None
cwd = None
if workspace and _is_windows() and isinstance(sandbox, LocalSandbox) and sandbox._is_cmd_shell(sandbox._get_shell()):
cwd = workspace
else:
command = _apply_cwd_prefix(command, thread_data)
# POSIX-only: the Windows local sandbox may execute via
# PowerShell/cmd.exe where `export` is not valid syntax, so the id
# is published through the subprocess environment instead —
@ -2968,6 +3001,7 @@ def bash_tool(runtime: Runtime, command: str, description: str = "") -> str | To
runtime=runtime,
env=local_env,
timeout=command_timeout,
cwd=cwd,
)
content = _truncate_bash_output(
mask_secret_values(mask_local_paths_in_output(output, thread_data), redaction_env),

View File

@ -2,13 +2,14 @@
import os
import shutil
import subprocess
from pathlib import Path
from types import SimpleNamespace
import pytest
from deerflow.sandbox.local.local_sandbox import LocalSandbox, PathMapping
from deerflow.sandbox.tools import bash_tool, replace_virtual_paths_in_command
from deerflow.sandbox.tools import _apply_cwd_prefix, bash_tool, replace_virtual_paths_in_command
@pytest.fixture
@ -207,3 +208,135 @@ def test_public_bash_tool_preserves_thread_path_argument(powershell, tmp_path, m
assert "needle" in result
assert "Exit Code:" not in result
assert not result.startswith("Error:"), result
def _workspace_runtime(workspace, monkeypatch, *, filename="marker.txt"):
workspace.mkdir()
(workspace / filename).write_text("workspace-marker", encoding="utf-8")
sandbox = LocalSandbox("local", [PathMapping("/mnt/user-data/workspace", str(workspace))])
monkeypatch.setattr("deerflow.sandbox.tools.ensure_sandbox_initialized", lambda _: sandbox)
monkeypatch.setattr("deerflow.sandbox.tools.is_host_bash_allowed", lambda: True)
return SimpleNamespace(
state={"sandbox": {"sandbox_id": "local"}, "thread_data": {"workspace_path": str(workspace)}, "thread_directories_created": True},
context={"thread_id": "workspace-test"},
)
@pytest.mark.parametrize("apostrophe", ["\u2018", "\u2019"])
def test_public_bash_tool_enters_powershell_workspace_with_curly_apostrophe(powershell, tmp_path, monkeypatch, apostrophe):
runtime = _workspace_runtime(tmp_path / f"O{apostrophe}Brien workspace", monkeypatch)
assert bash_tool.func(runtime=runtime, command="Get-Content marker.txt").strip() == "workspace-marker"
@pytest.mark.skipif(os.name != "nt", reason="native Windows cmd.exe execution")
def test_public_bash_tool_enters_cmd_workspace_with_spaces(tmp_path, monkeypatch):
shell = shutil.which("cmd.exe")
assert shell is not None
monkeypatch.setattr(LocalSandbox, "_get_shell", staticmethod(lambda: shell))
workspace = tmp_path / "workspace with spaces"
runtime = _workspace_runtime(workspace, monkeypatch, filename="marker file.txt")
command = 'type "marker file.txt"'
assert bash_tool.func(runtime=runtime, command=command).strip() == "workspace-marker"
monkeypatch.chdir(tmp_path)
(tmp_path / "marker file.txt").write_text("inherited-directory-marker", encoding="utf-8")
workspace.rename(tmp_path / "renamed workspace")
result = bash_tool.func(runtime=runtime, command=command)
assert result.startswith("Error:"), result
assert "inherited-directory-marker" not in result
def test_public_bash_tool_passes_cmd_workspace_to_process_launch(tmp_path, monkeypatch):
from deerflow.sandbox.local import local_sandbox
workspace = tmp_path / "workspace with spaces"
runtime = _workspace_runtime(workspace, monkeypatch)
monkeypatch.setattr("deerflow.sandbox.tools._is_windows", lambda: True)
monkeypatch.setattr(local_sandbox, "os", SimpleNamespace(**{**vars(os), "name": "nt"}))
monkeypatch.setattr(LocalSandbox, "_get_shell", staticmethod(lambda: "cmd.exe"))
calls = []
def run(args, timeout, env, **kwargs):
calls.append((args, kwargs.get("cwd")))
return "workspace-marker", "", 0, False
monkeypatch.setattr(LocalSandbox, "_run_windows_command", staticmethod(run))
assert bash_tool.func(runtime=runtime, command='type "marker file.txt"') == "workspace-marker"
assert calls == [('cmd.exe /d /s /c "type "marker file.txt""', str(workspace))]
@pytest.mark.parametrize(
("shell", "expected_prefix"),
[
("/bin/bash", "cd '/tmp/thread data/workspace' && "),
("/bin/sh", "cd '/tmp/thread data/workspace' && "),
# Git Bash/MSYS on Windows reports as sh.exe and speaks POSIX.
("C:/Program Files/Git/bin/bash.exe", "cd '/tmp/thread data/workspace' && "),
# PowerShell 7 and Windows PowerShell 5.1: the 5.1 parser has no `&&`.
("/usr/local/bin/pwsh", "Set-Location -LiteralPath '/tmp/thread data/workspace' -ErrorAction Stop; "),
("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", "Set-Location -LiteralPath '/tmp/thread data/workspace' -ErrorAction Stop; "),
# cmd.exe keeps single quotes as literal characters, so `cd '<path>'` looks
# for a directory whose name includes them.
("C:\\Windows\\System32\\cmd.exe", 'cd /d "/tmp/thread data/workspace" && '),
],
)
def test_cwd_prefix_uses_syntax_the_selected_shell_can_parse(shell, expected_prefix):
workspace = "/tmp/thread data/workspace"
assert _apply_cwd_prefix("echo hi", {"workspace_path": workspace}, shell=shell) == f"{expected_prefix}echo hi"
def test_cwd_prefix_quotes_a_workspace_with_an_apostrophe():
workspace = "/tmp/O'Brien's thread/workspace"
assert _apply_cwd_prefix("echo hi", {"workspace_path": workspace}, shell="/bin/bash") == "cd '/tmp/O'\"'\"'Brien'\"'\"'s thread/workspace' && echo hi"
# PowerShell escapes a literal quote by doubling it inside a single-quoted string.
assert _apply_cwd_prefix("echo hi", {"workspace_path": workspace}, shell="pwsh") == "Set-Location -LiteralPath '/tmp/O''Brien''s thread/workspace' -ErrorAction Stop; echo hi"
@pytest.mark.parametrize("apostrophe", ["\u2018", "\u2019"])
def test_cwd_prefix_quotes_a_workspace_with_a_curly_apostrophe(apostrophe):
workspace = f"/tmp/O{apostrophe}Brien workspace"
prefix = _apply_cwd_prefix("echo hi", {"workspace_path": workspace}, shell="powershell.exe")
assert prefix == f"Set-Location -LiteralPath '/tmp/O{apostrophe * 2}Brien workspace' -ErrorAction Stop; echo hi"
@pytest.mark.parametrize("shell", ["/bin/bash", "pwsh", "C:\\Windows\\System32\\cmd.exe"])
def test_cwd_prefix_leaves_the_command_alone_without_a_workspace(shell):
assert _apply_cwd_prefix("echo hi", None, shell=shell) == "echo hi"
assert _apply_cwd_prefix("echo hi", {}, shell=shell) == "echo hi"
def test_powershell_prefix_skips_the_command_when_the_workspace_is_gone(powershell, tmp_path):
"""A vanished workspace must abort the command, not run it from the inherited cwd.
``Set-Location`` reports a missing directory as a non-terminating error, so
without ``-ErrorAction Stop`` the ``;``-separated command still runs — from
whatever directory the gateway was started in.
"""
missing = tmp_path / "workspace-that-was-removed"
command = _apply_cwd_prefix('Write-Output "SHOULD_NOT_RUN"', {"workspace_path": str(missing)}, shell=powershell)
completed = subprocess.run(
[powershell, "-NoProfile", "-Command", command],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=60,
)
assert completed.returncode != 0, completed.stdout
assert "SHOULD_NOT_RUN" not in completed.stdout
# Control: the same prefix does run the command once the workspace exists,
# so the assertion above cannot pass by the command never running at all.
workspace = tmp_path / "workspace"
workspace.mkdir()
ok_command = _apply_cwd_prefix('Write-Output "RAN"', {"workspace_path": str(workspace)}, shell=powershell)
ran = subprocess.run(
[powershell, "-NoProfile", "-Command", ok_command],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=60,
)
assert ran.returncode == 0, ran.stderr
assert "RAN" in ran.stdout

View File

@ -675,7 +675,7 @@ def test_execute_command_uses_cmd_command_mode_on_windows(monkeypatch):
[r"C:\Windows\System32\cmd.exe", "/c", "echo hello"],
600,
{"PATH": r"C:\Windows"},
{"encoding": "cp850"},
{"encoding": "cp850", "cwd": None},
)
]
@ -739,7 +739,7 @@ def test_execute_command_cmd_rechecks_console_page_between_commands(monkeypatch)
monkeypatch.setattr(LocalSandbox, "_get_shell", staticmethod(lambda: "cmd.exe"))
payloads = iter(["café".encode("cp437"), "你好".encode()])
def fake_run(args, timeout, env, **kwargs):
def fake_run(args, timeout, env, *, cwd=None, **kwargs):
capture = _BoundedPipeCapture(**kwargs)
capture.append(next(payloads))
return capture.read(), "", 0, False

View File

@ -1766,7 +1766,10 @@ def test_mask_local_paths_in_output_hides_acp_workspace_host_paths() -> None:
def test_apply_cwd_prefix_prepends_workspace() -> None:
"""Command is prefixed with cd <workspace> && when workspace_path is set."""
result = _apply_cwd_prefix("ls -la", _THREAD_DATA)
# Pin the POSIX shell: the prefix follows the shell that will run it (see
# test_local_command_path_spaces.py for the PowerShell/cmd.exe forms), so the
# default would make this assertion host-dependent.
result = _apply_cwd_prefix("ls -la", _THREAD_DATA, shell="/bin/bash")
assert result.startswith("cd ")
assert "ls -la" in result
assert "/tmp/deer-flow/threads/t1/user-data/workspace" in result
@ -1784,8 +1787,10 @@ def test_apply_cwd_prefix_missing_workspace_path() -> None:
def test_apply_cwd_prefix_quotes_path_with_spaces() -> None:
"""Workspace path containing spaces is properly shell-quoted."""
# The prefix follows the shell that will run it, so this POSIX assertion has
# to name the shell or it would depend on the host.
thread_data = {**_THREAD_DATA, "workspace_path": "/tmp/my workspace/t1"}
result = _apply_cwd_prefix("echo hello", thread_data)
result = _apply_cwd_prefix("echo hello", thread_data, shell="/bin/bash")
assert result == "cd '/tmp/my workspace/t1' && echo hello"

View File

@ -452,6 +452,10 @@ The `write_file` guidance reflects the active model's output token limit, includ
With `AioSandboxProvider`, shell execution runs inside isolated containers. With `LocalSandboxProvider`, file tools still map to per-thread directories on the host, but host `bash` is disabled by default because it is not a secure isolation boundary. Re-enable host bash only for fully trusted local workflows. Host bash commands have a wall-clock timeout, and long-lived processes should be started in the background with output redirected to a workspace log. If local command startup fails after spawning a child, DeerFlow attempts to kill and reap that child before propagating the startup error. On Windows, Git Bash/MSYS argument-conversion exclusions are limited to safe non-root virtual path prefixes, so host-native CLI launchers retain their normal MSYS compatibility. When the local sandbox falls back to PowerShell, it captures output as UTF-8 so CJK text does not depend on the Gateway host locale.
On Windows, relative paths in local commands start in the thread workspace.
PowerShell supports spaces and typographic apostrophes in the workspace path.
The `cmd.exe` fallback supports workspace paths on a local or mapped drive.
Docker AIO sandboxes default to their existing open egress behavior for
compatibility. Operators can set `sandbox.network.mode` to `isolated` or
`allowlist`; allowlist mode supports operator-defined domains and an interactive