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.

Prefer the .cmd sibling when Windows resolves an extensionless npm shim (#9238)

Shubhankar Tripathydfc4b3c9c7ad
diff --git a/unsloth_cli/claude_subagent_mcp.py b/unsloth_cli/claude_subagent_mcp.py
index b66d3c7ab93..94e09085a34 100644
--- a/unsloth_cli/claude_subagent_mcp.py
+++ b/unsloth_cli/claude_subagent_mcp.py
@@ -23,6 +23,8 @@ from unsloth_cli.commands.start import (
_SUBAGENT_PLAN_INSTRUCTIONS,
_claude_flags,
_claude_local_env,
+ _prefer_windows_cmd_sibling,
+ _resolved_launch_command,
_wsl_shim_env,
)
@@ -144,7 +146,7 @@ def run_local_agent(
local_env = _claude_local_env(base, key, entry)
child_env = dict(os.environ)
- executable = shutil.which("claude")
+ executable = _prefer_windows_cmd_sibling(shutil.which("claude"))
if executable is None:
raise RuntimeError("`claude` is not installed or is not on PATH.")
cancel_event = cancel_event or threading.Event()
@@ -208,8 +210,10 @@ def run_local_agent(
popen_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
else:
popen_kwargs["start_new_session"] = True
+ # Same CR/LF hazard as the Codex bridge: --append-system-prompt and the task
+ # both span lines, so resolve npm shims rather than spawning the .cmd raw.
process = subprocess.Popen(
- [executable, *command[1:]],
+ _resolved_launch_command(executable, command[1:], child_env),
**popen_kwargs,
)
deadline = _timeout_seconds()
diff --git a/unsloth_cli/codex_subagent_mcp.py b/unsloth_cli/codex_subagent_mcp.py
index f075e66404a..16d5d6d8860 100644
--- a/unsloth_cli/codex_subagent_mcp.py
+++ b/unsloth_cli/codex_subagent_mcp.py
@@ -25,6 +25,8 @@ from unsloth_cli.commands.start import (
_CODEX_SUBAGENT_ROUTING_INSTRUCTIONS,
_SUBAGENT_INSTRUCTIONS,
_merge_wslenv,
+ _prefer_windows_cmd_sibling,
+ _resolved_launch_command,
_wsl_shim_env,
)
@@ -82,7 +84,7 @@ def _result_text(stdout: str) -> str:
def run_local_agent(task: str, cancel_event: threading.Event | None = None) -> str:
config = _config()
- executable = shutil.which("codex")
+ executable = _prefer_windows_cmd_sibling(shutil.which("codex"))
if executable is None:
raise RuntimeError("`codex` is not installed or is not on PATH.")
cancel_event = cancel_event or threading.Event()
@@ -134,7 +136,10 @@ def run_local_agent(task: str, cancel_event: threading.Event | None = None) -> s
popen_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
else:
popen_kwargs["start_new_session"] = True
- process = subprocess.Popen([executable, *command[1:]], **popen_kwargs)
+ # cmd.exe splits CR/LF inside `%*` and the prompt always spans lines, so
+ # resolve npm shims here rather than spawning the .cmd raw.
+ launch_command = _resolved_launch_command(executable, command[1:], child_env)
+ process = subprocess.Popen(launch_command, **popen_kwargs)
try:
while True:
try:
diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.py
index 14f5f59e10a..fe677a4cfb7 100644
--- a/unsloth_cli/commands/start.py
+++ b/unsloth_cli/commands/start.py
@@ -3309,6 +3309,32 @@ def _probe_env(**extra: str) -> dict:
return env
+def _prefer_windows_cmd_sibling(executable: Optional[str]) -> Optional[str]:
+ """Prefer the sibling .cmd when Windows resolved an extensionless npm/pnpm shim.
+
+ cmd-shim writes ``to``, ``to.cmd`` and ``to.ps1``, and shutil.which can return
+ the extensionless POSIX shim, which CreateProcess rejects with WinError 193.
+ Measured on windows-latest: 3.12.0 probes the bare name before PATHEXT
+ (gh-109590), and 3.12.1 onwards do not. A PATHEXT holding "." reaches the same
+ place on any version. Substituted only when the file opens with a shebang, so a
+ real PE keeps priority over a stale wrapper beside it; matched on
+ not-a-Windows-suffix so a dotted bin name is caught too.
+ """
+ if executable is None or os.name != "nt":
+ return executable
+ if Path(executable).suffix.lower() in {".exe", ".com", ".cmd", ".bat", ".ps1"}:
+ return executable
+ with contextlib.suppress(OSError):
+ with open(executable, "rb") as resolved_file:
+ if resolved_file.read(2) == b"#!":
+ # .CMD only matters on case-sensitive volumes; no writer emits .bat.
+ for extension in (".cmd", ".CMD"):
+ sibling = Path(executable + extension)
+ if sibling.is_file():
+ return str(sibling)
+ return executable
+
+
def _which_with_install_dirs(name: str) -> Optional[str]:
# shutil.which(name), but searching the known agent install dirs too, so a version probe
# resolves the same binary _launch() will (it augments PATH before it runs). Without this an
@@ -3318,7 +3344,9 @@ def _which_with_install_dirs(name: str) -> Optional[str]:
original = os.environ.get("PATH")
_augment_path_with_install_dirs()
try:
- return shutil.which(name)
+ # Callers spawn this result directly, so the shim rescue is needed here
+ # too, not only in _resolved_launch_command.
+ return _prefer_windows_cmd_sibling(shutil.which(name))
finally:
if original is None:
os.environ.pop("PATH", None)
@@ -3345,13 +3373,13 @@ def _pinned_raw_github_commit(source: str) -> Optional[str]:
def _npm_executable() -> Optional[str]:
managed_node = _managed_node_tools()
if not (managed_node and managed_node[2]):
- executable = shutil.which("npm")
+ executable = _prefer_windows_cmd_sibling(shutil.which("npm"))
if executable and not _wsl_windows_executable([executable]):
return executable
if executable:
# WSL inherits the Windows PATH, so the rejected shim may shadow a native npm.
for directory in os.get_exec_path():
- candidate = shutil.which("npm", path = directory)
+ candidate = _prefer_windows_cmd_sibling(shutil.which("npm", path = directory))
if candidate and not _wsl_windows_executable([candidate]):
return candidate
@@ -3625,6 +3653,9 @@ def _resolved_launch_command(
environment: Optional[dict] = None,
) -> list:
"""Return an argv that preserves arguments through standard Windows npm shims."""
+ # _launch resolves with raw shutil.which, so rescue here too; the sibling
+ # then enters the parser below.
+ executable = _prefer_windows_cmd_sibling(executable)
if os.name == "nt" and Path(executable).suffix.lower() in {".cmd", ".bat"}:
# cmd.exe treats CR/LF inside `%*` as command separators, and Windows
# PowerShell's native-command bridge also rewrites embedded quotes. Match
diff --git a/unsloth_cli/tests/test_claude_subagent_mcp.py b/unsloth_cli/tests/test_claude_subagent_mcp.py
index 2155ca050db..a2bbf893d78 100644
--- a/unsloth_cli/tests/test_claude_subagent_mcp.py
+++ b/unsloth_cli/tests/test_claude_subagent_mcp.py
@@ -453,3 +453,46 @@ def test_timeout_can_be_disabled(monkeypatch):
assert bridge._timeout_seconds() == bridge._DEFAULT_TIMEOUT_SECONDS
monkeypatch.delenv("UNSLOTH_CLAUDE_SUBAGENT_TIMEOUT")
assert bridge._timeout_seconds() == bridge._DEFAULT_TIMEOUT_SECONDS
+
+
+def test_local_child_is_spawned_through_the_shim_resolver(monkeypatch, tmp_path):
+ # Pins the wiring: a Windows .cmd must reach the npm parser, not Popen (#9167).
+ # The parser behaviour itself is covered in test_start.py.
+ _stub_env(monkeypatch, tmp_path)
+ monkeypatch.setattr(bridge.shutil, "which", lambda _: r"C:\\nodejs\\claude.cmd")
+ captured = {}
+
+ def resolver(
+ executable,
+ arguments,
+ environment = None,
+ ):
+ captured["resolver"] = (executable, arguments, environment)
+ return ["C:\\nodejs\\node.exe", "cli.js", *arguments]
+
+ class Process:
+ pid = 1234
+ returncode = 0
+
+ def communicate(self, timeout):
+ return json.dumps({"is_error": False, "result": "LOCAL_OK"}), ""
+
+ def poll(self):
+ return self.returncode
+
+ def popen(command, **kwargs):
+ captured["command"] = command
+ return Process()
+
+ monkeypatch.setattr(bridge, "_resolved_launch_command", resolver)
+ monkeypatch.setattr(bridge.subprocess, "Popen", popen)
+ assert bridge.run_local_agent("multi\nline\ntask") == "LOCAL_OK"
+
+ executable, arguments, environment = captured["resolver"]
+ assert executable == r"C:\\nodejs\\claude.cmd"
+ assert arguments[0] == "--model"
+ assert any("multi\nline\ntask" in argument for argument in arguments)
+ assert environment is not None
+ # Popen spawns the resolver's argv, not the .cmd.
+ assert captured["command"][0] == "C:\\nodejs\\node.exe"
+ assert any("multi\nline\ntask" in part for part in captured["command"])
diff --git a/unsloth_cli/tests/test_codex_subagent_mcp.py b/unsloth_cli/tests/test_codex_subagent_mcp.py
index c0c97ca123b..0c724e16a9e 100644
--- a/unsloth_cli/tests/test_codex_subagent_mcp.py
+++ b/unsloth_cli/tests/test_codex_subagent_mcp.py
@@ -226,3 +226,56 @@ def test_local_child_process_is_stopped_on_cancellation(monkeypatch, tmp_path):
with pytest.raises(RuntimeError, match = "cancelled"):
bridge.run_local_agent("wait", cancel_event)
assert stopped == [process]
+
+
+def test_local_child_is_spawned_through_the_shim_resolver(monkeypatch, tmp_path):
+ # Pins the wiring: a Windows .cmd must reach the npm parser, not Popen (#9167).
+ # The parser behaviour itself is covered in test_start.py.
+ config = _write_config(tmp_path)
+ monkeypatch.setenv(bridge._CODEX_SUBAGENT_CONFIG_ENV, str(config))
+ monkeypatch.setattr(bridge.shutil, "which", lambda _: r"C:\\nodejs\\codex.cmd")
+ captured = {}
+
+ def resolver(
+ executable,
+ arguments,
+ environment = None,
+ ):
+ captured["resolver"] = (executable, arguments, environment)
+ return ["C:\\nodejs\\node.exe", "index.js", *arguments]
+
+ class Process:
+ pid = 1234
+ returncode = 0
+
+ def communicate(self, timeout):
+ return (
+ json.dumps(
+ {
+ "type": "item.completed",
+ "item": {"type": "agent_message", "text": "LOCAL_OK"},
+ }
+ ),
+ "",
+ )
+
+ def poll(self):
+ return self.returncode
+
+ def popen(command, **kwargs):
+ captured["command"] = command
+ return Process()
+
+ monkeypatch.setattr(bridge, "_resolved_launch_command", resolver)
+ monkeypatch.setattr(bridge.subprocess, "Popen", popen)
+ assert bridge.run_local_agent("multi\nline\ntask") == "LOCAL_OK"
+
+ executable, arguments, environment = captured["resolver"]
+ assert executable == r"C:\\nodejs\\codex.cmd"
+ # The resolver sees the real argv and the child env, as _launch passes them.
+ assert arguments[0] == "--oss"
+ assert any("multi\nline\ntask" in argument for argument in arguments)
+ assert environment is not None and bridge._CODEX_ENV_KEY in environment
+ # Popen spawns the resolver's argv, not the .cmd.
+ assert captured["command"][0] == "C:\\nodejs\\node.exe"
+ assert any("multi\nline\ntask" in part for part in captured["command"])
diff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.py
index a6062906926..b761498e91b 100644
--- a/unsloth_cli/tests/test_start.py
+++ b/unsloth_cli/tests/test_start.py
@@ -1771,6 +1771,141 @@ def test_resolved_launch_command_accepts_extensionless_node_target(monkeypatch,
]
+def test_resolved_launch_command_prefers_cmd_sibling_of_extensionless_shim(monkeypatch, tmp_path):
+ # which() can resolve the extensionless POSIX shim ahead of its .cmd sibling;
+ # CreateProcess rejects the former with WinError 193 (#9167).
+ _simulate_windows(monkeypatch)
+ posix_shim = tmp_path / "fake-agent"
+ posix_shim.write_text("#!/bin/sh\n", encoding = "utf-8")
+ cmd = tmp_path / "fake-agent.cmd"
+ target = tmp_path / "node_modules" / "fake-agent" / "index.js"
+ target.parent.mkdir(parents = True)
+ target.write_text("#!/usr/bin/env node\n", encoding = "utf-8")
+ cmd.write_bytes(_npm_node_cmd_shim(r"node_modules\fake-agent\index.js").encode())
+ monkeypatch.setattr(start.shutil, "which", lambda name: r"C:\Program Files\nodejs\node.exe")
+
+ assert start._resolved_launch_command(str(posix_shim), ["--flag"]) == [
+ r"C:\Program Files\nodejs\node.exe",
+ str(target),
+ "--flag",
+ ]
+
+
+def test_resolved_launch_command_keeps_extensionless_shim_without_sibling(monkeypatch, tmp_path):
+ # Nothing to substitute, so the path passes through unchanged.
+ _simulate_windows(monkeypatch)
+ executable = tmp_path / "fake-agent"
+ executable.write_text("#!/bin/sh\n", encoding = "utf-8")
+
+ assert start._resolved_launch_command(str(executable), ["--flag"]) == [
+ str(executable),
+ "--flag",
+ ]
+
+
+def test_prefer_cmd_sibling_leaves_an_unreadable_resolution_alone(monkeypatch, tmp_path):
+ # A directory, an unreadable file, or a delete between resolve and open must
+ # fall through instead of raising out of the launch path.
+ _simulate_windows(monkeypatch)
+ executable = tmp_path / "fake-agent"
+ executable.mkdir()
+ (tmp_path / "fake-agent.cmd").write_text("@ECHO off\n", encoding = "utf-8")
+
+ assert start._resolved_launch_command(str(executable), ["--flag"]) == [
+ str(executable),
+ "--flag",
+ ]
+
+
+def test_prefer_cmd_sibling_is_none_safe_and_posix_noop(monkeypatch, tmp_path):
+ assert start._prefer_windows_cmd_sibling(None) is None
+ # Pin os.name instead of relying on the host: on a Windows runner the rescue
+ # would fire and this would assert the opposite of what it means to check.
+ monkeypatch.setattr(start.os, "name", "posix")
+ shim = tmp_path / "fake-agent"
+ shim.write_text("#!/bin/sh\n", encoding = "utf-8")
+ (tmp_path / "fake-agent.cmd").write_text("@ECHO off\n", encoding = "utf-8")
+ assert start._prefer_windows_cmd_sibling(str(shim)) == str(shim)
+
+
+def test_resolved_launch_command_rescues_uppercase_cmd_sibling(monkeypatch, tmp_path):
+ # #9167's pnpm dir holds pi.CMD. A case-sensitive volume needs the .CMD probe;
+ # a case-insensitive one answers the earlier .cmd probe with the same file, so
+ # compare identity rather than spelling or this passes only on Linux.
+ _simulate_windows(monkeypatch)
+ posix_shim = tmp_path / "fake-agent"
+ posix_shim.write_text("#!/bin/sh\n", encoding = "utf-8")
+ cmd = tmp_path / "fake-agent.CMD"
+ cmd.write_text("@ECHO off\ncustom-wrapper %*\n", encoding = "utf-8")
+
+ resolved = start._resolved_launch_command(str(posix_shim), ["--flag"])
+ assert resolved[1:] == ["--flag"]
+ assert os.path.samefile(resolved[0], str(cmd))
+
+
+def test_which_with_install_dirs_applies_the_cmd_sibling_preference(monkeypatch, tmp_path):
+ # The version probes spawn this result directly, bypassing
+ # _resolved_launch_command, so the rescue must happen here too.
+ _simulate_windows(monkeypatch)
+ posix_shim = tmp_path / "fake-agent"
+ posix_shim.write_text("#!/bin/sh\n", encoding = "utf-8")
+ cmd = tmp_path / "fake-agent.cmd"
+ cmd.write_text("@ECHO off\n", encoding = "utf-8")
+ monkeypatch.setattr(start, "_augment_path_with_install_dirs", lambda: None)
+ monkeypatch.setattr(start.shutil, "which", lambda name: str(posix_shim))
+
+ assert start._which_with_install_dirs("fake-agent") == str(cmd)
+
+
+def test_resolved_launch_command_rescues_dotted_bin_name_shim(monkeypatch, tmp_path):
+ # cmd-shim appends .cmd to the whole bin name, so "foo.bar" pairs with
+ # "foo.bar.cmd" and still needs the sibling preference.
+ _simulate_windows(monkeypatch)
+ posix_shim = tmp_path / "fake.agent"
+ posix_shim.write_text("#!/bin/sh\n", encoding = "utf-8")
+ cmd = tmp_path / "fake.agent.cmd"
+ target = tmp_path / "node_modules" / "fake-agent" / "index.js"
+ target.parent.mkdir(parents = True)
+ target.write_text("#!/usr/bin/env node\n", encoding = "utf-8")
+ cmd.write_bytes(_npm_node_cmd_shim(r"node_modules\fake-agent\index.js").encode())
+ monkeypatch.setattr(start.shutil, "which", lambda name: r"C:\Program Files\nodejs\node.exe")
+
+ assert start._resolved_launch_command(str(posix_shim), ["--flag"]) == [
+ r"C:\Program Files\nodejs\node.exe",
+ str(target),
+ "--flag",
+ ]
+
+
+def test_resolved_launch_command_keeps_extensionless_pe_binary_over_stale_sibling(
+ monkeypatch, tmp_path
+):
+ # CreateProcess runs a PE regardless of its name, so a real executable keeps
+ # priority over a stale .cmd; only shebang files are treated as shims.
+ _simulate_windows(monkeypatch)
+ executable = tmp_path / "fake-agent"
+ executable.write_bytes(b"MZ\x90\x00")
+ stale = tmp_path / "fake-agent.cmd"
+ stale.write_text("@ECHO off\nold-wrapper %*\n", encoding = "utf-8")
+
+ assert start._resolved_launch_command(str(executable), ["--flag"]) == [
+ str(executable),
+ "--flag",
+ ]
+
+
+def test_resolved_launch_command_falls_through_to_non_npm_cmd_sibling(monkeypatch, tmp_path):
+ # A non-npm .cmd sibling is still what cmd.exe would have picked, so it is
+ # returned as-is.
+ _simulate_windows(monkeypatch)
+ posix_shim = tmp_path / "fake-agent"
+ posix_shim.write_text("#!/bin/sh\n", encoding = "utf-8")
+ cmd = tmp_path / "fake-agent.cmd"
+ cmd.write_text("@ECHO off\ncustom-wrapper %*\n", encoding = "utf-8")
+
+ assert start._resolved_launch_command(str(posix_shim), ["--flag"]) == [str(cmd), "--flag"]
+
+
def test_launch_windows_npm_shim_preserves_shebang_args_and_environment(monkeypatch, tmp_path):
_simulate_windows(monkeypatch)
cmd = tmp_path / "fake-agent.cmd"