Skip to content

The agent that grows with you

fix(browser): route any newline/% argument past a Windows .cmd shim losslessly

teknium16c9e583860ad
diff --git a/tests/tools/test_browser_eval_shim_args.py b/tests/tools/test_browser_eval_shim_args.py
index ed16c0e929a..39a2a7f7bf3 100644
--- a/tests/tools/test_browser_eval_shim_args.py
+++ b/tests/tools/test_browser_eval_shim_args.py
@@ -1,30 +1,61 @@
-"""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."""
+"""agent-browser CLI arguments must survive the Windows ``.cmd`` shim hop (#113838): cmd.exe
+re-parses the child command line, so a newline truncates an argument to its first line and
+``%VAR%`` expands. Host-specific bug — these are code-path invariants that run on every host."""
from __future__ import annotations
import base64
import importlib
+import json
import pkgutil
import tools
from tools import browser_tool_session as bt_session
_SCRIPT = "JSON.stringify(\n [...document.images].map(i => i.src)\n)"
+_TEXT = "line one\nline two %PATH% 100%"
+_SHIM = r"C:\Users\u\AppData\Roaming\npm\agent-browser.CMD"
-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]
+def _run_through_seam(monkeypatch, browser_cmd: str, command: str, args: list, stdout: str) -> tuple:
+ """Drive ``_run_browser_command`` up to the spawn with ``_spawn_and_collect`` captured; returns
+ ``(cmd_parts, stdin_payload, result)`` so the wiring — not just the helper — is under test."""
+ captured: dict = {}
- 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 fake_spawn(task_id, session_info, cmd_parts, cmd, engine, timeout, stdin_payload=None):
+ captured.update(cmd_parts=cmd_parts, stdin=stdin_payload)
+ return bt_session._interpret_browser_command_output(cmd, stdout, "", 0)
+
+ monkeypatch.setattr(bt_session, "_browser_command_preflight", lambda: {"browser_cmd": browser_cmd})
+ monkeypatch.setattr(bt_session, "_get_session_info", lambda task_id: {"session_name": "s", "cdp_url": None})
+ monkeypatch.setattr(bt_session._cloud, "_get_browser_engine", lambda: "auto")
+ monkeypatch.setattr(bt_session._cloud, "_is_headed_mode", lambda: False)
+ monkeypatch.setattr(bt_session, "_spawn_and_collect", fake_spawn)
+ result = bt_session._run_browser_command("t", command, args, timeout=5)
+ return captured["cmd_parts"], captured["stdin"], result
+
+
+def test_cmd_shim_routes_eval_and_multiline_text_losslessly(monkeypatch):
+ """Through ``_run_browser_command``: a ``.cmd`` argv[0] sends ``eval`` as ``--base64 <script>``
+ and any other command whose argv carries a newline or ``%`` as ``batch`` with the command as
+ JSON on stdin (cmd.exe never parses the text), with the batch entry unwrapped to the usual
+ ``{success, data, error}`` shape; plain arguments and non-shim spawns keep the raw argv."""
+ parts, stdin, _ = _run_through_seam(monkeypatch, _SHIM, "eval", [_SCRIPT], '{"success":true,"data":{"result":1}}')
+ assert parts[-3:-1] == ["eval", "--base64"] and stdin is None
+ assert base64.b64decode(parts[-1]).decode("utf-8") == _SCRIPT # byte-identical round trip
+
+ batch_out = json.dumps([{"command": ["fill", "@e3", _TEXT], "error": None,
+ "result": {"filled": "@e3"}, "success": True}])
+ parts, stdin, result = _run_through_seam(monkeypatch, _SHIM, "fill", ["@e3", _TEXT], batch_out)
+ assert parts[-1] == "batch" and not any(("\n" in p or "%" in p) for p in parts)
+ assert json.loads(stdin) == [["fill", "@e3", _TEXT]]
+ assert result == {"success": True, "data": {"filled": "@e3"}, "error": None}
+
+ parts, stdin, _ = _run_through_seam(monkeypatch, _SHIM, "fill", ["@e3", "one line"], '{"success":true,"data":{}}')
+ assert parts[-3:] == ["fill", "@e3", "one line"] and stdin is None
+ for argv0 in (r"C:\tools\agent-browser.exe", "/home/u/.local/bin/agent-browser"):
+ parts, stdin, _ = _run_through_seam(monkeypatch, argv0, "fill", ["@e3", _TEXT], '{"success":true,"data":{}}')
+ assert parts[-3:] == ["fill", "@e3", _TEXT] and stdin is None
def test_bundled_js_eval_payload_constants_are_single_line():
diff --git a/tools/browser_tool_session.py b/tools/browser_tool_session.py
index 75e27b2548c..144d8763ac0 100644
--- a/tools/browser_tool_session.py
+++ b/tools/browser_tool_session.py
@@ -109,17 +109,35 @@ 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 _shim_safe_args(argv0: str, command: str, args: List[str]) -> "tuple[str, List[str], Optional[bytes]]":
+ """``(spawn_command, spawn_args, stdin_payload)`` for one CLI command. Arguments 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 ``eval`` script arrives as its first line only (``SyntaxError:
+ Unexpected end of input``) and multi-line ``fill`` text is truncated the same way. ``eval``
+ scripts are sent base64-encoded (``agent-browser eval -b``); any other command whose argv carries
+ a newline or ``%`` is wrapped as ``batch`` with the command as a JSON array on stdin — cmd.exe
+ never sees the text (both forms present since the 0.26 floor). Every other spawn gets the raw
+ argv and no stdin."""
+ if not args or not argv0.lower().endswith((".cmd", ".bat")):
+ return command, args, None
+ if command == "eval":
+ script, *rest = args
+ return command, ["--base64", base64.b64encode(script.encode("utf-8")).decode("ascii"), *rest], None
+ if command == "batch" or not any(ch in arg for arg in args for ch in "\r\n%"):
+ return command, args, None
+ return "batch", [], json.dumps([[command, *args]]).encode("utf-8")
+
+
+def _unwrap_batch_result(result: Any, command: str) -> Dict[str, Any]:
+ """``batch --json`` prints ``[{command, success, result, error}]``; reshape the single entry
+ into the ``{success, data, error}`` dict every other command returns. Error dicts pass through."""
+ if not isinstance(result, list):
+ return result
+ if len(result) != 1 or not isinstance(result[0], dict):
+ return {"success": False, "error": f"Unexpected batch output for '{command}': {json.dumps(result)[:300]}"}
+ entry = result[0]
+ return {"success": bool(entry.get("success")), "data": entry.get("result"), "error": entry.get("error")}
def _prepare_session_socket_dir(session_name: str) -> str:
@@ -144,8 +162,10 @@ def _agent_browser_command_env(socket_dir: str) -> Dict[str, str]:
return env
-def _popen_agent_browser(argv: List[str], env: Dict[str, str], socket_dir: str, tag: str) -> "subprocess.Popen":
- """Spawn agent-browser with stdout/stderr redirected to ``socket_dir/_std{out,err}_<tag>``.
+def _popen_agent_browser(argv: List[str], env: Dict[str, str], socket_dir: str, tag: str,
+ stdin_payload: Optional[bytes] = None) -> "subprocess.Popen":
+ """Spawn agent-browser with stdout/stderr redirected to ``socket_dir/_std{out,err}_<tag>``;
+ ``stdin_payload`` (a ``batch`` JSON body) is served from ``_stdin_<tag>`` the same way.
Temp files, not pipes: the CLI forks a daemon that inherits its fds, so pipes never
see EOF until the timeout. Windows: CREATE_NO_WINDOW only (CREATE_NEW_PROCESS_GROUP
@@ -154,13 +174,20 @@ def _popen_agent_browser(argv: List[str], env: Dict[str, str], socket_dir: str,
"""
fds = [os.open(os.path.join(socket_dir, f"_{slot}_{tag}"), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
for slot in ("stdout", "stderr")]
+ stdin: Any = subprocess.DEVNULL
+ if stdin_payload is not None:
+ stdin_path = os.path.join(socket_dir, f"_stdin_{tag}")
+ with open(stdin_path, "wb") as f:
+ f.write(stdin_payload)
+ fds.append(os.open(stdin_path, os.O_RDONLY))
+ stdin = fds[-1]
try:
_popen_extra: dict = {}
if os.name == "nt":
_si = subprocess.STARTUPINFO()
_si.dwFlags |= subprocess.STARTF_USESTDHANDLES
_popen_extra = {"creationflags": windows_hide_flags(), "close_fds": True, "startupinfo": _si}
- return subprocess.Popen(argv, stdout=fds[0], stderr=fds[1], stdin=subprocess.DEVNULL, env=env, **_popen_extra)
+ return subprocess.Popen(argv, stdout=fds[0], stderr=fds[1], stdin=stdin, env=env, **_popen_extra)
finally:
for fd in fds:
os.close(fd)
@@ -520,7 +547,7 @@ def _browser_command_preflight() -> Dict[str, Any]:
def _spawn_and_collect(
task_id: str, session_info: Dict[str, Any], cmd_parts: List[str],
- command: str, engine: str, timeout: int,
+ command: str, engine: str, timeout: int, stdin_payload: Optional[bytes] = None,
) -> Dict[str, Any]:
"""Run the prepared agent-browser argv once and interpret its output (handles timeout)."""
task_socket_dir = _prepare_session_socket_dir(session_info["session_name"])
@@ -541,7 +568,7 @@ def _spawn_and_collect(
stdout_path = os.path.join(task_socket_dir, f"_stdout_{command}")
stderr_path = os.path.join(task_socket_dir, f"_stderr_{command}")
- proc = _popen_agent_browser(cmd_parts, browser_env, task_socket_dir, command)
+ proc = _popen_agent_browser(cmd_parts, browser_env, task_socket_dir, command, stdin_payload)
try:
proc.wait(timeout=timeout)
@@ -607,10 +634,12 @@ def _run_browser_command(
backend_args += ["--engine", engine]
argv = _agent_browser_argv(browser_cmd)
- cmd_parts = argv + backend_args + ["--json", command] + _shim_safe_eval_args(argv[0], command, args)
+ spawn_command, spawn_args, stdin_payload = _shim_safe_args(argv[0], command, args)
+ cmd_parts = argv + backend_args + ["--json", spawn_command] + spawn_args
try:
- result = _spawn_and_collect(task_id, session_info, cmd_parts, command, engine, timeout)
+ result = _unwrap_batch_result(
+ _spawn_and_collect(task_id, session_info, cmd_parts, command, engine, timeout, stdin_payload), command)
except Exception as e:
_bt.logger.warning("browser '%s' exception: %s", command, e, exc_info=True)
result = {"success": False, "error": str(e)}