Skip to content

The agent that grows with you

fix(browser): eval scripts reach a Windows .cmd shim base64-encoded; tests trimmed

teknium135a03bce1437
diff --git a/tests/tools/test_browser_eval_shim_args.py b/tests/tools/test_browser_eval_shim_args.py
new file mode 100644
index 00000000000..ed16c0e929a
--- /dev/null
+++ b/tests/tools/test_browser_eval_shim_args.py
@@ -0,0 +1,42 @@
+"""agent-browser CLI ``eval`` payloads must survive the Windows ``.cmd`` shim hop (#113838):
+cmd.exe re-parses the child command line, so a newline truncates the script to its first line.
+Host-specific bug — these are code-path invariants that run on every host."""
+
+from __future__ import annotations
+
+import base64
+import importlib
+import pkgutil
+
+import tools
+from tools import browser_tool_session as bt_session
+
+_SCRIPT = "JSON.stringify(\n [...document.images].map(i => i.src)\n)"
+
+
+def test_cmd_shim_sends_eval_script_base64_and_others_raw():
+ """A ``.cmd``/``.bat`` argv[0] gets ``--base64 <script>`` (lossless through cmd.exe); a
+ native binary, npx sentinel-expanded or POSIX path keeps the raw script; non-eval untouched."""
+ shim = bt_session._shim_safe_eval_args(r"C:\Users\u\AppData\Roaming\npm\npx.CMD", "eval", [_SCRIPT])
+ assert shim[0] == "--base64"
+ assert base64.b64decode(shim[1]).decode("utf-8") == _SCRIPT # byte-identical round trip
+ assert "\n" not in shim[1]
+
+ for argv0 in (r"C:\tools\agent-browser.exe", "/home/u/.local/bin/agent-browser", "npx"):
+ assert bt_session._shim_safe_eval_args(argv0, "eval", [_SCRIPT]) == [_SCRIPT]
+ assert bt_session._shim_safe_eval_args("npx.cmd", "open", ["https://example.com"]) == ["https://example.com"]
+
+
+def test_bundled_js_eval_payload_constants_are_single_line():
+ """Every ``*_JS`` string constant in ``tools/browser_*`` is one line — the fixed
+ ``_GET_IMAGES_JS`` and any future payload handed to the CLI ``eval`` as one argv element."""
+ seen = []
+ for mod_info in pkgutil.iter_modules(tools.__path__):
+ if not mod_info.name.startswith("browser_"):
+ continue
+ module = importlib.import_module(f"tools.{mod_info.name}")
+ for name, value in vars(module).items():
+ if name.endswith("_JS") and isinstance(value, str):
+ seen.append((mod_info.name, name))
+ assert "\n" not in value, f"tools/{mod_info.name}.py::{name} spans multiple lines"
+ assert ("browser_tool", "_GET_IMAGES_JS") in seen
diff --git a/tests/tools/test_browser_get_images_ssrf.py b/tests/tools/test_browser_get_images_ssrf.py
index 7e05dd8f016..8359d800358 100644
--- a/tests/tools/test_browser_get_images_ssrf.py
+++ b/tests/tools/test_browser_get_images_ssrf.py
@@ -83,27 +83,3 @@ def test_guard_does_not_block_on_failed_eval(monkeypatch):
result = json.loads(browser_tool.browser_get_images(task_id="test"))
assert result["success"] is False
assert "eval failed" in result["error"]
-
-
-def test_get_images_sends_single_line_eval_and_parses_images(monkeypatch):
- """Regression for #113838: Windows CLI transport must receive one eval argument."""
- captured = {}
-
- def _run(task_id, command, args=None, **kwargs):
- captured["task_id"] = task_id
- captured["command"] = command
- captured["args"] = args
- return {"success": True, "data": {"result": IMAGES_JS_RESULT}}
-
- monkeypatch.setattr(bt_session, "_run_browser_command", _run)
- monkeypatch.setattr(bt_eval_policy, "_eval_ssrf_guard_active", lambda tid: False)
-
- result = json.loads(browser_tool.browser_get_images(task_id="test"))
-
- assert captured["command"] == "eval"
- assert "\n" not in captured["args"][0]
- assert result == {
- "success": True,
- "images": json.loads(IMAGES_JS_RESULT),
- "count": 1,
- }
diff --git a/tools/browser_tool_session.py b/tools/browser_tool_session.py
index 4b9b353b3e0..75e27b2548c 100644
--- a/tools/browser_tool_session.py
+++ b/tools/browser_tool_session.py
@@ -4,6 +4,7 @@
Split out of ``tools/browser_tool.py``. Facade-owned state is read through ``_bt`` (``tools.browser_tool``, resolved per call) — no import cycle.
"""
+import base64
import json
import logging
import os
@@ -108,6 +109,19 @@ def _agent_browser_argv(browser_cmd: str) -> list:
return [browser_cmd]
+def _shim_safe_eval_args(argv0: str, command: str, args: List[str]) -> List[str]:
+ """``eval`` scripts that reach a ``.cmd``/``.bat`` shim (``npx.cmd``, npm's ``agent-browser.cmd``
+ on Windows) go through cmd.exe, which re-parses the child command line: a newline ends the
+ argument and ``%VAR%`` expands even inside quotes, so a multi-line script arrives as its first
+ line only (``SyntaxError: Unexpected end of input``). Send the script base64-encoded
+ (``agent-browser eval -b``, present since the 0.26 floor) so it arrives byte-identical;
+ every other spawn target gets the raw argv."""
+ if command != "eval" or not args or not argv0.lower().endswith((".cmd", ".bat")):
+ return args
+ script, *rest = args
+ return ["--base64", base64.b64encode(script.encode("utf-8")).decode("ascii"), *rest]
+
+
def _prepare_session_socket_dir(session_name: str) -> str:
"""Create the per-session socket dir (parallel workers must not share one) and claim it
with our PID BEFORE first use — another hermes process's orphan reaper rmtree's any
@@ -592,7 +606,8 @@ def _run_browser_command(
if engine != "auto" and not _bt._is_camofox_mode():
backend_args += ["--engine", engine]
- cmd_parts = _agent_browser_argv(browser_cmd) + backend_args + ["--json", command] + args
+ argv = _agent_browser_argv(browser_cmd)
+ cmd_parts = argv + backend_args + ["--json", command] + _shim_safe_eval_args(argv[0], command, args)
try:
result = _spawn_and_collect(task_id, session_info, cmd_parts, command, engine, timeout)