The agent that turns websites into APIs!
fix(windows): preserve BOM files and safe Maven project paths
kalil03218b9899021afa
diff --git a/src/reverse_api/cli.py b/src/reverse_api/cli.pyindex 0e4a1b7..25c54ba 100644--- a/src/reverse_api/cli.py+++ b/src/reverse_api/cli.py@@ -3036,7 +3036,18 @@ def _run_script_machine_payload(if sys.platform == "win32":from .runtime_commands import resolve_windows_command- steps[0] = resolve_windows_command([executable, *steps[0][1:]])+ try:+ steps[0] = resolve_windows_command([executable, *steps[0][1:]])+ except ValueError as e:+ return _build_run_payload(+ identifier=identifier,+ run_id=run_id,+ script_path=str(script),+ script_args=script_args,+ scripts=scripts,+ error=str(e),+ error_kind_hint="config_invalid",+ )binary_result = Nonefor cmd in steps:emit_event("process_started", run_id=run_id, script_path=str(script))diff --git a/src/reverse_api/config.py b/src/reverse_api/config.pyindex efc216a..a77bf34 100644--- a/src/reverse_api/config.py+++ b/src/reverse_api/config.py@@ -46,7 +46,7 @@ class ConfigManager:"""Load configuration from disk."""if self.config_path.exists():try:- with open(self.config_path, encoding="utf-8") as f:+ with open(self.config_path, encoding="utf-8-sig") as f:user_config = json.load(f)# Backward compatibility: migrate old config keysdiff --git a/src/reverse_api/session.py b/src/reverse_api/session.pyindex f0c5828..7932f11 100644--- a/src/reverse_api/session.py+++ b/src/reverse_api/session.py@@ -17,7 +17,7 @@ class SessionManager:"""Load history from disk."""if self.history_path.exists():try:- with open(self.history_path, encoding="utf-8") as f:+ with open(self.history_path, encoding="utf-8-sig") as f:self.history = json.load(f)except (json.JSONDecodeError, UnicodeError, OSError):# Fallback to empty history if file is corrupteddiff --git a/src/reverse_api/utils.py b/src/reverse_api/utils.pyindex 00b3b9a..c641a06 100644--- a/src/reverse_api/utils.py+++ b/src/reverse_api/utils.py@@ -783,9 +783,9 @@ def build_script_commands(script: Path, script_args: tuple[str, ...] = ()) -> tu"""Build the subprocess command(s) that run a non-Python generated client.Python clients are executed by the caller's shared-venv flow and are not- handled here. Commands use absolute paths so they work from any cwd; run- them with cwd=script.parent so relative artifacts (cookie jars, build- output) land next to the script.+ handled here. Run commands with cwd=script.parent so relative artifacts (cookie jars,+ build output) land next to the script. Maven deliberately uses a relative+ pom.xml to keep user directory names out of Windows batch arguments.Args:script: Path to the client script (any supported non-.py extension)@@ -818,7 +818,7 @@ def build_script_commands(script: Path, script_args: tuple[str, ...] = ()) -> tu"script arguments are not supported for Java clients: ""mvn exec:exec's program arguments are fixed in the pom.xml")- return [["mvn", "-q", "-f", str(d / "pom.xml"), "compile", "exec:exec"]], "mvn"+ return [["mvn", "-q", "-f", "pom.xml", "compile", "exec:exec"]], "mvn"if suffix == ".cs":cmd = ["dotnet", "run", "--project", str(d / "ApiClient.csproj")]if script_args:diff --git a/tests/test_run_command.py b/tests/test_run_command.pyindex 5b4ed62..9b5d6a7 100644--- a/tests/test_run_command.py+++ b/tests/test_run_command.py@@ -767,7 +767,7 @@ class TestBuildScriptCommands:from reverse_api.utils import build_script_commandsscript = tmp_path / "api_client.java"steps, tool = build_script_commands(script)- assert steps == [["mvn", "-q", "-f", str(tmp_path / "pom.xml"), "compile", "exec:exec"]]+ assert steps == [["mvn", "-q", "-f", "pom.xml", "compile", "exec:exec"]]assert tool == "mvn"def test_java_rejects_script_args(self, tmp_path):diff --git a/tests/test_windows_compatibility.py b/tests/test_windows_compatibility.pyindex 6acf91f..57a517c 100644--- a/tests/test_windows_compatibility.py+++ b/tests/test_windows_compatibility.py@@ -64,16 +64,17 @@ def test_nested_prompt_includes_under_legacy_locale(tmp_path, legacy_locale, monassert load("main", value="done") == f"{UNICODE_TEXT} done"-def test_unicode_persistence_under_legacy_locale(tmp_path, legacy_locale):[email protected]("encoding", ["utf-8", "utf-8-sig"])+def test_unicode_persistence_under_legacy_locale(tmp_path, legacy_locale, encoding):config_path = tmp_path / "config.json"- config_path.write_text(json.dumps({"agent_browser_notes": UNICODE_TEXT}, ensure_ascii=False), encoding="utf-8")+ config_path.write_text(json.dumps({"agent_browser_notes": UNICODE_TEXT}, ensure_ascii=False), encoding=encoding)config = ConfigManager(config_path)assert config.get("agent_browser_notes") == UNICODE_TEXTconfig.save()assert ConfigManager(config_path).get("agent_browser_notes") == UNICODE_TEXThistory_path = tmp_path / "history.json"- history_path.write_text(json.dumps([{"run_id": "test", "prompt": UNICODE_TEXT}], ensure_ascii=False), encoding="utf-8")+ history_path.write_text(json.dumps([{"run_id": "test", "prompt": UNICODE_TEXT}], ensure_ascii=False), encoding=encoding)session = SessionManager(history_path)assert session.get_run("test")["prompt"] == UNICODE_TEXTsession.save()@@ -271,3 +272,61 @@ def test_native_windows_cmd_probe(tmp_path, monkeypatch):launcher.write_bytes(b"@echo off\r\necho help\r\nexit /b 0\r\n")monkeypatch.setenv("PATH", str(tmp_path))assert _probe_help_argv(["probe"]) is None++[email protected]("machine", [False, True])+def test_windows_batch_rejection_is_configuration_error(tmp_path, monkeypatch, machine):+ import click++ from reverse_api import cli++ script = tmp_path / "api_client.ts"+ script.touch()+ monkeypatch.setattr("shutil.which", lambda _: "custom.cmd")+ monkeypatch.setattr(cli, "resolve_run", lambda *args, **kwargs: {"run_id": "test"})+ monkeypatch.setattr(cli, "discover_scripts", lambda *args, **kwargs: [script])+ with patch.object(sys, "platform", "win32"), patch.object(subprocess, "run") as run:+ if machine:+ payload = cli._run_script_machine_payload(+ identifier="test", script_args=("a&b",), file_name=None,+ list_scripts=False, auto_install=False, emit_event=lambda *a, **kw: None,+ )+ assert payload["error_kind"] == "config_invalid"+ assert "Cannot safely" in payload["error"]+ else:+ with pytest.raises(click.ClickException, match="Cannot safely"):+ cli._run_non_python_script(script, ("a&b",))+ run.assert_not_called()++[email protected](sys.platform != "win32", reason="requires native Windows batch execution")[email protected]("machine", [False, True])+def test_windows_maven_uses_relative_pom_in_special_directory(tmp_path, monkeypatch, machine):+ from reverse_api import cli++ project = tmp_path / "dev (ops) %PATH% !name! & 中文"+ project.mkdir()+ script = project / "api_client.java"+ script.touch()+ (project / "pom.xml").write_text("<project/>", encoding="utf-8")+ launcher = tmp_path / "mvn.cmd"+ # A real batch process verifies argv and the working directory without a+ # Maven dependency download; this is a launcher contract, not a Java build.+ launcher.write_bytes(+ b'@echo off\r\nif not exist pom.xml exit /b 98\r\n'+ b'if not "%~3"=="pom.xml" exit /b 99\r\necho relative-pom-ok\r\nexit /b 0\r\n'+ )+ monkeypatch.setattr("shutil.which", lambda command: str(launcher) if command == "mvn" else None)+ monkeypatch.setattr(cli, "resolve_run", lambda *args, **kwargs: {"run_id": "test"})+ monkeypatch.setattr(cli, "discover_scripts", lambda *args, **kwargs: [script])+ if machine:+ payload = cli._run_script_machine_payload(+ identifier="test", script_args=(), file_name=None,+ list_scripts=False, auto_install=False, emit_event=lambda *a, **kw: None,+ )+ assert payload["status"] == "ok", payload+ assert payload["stdout"].strip() == "relative-pom-ok"+ else:+ with pytest.raises(SystemExit) as exit_info:+ cli._run_non_python_script(script, ())+ assert exit_info.value.code == 0