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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Fix multiline prompts through Windows npm shims (#7567)
Lee Jackson92106ea1fbc1
diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.pyindex 3effc5fd747..bd8fa59ac2f 100644--- a/unsloth_cli/commands/start.py+++ b/unsloth_cli/commands/start.py@@ -2715,6 +2715,169 @@ def _wsl_shim_env(return env, tuple(dict.fromkeys((*wsl_env_bridge, *(f"{name}/p" for name in cwd_env), "PWD/p")))+_NPM_CMD_SHIM_HEAD = (+ "@ECHO off\n"+ "GOTO start\n"+ ":find_dp0\n"+ "SET dp0=%~dp0\n"+ "EXIT /b\n"+ ":start\n"+ "SETLOCAL\n"+ "CALL :find_dp0\n"+)+_NPM_NODE_CMD_SHIM_PREFIX = (+ re.escape(_NPM_CMD_SHIM_HEAD)+ + r"(?P<environment>(?:@SET [^=\r\n]+=[^\r\n]+\n)*)"+ + re.escape(+ '\nIF EXIST "%dp0%\\node.exe" (\n'+ + ' SET "_prog=%dp0%\\node.exe"\n'+ + ") ELSE (\n"+ + ' SET "_prog=node"\n'+ )+)+_NPM_NODE_CMD_SHIM_SUFFIX = (+ r"(?P<node_args>[^\r\n]*?)[ \t]+" + r'"%dp0%\\(?P<target>[^"\r\n]+)"[ \t]+%\*'+)+_NPM_NODE_CMD_SHIMS = (+ re.compile(+ _NPM_NODE_CMD_SHIM_PREFIX+ + re.escape(+ " SET PATHEXT=%PATHEXT:;.JS;=;%\n"+ + ")\n\n"+ + 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%"'+ )+ + _NPM_NODE_CMD_SHIM_SUFFIX,+ re.IGNORECASE,+ ),+ re.compile(+ _NPM_NODE_CMD_SHIM_PREFIX+ + re.escape(+ ")\n\n"+ + "endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "+ + "set PATHEXT=%PATHEXT:;.JS;=;% & "+ + '"%_prog%"'+ )+ + _NPM_NODE_CMD_SHIM_SUFFIX,+ re.IGNORECASE,+ ),+)+_NPM_NATIVE_CMD_SHIM = re.compile(+ re.escape(_NPM_CMD_SHIM_HEAD) + r'"%dp0%\\(?P<target>[^"\r\n]+)"[ \t]+%\*',+ re.IGNORECASE,+)+_NPM_NODE_SHEBANG = re.compile(+ r"^#!\s*(?:/usr/bin/env\s+(?:-S\s+)?((?:[^ \t=]+=[^ \t=]+\s+)*))?([^ \t]+)(.*)$"+)+_NPM_SHEBANG_DOLLAR = re.compile(r"\$\{?([^$@#?\- \t{}:]+)\}?")+++def _npm_batch_environment(declarations: str) -> str:+ lines = []+ for declaration in declarations.split():+ name, separator, value = declaration.partition("=")+ name = name.strip()+ value = value.strip()+ if separator and name and value:+ value = _NPM_SHEBANG_DOLLAR.sub(lambda match: f"%{match.group(1)}%", value)+ lines.append(f"@SET {name}={value}\n")+ return "".join(lines)+++def _windows_expand_environment(value: str, environment: dict) -> str:+ folded = {name.casefold(): item for name, item in environment.items()}+ return re.sub(+ r"%([^%\r\n]+)%",+ lambda match: folded.get(match.group(1).casefold(), ""),+ value,+ )+++def _npm_node_shim_metadata(target: Path, match, environment: dict) -> Optional[tuple]:+ environment_block = match.group("environment") or ""+ node_args_text = (match.group("node_args") or "").strip()+ known_node_suffix = target.suffix.lower() in {".js", ".cjs", ".mjs"}+ if not environment_block and not node_args_text and known_node_suffix:+ return [], {}++ first_line = target.read_text(encoding = "utf-8").splitlines()[0]+ shebang = _NPM_NODE_SHEBANG.fullmatch(first_line)+ if shebang is None or Path(shebang.group(2)).name.casefold() not in {"node", "node.exe"}:+ return None+ declarations = shebang.group(1) or ""+ if _npm_batch_environment(declarations).casefold() != environment_block.casefold():+ return None+ if (shebang.group(3) or "").strip() != node_args_text:+ return None+ try:+ node_args = shlex.split(node_args_text) if node_args_text else []+ except ValueError:+ return None++ updates = {}+ expanded_environment = dict(environment)+ for line in environment_block.splitlines():+ name, value = line.removeprefix("@SET ").split("=", 1)+ expanded = _windows_expand_environment(value, expanded_environment)+ expanded_environment[name] = expanded+ updates[name] = expanded+ return node_args, updates+++def _apply_windows_environment(environment: dict, updates: dict) -> None:+ for name, value in updates.items():+ existing = next((key for key in environment if key.casefold() == name.casefold()), None)+ if existing is not None and existing != name:+ del environment[existing]+ environment[name] = value+++def _resolved_launch_command(+ executable: str,+ arguments: list,+ environment: Optional[dict] = None,+) -> list:+ """Return an argv that preserves arguments through standard Windows npm shims."""+ 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+ # complete cmd-shim templates so custom wrappers keep their setup behavior.+ with contextlib.suppress(OSError, UnicodeError, IndexError):+ shim = Path(executable)+ contents = shim.read_text(encoding = "utf-8").replace("\r\n", "\n").strip()+ for pattern in _NPM_NODE_CMD_SHIMS:+ match = pattern.fullmatch(contents)+ if match is None:+ continue+ relative = Path(*re.split(r"[\\/]+", match.group("target")))+ target = (shim.parent / relative).resolve()+ if not target.is_file() or not any(+ part.casefold() == "node_modules" for part in target.parts+ ):+ continue+ metadata = _npm_node_shim_metadata(target, match, environment or os.environ)+ if metadata is None:+ continue+ node_args, environment_updates = metadata+ bundled_node = shim.parent / "node.exe"+ node = str(bundled_node) if bundled_node.is_file() else shutil.which("node.exe")+ if node:+ if environment is not None:+ _apply_windows_environment(environment, environment_updates)+ return [node, *node_args, str(target), *arguments]++ match = _NPM_NATIVE_CMD_SHIM.fullmatch(contents)+ if match is not None:+ relative = Path(*re.split(r"[\\/]+", match.group("target")))+ target = (shim.parent / relative).resolve()+ if (+ target.is_file()+ and any(part.casefold() == "node_modules" for part in target.parts)+ and target.suffix.lower() in {".exe", ".com"}+ ):+ return [str(target), *arguments]+ return [executable, *arguments]++def _launch(command: list,env: dict,@@ -2748,7 +2911,8 @@ def _launch(# handler, not SIG_IGN: exec preserves an ignored signal but resets a caught one.previous = signal.signal(signal.SIGINT, lambda *_: None)try:- code = subprocess.run([executable, *command[1:]], env = child_env).returncode+ launch_command = _resolved_launch_command(executable, command[1:], child_env)+ code = subprocess.run(launch_command, env = child_env).returncodefinally:signal.signal(signal.SIGINT, previous)# Negative returncode means killed by signal N; shells expect 128+N.diff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.pyindex cdc1250cff3..4f9bbc8e309 100644--- a/unsloth_cli/tests/test_start.py+++ b/unsloth_cli/tests/test_start.py@@ -1549,6 +1549,7 @@ def test_connect_claude_windows_shim_from_wsl_bridges_env(fake_studio, monkeypatassert captured["env"]["ANTHROPIC_BASE_URL"] == BASEassert captured["env"]["ANTHROPIC_MODEL"] == MODEL["id"]assert captured["env"]["PWD"] == str(tmp_path)+assert "PWD/p" in captured["env"]["WSLENV"].split(":")for name in ("ANTHROPIC_AUTH_TOKEN",@@ -1560,6 +1561,249 @@ def test_connect_claude_windows_shim_from_wsl_bridges_env(fake_studio, monkeypatassert name in captured["env"]["WSLENV"].split(":")+def _npm_node_cmd_shim(+ target: str,+ *,+ node_args: str = "",+ environment: tuple[tuple[str, str], ...] = (),+ cmd_shim_version: int = 7,+) -> str:+ environment_lines = "".join(f"@SET {name}={value}\r\n" for name, value in environment)+ legacy_pathext = " SET PATHEXT=%PATHEXT:;.JS;=;%\r\n" if cmd_shim_version < 9 else ""+ current_pathext = "set PATHEXT=%PATHEXT:;.JS;=;% & " if cmd_shim_version >= 9 else ""+ return (+ "@ECHO off\r\n"+ "GOTO start\r\n"+ ":find_dp0\r\n"+ "SET dp0=%~dp0\r\n"+ "EXIT /b\r\n"+ ":start\r\n"+ "SETLOCAL\r\n"+ "CALL :find_dp0\r\n"+ f"{environment_lines}"+ "\r\n"+ 'IF EXIST "%dp0%\\node.exe" (\r\n'+ ' SET "_prog=%dp0%\\node.exe"\r\n'+ ") ELSE (\r\n"+ ' SET "_prog=node"\r\n'+ f"{legacy_pathext}"+ ")\r\n"+ "\r\n"+ f"endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & {current_pathext}"+ f'"%_prog%" {node_args} "%dp0%\\{target}" %*\r\n'+ )+++def test_launch_windows_npm_shim_preserves_multiline_argument(monkeypatch, tmp_path):+ _simulate_windows(monkeypatch)+ cmd = tmp_path / "fake-agent.cmd"+ target = tmp_path / "node_modules" / "fake-agent" / "index.js"+ target.parent.mkdir(parents = True)+ target.write_text("", encoding = "utf-8")+ cmd.write_bytes(_npm_node_cmd_shim(r"node_modules\fake-agent\index.js").encode())+ captured = {}++ def which(name):+ return str(cmd) if name == "fake-agent" else r"C:\Program Files\nodejs\node.exe"++ def run(command, env):+ captured["command"] = command+ return SimpleNamespace(returncode = 0)++ monkeypatch.setattr(start.shutil, "which", which)+ monkeypatch.setattr(start.subprocess, "run", run)++ code = start._launch(+ ["fake-agent", 'first line\nsecond "quoted" line'],+ {},+ install_hint = "unused",+ )++ assert code == 0+ assert captured["command"] == [+ r"C:\Program Files\nodejs\node.exe",+ str(target),+ 'first line\nsecond "quoted" line',+ ]+++def test_resolved_launch_command_handles_current_npm_node_shim(monkeypatch, tmp_path):+ _simulate_windows(monkeypatch)+ 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",+ cmd_shim_version = 9,+ ).encode()+ )+ monkeypatch.setattr(start.shutil, "which", lambda name: r"C:\Program Files\nodejs\node.exe")++ assert start._resolved_launch_command(str(cmd), ["--flag"]) == [+ r"C:\Program Files\nodejs\node.exe",+ str(target),+ "--flag",+ ]+++def test_resolved_launch_command_ignores_node_js_pathext_shadow(monkeypatch, tmp_path):+ _simulate_windows(monkeypatch)+ 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())+ resolved_names = []++ def which(name):+ resolved_names.append(name)+ return {+ "node": r"C:\shadow\node.js",+ "node.exe": r"C:\Program Files\nodejs\node.exe",+ }.get(name)++ monkeypatch.setattr(start.shutil, "which", which)++ assert start._resolved_launch_command(str(cmd), ["--flag"]) == [+ r"C:\Program Files\nodejs\node.exe",+ str(target),+ "--flag",+ ]+ assert resolved_names == ["node.exe"]+++def test_resolved_launch_command_accepts_extensionless_node_target(monkeypatch, tmp_path):+ _simulate_windows(monkeypatch)+ cmd = tmp_path / "fake-agent.cmd"+ target = tmp_path / "node_modules" / "fake-agent" / "cli"+ 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\cli").encode())+ monkeypatch.setattr(start.shutil, "which", lambda name: r"C:\Program Files\nodejs\node.exe")++ assert start._resolved_launch_command(str(cmd), ["--flag"]) == [+ r"C:\Program Files\nodejs\node.exe",+ str(target),+ "--flag",+ ]+++def test_launch_windows_npm_shim_preserves_shebang_args_and_environment(monkeypatch, tmp_path):+ _simulate_windows(monkeypatch)+ 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_OPTIONS=--trace-warnings node --no-warnings\n",+ encoding = "utf-8",+ )+ cmd.write_bytes(+ _npm_node_cmd_shim(+ r"node_modules\fake-agent\index.js",+ node_args = "--no-warnings",+ environment = (("NODE_OPTIONS", "--trace-warnings"),),+ ).encode()+ )+ captured = {}++ def which(name):+ return str(cmd) if name == "fake-agent" else r"C:\Program Files\nodejs\node.exe"++ def run(command, env):+ captured["command"] = command+ captured["env"] = env+ return SimpleNamespace(returncode = 0)++ monkeypatch.setattr(start.shutil, "which", which)+ monkeypatch.setattr(start.subprocess, "run", run)++ code = start._launch(+ ["fake-agent", 'first line\nsecond "quoted" line'],+ {},+ install_hint = "unused",+ )++ assert code == 0+ assert captured["command"] == [+ r"C:\Program Files\nodejs\node.exe",+ "--no-warnings",+ str(target),+ 'first line\nsecond "quoted" line',+ ]+ assert captured["env"]["NODE_OPTIONS"] == "--trace-warnings"+++def test_resolved_launch_command_uses_native_npm_entrypoint(monkeypatch, tmp_path):+ _simulate_windows(monkeypatch)+ cmd = tmp_path / "fake-agent.cmd"+ target = tmp_path / "node_modules" / "fake-agent" / "agent.exe"+ target.parent.mkdir(parents = True)+ target.write_bytes(b"")+ cmd.write_bytes(+ (+ "@ECHO off\r\n"+ "GOTO start\r\n"+ ":find_dp0\r\n"+ "SET dp0=%~dp0\r\n"+ "EXIT /b\r\n"+ ":start\r\n"+ "SETLOCAL\r\n"+ "CALL :find_dp0\r\n"+ '"%dp0%\\node_modules\\fake-agent\\agent.exe" %*\r\n'+ ).encode()+ )++ assert start._resolved_launch_command(str(cmd), ["--flag", "two words"]) == [+ str(target),+ "--flag",+ "two words",+ ]+++def test_resolved_launch_command_handles_project_local_npm_shim(monkeypatch, tmp_path):+ _simulate_windows(monkeypatch)+ node_modules = tmp_path / "project" / "node_modules"+ cmd = node_modules / ".bin" / "fake-agent.cmd"+ target = node_modules / "fake-agent" / "index.js"+ cmd.parent.mkdir(parents = True)+ target.parent.mkdir(parents = True)+ target.write_text("", encoding = "utf-8")+ cmd.write_bytes(_npm_node_cmd_shim(r"..\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(cmd), ["--flag"]) == [+ r"C:\Program Files\nodejs\node.exe",+ str(target),+ "--flag",+ ]+++def test_resolved_launch_command_leaves_custom_npm_like_wrapper_unchanged(monkeypatch, tmp_path):+ _simulate_windows(monkeypatch)+ cmd = tmp_path / "custom-agent.cmd"+ target = tmp_path / "node_modules" / "fake-agent" / "index.js"+ target.parent.mkdir(parents = True)+ target.write_text("", encoding = "utf-8")+ contents = _npm_node_cmd_shim(r"node_modules\fake-agent\index.js")+ cmd.write_bytes(+ contents.replace(+ "CALL :find_dp0\r\n", "CALL :find_dp0\r\nSET AGENT_MODE=custom\r\n"+ ).encode()+ )++ assert start._resolved_launch_command(str(cmd), ["--flag"]) == [str(cmd), "--flag"]+++def test_resolved_launch_command_leaves_non_npm_batch_file_unchanged(monkeypatch, tmp_path):+ _simulate_windows(monkeypatch)+ cmd = tmp_path / "custom-agent.cmd"+ cmd.write_bytes(b'@echo off\r\n"%dp0%\\custom.exe" %*\r\n')++ assert start._resolved_launch_command(str(cmd), ["--flag"]) == [str(cmd), "--flag"]++@pytest.mark.skipif(os.name == "nt",reason = "WSL-from-Linux scenario (calling a Windows agent .exe from inside WSL); "