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.

Studio: run the isolated Windows Terminal on cmd.exe with stock git when Git Bash cannot start in MXC (#12164)

Daniel Hana19dae7bdd37
diff --git a/studio/backend/core/inference/mxc_adapter.py b/studio/backend/core/inference/mxc_adapter.py
index 5caeda556f8..742c1fdefc0 100644
--- a/studio/backend/core/inference/mxc_adapter.py
+++ b/studio/backend/core/inference/mxc_adapter.py
@@ -175,6 +175,10 @@ def release_runtime(proc) -> None:
if runtime_lease is not None:
proc._mxc_runtime_lease = None
runtime_lease.release()
+ drive_alias = getattr(proc, "_mxc_drive_alias", None)
+ if drive_alias is not None:
+ proc._mxc_drive_alias = None
+ drive_alias.release()
def abort(proc, *, grace_seconds: float = 1) -> None:
diff --git a/studio/backend/core/inference/mxc_drive_alias.py b/studio/backend/core/inference/mxc_drive_alias.py
new file mode 100644
index 00000000000..5801791d9d5
--- /dev/null
+++ b/studio/backend/core/inference/mxc_drive_alias.py
@@ -0,0 +1,297 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+"""Drive-letter aliases for the session workdir of an isolated cmd Terminal launch.
+
+Inside an MXC AppContainer, Git for Windows cannot resolve its working directory: the drive-letter form
+of GetFinalPathNameByHandleW is denied and the GetLongPathNameW fallback has to list every ancestor.
+From a drive root there is nothing above to resolve, so a launch runs from ``X:\\`` mapped onto the
+canonical workdir with DefineDosDeviceW, the same mapping ``subst`` makes. The mapping only changes how
+the workdir is spelled; MXC still grants the canonical folder and nothing else.
+"""
+
+from __future__ import annotations
+
+from contextlib import contextmanager
+import json
+import logging
+import os
+from pathlib import Path
+import threading
+import uuid
+
+logger = logging.getLogger(__name__)
+
+DRIVE_ALIAS_ENV = "UNSLOTH_MXC_DRIVE_ALIAS"
+LIMITATION_UNAVAILABLE = "terminal_workdir_drive_alias_unavailable"
+LOCK_TIMEOUT_SECONDS = 10
+LETTERS = "ZYXWVUTSRQPONMLKJIHG"
+DDD_REMOVE_DEFINITION = 0x2
+DDD_EXACT_MATCH_ON_REMOVE = 0x4
+
+_lock = threading.Lock()
+# normcase(target) -> [letter, target, lease count]; the leases this process holds.
+_active: dict[str, list] = {}
+# (letter, target) -> [letter, target, lease count]: held mappings another definition now covers. Still removed, by
+# exact match, when their last lease ends, so ours never resurfaces once the other one goes.
+_shadowed: dict[tuple[str, str], list] = {}
+_host = None
+
+
+def _on_windows() -> bool:
+ return os.name == "nt"
+
+
+def enabled() -> bool:
+ return os.environ.get(DRIVE_ALIAS_ENV, "").strip() != "0"
+
+
+class _Win32:
+ def __init__(self) -> None:
+ import ctypes
+ from ctypes import wintypes
+
+ self._ctypes = ctypes
+ self._kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)
+ self._kernel32.DefineDosDeviceW.argtypes = [
+ wintypes.DWORD,
+ wintypes.LPCWSTR,
+ wintypes.LPCWSTR,
+ ]
+ self._kernel32.DefineDosDeviceW.restype = wintypes.BOOL
+ self._kernel32.QueryDosDeviceW.argtypes = [
+ wintypes.LPCWSTR,
+ wintypes.LPWSTR,
+ wintypes.DWORD,
+ ]
+ self._kernel32.QueryDosDeviceW.restype = wintypes.DWORD
+ self._kernel32.GetLogicalDrives.restype = wintypes.DWORD
+
+ def logical_drives(self) -> int:
+ return int(self._kernel32.GetLogicalDrives())
+
+ def definitions(self, letter: str) -> list[str]:
+ """Every definition of the letter, the one in effect first."""
+ buffer = self._ctypes.create_unicode_buffer(32768)
+ size = self._kernel32.QueryDosDeviceW(f"{letter}:", buffer, len(buffer))
+ if not size:
+ return []
+ return [item for item in buffer[:size].split("\0") if item]
+
+ def query(self, letter: str) -> str | None:
+ found = self.definitions(letter)
+ return found[0] if found else None
+
+ def network_letters(self) -> set[str]:
+ """Persistent network drives, which stay undefined until they reconnect."""
+ import winreg
+
+ letters = set()
+ try:
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Network") as key:
+ index = 0
+ while True:
+ try:
+ letters.add(winreg.EnumKey(key, index).upper())
+ except OSError:
+ return letters
+ index += 1
+ except OSError:
+ return letters
+
+ def define(self, letter: str, target: str) -> bool:
+ return bool(self._kernel32.DefineDosDeviceW(0, f"{letter}:", target))
+
+ def remove(self, letter: str, target: str) -> bool:
+ flags = DDD_REMOVE_DEFINITION | DDD_EXACT_MATCH_ON_REMOVE
+ return bool(self._kernel32.DefineDosDeviceW(flags, f"{letter}:", target))
+
+ def process_alive(self, pid: int, create_time: float) -> bool:
+ import psutil
+ try:
+ return abs(psutil.Process(pid).create_time() - create_time) < 1e-3
+ except psutil.NoSuchProcess:
+ return False
+ except psutil.Error:
+ return True # unknown: never reclaim another process's mapping
+
+ def own_identity(self) -> tuple[int, float]:
+ import psutil
+ return os.getpid(), psutil.Process(os.getpid()).create_time()
+
+
+def _get_host():
+ global _host
+ if _host is None:
+ _host = _Win32()
+ return _host
+
+
+def _expected(target: str) -> str:
+ return "\\??\\" + target
+
+
+def record_path() -> Path:
+ from .mxc_runtime import _studio_root
+ return Path(os.path.abspath(_studio_root() / "mxc-runtime" / "drive-aliases.json"))
+
+
+def _load_record() -> dict[str, dict]:
+ try:
+ data = json.loads(record_path().read_text(encoding = "utf-8"))
+ except (OSError, ValueError):
+ return {}
+ aliases = data.get("aliases") if isinstance(data, dict) else None
+ if not isinstance(aliases, dict):
+ return {}
+ return {
+ str(k): v
+ for k, v in aliases.items()
+ if isinstance(v, dict) and isinstance(v.get("target"), str)
+ }
+
+
+def _save_record(aliases: dict[str, dict]) -> bool:
+ path = record_path()
+ temporary = path.with_name(f"{path.name}.{uuid.uuid4().hex}.tmp")
+ try:
+ temporary.write_text(
+ json.dumps({"aliases": aliases}, indent = 2, sort_keys = True), encoding = "utf-8"
+ )
+ os.replace(temporary, path)
+ return True
+ except OSError as exc:
+ logger.info("Could not write the MXC drive alias record: %s", exc)
+ return False
+ finally:
+ try:
+ temporary.unlink(missing_ok = True)
+ except OSError as exc:
+ # Raising here would skip the caller's removal of the mapping it just made.
+ logger.info("Could not remove %s: %s", temporary, exc)
+
+
+@contextmanager
+def _transaction():
+ """The alias record, locked across Studio processes; yields None when it cannot be locked."""
+ from filelock import FileLock, Timeout
+
+ path = record_path()
+ try:
+ path.parent.mkdir(parents = True, exist_ok = True)
+ lock = FileLock(str(path.with_suffix(".lock")), timeout = LOCK_TIMEOUT_SECONDS)
+ lock.acquire()
+ except (Timeout, OSError) as exc:
+ logger.info("Could not lock the MXC drive alias record: %s", exc)
+ yield None
+ return
+ try:
+ yield _load_record()
+ finally:
+ lock.release()
+
+
+def _reclaim(host, aliases: dict[str, dict], own_pid: int) -> None:
+ """Drop records whose owner is gone, removing the mapping only while it still names that target."""
+ for letter, entry in list(aliases.items()):
+ pid, created = entry.get("pid"), entry.get("pid_create_time")
+ if not isinstance(pid, int) or not isinstance(created, (int, float)):
+ continue
+ if pid == own_pid and any(active[0] == letter for active in _active.values()):
+ continue
+ if pid != own_pid and host.process_alive(pid, created):
+ continue
+ target = entry["target"]
+ if _expected(target) in host.definitions(letter) and not host.remove(letter, target):
+ continue # still defined, even under another definition, and not removable: keep the record
+ aliases.pop(letter)
+
+
+class AliasLease:
+ def __init__(self, letter: str, target: str) -> None:
+ self.letter = letter
+ self.target = target
+ self.root = f"{letter}:\\"
+ self._released = False
+
+ def release(self) -> None:
+ with _lock:
+ if self._released:
+ return
+ self._released = True
+ key = os.path.normcase(self.target)
+ entry = _active.get(key)
+ if entry is not None and entry[0] == self.letter:
+ table, slot = _active, key
+ else:
+ table, slot = _shadowed, (self.letter, key)
+ entry = _shadowed.get(slot)
+ if entry is None:
+ return
+ entry[2] -= 1
+ if entry[2] > 0:
+ return
+ table.pop(slot)
+ host = _get_host()
+ if not host.remove(self.letter, self.target) and _expected(
+ self.target
+ ) in host.definitions(self.letter):
+ return # still mapped: keep the record so a later acquire can reclaim it
+ with _transaction() as aliases:
+ if aliases is not None and self.letter in aliases:
+ aliases.pop(self.letter)
+ _save_record(aliases)
+
+
+def acquire(workdir: str) -> AliasLease | None:
+ """A drive letter naming ``workdir`` for one launch, or None when Studio cannot map one safely."""
+ if not _on_windows() or not enabled():
+ return None
+ target = os.path.abspath(workdir)
+ key = os.path.normcase(target)
+ try:
+ host = _get_host()
+ with _lock:
+ entry = _active.get(key)
+ if entry is not None:
+ if host.query(entry[0]) == _expected(entry[1]):
+ entry[2] += 1
+ return AliasLease(entry[0], entry[1])
+ # Covered by another definition: never touch that one; ours is removed when its leases end.
+ _shadowed[(entry[0], key)] = _active.pop(key)
+ with _transaction() as aliases:
+ if aliases is None:
+ return None
+ own_pid, own_created = host.own_identity()
+ _reclaim(host, aliases, own_pid)
+ drives = host.logical_drives()
+ network = host.network_letters()
+ for letter in LETTERS:
+ if (
+ drives & (1 << (ord(letter) - ord("A")))
+ or letter in aliases
+ or letter in network
+ ):
+ continue
+ if host.query(letter) is not None:
+ continue
+ if not host.define(letter, target):
+ continue
+ if host.query(letter) != _expected(target):
+ host.remove(letter, target)
+ continue
+ aliases[letter] = {
+ "target": target,
+ "pid": own_pid,
+ "pid_create_time": own_created,
+ }
+ if not _save_record(aliases):
+ # Without a record a crash would strand the letter; do not map at all.
+ host.remove(letter, target)
+ return None
+ _active[key] = [letter, target, 1]
+ return AliasLease(letter, target)
+ logger.info("No free drive letter to alias the MXC workdir %s", target)
+ return None
+ except Exception as exc: # noqa: BLE001 - an alias is an optimisation for git, never a launch failure
+ logger.info("Could not alias the MXC workdir %s: %s", target, exc)
+ return None
diff --git a/studio/backend/core/inference/mxc_policy.py b/studio/backend/core/inference/mxc_policy.py
index b1171199a10..4a346653f53 100644
--- a/studio/backend/core/inference/mxc_policy.py
+++ b/studio/backend/core/inference/mxc_policy.py
@@ -7,8 +7,10 @@ from __future__ import annotations
import hashlib
import json
import logging
+import ntpath
import os
from pathlib import Path
+import re
import shutil
import site
import subprocess
@@ -26,6 +28,11 @@ logger = logging.getLogger(__name__)
MAX_ENVIRONMENT_ENTRIES = 512
DACL_FALLBACK_ENV = "UNSLOTH_MXC_ALLOW_DACL_FALLBACK"
_WSL_TERMINAL_MARKERS = ("\\system32\\bash.exe", "\\windowsapps\\bash.exe")
+# CreateProcessW's lpCommandLine bound, in UTF-16 units; cmd itself stops at 8191 characters of payload.
+MAX_COMMAND_LINE = 32767
+_CMD_NAMES = {"cmd", "cmd.exe"}
+_CMD_SWITCHES = {"/d", "/s"}
+_DRIVE_ROOT = re.compile(r"[A-Za-z]:\\\Z")
def _studio_ui_policy() -> dict:
@@ -262,9 +269,81 @@ def _model_read_roots(workdir: str, granted: list[str]) -> list[str]:
return result
+def is_cmd_argv(argv) -> bool:
+ """``cmd [/d] [/s] /c <payload>``: the Terminal shape whose payload must reach cmd unescaped."""
+ if len(argv) < 3 or not all(isinstance(part, str) for part in argv):
+ return False
+ if ntpath.basename(argv[0]).casefold() not in _CMD_NAMES or argv[-2].casefold() != "/c":
+ return False
+ switches = [part.casefold() for part in argv[1:-2]]
+ return len(set(switches)) == len(switches) and set(switches) <= _CMD_SWITCHES
+
+
+def cmd_command_line(cmd_path: str, payload: str) -> str:
+ """cmd's own quoting: /s strips exactly the outer pair, so embedded quotes arrive as written.
+
+ list2cmdline escapes them as \\", which cmd does not understand: a quoted path then names a file
+ that cannot exist, and a denied read looks the same as a command that never ran.
+ """
+ if "\0" in payload:
+ raise MxcPolicyError("the Terminal command contains a NUL character")
+ if "\n" in payload or "\r" in payload:
+ raise MxcPolicyError(
+ "cmd runs only the first line of a multi-line command; send one command per call"
+ )
+ command_line = f'"{cmd_path}" /d /s /c "{payload}"'
+ if len(command_line) > MAX_COMMAND_LINE:
+ raise MxcPolicyError("the Terminal command exceeds the Windows command-line limit")
+ return command_line
+
+
+def host_spawn_args(argv):
+ """What Popen gets for an unisolated launch: a cmd Terminal keeps cmd's own quoting there too."""
+ if not is_cmd_argv(argv):
+ return argv
+ try:
+ return cmd_command_line(_system_cmd(), argv[-1])
+ except MxcPolicyError:
+ return argv # a multi-line or oversized command keeps today's argv behaviour on the host
+
+
+def _system_cmd() -> str:
+ """System32's cmd.exe. COMSPEC is caller-controlled, so it is never consulted."""
+ try:
+ import ctypes
+
+ buffer = ctypes.create_unicode_buffer(260)
+ size = ctypes.windll.kernel32.GetSystemDirectoryW(buffer, len(buffer))
+ if 0 < size < len(buffer):
+ return os.path.join(buffer.value, "cmd.exe")
+ except (AttributeError, OSError):
+ pass
+ system_root = os.environ.get("SystemRoot") or os.environ.get("WINDIR") or "C:\\Windows"
+ return ntpath.join(system_root, "System32", "cmd.exe")
+
+
+def _checked_cwd_alias(cwd_alias: str, workdir_identity: dict[str, int]) -> str:
+ """A drive letter defined to name the workdir: stock git cannot resolve a nested cwd inside the container."""
+ if not isinstance(cwd_alias, str) or not _DRIVE_ROOT.match(cwd_alias):
+ raise MxcPolicyError(
+ f"the MXC workdir alias must be a drive root such as Z:\\: {cwd_alias!r}"
+ )
+ try:
+ identity = _object_identity(cwd_alias, directory = True)
+ except OSError as exc:
+ raise MxcPolicyError(f"the MXC workdir alias cannot be opened: {cwd_alias}") from exc
+ if identity != workdir_identity:
+ raise MxcPolicyError(
+ f"the MXC workdir alias does not name the session workdir: {cwd_alias}"
+ )
+ return cwd_alias
+
+
def _selected_runtime(plan) -> str:
executable = plan.argv[0]
- if os.path.isabs(executable):
+ if plan.execution_kind == "terminal" and is_cmd_argv(plan.argv):
+ selected = _system_cmd()
+ elif os.path.isabs(executable):
selected = executable
elif plan.execution_kind == "terminal":
selected = shutil.which(executable, path = plan.env.get("PATH"))
@@ -307,6 +386,8 @@ def verify_launch_identities(request: dict) -> None:
raise MxcPolicyError("the selected workload executable changed before WXC dispatch")
if _object_identity(request["cwd"], directory = True) != request["workdirIdentity"]:
raise MxcPolicyError("the MXC workdir changed before WXC dispatch")
+ if request.get("cwdAlias") is not None:
+ _checked_cwd_alias(request["cwdAlias"], request["workdirIdentity"])
_safe_canonical_path(request["cwd"], directory = True)
_scan_workdir(request["cwd"], required = request["requireCompleteScan"])
@@ -332,7 +413,12 @@ def _with_session_packages(env: dict[str, str], workdir: str) -> dict[str, str]:
return env
-def build_launch_request(plan, *, run_id: str | None = None) -> dict:
+def build_launch_request(
+ plan,
+ *,
+ run_id: str | None = None,
+ cwd_alias: str | None = None,
+) -> dict:
if sys.platform != "win32":
raise MxcPolicyError("MXC policy construction is Windows-only")
if plan.execution_kind not in {"python", "terminal"}:
@@ -358,6 +444,13 @@ def build_launch_request(plan, *, run_id: str | None = None) -> dict:
mxc_read_grants.revoke_recorded()
execution_argv = list(plan.argv)
execution_argv[0] = selected_runtime
+ if plan.execution_kind == "terminal" and is_cmd_argv(plan.argv):
+ command_line = cmd_command_line(selected_runtime, plan.argv[-1])
+ else:
+ command_line = subprocess.list2cmdline(execution_argv)
+ workdir_identity = _object_identity(workdir, directory = True)
+ if cwd_alias is not None:
+ cwd_alias = _checked_cwd_alias(cwd_alias, workdir_identity)
run_id = run_id or uuid.uuid4().hex
workload_env = _with_session_packages(dict(plan.env), workdir)
# MXC's Windows ProcessContainer validator requires LOCALAPPDATA to be
@@ -370,8 +463,9 @@ def build_launch_request(plan, *, run_id: str | None = None) -> dict:
"containment": "processcontainer",
"lifecycle": {"destroyOnExit": True, "preservePolicy": False},
"process": {
- "commandLine": subprocess.list2cmdline(execution_argv),
- "cwd": workdir,
+ "commandLine": command_line,
+ # Grants, scans and identities stay on the canonical workdir; only the workload starts in the alias.
+ "cwd": cwd_alias or workdir,
"env": [f"{key}={value}" for key, value in sorted(workload_env.items())],
"timeout": 0
if plan.timeout_seconds is None
@@ -401,7 +495,8 @@ def build_launch_request(plan, *, run_id: str | None = None) -> dict:
"runtimePath": os.path.realpath(selected_runtime),
"runtimeIdentity": _object_identity(selected_runtime, directory = False),
"cwd": workdir,
- "workdirIdentity": _object_identity(workdir, directory = True),
+ "workdirIdentity": workdir_identity,
+ "cwdAlias": cwd_alias,
"config": config,
"configBytes": canonical_config_bytes(config),
"policyHash": compute_policy_hash(config),
diff --git a/studio/backend/core/inference/mxc_probe.py b/studio/backend/core/inference/mxc_probe.py
index f8cd2728f6a..a3cca4b580a 100644
--- a/studio/backend/core/inference/mxc_probe.py
+++ b/studio/backend/core/inference/mxc_probe.py
@@ -15,7 +15,7 @@ import threading
import time
from types import SimpleNamespace
-from . import mxc_adapter, mxc_policy, mxc_runtime
+from . import mxc_adapter, mxc_drive_alias, mxc_policy, mxc_runtime
_lock = threading.Lock()
_cache: dict[tuple, tuple[float, bool, str]] = {}
@@ -75,14 +75,22 @@ def host_prep_remediation() -> str | None:
return advice
+def _is_cmd(selected_executable: str) -> bool:
+ return Path(selected_executable).name.casefold() in mxc_policy._CMD_NAMES
+
+
def _terminal_probe(selected_executable: str, workdir: Path, canary: Path, outside_write: Path):
name = Path(selected_executable).name.casefold()
read_capture = workdir / "outside-read.txt"
- if name in {"cmd", "cmd.exe"}:
+ if _is_cmd(selected_executable):
+ # The quoted redirect is the positive control for quoting: a command line that mangles quotes
+ # also fails the denied read and write below, which would otherwise pass without isolation.
command = (
"echo ok>inside.txt"
+ ' & echo ok>"inside quoted.txt"'
f' & type "{canary}" >"{read_capture}" 2>nul'
f' & (echo bad>"{outside_write}") 2>nul'
+ " & cd"
" & echo UNSLOTH_MXC_TERMINAL_PROBE_OK"
)
return (selected_executable, "/d", "/s", "/c", command)
@@ -223,8 +231,21 @@ def _probe(
env = env,
)
+ # Production runs a cmd Terminal from a drive alias of its workdir, so the probe must too.
+ lease = None
+ if execution_kind == "terminal" and _is_cmd(selected_executable):
+ try:
+ lease = mxc_drive_alias.acquire(
+ mxc_policy._safe_canonical_path(str(workdir), directory = True)
+ )
+ except Exception:
+ lease = None
try:
- request = mxc_policy.build_launch_request(probe_plan)
+ request = (
+ mxc_policy.build_launch_request(probe_plan, cwd_alias = lease.root)
+ if lease
+ else mxc_policy.build_launch_request(probe_plan)
+ )
proc = mxc_adapter.spawn(
request,
cancel_event = cancel_event,
@@ -261,6 +282,8 @@ def _probe(
if proc.poll() is None:
mxc_adapter.abort(proc)
mxc_adapter.release_runtime(proc)
+ if lease is not None:
+ lease.release()
if (
proc.returncode != 0
or result.get("exitCode") != 0
@@ -281,6 +304,8 @@ def _probe(
or outside_write.exists()
or "outside-secret" in outside_read
or not (workdir / "inside.txt").is_file()
+ or (_is_cmd(selected_executable) and not (workdir / "inside quoted.txt").is_file())
+ or (lease is not None and lease.root.casefold() not in output.casefold().split())
):
return False, "the live MXC Terminal positive/negative controls failed"
return True, "the selected Terminal passed the live MXC positive and negative controls"
diff --git a/studio/backend/core/inference/os_sandbox.py b/studio/backend/core/inference/os_sandbox.py
index dfcd4c7109a..fb04119f794 100644
--- a/studio/backend/core/inference/os_sandbox.py
+++ b/studio/backend/core/inference/os_sandbox.py
@@ -213,7 +213,11 @@ class PreparedSandboxLaunch:
def spawn_prepared_launch(prepared: PreparedSandboxLaunch, **popen_kwargs: Any) -> object:
if prepared.spawn_callback is not None:
return prepared.spawn_callback(prepared, popen_kwargs)
- proc = subprocess.Popen(prepared.argv, **popen_kwargs)
+ argv = prepared.argv
+ if sys.platform == "win32":
+ from . import mxc_policy
+ argv = mxc_policy.host_spawn_args(argv)
+ proc = subprocess.Popen(argv, **popen_kwargs)
if prepared.execution_record is not None:
prepared.execution_record = replace(prepared.execution_record, execution_status = "started")
return proc
diff --git a/studio/backend/core/inference/sandbox_windows_mxc.py b/studio/backend/core/inference/sandbox_windows_mxc.py
index 039f4b16ea2..c6f33e8ed64 100644
--- a/studio/backend/core/inference/sandbox_windows_mxc.py
+++ b/studio/backend/core/inference/sandbox_windows_mxc.py
@@ -11,7 +11,7 @@ import os
import subprocess
import sys
-from . import mxc_adapter, mxc_policy, mxc_probe, mxc_read_grants, mxc_runtime
+from . import mxc_adapter, mxc_drive_alias, mxc_policy, mxc_probe, mxc_read_grants, mxc_runtime
from .os_sandbox import (
PreparedSandboxLaunch,
SandboxBuildError,
@@ -25,6 +25,22 @@ from .os_sandbox import (
logger = logging.getLogger(__name__)
+CMD_PROFILE_LIMITATION = "terminal_cmd_profile_git_hooks_pager_editor_disabled"
+
+
+def _workdir_alias(plan):
+ """(lease, limitations) for a cmd Terminal launch: stock git needs the workdir as a drive root."""
+ if plan.execution_kind != "terminal" or not mxc_policy.is_cmd_argv(plan.argv):
+ return None, ()
+ try:
+ workdir = mxc_policy._safe_canonical_path(plan.workdir, directory = True)
+ except Exception:
+ return None, () # build_launch_request refuses the same workdir with the real reason
+ lease = mxc_drive_alias.acquire(workdir)
+ if lease is None:
+ return None, (mxc_drive_alias.LIMITATION_UNAVAILABLE,)
+ return lease, (CMD_PROFILE_LIMITATION,)
+
def _capability_fingerprint(identity: str, execution_kind: str, selected_executable: str) -> str:
return hashlib.sha256(
@@ -131,11 +147,18 @@ def capability_snapshot(
def prepare(plan, capability):
+ lease, alias_limitations = _workdir_alias(plan)
try:
- request = mxc_policy.build_launch_request(plan)
+ request = (
+ mxc_policy.build_launch_request(plan, cwd_alias = lease.root)
+ if lease
+ else mxc_policy.build_launch_request(plan)
+ )
except Exception as exc:
+ if lease is not None:
+ lease.release()
raise SandboxBuildError(f"Windows MXC policy construction failed: {exc}") from exc
- launch_limitations = tuple(request.get("launchLimitations", ()))
+ launch_limitations = tuple(request.get("launchLimitations", ())) + alias_limitations
record = _record(
plan,
capability,
@@ -167,6 +190,9 @@ def prepare(plan, capability):
execution_record = record,
launch_limitations = launch_limitations,
)
+ if lease is not None:
+ # Runs on every exit path, spawned or not; release_runtime drops it first once the workload is gone.
+ prepared.cleanup_callbacks.append(lease.release)
def launch(_prepared, kwargs):
try:
@@ -181,6 +207,8 @@ def prepare(plan, capability):
proc = mxc_adapter.spawn(request, cancel_event = plan.cancel_event, popen_kwargs = kwargs)
except Exception as exc:
may_have_started = bool(getattr(exc, "may_have_started", False))
+ if lease is not None and not may_have_started:
+ lease.release()
cancelled = isinstance(exc, mxc_adapter.MxcLaunchCancelled)
refused = getattr(exc, "stage", None) == "policy"
if plan.requested_mode == "auto" and not (may_have_started or cancelled or refused):
@@ -190,7 +218,7 @@ def prepare(plan, capability):
"env": with_session_packages(kwargs.get("env") or plan.env, plan.workdir),
}
try:
- proc = subprocess.Popen(plan.argv, **kwargs)
+ proc = subprocess.Popen(mxc_policy.host_spawn_args(plan.argv), **kwargs)
except OSError as fallback_exc:
raise SandboxBuildError(
f"Windows MXC and software-safeguard launches both failed: {fallback_exc}"
@@ -239,6 +267,8 @@ def prepare(plan, capability):
execution_status = "dispatched",
backend_tier = str(getattr(proc, "_mxc_backend_tier", "unknown")),
)
+ if lease is not None:
+ proc._mxc_drive_alias = lease
prepared.cleanup_callbacks.append(lambda: mxc_adapter.release_runtime(proc))
return proc
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 5d3ea03ee18..5fc9a3cbac0 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -415,7 +415,9 @@ _SUBSTITUTION_SPAN_STEP = 64
# Quote state of a backslash and the character behind it. Distinct from the surrounding quoting because bash expands
# neither: the `$(` in `sed "s/\$(CC)/gcc/" Makefile` opens no command substitution.
_ESCAPED_CHAR_STATE = "\\"
-_WIN_CONDITIONAL_KEYWORDS = frozenset({"exist", "defined", "errorlevel", "not"})
+_WIN_CONDITIONAL_KEYWORDS = frozenset({"exist", "defined", "errorlevel", "cmdextversion", "not"})
+# cmd's `IF [/I] [NOT] a OP b command`: the comparison stands where the command word would.
+_WIN_COMPARISON_OPS = frozenset({"==", "equ", "neq", "lss", "leq", "gtr", "geq"})
_FIND_EXEC_FLAGS = frozenset({"-exec", "-execdir", "-ok", "-okdir"})
# A find action is COMPLETE at its terminator: words after it are find's next predicate, not CMD's. Reading past it
# took a following `-exec grep -e safe {} +` for sed's script.
@@ -1575,13 +1577,14 @@ def _join_escaped_newlines(text: str) -> str:
return "".join(out)
-def _find_blocked_commands(command: str) -> set[str]:
+def _find_blocked_commands(command: str, posix: "bool | None" = None) -> set[str]:
"""Detect blocked commands at shell command position only.
A token is at command position if it is the first token, or follows a shell separator /
brace-group opener / new-command keyword, or a command-prefix wrapper like `env` / `time` /
`xargs`. Tokens in argument position pass through. Also scans `find ... -exec CMD` and recurses
- into bash -c / cmd /c.
+ into bash -c / cmd /c. ``posix`` names the dialect of the shell that will run the command; None
+ keeps the host default (_shell_is_posix).
"""
blocked: set[str] = set()
@@ -1600,7 +1603,7 @@ def _find_blocked_commands(command: str) -> set[str]:
# rm -rf x` and at a line break. 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 `if true; then rm -rf x; fi` came back with nothing
# blocked.
- lexed_posix = _shell_is_posix()
+ lexed_posix = _shell_is_posix() if posix is None else posix
try:
if not lexed_posix:
tokens = shlex.split(command, posix = False)
@@ -1689,14 +1692,37 @@ def _find_blocked_commands(command: str) -> set[str]:
sed_xargs: "dict[int, int]" = {} # sed word -> the xargs that builds its argv
xargs_index = -1 # an xargs awaiting the command it wraps
coproc_kw = False # the word just consumed was the `coproc` KEYWORD, so a name may follow
+ if_condition = False # just after cmd's IF, where a comparison may precede the command
+ skip_tokens = 0
for token_index, token in enumerate(tokens):
after_coproc = coproc_kw
coproc_kw = False
+ if skip_tokens:
+ skip_tokens -= 1
+ continue
if skip_operand:
# `exec -a NAME cmd` and `if exist FILE cmd` both put an operand where the command word would otherwise
# be.
skip_operand = False
continue
+ if expect_command and token.lower() == "if":
+ # cmd's IF is case-insensitive; reading `IF` as the command word hid the command after its condition.
+ if_condition = True
+ prefix_pending = False
+ prefix_command = ""
+ xargs_index = -1
+ continue
+ if if_condition and expect_command:
+ low = token.lower()
+ if low in {"/i", "not"}:
+ continue
+ if_condition = False
+ following = tokens[token_index + 1].lower() if token_index + 1 < len(tokens) else ""
+ if following in _WIN_COMPARISON_OPS:
+ skip_tokens = 2
+ continue
+ if "==" in token.strip("="):
+ continue
if expect_command and token.lower() in _WIN_CONDITIONAL_KEYWORDS:
skip_operand = token.lower() != "not"
continue
@@ -1710,8 +1736,9 @@ def _find_blocked_commands(command: str) -> set[str]:
continue
# A keyword only separates where a COMMAND may start. A quoted operator is DATA the command receives, not a
# separator, so it leaves command position alone: `grep '|&' rm file` runs nothing and must not be refused.
+ # Folded: cmd's FOR ... DO is case-insensitive; in bash a capitalised keyword is only a command name.
if (_looks_like_separator(token) and token_index not in quoted_separators) or (
- token in _SHELL_KEYWORDS_AS_SEP and expect_command
+ token.lower() in _SHELL_KEYWORDS_AS_SEP and expect_command
):
coproc_kw = expect_command and token == "coproc"
expect_command = True
@@ -1777,7 +1804,7 @@ def _find_blocked_commands(command: str) -> set[str]:
break
_name, _sep, _value = nxt.partition("=")
if _sep and _value:
- blocked |= _find_blocked_commands(_value)
+ blocked |= _find_blocked_commands(_value, posix = posix)
# find's `-exec`/`-execdir` and fd's `-x` / `-X` / `--exec` / `--exec-batch` all invoke CMD directly. Reading only
# find's own flags left every fd form unscanned, so `fd -x rm -rf x` reached the hard blocklist as nothing at all.
@@ -1970,14 +1997,14 @@ def _find_blocked_commands(command: str) -> set[str]:
continue # skip Windows switches like /s, /q, /v:on
prev_base = os.path.basename(prev).lower()
if is_unix_c and prev_base in _SHELLS:
- blocked |= _find_blocked_commands(tokens[i + 1])
+ blocked |= _find_blocked_commands(tokens[i + 1], posix = posix)
elif is_win_c and prev_base in _SHELLS_WIN:
# The cmd lexer keeps the marks, so `cmd /c "powershell ls"` would recurse on a first word of
# `"powershell` and match nothing.
payload = tokens[i + 1]
if len(payload) > 1 and payload[0] == '"' and payload[-1] == '"':
payload = payload[1:-1]
- blocked |= _find_blocked_commands(payload)
+ blocked |= _find_blocked_commands(payload, posix = posix)
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
@@ -1994,14 +2021,14 @@ def _find_blocked_commands(command: str) -> set[str]:
# runnable; deciding whether `start` itself is executed is deliberately not attempted, since every local
# approximation under-approximated.
if j < len(tokens):
- blocked |= _find_blocked_commands(tokens[j])
+ blocked |= _find_blocked_commands(tokens[j], posix = posix)
if j + 1 < len(tokens) and _is_start_title(tokens[j]):
k = j + 1
# `start "my window" /min prog` puts switches after the title too.
while k < len(tokens) and _win_switch(tokens[k].lower()) in _START_SWITCHES:
k += 2 if _win_switch(tokens[k].lower()) in _START_SWITCHES_WITH_VALUE else 1
if k < len(tokens):
- blocked |= _find_blocked_commands(tokens[k])
+ blocked |= _find_blocked_commands(tokens[k], posix = posix)
# 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
@@ -2051,7 +2078,7 @@ def _find_blocked_commands(command: str) -> set[str]:
for variant in _sed_program_variants(alternative, sed_vars or {}):
for payload in _sed_exec_payloads(variant):
if payload:
- blocked |= _find_blocked_commands(payload)
+ blocked |= _find_blocked_commands(payload, posix = posix)
return blocked
@@ -5693,10 +5720,38 @@ def _command_references_sensitive(command: str) -> bool:
return any(_glob_hits_sensitive(c) or _references_sensitive_path(c) for c in candidates)
+_CMD_ECHO_OFF_RE = re.compile(r"(?<![^\s&|()])@+")
+# cmd control flow that runs the command after it: IF's condition, FOR's DO and CALL become separators.
+_CMD_CONTROL_RE = re.compile(
+ r"(?i)(?<![^\s&|()])(?:if\s+(?:/i\s+)?(?:not\s+)?(?:(?:exist|defined|errorlevel|cmdextversion)\s+\S+"
+ r"|\S+?\s*==\s*\S+|\S+\s+(?:equ|neq|lss|leq|gtr|geq)\s+\S+)|do|call)(?=\s)"
+)
+
+
+def _cmd_reading(command: str) -> str:
+ """How cmd splits a command for the POSIX classifiers: ' is an ordinary character, ^ only escapes,
+ a leading @ only turns the echo off, and IF / FOR ... DO / CALL run the command that follows."""
+ text = _CMD_ECHO_OFF_RE.sub("", command.replace("^", "").replace("'", " "))
+ return _CMD_CONTROL_RE.sub(" & ", text)
+
+
+def _reads_differently_under_cmd(command: str) -> bool:
+ """True when the isolated cmd Terminal will run ``command`` and cmd would split it unlike bash."""
+ return (
+ sys.platform == "win32"
+ and _cmd_reading(command) != command
+ and _terminal_profile() == "cmd_isolated"
+ )
+
+
def _terminal_is_potentially_unsafe(command: str) -> bool:
"""Classify a terminal command for auto mode (fail closed)."""
if not command or not command.strip():
return False
+ if _reads_differently_under_cmd(command) and _terminal_is_potentially_unsafe(
+ _cmd_reading(command)
+ ):
+ return True
# Redirections and substitutions can hide writes or nested commands; a quoted ">" false-positives into a prompt,
# which is the safe direction.
if ">" in command or "`" in command or "$(" in command or "<(" in command:
@@ -7999,6 +8054,12 @@ def _terminal_is_high_risk(command: str, _depth: int = 0) -> bool:
return True
if not command or not command.strip():
return False
+ if (
+ _depth == 0
+ and _reads_differently_under_cmd(command)
+ and _terminal_is_high_risk(_cmd_reading(command))
+ ):
+ return True
# A credential/secret path read or write, or a sandbox escape (../), asks.
if _command_references_sensitive(command):
return True
@@ -9192,7 +9253,22 @@ def _reusable_sandbox_temp_dir(temp_dir: str, workdir: str) -> bool:
return _is_sandbox_temp_dir(temp_dir, workdir) and os.access(temp_dir, os.W_OK | os.X_OK)
-def _build_safe_env(workdir: str) -> dict[str, str]:
+# Git for Windows starts hooks, the pager and the editor through its MSYS sh.exe, which cannot start inside MXC, so a
+# hook turns every commit into a failure and an editor hangs the call. Compatibility defaults, not a boundary: a
+# command can override them with git -c, and MXC is what confines it. core.hooksPath=NUL names no hook at all.
+_ISOLATED_CMD_GIT_ENV = {
+ "GIT_CONFIG_COUNT": "1",
+ "GIT_CONFIG_KEY_0": "core.hooksPath",
+ "GIT_CONFIG_VALUE_0": "NUL",
+ "GIT_PAGER": "",
+ "GIT_EDITOR": "unsloth-no-editor",
+ "GIT_SEQUENCE_EDITOR": "unsloth-no-editor",
+ "GIT_TERMINAL_PROMPT": "0",
+ "GCM_INTERACTIVE": "never",
+}
+
+
+def _build_safe_env(workdir: str, shell: "str | None" = None) -> dict[str, str]:
"""Build a minimal, credential-free environment for sandboxed subprocesses.
Whitelist-built from scratch (parent env NOT inherited): only
@@ -9206,6 +9282,9 @@ def _build_safe_env(workdir: str) -> dict[str, str]:
pinned. On Windows only, Git-for-Windows install dirs from the host PATH are appended so bare
``git`` resolves (#7317). User-writable host PATH entries are never inherited: they could shadow
auto-safe terminal commands.
+
+ ``shell="cmd_isolated"`` is the Windows MXC Terminal on cmd.exe: Git Bash's userland stays off
+ PATH and git gets the non-interactive settings in _ISOLATED_CMD_GIT_ENV.
"""
# Start from the running interpreter's dir so 'python'/'pip' resolve to the same environment the Unsloth server
# runs in.
@@ -9223,7 +9302,8 @@ def _build_safe_env(workdir: str) -> dict[str, str]:
sysroot = os.environ.get("SystemRoot", r"C:\Windows")
# Ahead of System32 and its DOS twins (bare `find` would hit FIND.EXE, not GNU find), behind the interpreter
# dirs so a Git-shipped python.exe cannot shadow the environment this server runs in.
- path_entries.extend(_windows_bash_userland_dirs())
+ if shell != "cmd_isolated":
+ path_entries.extend(_windows_bash_userland_dirs())
path_entries.extend([os.path.join(sysroot, "System32"), sysroot])
else:
path_entries.extend(["/usr/local/bin", "/usr/bin", "/bin"])
@@ -9236,6 +9316,9 @@ def _build_safe_env(workdir: str) -> dict[str, str]:
# Append the CANONICAL (realpath) trusted git dir, scanning past any untrusted user shim that sorts first on
# PATH; the canonical path cannot be retargeted via a junction after the trust check.
_trusted_git_dir, git_ext = _resolve_trusted_windows_git()
+ if not _trusted_git_dir and shell == "cmd_isolated":
+ # Git installed for Git Bash only is not on PATH; bash found it, so use its Git\cmd.
+ _trusted_git_dir, git_ext = _windows_bash_git_cmd_dir(), ".EXE"
if _trusted_git_dir:
path_entries.append(_trusted_git_dir)
@@ -9274,6 +9357,8 @@ def _build_safe_env(workdir: str) -> dict[str, str]:
# cmd/CreateProcess search cwd before PATH for bare names; disable so a workdir rg.exe/git.exe cannot shadow
# auto-approved commands.
env["NoDefaultCurrentDirectoryInExePath"] = "1"
+ if shell == "cmd_isolated":
+ env.update(_ISOLATED_CMD_GIT_ENV)
return env
@@ -9807,6 +9892,23 @@ def _windows_bash() -> "str | None":
return None
+def _windows_bash_git_cmd_dir() -> str:
+ """The trusted ``Git\\cmd`` dir of the install the resolved bash belongs to, or ""."""
+ bash = _windows_bash()
+ if not bash:
+ return ""
+ bin_dir = os.path.dirname(bash)
+ for root in (os.path.dirname(bin_dir), os.path.dirname(os.path.dirname(bin_dir))):
+ candidate = os.path.join(root, "cmd")
+ if (
+ root
+ and os.path.isfile(os.path.join(candidate, "git.exe"))
+ and _is_trusted_windows_program_dir(candidate)
+ ):
+ return os.path.realpath(candidate)
+ return ""
+
+
def _windows_bash_userland_dirs() -> list[str]:
"""Trusted dirs holding the resolved bash and the POSIX tools beside it.
@@ -9852,6 +9954,87 @@ def _get_shell_cmd(command: str) -> list[str]:
return ["bash", "-c", command]
+def _windows_system_cmd() -> str:
+ """System32 cmd.exe, resolved the same way MXC policy resolves it; never COMSPEC or PATH."""
+ from .mxc_policy import _system_cmd
+ return _system_cmd()
+
+
+def _terminal_profile(disable_sandbox: bool = False) -> str:
+ """Which shell the Terminal runs: "bash", "cmd_isolated" or "cmd_fallback".
+
+ Git Bash cannot start inside MXC (microsoft/mxc#1061), so when the MXC probe names exactly that
+ failure and cmd.exe qualifies instead, Auto runs the Terminal isolated on cmd rather than
+ unsandboxed on bash. Only the MSYS verdict triggers the cmd probe, so hosts without a working MXC
+ pay nothing extra. Full access and UNSLOTH_MXC_TERMINAL_CMD=0 keep the host shell.
+ """
+ if sys.platform != "win32":
+ return "bash"
+ bash = _windows_bash()
+ host_default = "bash" if bash else "cmd_fallback"
+ if disable_sandbox or os.environ.get("UNSLOTH_MXC_TERMINAL_CMD") == "0":
+ return host_default
+ try:
+ from . import mxc_policy, mxc_probe
+
+ if bash:
+ # Measured only on MXC's DACL tier; BaseContainer hosts keep bash until it is.
+ if not mxc_policy.dacl_fallback_enabled():
+ return "bash"
+ verdict = os_sandbox.capability_snapshot(
+ execution_kind = "terminal", selected_executable = bash
+ )
+ if verdict.available or verdict.reason != mxc_probe.MSYS_NAMESPACE_REASON:
+ return "bash"
+ cmd = os_sandbox.capability_snapshot(
+ execution_kind = "terminal", selected_executable = _windows_system_cmd()
+ )
+ return "cmd_isolated" if cmd.available else host_default
+ except Exception as exc: # noqa: BLE001 - a probe failure must never take the Terminal away
+ logger.warning(f"terminal profile check failed, keeping the host shell: {exc}")
+ return host_default
+
+
+# The last profile a request advertised, so an expired probe verdict is refreshed off the request path.
+_request_profile: list = [None, 0.0]
+_request_profile_lock = threading.Lock()
+_REQUEST_PROFILE_REFRESH_SECONDS = 240.0
+
+
+def _refresh_request_profile() -> str:
+ profile = _terminal_profile(False)
+ with _request_profile_lock:
+ _request_profile[:] = [profile, time.monotonic()]
+ return profile
+
+
+def _profile_for_request() -> str:
+ with _request_profile_lock:
+ profile, computed = _request_profile
+ stale = (
+ profile is not None and time.monotonic() - computed > _REQUEST_PROFILE_REFRESH_SECONDS
+ )
+ if stale:
+ _request_profile[1] = time.monotonic() # one refresh in flight at a time
+ if profile is None:
+ return _refresh_request_profile()
+ if stale:
+ threading.Thread(target = _refresh_request_profile, daemon = True).start()
+ return profile
+
+
+def apply_terminal_profile_for_request(tools: list[dict]) -> list[dict]:
+ """Sandboxed requests only: advertise the shell _bash_exec will pick for this request. Only the
+ first call can block on the MXC probe, so async callers run it in a worker thread; later calls
+ reuse the last profile and refresh it in the background. A list without the Terminal never probes."""
+ if not any(
+ isinstance(t, dict) and (t.get("function") or {}).get("name") == "terminal"
+ for t in tools or ()
+ ):
+ return tools
+ return apply_terminal_profile_description(tools, _profile_for_request())
+
+
def _shell_argv(command: str, workdir: str, confinement) -> "tuple[list[str], str | None]":
"""Keep a confined account's command text off argv: other accounts' tools can read
/proc/<pid>/cmdline and Landlock cannot deny per-pid reads."""
@@ -12467,6 +12650,43 @@ TERMINAL_TOOL_FULL_ACCESS = {
},
}
+# The isolated Windows Terminal (see _terminal_profile) is cmd.exe inside MXC whatever the host shell is, so it gets
+# its own schema, chosen per request; the module default keeps describing the host shell.
+_ISOLATED_CMD_SHELL_NOTE = (
+ " The shell is cmd, running isolated, not bash: send one command per call, chain with &&, use "
+ "double quotes only, and use relative paths. git, when installed, runs without hooks, a pager or "
+ "an editor, so pass -m to git commit."
+)
+
+TERMINAL_TOOL_CMD_ISOLATED = {
+ "type": "function",
+ "function": {
+ **TERMINAL_TOOL["function"],
+ "description": "Execute a terminal command and return stdout/stderr."
+ + _SANDBOX_PATHS_NOTE
+ + _ISOLATED_CMD_SHELL_NOTE,
+ },
+}
+
+
+def apply_terminal_profile_description(tools: list[dict], profile: str) -> list[dict]:
+ """Swap the terminal schema for the one matching ``profile``. Like
+ apply_full_access_tool_descriptions, the input list is never mutated and a list with nothing to
+ swap is returned as-is; only "cmd_isolated" changes anything."""
+ if not tools or profile != "cmd_isolated":
+ return tools
+ swapped = False
+ out: list[dict] = []
+ for tool in tools:
+ name = (tool.get("function") or {}).get("name") if isinstance(tool, dict) else None
+ if name == "terminal":
+ out.append(TERMINAL_TOOL_CMD_ISOLATED)
+ swapped = True
+ else:
+ out.append(tool)
+ return out if swapped else tools
+
+
# edit_file is registered below, once its schema exists.
_FULL_ACCESS_TOOL_BY_NAME = {
"python": PYTHON_TOOL_FULL_ACCESS,
@@ -21120,6 +21340,12 @@ def _python_exec(
pass
+_CMD_MULTILINE_REFUSED = (
+ "Execution error: the Terminal runs cmd, which runs only the first line of a multi-line "
+ "command. Send one line per call and chain dependent commands with &&."
+)
+
+
def _bash_exec(
command: str,
cancel_event = None,
@@ -21146,9 +21372,29 @@ def _bash_exec(
):
return _STUDIO_CREDENTIAL_BLOCKED
+ # Chosen once, so the blocklist, env and argv all agree on the shell that will run this call.
+ profile = _terminal_profile(disable_sandbox)
+ if profile == "cmd_isolated":
+ # Models often end a command with a newline; cmd /s /c cannot carry one.
+ command = command.strip()
+ if "\n" in command or "\r" in command:
+ return _CMD_MULTILINE_REFUSED
+
# Block dangerous commands (skipped when the sandbox is disabled)
if not disable_sandbox:
- blocked = _find_blocked_commands(command)
+ if profile == "cmd_isolated":
+ # The cmd lexer misses separators glued to a word (a&powershell), cmd drops ^ escapes and
+ # ' does not quote, so screen every reading; defence in depth, MXC is the boundary.
+ unescaped = command.replace("^", "")
+ blocked = set().union(
+ *(
+ _find_blocked_commands(text, posix = posix)
+ for text in (command, unescaped, _cmd_reading(command))
+ for posix in (False, True)
+ )
+ )
+ else:
+ blocked = _find_blocked_commands(command)
if blocked:
# Capped for the same reason the Python analyzer's error is: it lists what it found in the command it was
# handed.
@@ -21184,7 +21430,11 @@ def _bash_exec(
# Same pre-run snapshot as _python_exec. A command that writes a file used to produce "(no output)" and no
# other trace anywhere in the product.
_before = _snapshot_workdir_files(workdir)
- safe_env = _build_bypass_env(workdir) if disable_sandbox else _build_safe_env(workdir)
+ safe_env = (
+ _build_bypass_env(workdir)
+ if disable_sandbox
+ else _build_safe_env(workdir, shell = profile if profile == "cmd_isolated" else None)
+ )
popen_kwargs = dict(
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT,
@@ -21199,11 +21449,19 @@ def _bash_exec(
if sys.platform == "win32":
popen_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
- shell_argv, _scratch_name = _shell_argv(command, workdir, confinement)
+ if profile == "cmd_isolated":
+ shell_argv, _scratch_name = [_windows_system_cmd(), "/c", command], None
+ else:
+ shell_argv, _scratch_name = _shell_argv(command, workdir, confinement)
if _scratch_name:
with _scratch_lock:
_active_scratch.add(_scratch_name)
requested_mode = _requested_execution_mode(tool_execution_mode, disable_sandbox)
+ host_reach_approved = host_access_approved and _reaches_host_paths("terminal", command)
+ if profile == "cmd_isolated" and requested_mode == "auto" and not host_reach_approved:
+ # Written for the isolated cmd Terminal and screened only by its lexer: never replayed on the host if
+ # isolation drops out between the profile check and the launch.
+ requested_mode = "required"
base_preexec = (
None
if sys.platform == "win32"
@@ -21221,8 +21479,7 @@ def _bash_exec(
execution_kind = "terminal",
cancel_event = cancel_event,
),
- host_access_approved = host_access_approved
- and _reaches_host_paths("terminal", command),
+ host_access_approved = host_reach_approved,
)
proc = os_sandbox.spawn_prepared_launch(
prepared, **_apply_prepared_launch(prepared, popen_kwargs)
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 8253b0d9b4d..f6a6ed12180 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -5920,6 +5920,10 @@ async def _select_request_tools(
# how that server runs.
if payload.bypass_permissions:
tools = apply_full_access_tool_descriptions(tools)
+ elif sys.platform == "win32":
+ # The isolated Windows Terminal runs cmd, not the host's Git Bash; say so in the schema.
+ from core.inference.tools import apply_terminal_profile_for_request
+ tools = await asyncio.to_thread(apply_terminal_profile_for_request, tools)
if mcp_allowed:
tools = tools + await get_enabled_mcp_tools()
# getattr: callers hand in lighter payload objects than the request models, not all of
@@ -36221,6 +36225,9 @@ async def anthropic_count_tokens(
# Same schemas /messages renders under Full access, or the count prices a different prompt.
from core.inference.tools import apply_full_access_tool_descriptions
openai_tools = apply_full_access_tool_descriptions(openai_tools)
+ elif sys.platform == "win32":
+ from core.inference.tools import apply_terminal_profile_for_request
+ openai_tools = await asyncio.to_thread(apply_terminal_profile_for_request, openai_tools)
_count_nudge = _build_tool_action_nudge(
tools = openai_tools,
model_name = _llama_public_model_id(llama_backend, payload.model),
@@ -36979,6 +36986,9 @@ async def anthropic_messages(
_full_access = bool(getattr(payload, "bypass_permissions", False))
if _full_access:
openai_tools = apply_full_access_tool_descriptions(openai_tools)
+ elif sys.platform == "win32":
+ from core.inference.tools import apply_terminal_profile_for_request
+ openai_tools = await asyncio.to_thread(apply_terminal_profile_for_request, openai_tools)
server_tool_choice = openai_tool_choice
if isinstance(server_tool_choice, dict):
diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.py
index f7ff36d4934..3248b9bcce4 100644
--- a/studio/backend/tests/conftest.py
+++ b/studio/backend/tests/conftest.py
@@ -119,6 +119,13 @@ def _skills_home_root(tmp_path_factory):
_skills_home_counter = itertools.count()
[email protected](autouse = True)
+def _no_real_mxc_drive_aliases(monkeypatch):
+ # A Windows test host would otherwise map real drive letters; test_mxc_drive_alias.py and the native
+ # MXC tests opt back in.
+ monkeypatch.setenv("UNSLOTH_MXC_DRIVE_ALIAS", "0")
+
+
@pytest.fixture(autouse = True)
def _isolate_agent_skills(_skills_home_root, monkeypatch):
# A developer's own ~/.agents or ~/.claude skills must not leak into tool-selection tests.
diff --git a/studio/backend/tests/test_mxc_cmd_command_line.py b/studio/backend/tests/test_mxc_cmd_command_line.py
new file mode 100644
index 00000000000..0ea29363935
--- /dev/null
+++ b/studio/backend/tests/test_mxc_cmd_command_line.py
@@ -0,0 +1,278 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+import subprocess
+from types import SimpleNamespace
+
+import pytest
+
+from core.inference import mxc_policy, mxc_probe, mxc_runtime, os_sandbox
+
+
[email protected](autouse = True)
+def _dacl_journal_outside_grants(monkeypatch, tmp_path):
+ outside = Path(os.path.abspath(os.sep)) / "unsloth-test-dacl-journal-never-created"
+ monkeypatch.setattr(mxc_runtime, "dacl_state_path", lambda: outside)
+ monkeypatch.setattr(mxc_runtime, "dacl_state_dir", lambda: tmp_path)
+
+
+def system_cmd(monkeypatch, tmp_path):
+ cmd = tmp_path / "Windows" / "System32" / "cmd.exe"
+ cmd.parent.mkdir(parents = True)
+ cmd.touch()
+ monkeypatch.setattr(mxc_policy.sys, "platform", "win32")
+ monkeypatch.setattr(mxc_policy, "_system_cmd", lambda: str(cmd))
+ return str(cmd)
+
+
+def _workdir(tmp_path):
+ workdir = tmp_path / "session"
+ workdir.mkdir()
+ return workdir
+
+
+def _cmd_plan(
+ workdir,
+ payload,
+ argv0 = "cmd",
+):
+ return os_sandbox.ToolLaunchPlan(
+ argv = (argv0, "/c", payload),
+ workdir = str(workdir),
+ env = {"PATH": ""},
+ execution_kind = "terminal",
+ )
+
+
+ "argv, expected",
+ [
+ (("cmd", "/c", "dir"), True),
+ (("CMD.EXE", "/C", "dir"), True),
+ (("C:\\Windows\\System32\\cmd.exe", "/d", "/s", "/c", "dir"), True),
+ (("cmd", "/s", "/d", "/c", "dir"), True),
+ (("cmd", "//c", "dir"), False),
+ (("cmd", "//d", "/c", "dir"), False),
+ (("cmd", "/d", "/d", "/c", "dir"), False),
+ (("cmd", "/k", "dir"), False),
+ (("cmd", "/c", "dir", "extra"), False),
+ (("cmd", "/c"), False),
+ (("bash.exe", "-c", "ls"), False),
+ (("cmdx.exe", "/c", "dir"), False),
+ ],
+)
+def test_is_cmd_argv(argv, expected):
+ assert mxc_policy.is_cmd_argv(argv) is expected
+
+
+def test_cmd_command_line_keeps_embedded_quotes():
+ payload = '"C:\\Program Files\\Git\\cmd\\git.exe" commit -m "quoted msg" && type "a b.txt"'
+ assert mxc_policy.cmd_command_line("C:\\Windows\\System32\\cmd.exe", payload) == (
+ '"C:\\Windows\\System32\\cmd.exe" /d /s /c '
+ '""C:\\Program Files\\Git\\cmd\\git.exe" commit -m "quoted msg" && type "a b.txt""'
+ )
+
+
+ "payload, message",
+ [
+ ("echo a\x00b", "NUL"),
+ ("echo a\necho b", "first line"),
+ ("echo a\recho b", "first line"),
+ ("x" * mxc_policy.MAX_COMMAND_LINE, "command-line limit"),
+ ],
+ ids = ["nul", "newline", "carriage_return", "too_long"],
+)
+def test_cmd_command_line_refuses_what_cmd_would_not_run_as_written(payload, message):
+ with pytest.raises(mxc_policy.MxcPolicyError, match = message):
+ mxc_policy.cmd_command_line("C:\\Windows\\System32\\cmd.exe", payload)
+
+
+def test_cmd_terminal_runs_system32_cmd_with_its_own_quoting(monkeypatch, tmp_path, system_cmd):
+ elsewhere = tmp_path / "elsewhere" / "cmd.exe"
+ elsewhere.parent.mkdir()
+ elsewhere.touch()
+ monkeypatch.setenv("COMSPEC", str(elsewhere))
+ payload = 'type "outside secret.txt" & echo END'
+ for index, argv0 in enumerate(("cmd", str(elsewhere))):
+ workdir = tmp_path / f"session-{index}"
+ workdir.mkdir()
+ request = mxc_policy.build_launch_request(_cmd_plan(workdir, payload, argv0))
+ assert request["runtimePath"] == os.path.realpath(system_cmd)
+ assert request["config"]["process"]["commandLine"] == f'"{system_cmd}" /d /s /c "{payload}"'
+
+
+def test_non_cmd_terminal_keeps_argument_quoting(monkeypatch, tmp_path):
+ shell = tmp_path / "Program Files" / "Git" / "bin" / "bash.exe"
+ shell.parent.mkdir(parents = True)
+ shell.touch()
+ monkeypatch.setattr(mxc_policy.sys, "platform", "win32")
+ plan = os_sandbox.ToolLaunchPlan(
+ argv = (str(shell), "-c", 'echo "a b" > "c d.txt"'),
+ workdir = str(_workdir(tmp_path)),
+ env = {"PATH": str(shell.parent)},
+ execution_kind = "terminal",
+ )
+ request = mxc_policy.build_launch_request(plan)
+ assert request["config"]["process"]["commandLine"] == subprocess.list2cmdline(list(plan.argv))
+
+
+def _alias_identity(
+ monkeypatch,
+ workdir,
+ alias = "Z:\\",
+):
+ real = mxc_policy._object_identity
+ target = {"path": str(workdir)}
+
+ def identity(path, *, directory):
+ if path == alias:
+ return real(target["path"], directory = True)
+ return real(path, directory = directory)
+
+ monkeypatch.setattr(mxc_policy, "_object_identity", identity)
+ return target
+
+
+def test_workdir_alias_is_only_the_workload_cwd(monkeypatch, tmp_path, system_cmd):
+ workdir = _workdir(tmp_path)
+ _alias_identity(monkeypatch, workdir)
+ request = mxc_policy.build_launch_request(_cmd_plan(workdir, "git status"), cwd_alias = "Z:\\")
+ canonical = os.path.realpath(workdir)
+ assert request["config"]["process"]["cwd"] == "Z:\\"
+ assert request["config"]["filesystem"]["readwritePaths"] == [canonical]
+ assert "Z:\\" not in request["config"]["filesystem"]["readonlyPaths"]
+ assert request["cwd"] == canonical
+ assert request["cwdAlias"] == "Z:\\"
+ assert request["policyHash"] == mxc_policy.compute_policy_hash(request["config"])
+
+
+def test_no_alias_keeps_the_canonical_cwd(tmp_path, system_cmd):
+ request = mxc_policy.build_launch_request(_cmd_plan(_workdir(tmp_path), "git status"))
+ assert request["config"]["process"]["cwd"] == request["cwd"]
+ assert request["cwdAlias"] is None
+
+
[email protected]("alias", ["Z:", "Z:\\sub", "ZZ:\\", "\\\\?\\Z:\\", "Z:/", 5])
+def test_workdir_alias_must_be_a_drive_root(monkeypatch, tmp_path, system_cmd, alias):
+ workdir = _workdir(tmp_path)
+ with pytest.raises(mxc_policy.MxcPolicyError, match = "drive root"):
+ mxc_policy.build_launch_request(_cmd_plan(workdir, "dir"), cwd_alias = alias)
+
+
+def test_workdir_alias_naming_another_folder_is_refused(monkeypatch, tmp_path, system_cmd):
+ workdir = _workdir(tmp_path)
+ target = _alias_identity(monkeypatch, workdir)
+ other = tmp_path / "other-session"
+ other.mkdir()
+ target["path"] = str(other)
+ with pytest.raises(mxc_policy.MxcPolicyError, match = "does not name the session workdir"):
+ mxc_policy.build_launch_request(_cmd_plan(workdir, "dir"), cwd_alias = "Z:\\")
+
+
+def test_alias_moved_before_dispatch_is_refused(monkeypatch, tmp_path, system_cmd):
+ workdir = _workdir(tmp_path)
+ target = _alias_identity(monkeypatch, workdir)
+ request = mxc_policy.build_launch_request(_cmd_plan(workdir, "dir"), cwd_alias = "Z:\\")
+ mxc_policy.verify_launch_identities(request)
+ other = tmp_path / "other-session"
+ other.mkdir()
+ target["path"] = str(other)
+ with pytest.raises(mxc_policy.MxcPolicyError, match = "does not name the session workdir"):
+ mxc_policy.verify_launch_identities(request)
+
+
+def test_cmd_probe_uses_the_production_shape(tmp_path):
+ argv = mxc_probe._terminal_probe(
+ str(tmp_path / "cmd.exe"), tmp_path, tmp_path / "canary.txt", tmp_path / "outside.txt"
+ )
+ assert mxc_policy.is_cmd_argv(argv)
+ assert argv[1:4] == ("/d", "/s", "/c")
+ assert 'echo ok>"inside quoted.txt"' in argv[-1]
+ mxc_policy.cmd_command_line("C:\\Windows\\System32\\cmd.exe", argv[-1])
+
+
+def _cmd_probe(
+ monkeypatch,
+ tmp_path,
+ *,
+ quoted_file,
+ alias_root = None,
+ started_in = None,
+):
+ seen = {}
+
+ class Finished:
+ returncode = 0
+
+ def poll(self):
+ return 0
+
+ def communicate(self, timeout = None):
+ workdir = Path(seen["plan"].workdir)
+ (workdir / "inside.txt").write_text("ok", encoding = "utf-8")
+ if quoted_file:
+ (workdir / "inside quoted.txt").write_text("ok", encoding = "utf-8")
+ cwd = started_in if started_in is not None else (seen["cwd_alias"] or str(workdir))
+ return f"{cwd}\nUNSLOTH_MXC_TERMINAL_PROBE_OK\n", None
+
+ def build(plan, cwd_alias = None):
+ seen["plan"], seen["cwd_alias"] = plan, cwd_alias
+ return {}
+
+ class Lease:
+ root = alias_root
+ released = False
+
+ def release(self):
+ Lease.released = True
+
+ monkeypatch.setattr(mxc_probe.mxc_policy, "_safe_canonical_path", lambda path, directory: path)
+ monkeypatch.setattr(
+ mxc_probe.mxc_drive_alias, "acquire", lambda _w: Lease() if alias_root else None
+ )
+ seen["lease"] = Lease
+
+ monkeypatch.setattr(mxc_probe.sys, "platform", "win32")
+ monkeypatch.setattr(
+ mxc_probe.sys, "getwindowsversion", lambda: SimpleNamespace(build = 26100), raising = False
+ )
+ monkeypatch.setattr(mxc_probe.mxc_runtime, "wxc_path", lambda: tmp_path / "wxc-exec.exe")
+ monkeypatch.setattr(mxc_probe.mxc_policy, "build_launch_request", build)
+ monkeypatch.setattr(mxc_probe.mxc_adapter, "spawn", lambda *_a, **_k: Finished())
+ monkeypatch.setattr(mxc_probe.mxc_adapter, "abort", lambda _proc: None)
+ monkeypatch.setattr(mxc_probe.mxc_adapter, "release_runtime", lambda _proc: None)
+ monkeypatch.setattr(
+ mxc_probe.mxc_adapter,
+ "completion_result",
+ lambda _proc: {"exitCode": 0, "cleanup": "complete"},
+ )
+ monkeypatch.setattr(mxc_probe.subprocess, "CREATE_NO_WINDOW", 0, raising = False)
+ result = mxc_probe._probe(str(tmp_path / "cmd.exe"), "terminal")
+ return result if alias_root is None else (*result, seen)
+
+
+def test_cmd_probe_needs_the_quoted_positive_control(monkeypatch, tmp_path):
+ mxc_probe.invalidate_cache()
+ assert _cmd_probe(monkeypatch, tmp_path, quoted_file = True)[0] is True
+ available, reason = _cmd_probe(monkeypatch, tmp_path, quoted_file = False)
+ assert available is False
+ assert "controls failed" in reason
+
+
+def test_cmd_probe_runs_from_the_drive_alias_like_production(monkeypatch, tmp_path):
+ available, _reason, seen = _cmd_probe(
+ monkeypatch, tmp_path, quoted_file = True, alias_root = "Z:\\"
+ )
+ assert available is True
+ assert seen["cwd_alias"] == "Z:\\"
+ assert seen["lease"].released
+ available, reason, seen = _cmd_probe(
+ monkeypatch, tmp_path, quoted_file = True, alias_root = "Z:\\", started_in = str(tmp_path)
+ )
+ assert available is False and "controls failed" in reason
+ assert seen["lease"].released
diff --git a/studio/backend/tests/test_mxc_drive_alias.py b/studio/backend/tests/test_mxc_drive_alias.py
new file mode 100644
index 00000000000..35ded27b7e5
--- /dev/null
+++ b/studio/backend/tests/test_mxc_drive_alias.py
@@ -0,0 +1,420 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+import pytest
+
+from core.inference import mxc_adapter, mxc_drive_alias, mxc_runtime, os_sandbox
+
+
+class _Host:
+ """A fake DOS-device table: letter -> stack of targets, the first one in effect."""
+
+ def __init__(self, drives = ""):
+ self.table: dict[str, list[str]] = {}
+ self.drives = drives
+ self.alive: dict[int, float] = {4242: 1.0}
+ self.pid = 4242
+ self.refuse_define: set[str] = set()
+ self.redirect: dict[str, str] = {}
+ self.removed: list[tuple[str, str]] = []
+ self.network: set[str] = set()
+
+ def logical_drives(self):
+ return sum(1 << (ord(d) - ord("A")) for d in self.drives)
+
+ def definitions(self, letter):
+ return list(self.table.get(letter) or [])
+
+ def query(self, letter):
+ stack = self.table.get(letter)
+ return stack[0] if stack else None
+
+ def network_letters(self):
+ return set(self.network)
+
+ def define(self, letter, target):
+ if letter in self.refuse_define:
+ return False
+ self.table.setdefault(letter, []).insert(0, "\\??\\" + self.redirect.get(letter, target))
+ return True
+
+ def remove(self, letter, target):
+ stack = self.table.get(letter) or []
+ if "\\??\\" + target not in stack:
+ return False
+ stack.remove("\\??\\" + target)
+ self.removed.append((letter, target))
+ if not stack:
+ self.table.pop(letter, None)
+ return True
+
+ def process_alive(self, pid, create_time):
+ return self.alive.get(pid) == create_time
+
+ def own_identity(self):
+ return self.pid, self.alive[self.pid]
+
+
+def host(monkeypatch, tmp_path):
+ fake = _Host()
+ monkeypatch.setattr(mxc_drive_alias, "_on_windows", lambda: True)
+ monkeypatch.setattr(mxc_drive_alias, "_host", fake)
+ monkeypatch.setattr(mxc_drive_alias, "_active", {})
+ monkeypatch.setattr(mxc_drive_alias, "_shadowed", {})
+ monkeypatch.setattr(
+ mxc_drive_alias, "record_path", lambda: tmp_path / "state" / "drive-aliases.json"
+ )
+ monkeypatch.delenv(mxc_drive_alias.DRIVE_ALIAS_ENV, raising = False)
+ return fake
+
+
+def _workdir(tmp_path, name = "session"):
+ path = tmp_path / name
+ path.mkdir(exist_ok = True)
+ return str(path)
+
+
+def _record():
+ return json.loads(mxc_drive_alias.record_path().read_text(encoding = "utf-8"))["aliases"]
+
+
+def test_maps_the_highest_free_letter_and_records_it(host, tmp_path):
+ host.drives = "CDZ"
+ host.table["Y"] = ["\\??\\C:\\someone-else"]
+ workdir = _workdir(tmp_path)
+ lease = mxc_drive_alias.acquire(workdir)
+ assert lease.letter == "X" and lease.root == "X:\\" and lease.target == workdir
+ assert host.query("X") == "\\??\\" + workdir
+ assert _record()["X"] == {"target": workdir, "pid": 4242, "pid_create_time": 1.0}
+ lease.release()
+ assert host.query("X") is None and host.query("Y") == "\\??\\C:\\someone-else"
+ assert _record() == {}
+
+
+def test_a_definition_that_does_not_verify_is_removed_and_skipped(host, tmp_path):
+ host.redirect["Z"] = "C:\\elsewhere"
+ host.refuse_define.add("Y")
+ workdir = _workdir(tmp_path)
+ lease = mxc_drive_alias.acquire(workdir)
+ assert lease.letter == "X"
+ # Removal is exact-match on our own target, so the misdirected definition stays for its owner.
+ assert host.query("Z") == "\\??\\C:\\elsewhere"
+ assert ("Z", "C:\\elsewhere") not in host.removed
+
+
+def test_concurrent_launches_of_one_workdir_share_a_letter(host, tmp_path):
+ workdir = _workdir(tmp_path)
+ first = mxc_drive_alias.acquire(workdir)
+ second = mxc_drive_alias.acquire(workdir)
+ other = mxc_drive_alias.acquire(_workdir(tmp_path, "other"))
+ assert first.letter == second.letter == "Z" and other.letter == "Y"
+ first.release()
+ first.release() # idempotent: a second release must not drop the other lease
+ assert host.query("Z") == "\\??\\" + workdir
+ second.release()
+ assert host.query("Z") is None
+ other.release()
+ assert host.table == {}
+
+
+def test_a_letter_redefined_by_someone_else_is_left_alone(host, tmp_path):
+ workdir = _workdir(tmp_path)
+ lease = mxc_drive_alias.acquire(workdir)
+ host.table["Z"].insert(0, "\\??\\C:\\other-owner")
+ again = mxc_drive_alias.acquire(workdir)
+ assert again.letter == "Y"
+ lease.release()
+ # The other definition stays in effect; ours under it is removed, so it cannot resurface later.
+ assert host.definitions("Z") == ["\\??\\C:\\other-owner"]
+ again.release()
+ assert host.query("Y") is None
+
+
+def test_a_dead_owners_mapping_is_reclaimed_only_while_it_still_matches(host, tmp_path):
+ stale, moved = _workdir(tmp_path, "stale"), _workdir(tmp_path, "moved")
+ host.table["Z"] = ["\\??\\" + stale]
+ host.table["Y"] = ["\\??\\C:\\now-someone-else"]
+ path = mxc_drive_alias.record_path()
+ path.parent.mkdir(parents = True)
+ path.write_text(
+ json.dumps(
+ {
+ "aliases": {
+ "Z": {"target": stale, "pid": 99, "pid_create_time": 5.0},
+ "Y": {"target": moved, "pid": 99, "pid_create_time": 5.0},
+ }
+ }
+ ),
+ encoding = "utf-8",
+ )
+ lease = mxc_drive_alias.acquire(_workdir(tmp_path))
+ assert ("Z", stale) in host.removed
+ assert host.query("Y") == "\\??\\C:\\now-someone-else"
+ assert lease.letter == "Z"
+ assert set(_record()) == {"Z"}
+
+
+def test_a_dead_owners_mapping_under_another_definition_is_still_removed(host, tmp_path):
+ stale = _workdir(tmp_path, "stale")
+ host.table["Z"] = ["\\??\\C:\\other-owner", "\\??\\" + stale]
+ path = mxc_drive_alias.record_path()
+ path.parent.mkdir(parents = True)
+ path.write_text(
+ json.dumps({"aliases": {"Z": {"target": stale, "pid": 99, "pid_create_time": 5.0}}}),
+ encoding = "utf-8",
+ )
+ lease = mxc_drive_alias.acquire(_workdir(tmp_path))
+ assert ("Z", stale) in host.removed
+ assert host.definitions("Z") == ["\\??\\C:\\other-owner"]
+ assert lease.letter == "Y"
+
+
+def test_a_disconnected_network_drive_letter_is_skipped(host, tmp_path):
+ host.network = {"Z"}
+ assert mxc_drive_alias.acquire(_workdir(tmp_path)).letter == "Y"
+
+
+def test_a_live_owners_mapping_is_never_reclaimed(host, tmp_path):
+ theirs = _workdir(tmp_path, "theirs")
+ host.alive[77] = 3.0
+ host.table["Z"] = ["\\??\\" + theirs]
+ path = mxc_drive_alias.record_path()
+ path.parent.mkdir(parents = True)
+ path.write_text(
+ json.dumps({"aliases": {"Z": {"target": theirs, "pid": 77, "pid_create_time": 3.0}}}),
+ encoding = "utf-8",
+ )
+ lease = mxc_drive_alias.acquire(_workdir(tmp_path))
+ assert lease.letter == "Y" and host.query("Z") == "\\??\\" + theirs
+ assert host.removed == []
+
+
+def test_a_locked_record_maps_nothing(host, tmp_path, monkeypatch):
+ from contextlib import contextmanager
+
+ @contextmanager
+ def locked():
+ yield None
+
+ monkeypatch.setattr(mxc_drive_alias, "_transaction", locked)
+ assert mxc_drive_alias.acquire(_workdir(tmp_path)) is None
+ assert host.table == {}
+
+
+def test_an_unwritable_record_undoes_the_mapping(host, tmp_path, monkeypatch):
+ monkeypatch.setattr(mxc_drive_alias, "_save_record", lambda _aliases: False)
+ assert mxc_drive_alias.acquire(_workdir(tmp_path)) is None
+ assert host.table == {}
+
+
+def test_a_record_temp_file_that_cannot_be_removed_still_undoes_the_mapping(
+ host, tmp_path, monkeypatch
+):
+ # Security software holding the new file: the replace and the cleanup both fail.
+ real_replace, real_unlink = os.replace, Path.unlink
+
+ def held(path, *args, **kwargs):
+ if str(path).endswith(".tmp"):
+ raise PermissionError("the file is in use")
+ return real_unlink(path, *args, **kwargs)
+
+ monkeypatch.setattr(
+ os,
+ "replace",
+ lambda src, dst: held(src) if str(src).endswith(".tmp") else real_replace(src, dst),
+ )
+ monkeypatch.setattr(Path, "unlink", held)
+ assert mxc_drive_alias.acquire(_workdir(tmp_path)) is None
+ assert host.table == {}
+
+
+def test_no_free_letter_maps_nothing(host, tmp_path):
+ host.drives = mxc_drive_alias.LETTERS
+ assert mxc_drive_alias.acquire(_workdir(tmp_path)) is None
+
+
+def test_off_windows_and_opted_out_map_nothing(host, tmp_path, monkeypatch):
+ monkeypatch.setenv(mxc_drive_alias.DRIVE_ALIAS_ENV, "0")
+ assert mxc_drive_alias.acquire(_workdir(tmp_path)) is None
+ monkeypatch.delenv(mxc_drive_alias.DRIVE_ALIAS_ENV)
+ monkeypatch.setattr(mxc_drive_alias, "_on_windows", lambda: False)
+ assert mxc_drive_alias.acquire(_workdir(tmp_path)) is None
+ assert host.table == {}
+
+
+def test_release_runtime_drops_the_alias():
+ class _Lease:
+ released = 0
+
+ def release(self):
+ self.released += 1
+
+ class _Proc:
+ pass
+
+ proc, lease = _Proc(), _Lease()
+ proc._mxc_drive_alias = lease
+ mxc_adapter.release_runtime(proc)
+ mxc_adapter.release_runtime(proc)
+ assert lease.released == 1
+
+
+# prepare() wiring: only a cmd Terminal launch gets an alias, and it is released on every path.
+
+
[email protected](autouse = True)
+def _dacl_journal_outside_grants(monkeypatch, tmp_path):
+ outside = Path(os.path.abspath(os.sep)) / "unsloth-test-dacl-journal-never-created"
+ monkeypatch.setattr(mxc_runtime, "dacl_state_path", lambda: outside)
+ monkeypatch.setattr(mxc_runtime, "dacl_state_dir", lambda: tmp_path)
+
+
+class _FakeLease:
+ def __init__(self):
+ self.root = "Z:\\"
+ self.released = 0
+
+ def release(self):
+ self.released += 1
+
+
+def _terminal_plan(tmp_path, argv = ("cmd", "/c", "git status")):
+ return os_sandbox.ToolLaunchPlan(
+ argv = argv,
+ workdir = str(tmp_path),
+ env = {"PATH": "trusted"},
+ requested_mode = "auto",
+ timeout_seconds = 10,
+ execution_kind = "terminal",
+ )
+
+
+def _capability(sandbox_windows_mxc, identity, plan):
+ return os_sandbox.SandboxCapability(
+ backend = "mxc-processcontainer",
+ available = True,
+ reason = "qualified",
+ environment = "win32",
+ profile_id = mxc_runtime.PROFILE_ID,
+ environment_fingerprint = sandbox_windows_mxc._capability_fingerprint(
+ identity, "terminal", plan.argv[0]
+ ),
+ )
+
+
+def backend(monkeypatch, tmp_path):
+ from core.inference import sandbox_windows_mxc
+
+ calls, leases = [], []
+
+ def build(plan, *, cwd_alias = None):
+ calls.append(cwd_alias)
+ return {"policyHash": "sha256:controlled"}
+
+ def acquire(workdir):
+ lease = _FakeLease()
+ leases.append((workdir, lease))
+ return lease
+
+ monkeypatch.setattr(sandbox_windows_mxc.mxc_policy, "build_launch_request", build)
+ monkeypatch.setattr(
+ sandbox_windows_mxc.mxc_policy, "_safe_canonical_path", lambda path, directory: path
+ )
+ monkeypatch.setattr(sandbox_windows_mxc.mxc_drive_alias, "acquire", acquire)
+ monkeypatch.setattr(
+ sandbox_windows_mxc.mxc_runtime, "installation_identity", lambda: "qualified-wxc"
+ )
+ return sandbox_windows_mxc, calls, leases
+
+
+def test_a_cmd_terminal_launch_runs_from_the_alias_and_releases_it(backend, tmp_path, monkeypatch):
+ sandbox_windows_mxc, calls, leases = backend
+
+ class _Proc:
+ pass
+
+ monkeypatch.setattr(sandbox_windows_mxc.mxc_adapter, "spawn", lambda *_a, **_k: _Proc())
+ plan = _terminal_plan(tmp_path)
+ prepared = sandbox_windows_mxc.prepare(
+ plan, _capability(sandbox_windows_mxc, "qualified-wxc", plan)
+ )
+ assert calls == ["Z:\\"] and leases[0][0] == str(tmp_path)
+ assert sandbox_windows_mxc.CMD_PROFILE_LIMITATION in prepared.execution_record.limitations
+ proc = os_sandbox.spawn_prepared_launch(prepared)
+ assert proc._mxc_drive_alias is leases[0][1]
+ prepared.cleanup()
+ assert leases[0][1].released >= 1 and proc._mxc_drive_alias is None
+
+
+def test_python_and_non_cmd_terminal_launches_get_no_alias(backend, tmp_path):
+ sandbox_windows_mxc, calls, leases = backend
+ for plan in (
+ _terminal_plan(tmp_path, argv = ("C:\\Program Files\\Git\\bin\\bash.exe", "-c", "ls")),
+ os_sandbox.ToolLaunchPlan(
+ argv = ("python.exe", "-c", "1"),
+ workdir = str(tmp_path),
+ env = {},
+ requested_mode = "auto",
+ timeout_seconds = 10,
+ execution_kind = "python",
+ ),
+ ):
+ prepared = sandbox_windows_mxc.prepare(
+ plan, _capability(sandbox_windows_mxc, "qualified-wxc", plan)
+ )
+ assert mxc_drive_alias.LIMITATION_UNAVAILABLE not in prepared.execution_record.limitations
+ assert calls == [None, None] and leases == []
+
+
+def test_a_cmd_launch_without_a_letter_is_named_on_the_record(backend, tmp_path, monkeypatch):
+ sandbox_windows_mxc, calls, _leases = backend
+ monkeypatch.setattr(sandbox_windows_mxc.mxc_drive_alias, "acquire", lambda _workdir: None)
+ plan = _terminal_plan(tmp_path)
+ prepared = sandbox_windows_mxc.prepare(
+ plan, _capability(sandbox_windows_mxc, "qualified-wxc", plan)
+ )
+ assert calls == [None]
+ assert mxc_drive_alias.LIMITATION_UNAVAILABLE in prepared.execution_record.limitations
+
+
+def test_the_alias_is_released_when_policy_or_spawn_fails(backend, tmp_path, monkeypatch):
+ sandbox_windows_mxc, _calls, leases = backend
+ plan = _terminal_plan(tmp_path)
+ capability = _capability(sandbox_windows_mxc, "qualified-wxc", plan)
+
+ def refuse(plan, *, cwd_alias = None):
+ raise RuntimeError("controlled policy refusal")
+
+ monkeypatch.setattr(sandbox_windows_mxc.mxc_policy, "build_launch_request", refuse)
+ with pytest.raises(os_sandbox.SandboxBuildError):
+ sandbox_windows_mxc.prepare(plan, capability)
+ assert leases[-1][1].released == 1
+
+ monkeypatch.setattr(
+ sandbox_windows_mxc.mxc_policy,
+ "build_launch_request",
+ lambda plan, *, cwd_alias = None: {"policyHash": "sha256:controlled"},
+ )
+
+ def fail(*_args, **_kwargs):
+ raise sandbox_windows_mxc.mxc_adapter.MxcAdapterError("controlled refusal", stage = "policy")
+
+ monkeypatch.setattr(sandbox_windows_mxc.mxc_adapter, "spawn", fail)
+ prepared = sandbox_windows_mxc.prepare(plan, capability)
+ with pytest.raises(os_sandbox.SandboxBuildError):
+ os_sandbox.spawn_prepared_launch(prepared)
+ assert leases[-1][1].released == 1
+
+
+def test_a_mapping_that_cannot_be_removed_keeps_its_record(host, tmp_path, monkeypatch):
+ lease = mxc_drive_alias.acquire(_workdir(tmp_path))
+ monkeypatch.setattr(host, "remove", lambda _letter, _target: False)
+ lease.release()
+ assert set(_record()) == {"Z"}
diff --git a/studio/backend/tests/test_mxc_native_windows.py b/studio/backend/tests/test_mxc_native_windows.py
index 9574a17a482..144f079992a 100644
--- a/studio/backend/tests/test_mxc_native_windows.py
+++ b/studio/backend/tests/test_mxc_native_windows.py
@@ -25,6 +25,12 @@ from core.inference import (
)
[email protected](autouse = True)
+def _real_drive_aliases(monkeypatch):
+ # The native cmd Terminal runs from a real drive alias of its workdir, as in production.
+ monkeypatch.delenv("UNSLOTH_MXC_DRIVE_ALIAS", raising = False)
+
+
@pytest.fixture(autouse = True)
def _stage_installed_native_runtime():
"""Copy an explicitly installed runtime into pytest's isolated Studio home."""
diff --git a/studio/backend/tests/test_windows_cmd_terminal_profile.py b/studio/backend/tests/test_windows_cmd_terminal_profile.py
new file mode 100644
index 00000000000..1b8ceeda9f8
--- /dev/null
+++ b/studio/backend/tests/test_windows_cmd_terminal_profile.py
@@ -0,0 +1,375 @@
+# 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 isolated Windows Terminal: cmd.exe inside MXC when Git Bash cannot start there.
+
+Faked platform throughout, since studio-backend-ci is Linux-only; the native tests cover a real host.
+"""
+
+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 mxc_policy, mxc_probe, os_sandbox, tools
+
+BASH = r"C:\Program Files\Git\bin\bash.exe"
+
+
+def _cap(available, reason = ""):
+ return os_sandbox.SandboxCapability(backend = "mxc", available = available, reason = reason)
+
+
+def windows(monkeypatch):
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setenv("SystemRoot", r"C:\Windows")
+ monkeypatch.delenv("UNSLOTH_MXC_TERMINAL_CMD", raising = False)
+ monkeypatch.setattr(tools, "_request_profile", [None, 0.0])
+ calls = []
+
+ def host(
+ bash = BASH,
+ bash_cap = None,
+ cmd_cap = None,
+ dacl = True,
+ ):
+ monkeypatch.setattr(tools, "_windows_bash", lambda: bash)
+ monkeypatch.setattr(mxc_policy, "dacl_fallback_enabled", lambda: dacl)
+
+ def snapshot(
+ *,
+ execution_kind = None,
+ selected_executable = None,
+ **_kw,
+ ):
+ calls.append(selected_executable)
+ if selected_executable == BASH:
+ return bash_cap
+ return cmd_cap
+
+ monkeypatch.setattr(os_sandbox, "capability_snapshot", snapshot)
+ return calls
+
+ return host
+
+
+MSYS = mxc_probe.MSYS_NAMESPACE_REASON
+
+
+ "bash, bash_cap, cmd_cap, expected",
+ [
+ (BASH, _cap(True), _cap(True), "bash"),
+ (BASH, _cap(False, MSYS), _cap(True), "cmd_isolated"),
+ (BASH, _cap(False, MSYS), _cap(False, "no"), "bash"),
+ (BASH, _cap(False, "the live MXC probe did not complete cleanly"), _cap(True), "bash"),
+ (None, None, _cap(True), "cmd_isolated"),
+ (None, None, _cap(False, "no"), "cmd_fallback"),
+ ],
+)
+def test_profile_matrix(windows, bash, bash_cap, cmd_cap, expected):
+ windows(bash = bash, bash_cap = bash_cap, cmd_cap = cmd_cap)
+ assert tools._terminal_profile() == expected
+
+
+def test_cmd_is_only_probed_after_the_msys_verdict(windows):
+ calls = windows(
+ bash_cap = _cap(False, "the live MXC probe did not complete cleanly"), cmd_cap = _cap(True)
+ )
+ tools._terminal_profile()
+ assert calls == [BASH]
+
+
+def test_full_access_and_opt_out_keep_the_host_shell(windows, monkeypatch):
+ calls = windows(bash_cap = _cap(False, MSYS), cmd_cap = _cap(True))
+ assert tools._terminal_profile(disable_sandbox = True) == "bash"
+ monkeypatch.setenv("UNSLOTH_MXC_TERMINAL_CMD", "0")
+ assert tools._terminal_profile() == "bash"
+ assert calls == []
+
+
+def test_a_probe_error_keeps_the_host_shell(windows, monkeypatch):
+ windows()
+
+ def boom(**_kw):
+ raise RuntimeError("probe exploded")
+
+ monkeypatch.setattr(os_sandbox, "capability_snapshot", boom)
+ assert tools._terminal_profile() == "bash"
+
+
+def test_posix_is_always_bash(monkeypatch):
+ monkeypatch.setattr(sys, "platform", "linux")
+ assert tools._terminal_profile() == "bash"
+
+
+def _userland(monkeypatch, tmp_path):
+ bin_dir = tmp_path / "Git" / "usr" / "bin"
+ bin_dir.mkdir(parents = True)
+ monkeypatch.setattr(tools, "_windows_bash_userland_dirs", lambda: [str(bin_dir)])
+ monkeypatch.setattr(
+ tools, "_resolve_trusted_windows_git", lambda: (str(tmp_path / "Git" / "cmd"), ".EXE")
+ )
+ return str(bin_dir)
+
+
+def test_cmd_env_drops_bash_userland_and_disables_git_helpers(windows, monkeypatch, tmp_path):
+ windows()
+ userland = _userland(monkeypatch, tmp_path)
+ env = tools._build_safe_env(str(tmp_path), shell = "cmd_isolated")
+ path = env["PATH"].split(";") if ";" in env["PATH"] else env["PATH"].split(":")
+ assert userland not in path
+ assert str(tmp_path / "Git" / "cmd") in env["PATH"]
+ assert env["GIT_CONFIG_COUNT"] == "1"
+ assert (env["GIT_CONFIG_KEY_0"], env["GIT_CONFIG_VALUE_0"]) == ("core.hooksPath", "NUL")
+ assert env["GIT_PAGER"] == ""
+ assert env["GIT_EDITOR"] == env["GIT_SEQUENCE_EDITOR"] == "unsloth-no-editor"
+ assert env["GIT_TERMINAL_PROMPT"] == "0"
+
+
+def test_cmd_env_finds_git_installed_for_git_bash_only(windows, monkeypatch, tmp_path):
+ windows()
+ _userland(monkeypatch, tmp_path)
+ (tmp_path / "Git" / "bin").mkdir()
+ (tmp_path / "Git" / "cmd").mkdir()
+ (tmp_path / "Git" / "cmd" / "git.exe").write_bytes(b"MZ")
+ monkeypatch.setattr(tools, "_resolve_trusted_windows_git", lambda: ("", ""))
+ monkeypatch.setattr(tools, "_windows_bash", lambda: str(tmp_path / "Git" / "bin" / "bash.exe"))
+ monkeypatch.setattr(tools, "_is_trusted_windows_program_dir", lambda _path: True)
+ env = tools._build_safe_env(str(tmp_path), shell = "cmd_isolated")
+ assert os.path.realpath(tmp_path / "Git" / "cmd") in env["PATH"]
+ assert str(tmp_path / "Git" / "cmd") not in tools._build_safe_env(str(tmp_path))["PATH"]
+
+
+def test_default_env_is_unchanged(windows, monkeypatch, tmp_path):
+ windows()
+ userland = _userland(monkeypatch, tmp_path)
+ env = tools._build_safe_env(str(tmp_path))
+ assert userland in env["PATH"]
+ assert not any(key.startswith("GIT_") for key in env)
+
+
+def test_blocklist_still_catches_blocked_commands_under_cmd(windows):
+ windows() # bash on the host: the lexer must follow the explicit dialect, not the host shell
+ for command in (
+ "rm -rf x",
+ "echo hi && rm -rf x",
+ 'cmd /c "rm -rf x"',
+ "echo hi & dd if=a of=b",
+ ):
+ assert tools._find_blocked_commands(command, posix = False), command
+ assert tools._find_blocked_commands("echo rm", posix = False) == set()
+
+
+def test_description_swap_is_copy_on_write():
+ original = tools.TERMINAL_TOOL["function"]["description"]
+ listed = list(tools.ALL_TOOLS)
+ swapped = tools.apply_terminal_profile_description(listed, "cmd_isolated")
+ assert listed == list(tools.ALL_TOOLS)
+ assert tools.TERMINAL_TOOL["function"]["description"] == original
+ terminal = next(t for t in swapped if t["function"]["name"] == "terminal")
+ assert "The shell is cmd, running isolated" in terminal["function"]["description"]
+ assert terminal["function"]["parameters"] == tools.TERMINAL_TOOL["function"]["parameters"]
+ others = [t for t in swapped if t["function"]["name"] != "terminal"]
+ assert others == [t for t in listed if t["function"]["name"] != "terminal"]
+ for profile in ("bash", "cmd_fallback"):
+ assert tools.apply_terminal_profile_description(listed, profile) is listed
+
+
+def _exec(monkeypatch, tmp_path, command, **kwargs):
+ seen = {}
+ monkeypatch.setattr(tools, "_get_workdir", lambda _sid: str(tmp_path))
+ monkeypatch.setattr(tools, "_account_confinement", lambda: None)
+ monkeypatch.setattr(tools.subprocess, "CREATE_NO_WINDOW", 0, raising = False)
+ monkeypatch.setattr(tools, "_resolve_trusted_windows_git", lambda: ("", ""))
+ monkeypatch.setattr(tools, "_windows_bash_userland_dirs", lambda: [])
+
+ def prepare(plan, **_kw):
+ seen["plan"] = plan
+ raise os_sandbox.SandboxUnavailableError("stop here")
+
+ monkeypatch.setattr(tools, "_prepare_tool_launch", prepare)
+ result = tools._bash_exec(command, session_id = "s1", **kwargs)
+ return seen.get("plan"), result
+
+
+def test_cmd_isolated_runs_system_cmd_with_the_git_env(windows, monkeypatch, tmp_path):
+ windows(bash_cap = _cap(False, MSYS), cmd_cap = _cap(True))
+ plan, _result = _exec(monkeypatch, tmp_path, 'git commit -m "a b"')
+ assert plan.argv == (tools._windows_system_cmd(), "/c", 'git commit -m "a b"')
+ assert plan.argv[0].lower().endswith("\\system32\\cmd.exe")
+ assert plan.env["GIT_CONFIG_VALUE_0"] == "NUL"
+ assert plan.execution_kind == "terminal"
+
+
+def test_cmd_isolated_refuses_multiline(windows, monkeypatch, tmp_path):
+ windows(bash_cap = _cap(False, MSYS), cmd_cap = _cap(True))
+ plan, result = _exec(monkeypatch, tmp_path, "echo one\necho two")
+ assert plan is None
+ assert result == tools._CMD_MULTILINE_REFUSED
+
+
+def test_bash_profile_keeps_multiline_and_bash_argv(windows, monkeypatch, tmp_path):
+ windows(bash_cap = _cap(True), cmd_cap = _cap(True))
+ plan, _result = _exec(monkeypatch, tmp_path, "echo one\necho two")
+ assert plan.argv == (BASH, "-c", "echo one\necho two")
+ assert "GIT_CONFIG_COUNT" not in plan.env
+
+
+def test_bash_hosts_keep_bash_outside_the_measured_dacl_tier(windows):
+ windows(bash_cap = _cap(False, MSYS), cmd_cap = _cap(True), dacl = False)
+ assert tools._terminal_profile() == "bash"
+
+
+def test_cmd_isolated_strips_a_trailing_newline(windows, monkeypatch, tmp_path):
+ windows(bash_cap = _cap(False, MSYS), cmd_cap = _cap(True))
+ plan, _result = _exec(monkeypatch, tmp_path, "git status\r\n")
+ assert plan.argv[2] == "git status"
+
+
+def test_cmd_isolated_is_never_replayed_on_the_host(windows, monkeypatch, tmp_path):
+ windows(bash_cap = _cap(False, MSYS), cmd_cap = _cap(True))
+ plan, _result = _exec(monkeypatch, tmp_path, "dir")
+ assert plan.requested_mode == "required"
+
+
+ "command",
+ [
+ "echo a&rm -rf x",
+ "dir&&rm -rf x",
+ "echo x|rm -rf x",
+ "r^m -rf x",
+ '"r"m -rf x',
+ ],
+)
+def test_cmd_isolated_screens_every_reading_of_the_command(windows, monkeypatch, tmp_path, command):
+ windows(bash_cap = _cap(False, MSYS), cmd_cap = _cap(True))
+ plan, result = _exec(monkeypatch, tmp_path, command)
+ assert plan is None
+ assert result.startswith("Blocked command(s) for safety: rm"), result
+
+
+def test_cmd_isolated_does_not_treat_single_quotes_as_quoting(windows, monkeypatch, tmp_path):
+ windows(bash_cap = _cap(False, MSYS), cmd_cap = _cap(True))
+ monkeypatch.setattr(
+ tools, "_BLOCKED_COMMANDS", tools._BLOCKED_COMMANDS_COMMON | tools._BLOCKED_COMMANDS_WIN
+ )
+ plan, result = _exec(monkeypatch, tmp_path, "echo 'ok & rmdir /s /q x & echo done'")
+ assert plan is None
+ assert result.startswith("Blocked command(s) for safety: rmdir"), result
+
+
+ "command",
+ [
+ "if 1==1 rmdir /s /q x",
+ "IF exist x rmdir /s /q x",
+ "if /i not a==b rmdir x",
+ "if 1 equ 1 rmdir x",
+ "if 1 == 1 rmdir x",
+ 'if "a"=="a" rmdir x',
+ "if cmdextversion 1 rmdir x",
+ "FOR %i IN (1) DO rmdir x",
+ ],
+)
+def test_the_blocklist_reads_past_a_cmd_if_condition(windows, monkeypatch, command):
+ windows()
+ monkeypatch.setattr(
+ tools, "_BLOCKED_COMMANDS", tools._BLOCKED_COMMANDS_COMMON | tools._BLOCKED_COMMANDS_WIN
+ )
+ found = tools._find_blocked_commands(command, posix = False) | tools._find_blocked_commands(
+ command, posix = True
+ )
+ assert "rmdir" in found, command
+ assert tools._find_blocked_commands("if 1==1 echo rmdir", posix = False) == set()
+
+
+def test_a_tool_list_without_the_terminal_never_probes(windows):
+ calls = windows(bash_cap = _cap(False, MSYS), cmd_cap = _cap(True))
+ listed = [t for t in tools.ALL_TOOLS if t["function"]["name"] != "terminal"]
+ assert tools.apply_terminal_profile_for_request(listed) is listed
+ assert calls == []
+
+
+def test_requests_reuse_the_profile_and_refresh_it_off_the_request_path(windows, monkeypatch):
+ calls = windows(bash_cap = _cap(False, MSYS), cmd_cap = _cap(True))
+ started = []
+ monkeypatch.setattr(
+ tools.threading, "Thread", lambda target, daemon: started.append(target) or _NoThread()
+ )
+ assert "cmd" in _terminal_description(tools.apply_terminal_profile_for_request(tools.ALL_TOOLS))
+ probed = len(calls)
+ tools.apply_terminal_profile_for_request(tools.ALL_TOOLS)
+ assert len(calls) == probed and started == []
+ tools._request_profile[1] -= tools._REQUEST_PROFILE_REFRESH_SECONDS + 1
+ tools.apply_terminal_profile_for_request(tools.ALL_TOOLS)
+ tools.apply_terminal_profile_for_request(tools.ALL_TOOLS)
+ assert len(calls) == probed and started == [tools._refresh_request_profile]
+
+
+class _NoThread:
+ def start(self):
+ pass
+
+
+def _terminal_description(listed):
+ return next(t for t in listed if t["function"]["name"] == "terminal")["function"]["description"]
+
+
+def test_approval_reads_a_cmd_command_the_way_cmd_splits_it(windows, monkeypatch):
+ windows(bash_cap = _cap(False, MSYS), cmd_cap = _cap(True))
+ command = "echo 'hi & del victim.txt & echo bye'"
+ assert tools._terminal_is_high_risk(command) is True
+ monkeypatch.setattr(tools, "_terminal_profile", lambda *_a, **_k: "bash")
+ assert tools._terminal_is_high_risk(command) is False # bash keeps the whole thing one argument
+
+
+def test_cmd_echo_off_prefix_does_not_hide_the_command(windows, monkeypatch, tmp_path):
+ windows(bash_cap = _cap(False, MSYS), cmd_cap = _cap(True))
+ monkeypatch.setattr(
+ tools, "_BLOCKED_COMMANDS", tools._BLOCKED_COMMANDS_COMMON | tools._BLOCKED_COMMANDS_WIN
+ )
+ for command in ("@rmdir /s /q x", "echo a & @@rmdir x", "(@rmdir x)"):
+ plan, result = _exec(monkeypatch, tmp_path, command)
+ assert plan is None
+ assert result.startswith("Blocked command(s) for safety: rmdir"), result
+ assert tools._terminal_is_high_risk("@del /q victim.txt") is True
+ assert tools._cmd_reading("git log @{u} [email protected]") == "git log {u} [email protected]"
+
+
+def test_approval_and_blocklist_read_cmd_control_flow(windows, monkeypatch, tmp_path):
+ windows(bash_cap = _cap(False, MSYS), cmd_cap = _cap(True))
+ for command in ("IF 1==1 del /q victim.txt", "call del x", "for %i in (1) DO del x"):
+ assert tools._terminal_is_high_risk(command) is True, command
+ assert tools._terminal_is_high_risk('git commit -m "call me"') is False
+ monkeypatch.setattr(
+ tools, "_BLOCKED_COMMANDS", tools._BLOCKED_COMMANDS_COMMON | tools._BLOCKED_COMMANDS_WIN
+ )
+ plan, result = _exec(monkeypatch, tmp_path, "call rmdir /s /q build")
+ assert plan is None
+ assert result.startswith("Blocked command(s) for safety: rmdir"), result
+
+
+def test_an_approval_that_stays_in_the_workdir_keeps_cmd_isolation_required(
+ windows, monkeypatch, tmp_path
+):
+ windows(bash_cap = _cap(False, MSYS), cmd_cap = _cap(True))
+ plan, _result = _exec(monkeypatch, tmp_path, "dir", host_access_approved = True)
+ assert plan.requested_mode == "required"
+
+
+def test_host_launches_keep_cmd_quoting(monkeypatch):
+ monkeypatch.setattr(mxc_policy, "_system_cmd", lambda: r"C:\Windows\System32\cmd.exe")
+ assert mxc_policy.host_spawn_args(["cmd", "/c", 'type "a b.txt"']) == (
+ '"C:\\Windows\\System32\\cmd.exe" /d /s /c "type "a b.txt""'
+ )
+ assert mxc_policy.host_spawn_args(["bash", "-c", "ls"]) == ["bash", "-c", "ls"]
+ multiline = ["cmd", "/c", "echo a\necho b"]
+ assert mxc_policy.host_spawn_args(multiline) is multiline