Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

fix(studio): run bash and name the real platform for the terminal tool on Windows (#7885)

Leo Borcherding677685ea7bc0
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index aaa840eaae0..535469d8465 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -7,6 +7,7 @@
import ast
import codecs
import fnmatch
+import functools
import http.client
import os
import signal
@@ -1332,6 +1333,16 @@ def _exec_scan_layout(
return frozenset(exec_flags), frozenset(stops), frozenset(redirects)
+def _win_switch(token: str) -> str:
+ """Collapse a Git Bash `//x` switch to the `/x` cmd.exe actually receives."""
+ return token[1:] if token.startswith("//") else token
+
+
+# `start` launches its argument as a program, so that argument is a command
+# position. These switches precede it; the value-taking ones eat a token.
+_START_SWITCHES_WITH_VALUE = {"/d", "/node", "/affinity", "/machine"}
+
+
def _find_blocked_commands(command: str) -> set[str]:
"""Detect blocked commands at shell command position only.
@@ -1350,9 +1361,13 @@ def _find_blocked_commands(command: str) -> set[str]:
# punctuation_chars splits separators into their own tokens, so command
# position is detected even in `echo done; rm -rf x` (no whitespace).
- lexed_posix = sys.platform != "win32"
+ # Keyed to the shell that will actually run this, not to the OS: on a
+ # Windows host with bash the non-posix lexer never split on `;`, so the
+ # command after a control-flow keyword stayed unread and
+ # `if true; then rm -rf x; fi` came back with nothing blocked.
+ lexed_posix = _shell_is_posix()
try:
- if sys.platform == "win32":
+ if not lexed_posix:
tokens = shlex.split(command, posix = False)
else:
lexer = shlex.shlex(command, posix = True, punctuation_chars = ";&|()`")
@@ -1362,10 +1377,10 @@ def _find_blocked_commands(command: str) -> set[str]:
tokens = command.split()
lexed_posix = False
# Which separator tokens the shell only produced because the quoting was
- # stripped. The non-posix (Windows) lexer KEEPS the quote marks, so a quoted
+ # stripped. The non-posix (cmd) lexer KEEPS the quote marks, so a quoted
# `';'` never looks like a separator there and nothing has to be recovered;
# the split() fallback has no quoting model at all, so it reports nothing
- # either and both platforms reach the same verdict.
+ # either and both shells reach the same verdict.
quoted_separators = (
_quoted_separator_indexes(command, tokens, ";&|()`") if lexed_posix else frozenset()
)
@@ -1611,7 +1626,9 @@ def _find_blocked_commands(command: str) -> set[str]:
is_unix_c = tok_lower == "-c" or (
tok_lower.startswith("-") and tok_lower.endswith("c") and not tok_lower.startswith("--")
)
- is_win_c = tok_lower == "/c"
+ # Git Bash mangles a lone /c into a path, so models write //c and MSYS
+ # hands cmd back a single slash; /k runs the payload the same way.
+ is_win_c = _win_switch(tok_lower) in ("/c", "/k")
if not (is_unix_c or is_win_c) or i < 1 or i + 1 >= len(tokens):
continue
# Look back past flags for the shell binary. Windows flags and absolute
@@ -1629,6 +1646,24 @@ def _find_blocked_commands(command: str) -> set[str]:
blocked |= _find_blocked_commands(tokens[i + 1])
break # stop at first non-flag token
+ # `cmd /c start "" prog` puts prog in a command position the scan above
+ # sees only as an argument, so screen what start actually launches.
+ for i, token in enumerate(tokens):
+ if os.path.basename(token).lower() not in ("start", "start.exe"):
+ continue
+ j = i + 1
+ while j < len(tokens):
+ switch = _win_switch(tokens[j].lower())
+ if not switch.startswith("/"):
+ break
+ # /d C:\dir and friends carry their value in the next token.
+ j += 2 if switch in _START_SWITCHES_WITH_VALUE else 1
+ # `start ""` is the idiom for "no title"; anything else is the program.
+ if j < len(tokens) and tokens[j] == "":
+ j += 1
+ if j < len(tokens):
+ blocked |= _find_blocked_commands(tokens[j])
+
# sed's `e COMMAND` hands COMMAND to the shell, a real command position the
# scan above sees only as a text argument, so screen it like `bash -c`. The
# pattern-space forms yield an empty payload; the auto gate prompts on those.
@@ -4432,8 +4467,8 @@ _HIGH_RISK_COMMANDS = frozenset(
"blkdiscard",
"chattr",
"truncate",
- # Windows cmd.exe built-ins that delete files / trees (the terminal
- # executor runs `cmd /c` there, and these are not in _BLOCKED_COMMANDS_WIN)
+ # Windows cmd.exe built-ins that delete files / trees (reachable when the
+ # terminal executor falls back to `cmd /c`; not in _BLOCKED_COMMANDS_WIN)
"del",
"erase",
"rd",
@@ -6895,9 +6930,70 @@ def _harden_parent_against_proc_env_leak() -> bool:
return True
+# System32\bash.exe and the WindowsApps shim are the WSL launcher, which runs the
+# command inside the WSL filesystem: the sandbox workdir and the blocklist's path
+# checks would both apply to the wrong tree. Only a native Win32 bash is usable.
+_WSL_BASH_MARKERS = ("\\system32\\", "\\windowsapps\\")
+# os.path.join, not a literal `Git\bin\...`, so the probe uses the host
+# separator and the resolver stays testable on POSIX.
+_WIN_BASH_RELATIVE = (
+ os.path.join("Git", "bin", "bash.exe"),
+ os.path.join("Git", "usr", "bin", "bash.exe"),
+)
+
+
+def _is_trusted_windows_bash(path: str) -> bool:
+ """True when ``path`` is a native Win32 bash under a system install root.
+
+ The shell runs every sandboxed command, so an untrusted one defeats the
+ PATH / PATHEXT / NoDefaultCurrentDirectoryInExePath hardening in
+ _build_safe_env: a bash.exe in a user-writable dir (Scoop, a per-user Git,
+ a project checkout) would execute attacker-controlled code for a command
+ that already passed the blocklist. Same Program Files trust boundary as
+ the sandbox git PATH entry (#7317), and fails closed.
+ """
+ lowered = path.replace("/", "\\").lower()
+ if any(marker in lowered for marker in _WSL_BASH_MARKERS):
+ return False
+ return _is_trusted_windows_program_dir(os.path.dirname(path))
+
+
[email protected]_cache(maxsize = 1)
+def _windows_bash() -> "str | None":
+ """Path to a trusted native Win32 bash, or None when only cmd is available."""
+ candidates: list[str] = []
+ for root in _windows_program_roots():
+ candidates.extend(os.path.join(root, relative) for relative in _WIN_BASH_RELATIVE)
+ # shutil.which returns only the FIRST PATH match, which may be an untrusted
+ # shim; scan the rest too so it cannot mask a trusted Git install (#7317).
+ primary = shutil.which("bash")
+ if primary:
+ candidates.append(primary)
+ for entry in (os.environ.get("PATH") or "").split(os.pathsep):
+ entry = entry.strip().strip('"')
+ if entry and os.path.isabs(entry):
+ candidates.append(os.path.join(entry, "bash.exe"))
+ for candidate in candidates:
+ if os.path.isfile(candidate) and _is_trusted_windows_bash(candidate):
+ return candidate
+ return None
+
+
+def _shell_is_posix() -> bool:
+ """True when the shell that will run a command parses POSIX syntax."""
+ return sys.platform != "win32" or _windows_bash() is not None
+
+
def _get_shell_cmd(command: str) -> list[str]:
"""Return the platform-appropriate shell invocation for a command string."""
if sys.platform == "win32":
+ # why: the model is told this tool is bash and writes bash. cmd /c runs
+ # only the first line of a multi-line command, keeps single quotes
+ # literal, and does not understand bash quoting, so a correct script
+ # silently half-executes. Use a real bash when the host has one.
+ bash = _windows_bash()
+ if bash:
+ return [bash, "-c", command]
return ["cmd", "/c", command]
return ["bash", "-c", command]
@@ -7001,13 +7097,58 @@ WEB_SEARCH_TOOL = {
},
}
-# Appended to the python/terminal descriptions: models habitually write to
-# /mnt/data (a ChatGPT code-interpreter path), which does not exist here.
-_SANDBOX_PATHS_NOTE = (
- " Read and write files using relative paths in the current working "
- "directory, which persists for this conversation; absolute paths like "
- "/mnt/data or /tmp/outputs do not exist."
-)
+
+def _build_sandbox_paths_note() -> str:
+ """Platform and working-directory note, on BOTH tool descriptions.
+
+ Models habitually write to /mnt/data, a ChatGPT code-interpreter path that
+ does not exist here, so the POSIX text names it. Naming only POSIX paths on
+ Windows reads as "you are on Linux" and models then refuse to invoke Windows
+ programs that are in fact available, so that text says where the code runs
+ instead: without it a model assumes the pipe is its only output and declines
+ to open a window it believes nobody can see.
+ """
+ if sys.platform != "win32":
+ return (
+ " Read and write files using relative paths in the current working "
+ "directory, which persists for this conversation; absolute paths like "
+ "/mnt/data or /tmp/outputs do not exist."
+ )
+ return (
+ " You are on Windows, and this runs on the user's own machine. Read and "
+ "write files using relative paths in the current working directory, which "
+ "persists for this conversation."
+ )
+
+
+def _build_terminal_shell_note() -> str:
+ """Shell-specific note, on the TERMINAL description only.
+
+ Which shell runs is read from the resolver, not assumed: telling a model it
+ has bash on a host where _get_shell_cmd fell back to cmd reintroduces the
+ multi-line half-execution this note exists to prevent. It stays off the
+ python description because none of it applies to the python sandbox, and
+ naming a shell there invites subprocess/os.system as a way past the terminal
+ blocklist. No program is named either: powershell/pwsh are on that blocklist
+ and `cmd /c start` is not, so recommending one hands back a hard block and
+ recommending the other advertises the gap.
+ """
+ if sys.platform != "win32":
+ return ""
+ if _windows_bash():
+ return (
+ " The shell is bash (Git for Windows), and native Windows programs are "
+ "available; a program you start detached opens a window on the user's "
+ "desktop."
+ )
+ return (
+ " The shell is cmd, not bash: send one command per call, chain with &&, and "
+ "do not use bash syntax such as multi-line loops or single-quoted arguments."
+ )
+
+
+_SANDBOX_PATHS_NOTE = _build_sandbox_paths_note()
+_TERMINAL_SHELL_NOTE = _build_terminal_shell_note()
PYTHON_TOOL = {
"type": "function",
@@ -7032,7 +7173,9 @@ TERMINAL_TOOL = {
"type": "function",
"function": {
"name": "terminal",
- "description": "Execute a terminal command and return stdout/stderr." + _SANDBOX_PATHS_NOTE,
+ "description": "Execute a terminal command and return stdout/stderr."
+ + _SANDBOX_PATHS_NOTE
+ + _TERMINAL_SHELL_NOTE,
"parameters": {
"type": "object",
"properties": {
diff --git a/studio/backend/tests/test_bypass_permissions.py b/studio/backend/tests/test_bypass_permissions.py
index 0e9efb33e89..56fd0468a39 100644
--- a/studio/backend/tests/test_bypass_permissions.py
+++ b/studio/backend/tests/test_bypass_permissions.py
@@ -162,7 +162,10 @@ def test_bash_blocklist_enforced_when_sandboxed(captured_popen):
def test_bash_blocklist_skipped_when_bypassed(captured_popen):
out = _bash_exec("rm -rf /", None, 5, "t", disable_sandbox = True)
assert out == "FAKEOUT" # blocklist skipped -> reached (faked) execution
- assert captured_popen["cmd"][0] in ("bash", "cmd")
+ # Windows resolves bash to an absolute path (Git for Windows), so compare the
+ # program name rather than the spelling of argv[0].
+ shell = os.path.basename(captured_popen["cmd"][0]).lower()
+ assert shell in ("bash", "bash.exe", "cmd", "cmd.exe")
@_POSIX_ONLY
diff --git a/studio/backend/tests/test_tool_output_streaming.py b/studio/backend/tests/test_tool_output_streaming.py
index 28bd79cc6ef..770f5c1c8b8 100644
--- a/studio/backend/tests/test_tool_output_streaming.py
+++ b/studio/backend/tests/test_tool_output_streaming.py
@@ -971,7 +971,12 @@ def test_code_tool_descriptions_mention_relative_paths():
for tool in (PYTHON_TOOL, TERMINAL_TOOL):
description = tool["function"]["description"]
assert "relative paths" in description
- assert "/mnt/data" in description
+ if sys.platform == "win32":
+ # Naming POSIX-only paths there reads as "you are on Linux", and
+ # models then decline to run Windows programs that do exist.
+ assert "Windows" in description
+ else:
+ assert "/mnt/data" in description
def test_python_exec_mnt_data_open_is_remapped_into_workdir():
diff --git a/studio/backend/tests/test_windows_bash_shell.py b/studio/backend/tests/test_windows_bash_shell.py
new file mode 100644
index 00000000000..665057d04ae
--- /dev/null
+++ b/studio/backend/tests/test_windows_bash_shell.py
@@ -0,0 +1,306 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The terminal tool must run bash on Windows, not cmd.
+
+Models write bash for a shell tool, and every other platform runs bash. ``cmd /c``
+executes only the first line of a multi-line command, leaves single quotes in
+the argument, and does not understand bash quoting, so a correct script
+half-executes and reports success. These run on every OS by faking the platform,
+because studio-backend-ci is Linux-only.
+"""
+
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+_BACKEND_ROOT = Path(__file__).resolve().parents[1]
+if str(_BACKEND_ROOT) not in sys.path:
+ sys.path.insert(0, str(_BACKEND_ROOT))
+
+from core.inference import tools
+
+
[email protected](autouse = True)
+def _clear_bash_cache():
+ # Bound before the test so a monkeypatched _windows_bash (a plain lambda,
+ # with no cache_clear) does not break teardown.
+ cached = tools._windows_bash
+ cached.cache_clear()
+ yield
+ cached.cache_clear()
+
+
+def _fake_trusted_root(monkeypatch, root):
+ """Point the Program Files trust check at ``root``.
+
+ _windows_program_roots goes through SHGetKnownFolderPath, absent off
+ Windows. The roots are faked here rather than %ProgramFiles%, which the
+ resolver deliberately does not read (a caller could relocate the boundary).
+ """
+ monkeypatch.setattr(tools, "_windows_program_roots", lambda: [str(root)])
+
+
+def test_posix_shell_is_unchanged(monkeypatch):
+ monkeypatch.setattr(sys, "platform", "linux")
+ assert tools._get_shell_cmd("echo hi") == ["bash", "-c", "echo hi"]
+
+
+def test_windows_uses_bash_when_present(monkeypatch):
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(tools, "_windows_bash", lambda: r"C:\Program Files\Git\bin\bash.exe")
+ assert tools._get_shell_cmd("echo hi") == [
+ r"C:\Program Files\Git\bin\bash.exe",
+ "-c",
+ "echo hi",
+ ]
+
+
+def test_windows_falls_back_to_cmd_without_bash(monkeypatch):
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(tools, "_windows_bash", lambda: None)
+ assert tools._get_shell_cmd("echo hi") == ["cmd", "/c", "echo hi"]
+
+
+def test_prefers_git_for_windows_over_path(monkeypatch, tmp_path):
+ git_bash = tmp_path / "Git" / "bin" / "bash.exe"
+ git_bash.parent.mkdir(parents = True)
+ git_bash.write_text("")
+ _fake_trusted_root(monkeypatch, tmp_path)
+ monkeypatch.setattr(os, "environ", {})
+ monkeypatch.setattr(tools.shutil, "which", lambda _name: r"C:\somewhere\else\bash.exe")
+ assert tools._windows_bash() == str(git_bash)
+
+
+def test_untrusted_path_bash_is_rejected(monkeypatch, tmp_path):
+ # A bash in a user-writable dir (Scoop, a per-user Git, a project checkout)
+ # would run every sandboxed command, defeating the PATH/PATHEXT hardening in
+ # _build_safe_env: the command passed the blocklist, then the shell itself is
+ # attacker-controlled. cmd is worse to write for but stays trusted.
+ scoop_bash = tmp_path / "scoop" / "shims" / "bash.exe"
+ scoop_bash.parent.mkdir(parents = True)
+ scoop_bash.write_text("")
+ _fake_trusted_root(monkeypatch, tmp_path / "Program Files")
+ monkeypatch.setattr(os, "environ", {"PATH": str(scoop_bash.parent)})
+ monkeypatch.setattr(tools.shutil, "which", lambda _name: str(scoop_bash))
+ assert tools._windows_bash() is None
+
+
+def test_trusted_path_bash_behind_an_untrusted_shim_is_found(monkeypatch, tmp_path):
+ # shutil.which stops at the first hit, so a user shim early on PATH used to
+ # decide the answer for a host that does have a trusted bash.
+ shim = tmp_path / "shims" / "bash.exe"
+ shim.parent.mkdir(parents = True)
+ shim.write_text("")
+ trusted_dir = tmp_path / "Program Files" / "Git" / "bin"
+ trusted_dir.mkdir(parents = True)
+ (trusted_dir / "bash.exe").write_text("")
+ _fake_trusted_root(monkeypatch, tmp_path / "Program Files")
+ monkeypatch.setattr(
+ os, "environ", {"PATH": os.pathsep.join([str(shim.parent), str(trusted_dir)])}
+ )
+ monkeypatch.setattr(tools.shutil, "which", lambda _name: str(shim))
+ assert tools._windows_bash() == str(trusted_dir / "bash.exe")
+
+
+ "wsl_path",
+ [
+ r"C:\Windows\System32\bash.exe",
+ r"C:\Users\me\AppData\Local\Microsoft\WindowsApps\bash.exe",
+ "C:/Windows/System32/bash.exe",
+ ],
+)
+def test_wsl_launcher_is_rejected(monkeypatch, wsl_path):
+ # WSL's bash runs in a different filesystem, so the sandbox workdir would not
+ # apply. Falling back to cmd is worse but stays inside the sandbox. The dir
+ # is trusted here so the marker is the only thing that can reject these.
+ monkeypatch.setattr(tools, "_is_trusted_windows_program_dir", lambda _dir: True)
+ assert tools._is_trusted_windows_bash(wsl_path) is False
+
+
+def test_windowsapps_under_program_files_is_still_rejected(monkeypatch, tmp_path):
+ # A store package installs under Program Files, so the trust check alone
+ # would accept the WSL shim there.
+ store_bash = tmp_path / "WindowsApps" / "bash.exe"
+ store_bash.parent.mkdir(parents = True)
+ store_bash.write_text("")
+ _fake_trusted_root(monkeypatch, tmp_path)
+ monkeypatch.setattr(os, "environ", {})
+ monkeypatch.setattr(tools.shutil, "which", lambda _name: str(store_bash))
+ assert tools._windows_bash() is None
+
+
+def test_no_bash_anywhere_returns_none(monkeypatch):
+ monkeypatch.setattr(tools, "_windows_program_roots", lambda: [])
+ monkeypatch.setattr(os, "environ", {})
+ monkeypatch.setattr(tools.shutil, "which", lambda _name: None)
+ assert tools._windows_bash() is None
+
+
+def test_blocklist_lexes_bash_syntax_when_the_shell_is_bash(monkeypatch):
+ # The scan is keyed to the shell, not the OS: the non-posix lexer never
+ # splits on `;`, so a blocked command after a control-flow keyword stayed in
+ # argument position and `if true; then rm -rf x; fi` really ran under bash.
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(tools, "_windows_bash", lambda: r"C:\Program Files\Git\bin\bash.exe")
+ assert "rm" in tools._find_blocked_commands("if true; then rm -rf x; fi")
+ assert "curl" in tools._find_blocked_commands("for i in 1; do curl http://x; done")
+
+
[email protected]("command", ["'rm' -rf x", '"rm" -rf x', "echo hi; 'rm' -rf x"])
+def test_blocklist_sees_through_quoting_when_the_shell_is_bash(monkeypatch, command):
+ # The non-posix lexer keeps the quote marks and _token_basename strips only
+ # meta-chars, so `'rm'` never matched `rm`. Harmless in front of cmd, where
+ # it is a literal unknown program; under bash it really deletes.
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(tools, "_windows_bash", lambda: r"C:\Program Files\Git\bin\bash.exe")
+ assert "rm" in tools._find_blocked_commands(command)
+
+
+def test_blocklist_still_catches_the_plain_form_under_cmd(monkeypatch):
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(tools, "_windows_bash", lambda: None)
+ assert "rm" in tools._find_blocked_commands("rm -rf x")
+
+
[email protected](sys.platform != "win32", reason = "Windows shell behaviour")
+def test_multiline_script_runs_every_line_on_windows():
+ # The regression itself: under cmd /c only the first line ran, so the loop
+ # body and the redirect were silently dropped.
+ if tools._windows_bash() is None:
+ pytest.skip("no native Win32 bash on this host")
+ script = "\n".join(
+ [
+ "value=unsloth",
+ "for i in 1 2 3; do",
+ ' echo "line $i $value"',
+ "done",
+ ]
+ )
+ out = tools._bash_exec(script)
+ for expected in ("line 1 unsloth", "line 2 unsloth", "line 3 unsloth"):
+ assert expected in out, out
+
+
+def test_paths_note_names_the_real_platform():
+ # A note that only cites /mnt/data and /tmp/outputs reads as "you are on
+ # Linux", and models then decline to launch Windows programs that do exist.
+ note = tools._SANDBOX_PATHS_NOTE
+ if sys.platform == "win32":
+ assert "Windows" in note
+ assert "/mnt/data" not in note
+ assert "/tmp/outputs" not in note
+ else:
+ assert "/mnt/data" in note
+
+
+def test_shell_note_names_the_shell_that_will_run(monkeypatch):
+ # Telling a model it has bash on a host that fell back to cmd reintroduces
+ # the multi-line half-execution this note exists to prevent.
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(tools, "_windows_bash", lambda: r"C:\Program Files\Git\bin\bash.exe")
+ assert "The shell is bash" in tools._build_terminal_shell_note()
+ monkeypatch.setattr(tools, "_windows_bash", lambda: None)
+ cmd_note = tools._build_terminal_shell_note()
+ assert "cmd, not bash" in cmd_note
+ assert "one command per call" in cmd_note
+
+
+def test_posix_shell_note_is_empty(monkeypatch):
+ # The POSIX descriptions are unchanged by this PR.
+ monkeypatch.setattr(sys, "platform", "linux")
+ assert tools._build_terminal_shell_note() == ""
+
+
[email protected]("bash", [r"C:\Program Files\Git\bin\bash.exe", None])
+def test_notes_never_recommend_a_blocked_program(monkeypatch, bash):
+ # powershell/pwsh are in _BLOCKED_COMMANDS_WIN, so a sandboxed user who
+ # follows the prompt gets a hard block instead of a command. `cmd /c start`
+ # is not blocked, which makes naming it worse: it advertises the gap.
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(tools, "_windows_bash", lambda: bash)
+ text = (tools._build_sandbox_paths_note() + tools._build_terminal_shell_note()).lower()
+ for program in tools._BLOCKED_COMMANDS_WIN:
+ assert program not in text
+ assert "start-process" not in text
+ assert "/c start" not in text
+
+
+def test_terminal_tool_description_is_the_two_notes_appended():
+ # _TERMINAL_SHELL_NOTE is "" off Windows, so `note in description` proves
+ # nothing about the shell half there. Compare the whole string instead, which
+ # at least pins the composition, and cover the note's own content below.
+ description = tools.TERMINAL_TOOL["function"]["description"]
+ assert description == (
+ "Execute a terminal command and return stdout/stderr."
+ + tools._SANDBOX_PATHS_NOTE
+ + tools._TERMINAL_SHELL_NOTE
+ )
+
+
[email protected]("bash", [r"C:\Program Files\Git\bin\bash.exe", None])
+def test_windows_shell_note_is_never_empty(monkeypatch, bash):
+ # The half the test above cannot reach on a Linux runner: whichever shell the
+ # resolver lands on, the terminal description gains a sentence naming it.
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(tools, "_windows_bash", lambda: bash)
+ note = tools._build_terminal_shell_note()
+ assert note.startswith(" The shell is ")
+ assert note not in tools._build_sandbox_paths_note()
+
+
+def test_python_tool_description_omits_the_shell():
+ # The shell note on the python description would point a model at
+ # subprocess/os.system as a way around the terminal blocklist, and none of
+ # it applies to the python sandbox anyway.
+ description = tools.PYTHON_TOOL["function"]["description"]
+ assert tools._SANDBOX_PATHS_NOTE in description
+ assert "shell" not in description.lower()
+ if sys.platform == "win32":
+ assert tools._TERMINAL_SHELL_NOTE not in description
+
+
+def test_notes_say_where_commands_run(monkeypatch):
+ # Without this, models decline to launch a window they believe the user
+ # cannot see, and hand back manual instructions instead.
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(tools, "_windows_bash", lambda: r"C:\Program Files\Git\bin\bash.exe")
+ assert "user's own machine" in tools._build_sandbox_paths_note()
+ assert "opens a window on the user's desktop" in tools._build_terminal_shell_note()
+
+
+ "command",
+ [
+ "cmd /c powershell -Command ls",
+ "cmd //c powershell -Command ls",
+ "cmd //k powershell -Command ls",
+ 'cmd //c start "" powershell -Command ls',
+ 'cmd //c start /b "" pwsh -Command ls',
+ 'cmd //c start //min "" powershell -Command ls',
+ r'cmd //c start /d C:/tmp "" powershell -Command ls',
+ ],
+)
+def test_cmd_shellout_is_screened_through_mangled_switches(command):
+ # Git Bash turns a lone /c into a path, so a model writes //c. That spelling
+ # skipped the nested scan, making `cmd //c powershell` reachable where
+ # `cmd /c powershell` was blocked, and `start` launches its argument too.
+ assert tools._find_blocked_commands(command)
+
+
+ "command",
+ [
+ 'cmd //c start "" bash -c "bash /c/x.sh"',
+ "cmd //c start wt",
+ "cmd //c dir",
+ "start notepad",
+ ],
+)
+def test_detached_windows_stay_launchable(command):
+ # `start` is the only route to a window on the user's desktop, which the
+ # terminal description promises, so screening must not blanket-block cmd.
+ assert not tools._find_blocked_commands(command)