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.

unsloth start (Windows): pass the sub-agent task over stdin so non-npm .cmd shims don't mangle it (#14300)

Leo Borcherding705bcc0afe97
diff --git a/unsloth_cli/claude_subagent_mcp.py b/unsloth_cli/claude_subagent_mcp.py
index 5ff302bbae8..3f5662ae878 100644
--- a/unsloth_cli/claude_subagent_mcp.py
+++ b/unsloth_cli/claude_subagent_mcp.py
@@ -190,8 +190,9 @@ def run_local_agent(
else "Bash,Read,Edit,Write,Grep,Glob,NotebookEdit",
"--append-system-prompt",
_SUBAGENT_PLAN_INSTRUCTIONS if read_only else _SUBAGENT_INSTRUCTIONS,
- f"Task: {task}",
]
+ # The task goes over stdin: a non-npm .cmd shim runs argv through cmd.exe, where a quote and & in it run a command.
+ prompt: str | None = f"Task: {task}"
bridged, wsl_names = _wsl_shim_env(command, local_env, _CLAUDE_ENV_UNSET)
if wsl_names:
from unsloth_cli.commands.start import _merge_wslenv
@@ -207,7 +208,7 @@ def run_local_agent(
popen_kwargs: dict[str, Any] = {
"cwd": os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd(),
"env": child_env,
- "stdin": subprocess.DEVNULL,
+ "stdin": subprocess.PIPE,
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE,
"text": True,
@@ -228,9 +229,11 @@ def run_local_agent(
try:
while True:
try:
- stdout, stderr = process.communicate(timeout = _CANCEL_POLL_SECONDS)
+ stdout, stderr = process.communicate(input = prompt, timeout = _CANCEL_POLL_SECONDS)
break
except subprocess.TimeoutExpired:
+ # communicate() refuses input once started; the first call keeps writing it.
+ prompt = None
if cancel_event.is_set():
_stop_child(process)
raise RuntimeError("The local Claude agent was cancelled.")
diff --git a/unsloth_cli/codex_subagent_mcp.py b/unsloth_cli/codex_subagent_mcp.py
index cefd046a939..f0a4b0b3952 100644
--- a/unsloth_cli/codex_subagent_mcp.py
+++ b/unsloth_cli/codex_subagent_mcp.py
@@ -134,8 +134,10 @@ def run_local_agent(
"--ephemeral",
"--json",
"--skip-git-repo-check",
- f"{_SUBAGENT_INSTRUCTIONS}\n\nTask: {task}",
+ # `-` reads the prompt from stdin: a non-npm .cmd shim runs argv through cmd.exe, where a quote and & in the task run a command.
+ "-",
]
+ prompt: str | None = f"{_SUBAGENT_INSTRUCTIONS}\n\nTask: {task}"
local_env = {
_CODEX_ENV_KEY: config["api_key"],
"CODEX_HOME": config["codex_home"],
@@ -155,7 +157,7 @@ def run_local_agent(
popen_kwargs: dict[str, Any] = {
"cwd": os.getcwd(),
"env": child_env,
- "stdin": subprocess.DEVNULL,
+ "stdin": subprocess.PIPE,
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE,
"text": True,
@@ -166,16 +168,17 @@ def run_local_agent(
popen_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
else:
popen_kwargs["start_new_session"] = True
- # cmd.exe splits CR/LF inside `%*` and the prompt always spans lines, so resolve npm shims rather
- # than spawning the .cmd raw.
+ # Resolve npm shims rather than spawning the .cmd raw; cmd.exe also splits CR/LF inside `%*`.
launch_command = _resolved_launch_command(executable, command[1:], child_env)
process = subprocess.Popen(launch_command, **popen_kwargs)
try:
while True:
try:
- stdout, stderr = process.communicate(timeout = _CANCEL_POLL_SECONDS)
+ stdout, stderr = process.communicate(input = prompt, timeout = _CANCEL_POLL_SECONDS)
break
except subprocess.TimeoutExpired:
+ # communicate() refuses input once started; the first call keeps writing it.
+ prompt = None
if cancel_event.is_set():
_stop_child(process)
raise RuntimeError("The local Codex agent was cancelled.")
diff --git a/unsloth_cli/tests/test_claude_subagent_mcp.py b/unsloth_cli/tests/test_claude_subagent_mcp.py
index 405aa4ecfa8..a7687b4f232 100644
--- a/unsloth_cli/tests/test_claude_subagent_mcp.py
+++ b/unsloth_cli/tests/test_claude_subagent_mcp.py
@@ -296,7 +296,11 @@ def test_local_child_uses_unsloth_without_overwriting_parent_auth(
pid = 1234
returncode = 0
- def communicate(self, timeout):
+ def communicate(
+ self,
+ input = None,
+ timeout = None,
+ ):
captured["timeout"] = timeout
return json.dumps({"is_error": False, "result": "LOCAL_OK"}), ""
@@ -318,7 +322,7 @@ def test_local_child_uses_unsloth_without_overwriting_parent_auth(
assert command[command.index("--tools") + 1] == "Bash,Read,Edit,Write,Grep,Glob,NotebookEdit"
assert "--disallowedTools" not in command
assert captured["cwd"] == str(tmp_path)
- assert captured["stdin"] is bridge.subprocess.DEVNULL
+ assert captured["stdin"] is bridge.subprocess.PIPE
assert captured["stdout"] is bridge.subprocess.PIPE
assert captured["stderr"] is bridge.subprocess.PIPE
if os.name == "nt":
@@ -359,7 +363,11 @@ def test_local_child_sheds_inherited_provider_routing(monkeypatch, tmp_path):
pid = 1234
returncode = 0
- def communicate(self, timeout):
+ def communicate(
+ self,
+ input = None,
+ timeout = None,
+ ):
return json.dumps({"is_error": False, "result": "LOCAL_OK"}), ""
def poll(self):
@@ -401,7 +409,11 @@ def test_read_only_local_child_uses_plan_mode(monkeypatch, tmp_path):
pid = 1234
returncode = 0
- def communicate(self, timeout):
+ def communicate(
+ self,
+ input = None,
+ timeout = None,
+ ):
return json.dumps({"is_error": False, "result": "PLAN_OK"}), ""
def poll(self):
@@ -436,7 +448,11 @@ def test_local_child_process_is_stopped_on_cancellation(monkeypatch, tmp_path):
pid = 1234
returncode = None
- def communicate(self, timeout):
+ def communicate(
+ self,
+ input = None,
+ timeout = None,
+ ):
cancel_event.set()
raise bridge.subprocess.TimeoutExpired("claude", timeout)
@@ -551,7 +567,11 @@ def test_failed_child_reports_why_it_stopped_not_its_warnings(monkeypatch, tmp_p
pid = 1234
returncode = 1
- def communicate(self, timeout):
+ def communicate(
+ self,
+ input = None,
+ timeout = None,
+ ):
payload = {
"is_error": True,
"terminal_reason": "rapid_refill_breaker",
@@ -582,7 +602,11 @@ def test_child_is_stopped_when_it_produces_nothing_before_the_deadline(monkeypat
class _Hanging:
returncode = None
- def communicate(self, timeout = None):
+ def communicate(
+ self,
+ input = None,
+ timeout = None,
+ ):
raise subprocess.TimeoutExpired("claude", timeout)
def poll(self):
@@ -624,7 +648,12 @@ def test_local_child_is_spawned_through_the_shim_resolver(monkeypatch, tmp_path)
pid = 1234
returncode = 0
- def communicate(self, timeout):
+ def communicate(
+ self,
+ input = None,
+ timeout = None,
+ ):
+ captured["input"] = input
return json.dumps({"is_error": False, "result": "LOCAL_OK"}), ""
def poll(self):
@@ -641,7 +670,68 @@ def test_local_child_is_spawned_through_the_shim_resolver(monkeypatch, tmp_path)
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 not any("multi\nline\ntask" in argument for argument in arguments)
assert environment is not None
assert captured["command"][0] == "C:\\nodejs\\node.exe"
- assert any("multi\nline\ntask" in part for part in captured["command"])
+ assert captured["input"] == "Task: multi\nline\ntask"
+
+
+def test_task_reaches_the_child_over_stdin_not_argv(monkeypatch, tmp_path):
+ _stub_env(monkeypatch, tmp_path)
+ task = 'summarize the README" & echo INJECTED-BY-TASK & "'
+ captured = {"inputs": []}
+
+ class Process:
+ pid = 1234
+ returncode = 0
+
+ def communicate(
+ self,
+ input = None,
+ timeout = None,
+ ):
+ captured["inputs"].append(input)
+ return json.dumps({"is_error": False, "result": "LOCAL_OK"}), ""
+
+ def poll(self):
+ return self.returncode
+
+ def popen(command, **kwargs):
+ captured["command"] = command
+ captured["stdin"] = kwargs.get("stdin")
+ return Process()
+
+ monkeypatch.setattr(bridge.subprocess, "Popen", popen)
+ assert bridge.run_local_agent(task) == "LOCAL_OK"
+ assert not any(task in part for part in captured["command"])
+ assert captured["stdin"] is subprocess.PIPE
+ assert captured["inputs"] == [f"Task: {task}"]
+
+
[email protected](os.name != "nt", reason = "cmd.exe shim parsing is Windows-only")
+def test_task_cannot_break_out_of_a_non_npm_cmd_shim(monkeypatch, tmp_path):
+ # pnpm-style shim: not npm's template, so the resolver leaves it to cmd.exe.
+ shim = tmp_path / "claude.cmd"
+ shim.write_bytes(
+ b'@SETLOCAL\r\n@IF NOT DEFINED NODE_PATH (\r\n @SET "NODE_PATH=x"\r\n)\r\n'
+ b'@echo {"is_error": false, "result": "SHIM_OK"}\r\n@findstr "^"\r\n'
+ )
+ _stub_env(monkeypatch, tmp_path)
+ monkeypatch.setattr(bridge.shutil, "which", lambda _: str(shim))
+ seen = {}
+
+ class RecordingPopen(subprocess.Popen):
+ def communicate(self, *args, **kwargs):
+ stdout, stderr = super().communicate(*args, **kwargs)
+ seen["stdout"] = stdout
+ return stdout, stderr
+
+ monkeypatch.setattr(bridge.subprocess, "Popen", RecordingPopen)
+ task = 'summarize the README" & echo INJECTED-BY-TASK & "'
+ try:
+ bridge.run_local_agent(task)
+ except RuntimeError:
+ pass # On a broken-out command line the trailing `"` fails; the stdout check below is the test.
+ lines = [line.strip() for line in seen["stdout"].splitlines()]
+ assert "INJECTED-BY-TASK" not in lines
+ assert f"Task: {task}" in lines
diff --git a/unsloth_cli/tests/test_codex_subagent_mcp.py b/unsloth_cli/tests/test_codex_subagent_mcp.py
index ed52a7b0f1e..8e2e458d6f7 100644
--- a/unsloth_cli/tests/test_codex_subagent_mcp.py
+++ b/unsloth_cli/tests/test_codex_subagent_mcp.py
@@ -147,8 +147,13 @@ def test_local_child_uses_explicit_unsloth_profile(
pid = 1234
returncode = 0
- def communicate(self, timeout):
+ def communicate(
+ self,
+ input = None,
+ timeout = None,
+ ):
captured["timeout"] = timeout
+ captured["input"] = input
return (
json.dumps(
{
@@ -182,9 +187,10 @@ def test_local_child_uses_explicit_unsloth_profile(
"--json",
"--skip-git-repo-check",
]
- assert command[-1].endswith("Task: reply exactly LOCAL_OK")
+ assert command[-1] == "-"
+ assert captured["input"].endswith("Task: reply exactly LOCAL_OK")
assert captured["cwd"] == os.getcwd()
- assert captured["stdin"] is subprocess.DEVNULL
+ assert captured["stdin"] is subprocess.PIPE
assert captured["stdout"] is subprocess.PIPE
assert captured["stderr"] is subprocess.PIPE
if os.name == "nt":
@@ -276,7 +282,11 @@ def test_failed_child_reports_its_last_error_not_its_banner(monkeypatch, tmp_pat
pid = 1234
returncode = 1
- def communicate(self, timeout):
+ def communicate(
+ self,
+ input = None,
+ timeout = None,
+ ):
events = [
{"type": "turn.started"},
{"type": "turn.failed", "error": {"message": reason}},
@@ -305,7 +315,11 @@ def test_local_child_process_is_stopped_on_cancellation(monkeypatch, tmp_path):
pid = 1234
returncode = None
- def communicate(self, timeout):
+ def communicate(
+ self,
+ input = None,
+ timeout = None,
+ ):
cancel_event.set()
raise subprocess.TimeoutExpired("codex", timeout)
@@ -344,7 +358,12 @@ def test_local_child_is_spawned_through_the_shim_resolver(monkeypatch, tmp_path)
pid = 1234
returncode = 0
- def communicate(self, timeout):
+ def communicate(
+ self,
+ input = None,
+ timeout = None,
+ ):
+ captured["input"] = input
return (
json.dumps(
{
@@ -369,7 +388,48 @@ def test_local_child_is_spawned_through_the_shim_resolver(monkeypatch, tmp_path)
executable, arguments, environment = captured["resolver"]
assert executable == r"C:\\nodejs\\codex.cmd"
assert arguments[0] == "--oss"
- assert any("multi\nline\ntask" in argument for argument in arguments)
+ assert arguments[-1] == "-"
assert environment is not None and bridge._CODEX_ENV_KEY in environment
assert captured["command"][0] == "C:\\nodejs\\node.exe"
- assert any("multi\nline\ntask" in part for part in captured["command"])
+ assert captured["input"].endswith("Task: multi\nline\ntask")
+
+
+def test_prompt_reaches_the_child_over_stdin_once_even_after_a_poll_timeout(monkeypatch, tmp_path):
+ # A non-npm codex.cmd runs argv through cmd.exe, so the task must not be in it.
+ config = _write_config(tmp_path)
+ monkeypatch.setenv(bridge._CODEX_SUBAGENT_CONFIG_ENV, str(config))
+ monkeypatch.setattr(bridge.shutil, "which", lambda _: "/usr/local/bin/codex")
+ task = 'summarize the README" & echo INJECTED-BY-TASK & "'
+ captured = {"inputs": []}
+
+ class Process:
+ pid = 1234
+ returncode = 0
+
+ def communicate(
+ self,
+ input = None,
+ timeout = None,
+ ):
+ captured["inputs"].append(input)
+ if len(captured["inputs"]) == 1:
+ raise subprocess.TimeoutExpired("codex", timeout)
+ event = {"type": "item.completed", "item": {"type": "agent_message", "text": "OK"}}
+ return json.dumps(event), ""
+
+ def poll(self):
+ return self.returncode
+
+ def popen(command, **kwargs):
+ captured["command"] = command
+ captured["stdin"] = kwargs.get("stdin")
+ return Process()
+
+ monkeypatch.setattr(bridge.subprocess, "Popen", popen)
+ assert bridge.run_local_agent(task) == "OK"
+ assert not any(task in part for part in captured["command"])
+ assert captured["command"][-1] == "-"
+ assert captured["stdin"] is subprocess.PIPE
+ first, retry = captured["inputs"]
+ assert first.endswith(f"Task: {task}") and first.startswith(bridge._SUBAGENT_INSTRUCTIONS)
+ assert retry is None