The agent that turns websites into APIs!
fix(windows): preserve arguments through native npm launchers
kalil032143dbe62c1c56
diff --git a/src/reverse_api/agent_browser.py b/src/reverse_api/agent_browser.pyindex 2753fe7..3b6666d 100644--- a/src/reverse_api/agent_browser.py+++ b/src/reverse_api/agent_browser.py@@ -19,6 +19,7 @@ from typing import Anyfrom rich.console import Console+from .runtime_commands import resolve_windows_commandfrom .utils import get_config_path_AGENT_BROWSER_TOOLS = frozenset(@@ -97,10 +98,9 @@ def agent_browser_extra_notes() -> str:def _probe_help_argv(argv_without_help: list[str]) -> str | None:argv = [*argv_without_help, "--help"]- if sys.platform == "win32":- # CreateProcess does not search PATHEXT for npm's .cmd launchers.- argv[0] = shutil.which(argv[0]) or argv[0]try:+ if sys.platform == "win32":+ argv = resolve_windows_command(argv)proc = subprocess.run(argv,capture_output=True,@@ -112,7 +112,7 @@ def _probe_help_argv(argv_without_help: list[str]) -> str | None:)except subprocess.TimeoutExpired:return f"timed out running `{shlex.join(argv_without_help)} --help`."- except OSError as e:+ except (OSError, ValueError) as e:return f"failed subprocess `{shlex.join(argv_without_help)}`: {e}"stdout = (proc.stdout or "").strip()@@ -232,7 +232,7 @@ def ensure_agent_browser_runtime() -> AgentBrowserSetup:try:proc = subprocess.run(- [npm, "install", "-g", "--yes", pkg],+ resolve_windows_command([npm, "install", "-g", "--yes", pkg]),capture_output=True,text=True,encoding="utf-8",@@ -244,7 +244,7 @@ def ensure_agent_browser_runtime() -> AgentBrowserSetup:except subprocess.TimeoutExpired:notices.append("`npm install -g …` timed out; falling back to `npx -y …` for this session.")return _finalize_npx_invoker(notices)- except OSError as e:+ except (OSError, ValueError) as e:notices.append(f"Could not spawn npm globally ({e}); falling back to `npx -y …`.")return _finalize_npx_invoker(notices)diff --git a/src/reverse_api/cli.py b/src/reverse_api/cli.pyindex 93dc46d..ed4ddf9 100644--- a/src/reverse_api/cli.py+++ b/src/reverse_api/cli.py@@ -2915,6 +2915,7 @@ def _run_non_python_script(script: Path, script_args: tuple[str, ...]) -> None:import shutilimport subprocess+ from .runtime_commands import resolve_windows_commandfrom .utils import build_script_commandstry:@@ -2925,7 +2926,10 @@ def _run_non_python_script(script: Path, script_args: tuple[str, ...]) -> None:if executable is None:raise click.ClickException(f"cannot run {script.name}: '{tool}' is missing from PATH — install it and retry")if sys.platform == "win32":- steps[0][0] = executable+ try:+ steps[0] = resolve_windows_command([executable, *steps[0][1:]])+ except ValueError as e:+ raise click.ClickException(str(e)) from ereturncode = 0for cmd in steps:returncode = subprocess.run(cmd, cwd=str(script.parent)).returncode@@ -3029,7 +3033,9 @@ def _run_script_machine_payload(error_kind_hint="config_invalid",)if sys.platform == "win32":- steps[0][0] = executable+ from .runtime_commands import resolve_windows_command++ steps[0] = resolve_windows_command([executable, *steps[0][1:]])result = Nonefor cmd in steps:emit_event("process_started", run_id=run_id, script_path=str(script))diff --git a/src/reverse_api/cursor_engineer.py b/src/reverse_api/cursor_engineer.pyindex a04b3f3..6ac607f 100644--- a/src/reverse_api/cursor_engineer.py+++ b/src/reverse_api/cursor_engineer.py@@ -14,6 +14,7 @@ from typing import Anyfrom .agent_browser import ensure_agent_browser_runtime, print_agent_browser_setup_noticesfrom .base_engineer import BaseEngineer+from .runtime_commands import resolve_windows_commandfrom .tui import ClaudeUI_BRIDGE_DIR = Path(__file__).resolve().parent / "cursor_bridge"@@ -75,7 +76,7 @@ def _ensure_cursor_bridge_deps() -> str | None:return "npm not found in PATH (required to install @cursor/sdk for sdk=cursor)"try:subprocess.run(- [npm, "install", "--no-fund", "--no-audit"],+ resolve_windows_command([npm, "install", "--no-fund", "--no-audit"]),cwd=str(_BRIDGE_DIR),check=True,timeout=600,@@ -87,7 +88,7 @@ def _ensure_cursor_bridge_deps() -> str | None:except subprocess.CalledProcessError as e:tail = (e.stderr or e.stdout or "")[-2000:]return f"npm install in cursor_bridge failed: {tail or e}"- except (OSError, subprocess.TimeoutExpired) as e:+ except (OSError, ValueError, subprocess.TimeoutExpired) as e:return f"npm install in cursor_bridge failed: {e}"if not _SDK_MARKER.is_dir():return "@cursor/sdk did not install under cursor_bridge/node_modules"diff --git a/src/reverse_api/opencode_runtime.py b/src/reverse_api/opencode_runtime.pyindex 400fb9a..17c2876 100644--- a/src/reverse_api/opencode_runtime.py+++ b/src/reverse_api/opencode_runtime.py@@ -22,6 +22,7 @@ from urllib.parse import urlparseimport httpx2 as httpx+from .runtime_commands import resolve_windows_commandfrom .utils import get_config_pathDEFAULT_OPENCODE_BASE_URL = "http://127.0.0.1:4096"@@ -276,7 +277,10 @@ def _start_managed_server()package = opencode_npx_package()- argv = [npx, "-y", package, "serve", "--hostname", host, "--port", str(port)]+ try:+ argv = resolve_windows_command([npx, "-y", package, "serve", "--hostname", host, "--port", str(port)])+ except ValueError as e:+ raise OpenCodeSetupError(str(e)) from echild_env = os.environ.copy()child_env.update(desired_env)try:diff --git a/src/reverse_api/runtime_commands.py b/src/reverse_api/runtime_commands.pynew file mode 100644index 0000000..3cd659e--- /dev/null+++ b/src/reverse_api/runtime_commands.py@@ -0,0 +1,44 @@+"""Resolve Windows launchers without interpreting arguments as batch syntax."""++from __future__ import annotations++import re+import shutil+import sys+from pathlib import Path+++def resolve_windows_command(argv: list[str]) -> list[str]:+ """Prefer native npm/npx entrypoints, and reject unsafe batch fallbacks.++ CreateProcess does not search PATHEXT, while .cmd files can invoke cmd.exe+ even with shell=False. list2cmdline does not escape batch metacharacters.+ """+ if sys.platform == "win32":+ return _resolve_batch_command(argv)+ return argv+++def _resolve_batch_command(argv: list[str]) -> list[str]:+ executable = shutil.which(argv[0]) or argv[0]+ if Path(executable).suffix.lower() not in {".cmd", ".bat"}:+ return [executable, *argv[1:]]++ name = Path(executable).stem.lower()+ node = shutil.which("node")+ if name in {"npm", "npx"} and node and Path(node).suffix.lower() == ".exe":+ # Standard Node installs and npm's global Windows shims place npm here.+ for root in (Path(executable).parent, Path(node).parent):+ entrypoint = root / "node_modules" / "npm" / "bin" / f"{name}-cli.js"+ if entrypoint.is_file():+ return [node, str(entrypoint), *argv[1:]]++ # Maven and nonstandard shims have no universal native entrypoint. Never+ # silently interpret their paths/arguments as commands or variable expansion.+ if any(re.search(r'[&|<>^()%!"\r\n]', arg) for arg in [executable, *argv[1:]]):+ raise ValueError(+ "Cannot safely pass shell metacharacters to a Windows batch launcher. "+ "For npm/npx, use a Node.js installation with its native npm entrypoints; "+ "otherwise use a native executable or paths/arguments without batch metacharacters."+ )+ return [executable, *argv[1:]]diff --git a/tests/test_runtime_commands.py b/tests/test_runtime_commands.pynew file mode 100644index 0000000..1811f40--- /dev/null+++ b/tests/test_runtime_commands.py@@ -0,0 +1,67 @@+"""Keep Windows batch syntax out of user-supplied client arguments."""++import json+import shutil+import subprocess+import sys+from unittest.mock import patch++import pytest++from reverse_api.runtime_commands import resolve_windows_command++[email protected]("argument", ["a&b", "a|b", "%PATH%", "!PATH!", "(a)", "a^b", 'a"b', "a\nb", "a>b", "a<b"])+def test_batch_fallback_refuses_metacharacters(argument):+ with patch.object(sys, "platform", "win32"), patch("shutil.which", return_value=None):+ with pytest.raises(ValueError, match="Cannot safely"):+ resolve_windows_command(["tool.cmd", argument])+++def test_native_npx_receives_arguments_verbatim(tmp_path, monkeypatch):+ root = tmp_path / "Node & Tools"+ entrypoint = root / "node_modules/npm/bin/npx-cli.js"+ entrypoint.parent.mkdir(parents=True)+ entrypoint.touch()+ node = str(root / "node.exe")+ monkeypatch.setattr(shutil, "which", lambda command: node if command == "node" else None)+ args = ["https://example.com/?a=1&b=2|three", "%PATH%", '!literal!', 'quoted"text']+ with patch.object(sys, "platform", "win32"):+ result = resolve_windows_command([str(root / "npx.cmd"), *args])+ assert result == [node, str(entrypoint), *args]+++def test_batch_fallback_keeps_spaces_and_rejects_unsafe_launcher_path():+ with patch.object(sys, "platform", "win32"), patch("shutil.which", return_value=None):+ assert resolve_windows_command(["Maven Tools/mvn.cmd", "plain path/pom.xml"]) == ["Maven Tools/mvn.cmd", "plain path/pom.xml"]+ with pytest.raises(ValueError, match="Cannot safely"):+ resolve_windows_command(["Tools&More/mvn.cmd", "compile"])++[email protected](sys.platform != "win32", reason="requires native Windows process argument parsing")+def test_native_node_preserves_shell_characters(tmp_path):+ node = shutil.which("node")+ assert node, "Node.js must be available on Windows CI"+ entrypoint = tmp_path / "node_modules/npm/bin/npx-cli.js"+ entrypoint.parent.mkdir(parents=True)+ entrypoint.write_text("console.log(JSON.stringify(process.argv.slice(2)))", encoding="utf-8")+ launcher = tmp_path / "npx.cmd"+ # If the batch path runs, the test must fail rather than executing user input.+ launcher.write_text("@exit /b 99\n", encoding="ascii")+ arguments = ["https://example.com/?a=1&b=2|three", "%PATH%", "!literal!", 'quoted"text', "中文", "a path with spaces"]+ argv = resolve_windows_command([str(launcher), *arguments])+ result = subprocess.run(argv, capture_output=True, encoding="utf-8", check=True)+ assert json.loads(result.stdout) == arguments++[email protected](sys.platform != "win32", reason="requires native Windows npm argument forwarding")+def test_real_npx_preserves_client_arguments(tmp_path):+ npx = shutil.which("npx")+ assert npx, "npx must be available on Windows CI"+ script = tmp_path / "echo args.js"+ script.write_text("console.log(JSON.stringify(process.argv.slice(2)))", encoding="utf-8")+ arguments = ["https://example.com/?a=1&b=2|three", "%PATH%", "!literal!", 'quoted"text', "中文"]+ argv = resolve_windows_command([npx, "--offline", "--", "node", str(script), *arguments])+ assert argv[0].lower().endswith("node.exe"), "must bypass the batch shim"+ result = subprocess.run(argv, capture_output=True, encoding="utf-8", check=True, timeout=30)+ assert json.loads(result.stdout) == arguments