Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(cua-driver-bench): publish the agent-desktop, Browser Use harness and Codex computer-use arm adapters (#6629)
Francesco Bonacci67b86c9b22f4
diff --git a/libs/cua-driver-bench/METHOD.md b/libs/cua-driver-bench/METHOD.mdindex 427bf2fa3d..cf0b564cb3 100644--- a/libs/cua-driver-bench/METHOD.md+++ b/libs/cua-driver-bench/METHOD.md@@ -261,6 +261,17 @@ differences are directional only.compare setups within a platform, not across platforms. The Windows releaserun covers the seven BenchLab tasks (MB-09, MB-10, MB-11, IR-01 to IR-04); itdoes not include CDB-G02 to CDB-G04.+* **Vendor setups are driven through Cua's adapters.** agent-desktop, the Browser Use+ harnesses and OpenAI's computer-use plugin are not built for Claude Code as their+ client, so each is run through a small adapter in `automated-eval/macos_bench/tools/`+ (`agent_desktop`, `browser_use_harness`, `codex_cu`). The adapters map each tool or+ command one to one and add no behaviour; the vendor's own skill or help text is the+ server instructions. The Codex setup is OpenAI's plugin with Claude choosing the+ actions, not OpenAI's own agent, and it needs the reader's own ChatGPT sign-in (Work or+ Codex access) and the ChatGPT desktop app with Computer Use enabled. It is not+ available on Linux yet and runs foreground only on Windows. A setup's result says how+ well that tool layer works under this client and prompt, not how well the vendor's own+ agent works.* **Driver versions are named per platform.** The release tables name theversion of each tool layer, and a table never mixes versions silently. macOS,foreground and background alike: Cua Driver 0.38.0, agent-desktop 1.2.0 anddiff --git a/libs/cua-driver-bench/README.md b/libs/cua-driver-bench/README.mdindex c1798d95d5..522068d304 100644--- a/libs/cua-driver-bench/README.md+++ b/libs/cua-driver-bench/README.md@@ -192,6 +192,8 @@ the agent harness and model are not confounded with the tool layer:| **Cua Driver**, driven by Claude Code | Run | Cua Driver's MCP server, with its skill and `run_script` on (Cua Driver 0.35 defaults), built from a pinned main commit (arm `cc-cua-driver-script`) || **Codex Computer-Use (Sky)**, driven by Claude Code | Run | OpenAI's `cua_repl` launcher from the ChatGPT app 26.930 plugin, talking to OpenAI's Sky computer-use service, registered in Claude Code as MCP server `codex-cu` (arm `cc-codex-cu`). Claude chooses the actions through this MCP bridge; OpenAI's model is not involved. || **Claude Computer-Use (Desktop helper): Claude Desktop 2.31226.0 computer-use helper via a minimal adapter; an internal interface, not an Anthropic-supported procedure** | Run | The `app-cu-helper` binary of Claude Desktop 2.31226.0, used unmodified in place, behind Cua's small MCP adapter ([`tools/claude_cu_helper/`](automated-eval/macos_bench/tools/claude_cu_helper)), registered in Claude Code as MCP server `claude-cu-helper` (arm `cc-claude-cu-helper`). The adapter adds a window list and window screenshots; all input goes through the helper. |+| **Vercel agent-desktop**, driven by Claude Code | Run (macOS and Windows) | agent-desktop 1.2.0 (Vercel Labs, Apache-2.0), an accessibility-tree CLI, behind Cua's small MCP adapter ([`tools/agent_desktop/`](automated-eval/macos_bench/tools/agent_desktop)): one MCP tool per CLI command, MCP server `agentdesktop` (arm `cc-agent-desktop`). The vendor skill text is the server instructions. |+| **Browser Use harness**, driven by Claude Code | Run (macOS and Windows) | The Browser Use macOS harness 0.2.1 or Windows harness 0.2.2 behind Cua's small MCP adapter ([`tools/browser_use_harness/`](automated-eval/macos_bench/tools/browser_use_harness)): one `macos_harness` (or `windows_harness`) tool that takes the vendor's own command line, plus `view_screenshot`; MCP server `browseruse` (arm `cc-browser-use`). The vendor skill is the server instructions. || **Cua Driver**, driven by Codex CLI | Planned (Amendment 23, not yet run) | The same Cua Driver build, daemon, MCP entry and system prompt as `cc-cua-driver-script`, driven by the Codex CLI bundled with the ChatGPT app, run as `codex app-server` (arm `cx-cua-driver`). No skill files: without a shell or file tool Codex cannot read one. No numbers yet. || **Codex Computer-Use (Sky)**, driven by Codex CLI | Planned (Amendments 20 and 23, not yet run) | The same Codex tool layer driven by OpenAI's own agent and model, with the same prompts, approvals, limits, guard and checkers (arm `cx-codex-cu`). No numbers yet. || **Claude Computer-Use (Desktop helper): Claude Desktop 2.31226.0 computer-use helper via a minimal adapter; an internal interface, not an Anthropic-supported procedure**, driven by Codex CLI | Planned (Amendment 23, not yet run) | The same helper, adapter and MCP entry as `cc-claude-cu-helper`, driven by the Codex CLI (arm `cx-claude-cu-helper`). No numbers yet. |@@ -274,6 +276,9 @@ doneThe launcher wraps both helper and capture; Terminal, the adapter and launcherreceive no new grants. No Claude Desktop binary,app code or asset is included in this repository; only Cua's adapter is.+* **Vercel agent-desktop** (arm `cc-agent-desktop`). In the VM, `npm install --prefix "$CDB_BENCH_WORK/agent-desktop" [email protected] --allow-scripts=agent-desktop` (npm 11; the package carries the prebuilt binaries and the install script only links the one for your platform). Give the `agent-desktop` binary Accessibility and Screen Recording in System Settings. Check it with `"$CDB_BENCH_WORK/agent-desktop/node_modules/.bin/agent-desktop" --version`. To use a binary elsewhere, set `CDB_AGENT_DESKTOP_BIN`. The adapter is `tools/agent_desktop/ad_mcp.py`; its `ad-instructions.md` is the skill text from the agent-desktop package (Apache-2.0, Vercel Labs), unmodified. The adapter offers the observe, act, window, clipboard and wait commands, and leaves out the skills, session, trace, notification, permission and system-surface commands. Physical input (`headed`) is the model's choice on the tools that can move the pointer, and forced on the tools that only exist as pointer input (`hover`, `drag`, `mouse_*`).+* **Browser Use macOS harness** (arm `cc-browser-use`). In the VM, `python3 -m venv "$CDB_BENCH_WORK/browser-use-harness/venv" && "$CDB_BENCH_WORK/browser-use-harness/venv/bin/pip" install macos-harness==0.2.1`, then run `macos-harness doctor` once by hand and approve what it asks for (Accessibility and Screen Recording for the helper it starts); the adapter refuses `doctor`, `install` and `approve` so the model cannot change the setup. Set `CDB_MACOS_HARNESS_BIN` to use another install. The adapter `tools/browser_use_harness/bu_mcp.py` reads the skill from `macos-harness skill`, so the instructions always match the installed version. `BU_SHOT=always` attaches the screenshot to every `get_app_state`; the default is the vendor's: only when the model opens the file named on the `Screenshot` line.+* **Codex Computer-Use (Sky): what you need before it works.** This arm drives OpenAI's computer-use plugin from the ChatGPT desktop app. It needs the ChatGPT desktop app with **Computer Use enabled** (Settings → Computer use → Any App) and you must sign in with **your own ChatGPT account that has Work or Codex access** (the app sign-in, or `codex login --device-auth` for the bundled Codex CLI). No credentials are shipped here or read by the harness. It is OpenAI's plugin with Claude choosing the actions through an MCP bridge, not OpenAI's own agent: the numbers describe the plugin as a tool layer under Claude Sonnet 5.5, not what OpenAI's agent can do with it. It is not available on Linux yet ([compatibility and limitations](https://learn.chatgpt.com/docs/linux/linux-app#compatibility-and-limitations)), and on Windows it runs foreground only ([Computer Use](https://learn.chatgpt.com/docs/computer-use)). The macOS release run used ChatGPT app 26.930; the Windows run used the ChatGPT/Codex app 26.1029.9216.0.* **Codex CLI setups** (arms `cx-codex-cu`, `cx-cua-driver`, `cx-claude-cu-helper`). Nothing extra to install beyond the matching Claude Code setup: they use the Codex CLI bundled in the same ChatGPT app (`Contents/Resources/codex-cli/CodexCLI.app`) and the MCP config of the matching Claude Code setup (`cc-codex-cu`, `cc-cua-driver-script` or `cc-claude-cu-helper`). Point `CDB_CODEX_GATEWAY` at an OpenAI-compatible Responses endpoint serving `gpt-6.1-sol` (default `http://127.0.0.1:4000/v1`). The pinned CLI build is in `pins.json` (`codex_native`).**Terms checks (open).** Two questions have not been reviewed:@@ -344,6 +349,12 @@ launch/linux_session.sh --evidence "$CDB_BENCH_WORK/evidence" -- <runner command```Seeds, the state file, the event log, the checkers and the sentinel summary are the same as on macOS.++Of the comparison setups, agent-desktop runs on Linux (`npm install [email protected]`, then+`run_bench.py --arms cc-agent-desktop` inside the session; the adapter is platform-neutral, but the release+tables do not include a Linux agent-desktop run). The Browser Use harnesses exist for macOS and Windows only, and+Codex computer use is not available on Linux yet+([compatibility and limitations](https://learn.chatgpt.com/docs/linux/linux-app#compatibility-and-limitations)).`tests/test_linux_session.py` and `tests/test_linux_tools.py` check the session and the tools without a model.### Windows (the BenchLab tasks)@@ -370,6 +381,35 @@ each task through the GUI with real input; `tests/test_windows_desktop.py` checkevery task, that doing nothing fails and leaves the user undisturbed, and that a deliberate disturbanceis seen.+#### The comparison setups on Windows++Each setup is one stdio MCP server in an `--mcp-config` file, run in the same interactive desktop session as the+trial. The adapters and the filter are in `automated-eval/macos_bench/tools/`; paths below are examples.++| Setup | Install | MCP server command |+| --- | --- | --- |+| agent-desktop 1.2.0 | `npm install [email protected]` (prebuilt `win32-x64` binary included) | `python -I -B tools\agent_desktop\ad_mcp.py` with `AD_BIN=<...>\node_modules\agent-desktop\bin\agent-desktop-win32-x64.exe` (agent-desktop 1.2.0 also has its own `mcp` subcommand; the Windows release run used that one) |+| Browser Use Windows harness 0.2.2 | `pip install "git+https://github.com/browser-use/windows-harness@46a37cf1d411c7816adffc274d5bdc2cca2bd9f0"` | `python -I -B tools\browser_use_harness\wh_mcp.py` with `WH_BIN=<...>\Scripts\windows-harness.exe` |+| Codex Computer-Use (ChatGPT/Codex app 26.1029.9216.0) | Install the app, enable Computer Use, sign in with your own ChatGPT account with Work or Codex access | `python tools\codex_cu\codex_cu_filter.py --allow BenchLab --windows-app "<app dir>\resources"` |++For Codex on Windows the filter does four things the plugin expects of the ChatGPT app and Claude Code does not+do: it adds the sandbox metadata to tool calls, answers the per-app approval prompt (accepting only apps on+`--allow`, here BenchLab, and declining everything else), answers Claude Code's `server/discover` probe locally,+and flattens the `js` tool's top-level `oneOf` input schema, which the Anthropic API rejects. Computer Use runs+foreground only on Windows, so run the foreground condition for it; the Windows release tables mark it that way.++A config file looks like this (server names are the ones the runner and the analysis expect: `agentdesktop`,+`browseruse`, `codex-cu`):++```json+{"mcpServers": {"agentdesktop": {"command": "python", "args": ["-I", "-B", "tools\\agent_desktop\\ad_mcp.py"],+ "env": {"AD_BIN": "C:\\bench\\agent-desktop\\node_modules\\agent-desktop\\bin\\agent-desktop-win32-x64.exe"}}}}+```++The agent command that `launch\windows_session.py` runs is then the same `claude -p` call as on macOS (see+[`RUNNER.md`](automated-eval/macos_bench/RUNNER.md), "The claude invocation"), with `--strict-mcp-config+--mcp-config <file>`, `--allowedTools mcp__<server>` and a system prompt that says "Windows desktop".+Where Windows differs:* **GUI-only guard.** A shell or script host (PowerShell, cmd, Windows Terminal, the script hosts,diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/RUNNER.md b/libs/cua-driver-bench/automated-eval/macos_bench/RUNNER.mdindex 844761a6c0..9310d8f864 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/RUNNER.md+++ b/libs/cua-driver-bench/automated-eval/macos_bench/RUNNER.md@@ -22,6 +22,8 @@ observed-pin comparison and doctor/CDP/page-info/deny probes remain prerequisite| `cc-codex-cu` | Codex Computer-Use (Sky) | OpenAI's `cua_repl` launcher from the ChatGPT app 26.930 plugin as MCP server `codex-cu` (`js`, `js_reset`), no skill || `cc-codex-cu-1007-browser` | Codex Computer-Use (Sky), app 26.1007 | The same launcher from app 26.1007 with the browser surface on || `cc-claude-cu-helper` | Claude Computer-Use (Desktop helper): Claude Desktop 2.31226.0 computer-use helper via a minimal adapter; an internal interface, not an Anthropic-supported procedure | Cua's adapter `tools/claude_cu_helper/cu_helper_mcp.py` as MCP server `claude-cu-helper` (`app_list_windows`, `app_screenshot` and the pinned input tools), no skill |+| `cc-agent-desktop` | Vercel agent-desktop | agent-desktop 1.2.0 behind `tools/agent_desktop/ad_mcp.py` as MCP server `agentdesktop` (one tool per CLI command), the vendor skill text as server instructions |+| `cc-browser-use` | Browser Use harness | Browser Use macOS harness 0.2.1 behind `tools/browser_use_harness/bu_mcp.py` as MCP server `browseruse` (`macos_harness`, `view_screenshot`), the vendor skill as server instructions || `cx-cua-driver`, `cx-codex-cu`, `cx-claude-cu-helper` | Cua Driver, Codex Computer-Use (Sky) and Claude Computer-Use (Desktop helper, with the label above), driven by Codex CLI (Amendment 23) | Not Claude Code: the bundled Codex CLI as `codex app-server` (`codex_native.py`) with GPT-6.1 Sol (`gpt-6.1-sol`, default effort low), given the MCP entry and system prompt of `cc-cua-driver-script`, `cc-codex-cu` or `cc-claude-cu-helper` || `cc-cua-driver`, `cc-cua-driver-main`, `cc-cua-driver-main-skill` | Internal baselines | Cua Driver 0.34.0 release; main with `run_script` off; main with the skill in the system prompt |diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/arms.py b/libs/cua-driver-bench/automated-eval/macos_bench/arms.pyindex 96d1f82116..3a947c35ca 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/arms.py+++ b/libs/cua-driver-bench/automated-eval/macos_bench/arms.py@@ -37,6 +37,8 @@ CLAUDE_ARMS = ("cc-cua-driver-main-skill","cc-cua-driver-script", # Amendment 6"cc-claude-cu-helper", # Amendment 11: Claude Desktop 2.31226.0 computer-use helper via a minimal adapter+ "cc-agent-desktop", # Vercel agent-desktop 1.2.0 behind tools/agent_desktop/ad_mcp.py+ "cc-browser-use", # Browser Use macOS harness 0.2.1 behind tools/browser_use_harness/bu_mcp.py)# cc-cua-driver-main: Amendment 3; cc-cua-driver-main-skill: Amendment 4. The default arm set of run_bench.py# stays the three arms of Amendment 3, so a run without --arms is unchanged.diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/claude_arms.py b/libs/cua-driver-bench/automated-eval/macos_bench/claude_arms.pyindex e4097bb02c..89eb1b9a03 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/claude_arms.py+++ b/libs/cua-driver-bench/automated-eval/macos_bench/claude_arms.py@@ -308,6 +308,54 @@ def check_cu_helper_pins(return out+# Other vendors' tools, driven by Claude Code through minimal stdlib MCP adapters kept in tools/. The vendor tool is+# installed by the reader (see README "Install each setup"); nothing of it is redistributed here. Server names are+# the names the adapters announce.+ADAPTER_TOOLS = HERE / "tools"+AGENT_DESKTOP_DIR = WORK / "agent-desktop"+AGENT_DESKTOP_BIN = Path(+ os.environ.get("CDB_AGENT_DESKTOP_BIN")+ or AGENT_DESKTOP_DIR / "node_modules" / ".bin" / "agent-desktop"+)+AGENT_DESKTOP_ADAPTER = ADAPTER_TOOLS / "agent_desktop" / "ad_mcp.py"+AGENT_DESKTOP_SERVER = "agentdesktop"+BROWSER_USE_DIR = WORK / "browser-use-harness"+BROWSER_USE_BIN = Path(+ os.environ.get("CDB_MACOS_HARNESS_BIN") or BROWSER_USE_DIR / "venv" / "bin" / "macos-harness"+)+BROWSER_USE_ADAPTER = ADAPTER_TOOLS / "browser_use_harness" / "bu_mcp.py"+BROWSER_USE_SERVER = "browseruse"+ADAPTER_ARMS = {+ "cc-agent-desktop": AGENT_DESKTOP_SERVER,+ "cc-browser-use": BROWSER_USE_SERVER,+}+++def adapter_entry(arm: str) -> dict[str, Any]:+ """The stdio MCP entry of an adapter arm: the adapter under a closed environment, pointing at the vendor binary."""+ env = {+ "HOME": os.environ.get("HOME", "/tmp"),+ "PATH": CLAUDE_PATH,+ "DO_NOT_TRACK": "1",+ }+ if arm == "cc-agent-desktop":+ script = AGENT_DESKTOP_ADAPTER+ env.update(+ {"AD_BIN": str(AGENT_DESKTOP_BIN), "AD_HEADED": "agent", "AGENT_DESKTOP_TELEMETRY": "0"}+ )+ elif arm == "cc-browser-use":+ script = BROWSER_USE_ADAPTER+ env.update({"BU_BIN": str(BROWSER_USE_BIN), "BU_SHOT": "ondemand"})+ else:+ raise ValueError(f"not an adapter arm: {arm}")+ return {+ "type": "stdio",+ "command": sys.executable,+ "args": ["-I", "-B", str(script)],+ "env": env,+ }++CODEX_CU_MCP_CANDIDATES = (WORK / "codex-access" / "mcp.json",WORK / "codex-access" / "mcp_cua_repl_computer.json",@@ -332,6 +380,10 @@ ARM_DESCRIPTIONS = {"cc-claude-cu-helper": "Claude Code + "+ CU_HELPER_LABEL+ " (MCP server claude-cu-helper; Amendment 11), no skill",+ "cc-agent-desktop": "Claude Code + Vercel agent-desktop 1.2.0 through a minimal MCP adapter (server agentdesktop), "+ "the vendor skill text as the server instructions",+ "cc-browser-use": "Claude Code + Browser Use macOS harness 0.2.1 through a minimal MCP adapter (server browseruse), "+ "the vendor skill as the server instructions",}SKILL_PROMPT_HEADER = (@@ -440,6 +492,13 @@ def mcp_config_for(path = run_dir / f"mcp-{arm}.json"path.write_text(json.dumps(config, indent=2) + "\n", "utf-8")return path, CU_HELPER_SERVER+ if arm in ADAPTER_ARMS:+ server = ADAPTER_ARMS[arm]+ path = run_dir / f"mcp-{arm}.json"+ path.write_text(+ json.dumps({"mcpServers": {server: adapter_entry(arm)}}, indent=2) + "\n", "utf-8"+ )+ return path, serverif arm in CODEX_ARMS:source = (resolve_codex_cu_config(codex_cu_config)diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/claude_events.py b/libs/cua-driver-bench/automated-eval/macos_bench/claude_events.pyindex 7973fcc4ee..9877942f5f 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/claude_events.py+++ b/libs/cua-driver-bench/automated-eval/macos_bench/claude_events.py@@ -110,12 +110,59 @@ CU_HELPER_CLASSES = {}+# Adapter arms: agent-desktop (server "agentdesktop", one tool per CLI command) and the Browser Use macOS harness+# (server "browseruse", one `macos_harness` tool whose command string starts with the vendor subcommand).+AGENT_DESKTOP_CLASSES = {+ "snapshot": "observe",+ "find": "observe",+ "get": "observe",+ "is": "observe",+ "screenshot": "observe",+ "list_windows": "observe",+ "list_apps": "observe",+ "click": "click",+ "double_click": "click",+ "right_click": "click",+ "mouse_click": "click",+ "type": "type",+ "set_value": "set_value",+ "press": "key",+ "scroll": "scroll",+ "scroll_to": "scroll",+ "mouse_wheel": "scroll",+ "drag": "drag",+}+BROWSER_USE_CLASSES = {+ "get_app_state": "observe",+ "list_apps": "observe",+ "click": "click",+ "perform_secondary_action": "click",+ "type_text": "type",+ "paste": "type",+ "set_value": "set_value",+ "press_key": "key",+ "scroll": "scroll",+ "drag": "drag",+}++def tool_class(name: str, tool_input: dict[str, Any] | None = None) -> str:server, tool = strip_mcp(name)if server is None:return "builtin"if server == "claude-cu-helper":return CU_HELPER_CLASSES.get(tool, "other")+ if server == "agentdesktop":+ return AGENT_DESKTOP_CLASSES.get(tool, "other")+ if server == "browseruse":+ if tool != "macos_harness":+ return "observe" if tool == "view_screenshot" else "other"+ words = str((tool_input or {}).get("command") or "").replace("macos-harness", " ").split()+ classes = [BROWSER_USE_CLASSES.get(w) for w in words if w in BROWSER_USE_CLASSES]+ for preferred in ("drag", "click", "type", "key", "scroll", "set_value", "observe"):+ if preferred in classes:+ return preferred+ return "other"if tool in CUA_CLASSES:return CUA_CLASSES[tool]if tool == "js":diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/pins.json b/libs/cua-driver-bench/automated-eval/macos_bench/pins.jsonindex f91d0b40e3..60204f9215 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/pins.json+++ b/libs/cua-driver-bench/automated-eval/macos_bench/pins.json@@ -133,5 +133,24 @@"codex_cli_sha256": "6b582e8813ce7e8ed4c52814ee5cf230dba647bf2292df747a4003f2657ef201","model": "gpt-6.1-sol","effort": "low"+ },+ "agent_desktop": {+ "version": "1.2.0",+ "package": "[email protected] on npm (vercel-labs/agent-desktop, Apache-2.0)",+ "adapter": "tools/agent_desktop/ad_mcp.py",+ "instructions": "tools/agent_desktop/ad-instructions.md"+ },+ "browser_use_harness": {+ "macos_harness_version": "0.2.1",+ "windows_harness_version": "0.2.2",+ "windows_harness_repo": "https://github.com/browser-use/windows-harness",+ "windows_harness_commit": "46a37cf1d411c7816adffc274d5bdc2cca2bd9f0",+ "macos_adapter": "tools/browser_use_harness/bu_mcp.py",+ "windows_adapter": "tools/browser_use_harness/wh_mcp.py"+ },+ "codex_cu_platforms": {+ "macos_chatgpt_app": "26.930",+ "windows_chatgpt_codex_app": "26.1029.9216.0",+ "filter": "tools/codex_cu/codex_cu_filter.py"}}diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/run_bench.py b/libs/cua-driver-bench/automated-eval/macos_bench/run_bench.pyindex e3279efaa1..958b31520a 100644--- a/libs/cua-driver-bench/automated-eval/macos_bench/run_bench.py+++ b/libs/cua-driver-bench/automated-eval/macos_bench/run_bench.py@@ -647,6 +647,18 @@ def real_capture_check(ctx: "Ctx", arm: str) -> tuple[str, str, str]:if window is None:raise RuntimeError("no layer-0 Calculator window")result = call("app_screenshot", {"app": "Calculator", "window_id": window["window_id"]})+ elif source in ca.ADAPTER_ARMS:+ # No capture tool: the adapters have no screenshot of the whole desktop. A read-only list proves the+ # vendor tool answers through the adapter.+ if source == "cc-agent-desktop":+ if "list_apps" not in tools:+ raise RuntimeError("unexpected agent-desktop tools/list")+ call("list_apps", {})+ else:+ if "macos_harness" not in tools:+ raise RuntimeError("unexpected macos-harness tools/list")+ call("macos_harness", {"command": "macos-harness list_apps"})+ return f"{arm} adapter answers", "pass", "tools/list and a read-only call"else:if not {"js", "js_reset"} <= tools.keys():raise RuntimeError("missing Codex tools")diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_vendor_adapters.py b/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_vendor_adapters.pynew file mode 100644index 0000000000..b27b2c64a3--- /dev/null+++ b/libs/cua-driver-bench/automated-eval/macos_bench/tests/test_vendor_adapters.py@@ -0,0 +1,276 @@+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++"""Adapters for agent-desktop, the Browser Use harnesses and the Codex computer-use filter (no GUI, no model)."""++from __future__ import annotations++import json+import os+import stat+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++HERE = Path(__file__).resolve().parent+TOOLS = HERE.parent / "tools"+for sub in ("agent_desktop", "browser_use_harness", "codex_cu"):+ sys.path.insert(0, str(TOOLS / sub))+sys.path.insert(0, str(HERE.parent))++import ad_mcp # noqa: E402+import arms # noqa: E402+import bu_mcp # noqa: E402+import claude_arms as ca # noqa: E402+import claude_events as ce # noqa: E402+import codex_cu_filter as cf # noqa: E402+++def rpc(script: Path, env: dict[str, str], *messages: dict) -> list[dict]:+ data = "".join(json.dumps(m) + "\n" for m in messages)+ out = subprocess.run(+ [sys.executable, "-I", "-B", str(script)],+ input=data,+ capture_output=True,+ text=True,+ env={"PATH": os.environ.get("PATH", ""), **env},+ timeout=60,+ )+ return [json.loads(line) for line in out.stdout.splitlines() if line.strip()]+++class AgentDesktopAdapterTest(unittest.TestCase):+ def test_every_tool_maps_to_a_cli_command(self) -> None:+ names = {t["name"] for t in ad_mcp.tools()}+ self.assertEqual(names, set(ad_mcp.T))+ self.assertEqual(+ ad_mcp.argv_for("click", {"ref": "@s:e3"}),+ ["click", "@s:e3"],+ )+ self.assertEqual(+ ad_mcp.argv_for("snapshot", {"app": "TextEdit", "interactive_only": True}),+ ["snapshot", "--app", "TextEdit", "-i"],+ )++ def test_headed_is_a_model_choice_only_in_agent_mode(self) -> None:+ self.assertEqual(ad_mcp.argv_for("click", {"ref": "@s:e3", "headed": True})[0], "--headed")+ self.assertEqual(ad_mcp.argv_for("click", {"ref": "@s:e3"})[0], "click")+ self.assertEqual(+ ad_mcp.argv_for("hover", {"xy": "1,2"})[0], "--headed"+ ) # pointer-only tool++ def test_negative_values_keep_their_sign_as_one_argument(self) -> None:+ self.assertEqual(+ ad_mcp.argv_for("mouse_wheel", {"x": 1, "y": 2, "dy": "-5"}),+ ["--headed", "mouse-wheel", "--x", "1", "--y", "2", "--dy=-5"],+ )++ def test_server_round_trip_with_a_fake_binary(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ fake = Path(tmp) / "agent-desktop"+ fake.write_text('#!/bin/sh\nprintf \'{"ok":true,"args":"%s"}\' "$*"\n')+ fake.chmod(fake.stat().st_mode | stat.S_IXUSR)+ replies = rpc(+ TOOLS / "agent_desktop" / "ad_mcp.py",+ {"AD_BIN": str(fake)},+ {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}},+ {"jsonrpc": "2.0", "id": 2, "method": "tools/list"},+ {+ "jsonrpc": "2.0",+ "id": 3,+ "method": "tools/call",+ "params": {"name": "list_apps", "arguments": {"app": "Finder"}},+ },+ )+ self.assertIn("agent-desktop", replies[0]["result"]["instructions"])+ self.assertGreater(len(replies[1]["result"]["tools"]), 30)+ self.assertIn("list-apps --app Finder", replies[2]["result"]["content"][0]["text"])+ self.assertFalse(replies[2]["result"]["isError"])+++class MacosHarnessAdapterTest(unittest.TestCase):+ def test_only_vendor_commands_joined_by_and_are_accepted(self) -> None:+ steps = bu_mcp.parse(+ 'macos-harness click --app "TextEdit" --element_index 12 && macos-harness get_app_state --app "TextEdit"'+ )+ self.assertEqual([s[0][0] for s in steps], ["click", "get_app_state"])+ self.assertEqual(steps[0][0][2], "TextEdit")++ def test_heredoc_goes_to_the_last_command_only(self) -> None:+ steps = bu_mcp.parse("macos-harness paste --app Notes <<'EOF'\nhello \"x\"\nEOF")+ self.assertEqual(steps[-1][1], 'hello "x"')++ def test_shell_syntax_and_vendor_admin_commands_are_refused(self) -> None:+ for command in (+ "macos-harness list_apps | cat",+ "macos-harness list_apps; ls",+ "macos-harness list_apps > /tmp/x",+ "macos-harness doctor",+ "macos-harness install",+ "ls",+ ):+ with self.assertRaises(ValueError, msg=command):+ bu_mcp.parse(command)++ def test_server_round_trip_with_a_fake_binary_and_screenshot_rule(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ shot = Path(tmp) / "s.jpeg"+ shot.write_bytes(b"\xff\xd8\xff\xd9")+ other = Path(tmp) / "other.jpeg"+ other.write_bytes(b"\xff\xd8\xff\xd9")+ fake = Path(tmp) / "macos-harness"+ fake.write_text(+ f'#!/bin/sh\nif [ "$1" = skill ]; then echo SKILLTEXT; exit 0; fi\n'+ f'echo "Screenshot (1x1 px): {shot}"\n'+ )+ fake.chmod(fake.stat().st_mode | stat.S_IXUSR)+ replies = rpc(+ TOOLS / "browser_use_harness" / "bu_mcp.py",+ {"BU_BIN": str(fake)},+ {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}},+ {+ "jsonrpc": "2.0",+ "id": 2,+ "method": "tools/call",+ "params": {+ "name": "macos_harness",+ "arguments": {"command": "macos-harness get_app_state --app Notes"},+ },+ },+ {+ "jsonrpc": "2.0",+ "id": 3,+ "method": "tools/call",+ "params": {"name": "view_screenshot", "arguments": {"path": str(shot)}},+ },+ {+ "jsonrpc": "2.0",+ "id": 4,+ "method": "tools/call",+ "params": {"name": "view_screenshot", "arguments": {"path": str(other)}},+ },+ )+ self.assertEqual(replies[0]["result"]["instructions"].strip(), "SKILLTEXT")+ self.assertFalse(replies[1]["result"]["isError"])+ self.assertEqual(replies[2]["result"]["content"][0]["type"], "image")+ self.assertTrue(replies[3]["result"]["isError"]) # a file the harness never printed+++class WindowsHarnessAdapterTest(unittest.TestCase):+ def test_it_compiles_and_names_only_the_allowed_subcommands(self) -> None:+ source = (TOOLS / "browser_use_harness" / "wh_mcp.py").read_text("utf-8")+ compile(source, "wh_mcp.py", "exec")+ self.assertIn('ALLOWED = {"apps", "see", "state", "exec", "skill"}', source)+ self.assertIn('os.environ.get("WH_BIN")', source)+++class CodexFilterTest(unittest.TestCase):+ def setUp(self) -> None:+ self.f = cf.Filter({"Calculator"}, "/tmp/work")++ def test_tools_call_gets_sandbox_meta(self) -> None:+ line = json.dumps(+ {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "js"}}+ ).encode()+ out = json.loads(self.f.rewrite_up(line + b"\n"))+ meta = out["params"]["_meta"][cf.KEY]+ self.assertEqual(meta["permissionProfile"], {"type": "disabled"})+ self.assertTrue(meta["sandboxCwd"].startswith("file://"))+ other = b'{"jsonrpc":"2.0","id":2,"method":"tools/list"}\n'+ self.assertEqual(self.f.rewrite_up(other), other)++ def test_approval_prompt_only_for_allowlisted_apps(self) -> None:+ def ask(text: str) -> dict:+ msg = {+ "jsonrpc": "2.0",+ "id": 7,+ "method": "elicitation/create",+ "params": {"message": text},+ }+ return json.loads(self.f.elicit_reply(json.dumps(msg).encode() + b"\n"))["result"]++ self.assertEqual(ask('Allow Computer Use to use "Calculator"?')["action"], "accept")+ self.assertEqual(ask('Allow Computer Use to use "Terminal"?')["action"], "decline")+ self.assertEqual(ask("Allow something else?")["action"], "decline")+ self.assertIsNone(self.f.elicit_reply(b'{"jsonrpc":"2.0","id":1,"method":"tools/list"}\n'))++ def test_server_discover_is_answered_locally(self) -> None:+ reply = json.loads(+ self.f.discover_reply(b'{"jsonrpc":"2.0","id":3,"method":"server/discover"}\n')+ )+ self.assertEqual(reply["error"]["code"], -32601)+ self.assertIsNone(+ self.f.discover_reply(b'{"jsonrpc":"2.0","id":3,"method":"initialize"}\n')+ )++ def test_one_of_schema_is_flattened(self) -> None:+ tools = {+ "jsonrpc": "2.0",+ "id": 2,+ "result": {+ "tools": [+ {+ "name": "js",+ "inputSchema": {+ "type": "object",+ "oneOf": [+ {"properties": {"code": {"type": "string"}}, "required": ["code"]},+ {"properties": {"completion_summary": {"type": "string"}}},+ ],+ },+ },+ {"name": "js_reset", "inputSchema": {"type": "object", "properties": {}}},+ ]+ },+ }+ out = json.loads(self.f.flatten_down(json.dumps(tools).encode() + b"\n"))["result"]["tools"]+ self.assertEqual(set(out[0]["inputSchema"]["properties"]), {"code", "completion_summary"})+ self.assertNotIn("oneOf", out[0]["inputSchema"])+ self.assertNotIn("required", out[0]["inputSchema"])++ def test_windows_command_points_at_the_app_package(self) -> None:+ command, env = cf.windows_command("C:/apps/resources", home="C:/home/bench")+ self.assertTrue(command[0].endswith("node.exe"))+ self.assertTrue(command[1].endswith("cua-repl.mjs"))+ self.assertEqual(env["CUA_REPL_ENABLED_SURFACES"], "computer")+++class ArmRegistrationTest(unittest.TestCase):+ def test_arms_are_named_claude_arms_but_not_default(self) -> None:+ for arm in ("cc-agent-desktop", "cc-browser-use"):+ self.assertIn(arm, arms.CLAUDE_ARMS)+ self.assertNotIn(arm, arms.DEFAULT_CLAUDE_ARMS)+ self.assertIn(arm, ca.ARM_DESCRIPTIONS)+ self.assertIn(arm, ca.ADAPTER_ARMS)++ def test_config_is_a_closed_stdio_entry_with_the_adapter(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ for arm, server in (+ ("cc-agent-desktop", "agentdesktop"),+ ("cc-browser-use", "browseruse"),+ ):+ path, name = ca.mcp_config_for(arm, Path(tmp))+ self.assertEqual(name, server)+ entry = json.loads(path.read_text("utf-8"))["mcpServers"][server]+ self.assertEqual(entry["args"][:2], ["-I", "-B"])+ self.assertTrue(Path(entry["args"][2]).is_file())+ self.assertEqual(entry["env"]["PATH"], ca.CLAUDE_PATH)++ def test_classes(self) -> None:+ self.assertEqual(ce.tool_class("mcp__agentdesktop__click"), "click")+ self.assertEqual(ce.tool_class("mcp__agentdesktop__snapshot"), "observe")+ self.assertEqual(+ ce.tool_class(+ "mcp__browseruse__macos_harness",+ {+ "command": "macos-harness type_text --app A --text x && macos-harness get_app_state --app A"+ },+ ),+ "type",+ )+++if __name__ == "__main__":+ unittest.main()diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/tools/agent_desktop/NOTICE.md b/libs/cua-driver-bench/automated-eval/macos_bench/tools/agent_desktop/NOTICE.mdnew file mode 100644index 0000000000..8049c63dbe--- /dev/null+++ b/libs/cua-driver-bench/automated-eval/macos_bench/tools/agent_desktop/NOTICE.md@@ -0,0 +1,4 @@+`ad-instructions.md` is the agent-desktop skill text from the `agent-desktop` npm package+(https://github.com/vercel-labs/agent-desktop, Copyright Vercel, Inc., Apache License 2.0,+https://www.apache.org/licenses/LICENSE-2.0). It is included unmodified, so the adapter can+serve the vendor's own instructions. Everything else in this directory is Cua's (FSL-1.1-MIT).diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/tools/agent_desktop/ad-instructions.md b/libs/cua-driver-bench/automated-eval/macos_bench/tools/agent_desktop/ad-instructions.mdnew file mode 100644index 0000000000..3858a83c8d--- /dev/null+++ b/libs/cua-driver-bench/automated-eval/macos_bench/tools/agent_desktop/ad-instructions.md@@ -0,0 +1,142 @@+---+name: agent-desktop+tags: computer-use, desktop-automation, accessibility, ai-agent, gui-automation, cli+requirements:+ - agent-desktop+description: >+ Operate desktop applications on macOS, Windows and Linux through native accessibility trees,+ using the agent-desktop CLI. Use when an AI agent must see or act on a desktop GUI:+ click buttons, fill forms, read UI state, navigate menus, toggle checkboxes, scroll,+ drag, type text, press shortcuts, take screenshots, manage windows, use the clipboard,+ launch or close apps, read notifications.+ Triggers on: "click button", "fill form", "open app", "read UI", "computer use",+ "operate desktop", "accessibility tree", "snapshot app", "type into field", "navigate menu",+ "toggle checkbox", "take screenshot", "desktop automation", "agent-desktop",+ or any desktop GUI task on macOS, Windows or Linux.+---++# agent-desktop++agent-desktop is a CLI that lets an AI agent observe and operate desktop apps through the OS accessibility tree. It is a tool, not an agent. Every command prints one JSON envelope (`ok`, `data` or `error`). The observe, act and verify loop runs in you.++## Shell syntax++Examples use a POSIX shell. In PowerShell, quote every ref (`'@s8f3k2p9:e1'`), because a bare `@token` is the splatting operator. Use `$env:NAME = 'value'` instead of `export`, and `| ConvertFrom-Json` instead of `$(...)` and `jq`. The Windows skill has the PowerShell forms.++## First run++1. Run `agent-desktop status`. It reports the platform, permissions and `supported_surfaces`.+2. Run `agent-desktop skills get platform`. It loads the skill for the OS the binary runs on (macOS, Windows or Linux).+3. For flags and syntax, run `agent-desktop <command> --help`. This skill does not repeat flag lists.++## The loop++Use `find` when you know the role or exact name. Otherwise map the app first and drill into one region.++```+agent-desktop snapshot --skeleton --app "Notes" -i --compact # shallow map, children_count on cut branches+agent-desktop snapshot --root @s8f3k2p9:e3 -i --compact # drill into one region+agent-desktop click @s8f3k2p9:e12 # act on a qualified ref+agent-desktop snapshot --root @s8f3k2p9:e3 -i --compact # verify: re-read the same region+```++- A small app needs no skeleton. Take a full `snapshot -i`.+- Never skeleton a surface (`--surface menu`, `sheet`, `alert`). A surface is already focused.+- An action that opens a menu, sheet or alert lists it in `data.surfaces`. Target that overlay next.+- After an async step, use `wait` (see `commands-system.md`). A fixed sleep is a race.++## Refs++- Output refs are qualified: `@<snapshot_id>:e<N>`, for example `@s8f3k2p9:e1`. Pass them to later commands as they are.+- Refs are valid for one snapshot. After any UI change, re-drill the affected region or take a new snapshot.+- Only addressable elements get refs. Static text and inert containers do not.+- `STALE_REF`: the ref no longer matches the live UI. Take a fresh snapshot and use the new ref.+- `AMBIGUOUS_TARGET`: more than one live element matches. Narrow the target with `find --role --name --exact` or `--root`, then use the new ref.+- `SNAPSHOT_NOT_FOUND`: the snapshot id expired. Snapshot again.++## Delivery and retry++Action results carry `data.disposition` and errors carry `error.disposition`, each with `delivery` and `retry`. Observation commands such as `snapshot` have none on success; their errors, and every `INVALID_ARGS` refusal, carry `not_delivered` and `retry: safe`.++- Retry or substitute an action only when `disposition.retry` is `safe`. Only `not_delivered` is safe.+- Any other delivery value means the action may have landed. A repeat can click, type or submit twice, and `toggle` can undo itself.+- On a result that is not safe, read the live state (`get`, `is`, or a fresh snapshot) and decide from that. `details.post_state` helps when present.+- Branch on `error.code` and `error.disposition`. Message and suggestion text can change.+- `details.retryable: false` means waiting cannot change the outcome. Try a different approach.++## Headless and headed++Ref actions are headless by default. They use semantic accessibility calls and do not take focus, move the cursor, synthesize keys or use the clipboard. If no semantic path exists, the action fails closed. Use the global `--headed` flag only when the user explicitly permits physical input, such as double-click, hover, drag, or focus. Never switch to headed mode to recover from a headless failure. Raw coordinates (`--xy`) never imply focus. Which actions need `--headed` differs by OS: read the platform skill.++## References++Load one only when you need it: `agent-desktop skills get desktop <reference>`.++| Reference | Open it when |+|-----------|--------------|+| `commands-observation` | You need `snapshot`, `find`, `get`, `is`, `screenshot`, `list-surfaces` semantics, partial trees, or the `--root` rules |+| `commands-interaction` | You choose between click, type, set-value, select, toggle, scroll, press and mouse commands, or you debug an action error |+| `commands-system` | You launch or close apps, manage windows, use the clipboard, `wait`, `batch`, sessions, multi-agent cursors, tracing, or load skills |+| `workflows` | You want worked patterns (forms, menus, dialogs, waiting for a new window, scroll-find, drag) and the anti-patterns list |+++---+---+name: agent-desktop-macos+tags: macos-automation, accessibility, ax, tcc, ai-agent, gui-automation, cli+requirements:+ - agent-desktop+description: >+ macOS platform guide for the agent-desktop CLI. Use for desktop automation+ on macOS: granting Accessibility and Screen Recording permission (TCC),+ what headed mode does on macOS (physical-first click, type and scroll),+ surfaces (menu, menubar, sheet, popover, alert), Notification Center,+ Chromium and Electron apps including launch --cdp, and fixing PERM_DENIED,+ empty accessibility trees, ACTION_FAILED and APP_UNRESPONSIVE.+---++# agent-desktop on macOS++Read the core skill first (`agent-desktop skills get desktop`) for the observe, act, verify loop. This skill covers only what is different on macOS. Symptoms and fixes are in [references/troubleshooting.md](references/troubleshooting.md).++## Requirements++- macOS 13 or later, Intel or Apple Silicon.+- Accessibility permission for the app that launches agent-desktop (Terminal, iTerm2, Warp, VS Code, Codex). macOS 27 and later name this list Device Control and Data Access. If System Settings lists the `agent-desktop` binary separately, grant it too.+- Screen Recording permission, only for `screenshot` and for `session start --screenshots` artifacts.+- Automation permission for System Events, only where a command reports it missing.++## First contact++1. Run `agent-desktop permissions`.+2. If a permission is denied, run `agent-desktop permissions --guide`. It opens the correct System Settings page with a panel that shows the user which app to drag into the list. The user confirms with Touch ID or a password, and the panel moves to the next missing permission by itself. The command returns at once with `"guide": "started"`, `"already_running"` or `"not_needed"`. `agent-desktop permissions --request` shows the system prompts instead.+3. If the guide cannot run, open System Settings > Privacy & Security > Accessibility (Device Control and Data Access on macOS 27 and later). Add the launching app and turn it on.+4. Run `agent-desktop permissions` to confirm `granted`. The next agent-desktop call sees a new grant, so the launching app does not need a restart.+5. Run `agent-desktop snapshot -i` to confirm. It reads the focused app. `snapshot --app Finder -i` returns `WINDOW_NOT_FOUND` when Finder has no open window.++`permissions` does not prompt. `permissions --request` can prompt, including for Automation. `permissions --guide` does not prompt and covers Accessibility and Screen Recording only. Automation reports `unknown` when macOS would need to prompt.++## What differs on macOS++**Headed is physical first** for `click`, `right-click`, `type`, `clear` and `scroll`. Core focuses the exact window of the ref. The adapter then sends a real click, key or wheel event to the verified point. `expand`, `collapse`, `set-value`, `select`, `toggle`, `check`, `uncheck`, `focus` and `scroll-to` stay semantic under `--headed`. Double-click, triple-click, `hover` and `drag` need `--headed`. Raw `--xy` input never changes focus.++**Judge delivery by observation.** AX return codes do not prove an effect. Finder returns success from an `AXConfirm` that does nothing. Snapshot again or use `get` and `is` to check the result.++**Surfaces.** Use `--surface menubar` for File, Edit and View menus and for menu bar apps (status items). While a menu, sheet, alert or popover is open, refs from the window tree behind it are the wrong target.++**Menus.** `right-click` headless uses `AXShowMenu`. If the menu opened but the app returned `APP_UNRESPONSIVE` with `retry: unsafe`, do not retry. Inspect the menu with `--surface menu`. For combo boxes and menu buttons, use `select @ref "Option"`. `select` needs a closed-to-open menu transition, so dismiss any open menu first.++**Notification Center.** The notification commands drive Notification Center through accessibility, with the rules in the core `commands-system` reference. When agent-desktop opens the center, it closes it afterwards and restores the previous app focus. Pass both `--expected-app` and `--expected-title` on a single dismiss or action, because the stack shifts. Use `wait --notification --app "App"` for banners that vanish before you list them.++**Chromium and Electron.** agent-desktop switches on the web accessibility of a Chromium renderer automatically when it needs it. For a dense running app, use `snapshot --skeleton -i --compact`, then drill with `--root @ref`.++**Identity.** `launch` accepts a display name (`"System Settings"`) or a bundle ID (`com.apple.systempreferences`). Other commands take the display name through `--app`. Window IDs such as `w-4521` stay valid for the life of the window. Find them with `list-windows`.++**Keys.** The primary modifier is `cmd`: `press cmd+c`, `press cmd+s`. Quit shortcuts such as `cmd+q`, `cmd+shift+q`, `cmd+alt+esc`, `ctrl+cmd+q` and `cmd+shift+delete` return `POLICY_DENIED` unless you pass `--force`. To quit an app, use `close-app`. Punctuation keys work in combos, as the symbol (`,` `.` `/` `;` `'` `[` `]` `\` `-` `=` `` ` ``) or by name (`comma`, `period`, `slash`, `semicolon`, `quote`, `leftbracket`, `rightbracket`, `backslash`, `minus`, `equal`, `grave`). Each one is sent with the key that types it in the active keyboard layout, so `press cmd+,` opens Settings on ANSI and JIS keyboards alike.++**Cursor overlay.** `cursor-overlay enable` draws the agent cursor in a click-through window. It never moves the OS pointer or activates an app. The macOS motion and image limits are in the core `commands-system` reference.++## Next step++When a command fails, find the symptom in [references/troubleshooting.md](references/troubleshooting.md).+diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/tools/agent_desktop/ad_mcp.py b/libs/cua-driver-bench/automated-eval/macos_bench/tools/agent_desktop/ad_mcp.pynew file mode 100644index 0000000000..1ac27ad182--- /dev/null+++ b/libs/cua-driver-bench/automated-eval/macos_bench/tools/agent_desktop/ad_mcp.py@@ -0,0 +1,480 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++"""Minimal stdlib MCP adapter for vercel-labs/agent-desktop (Apache-2.0; bench arm `cc-agent-desktop`).++agent-desktop is a plain CLI, so each MCP tool maps 1:1 to one CLI command. The command's stdout (one JSON envelope)+goes back as text and base64 PNGs become MCP image content. Tool descriptions are the CLI's own one-line command+help; the server instructions are the agent-desktop skill text (`ad-instructions.md`, from the agent-desktop+package, Apache-2.0, unmodified). No shell, no skills/session/trace/permissions/notification commands.++Environment:+ AD_BIN path of the agent-desktop executable (default: `agent-desktop` on PATH)+ AD_HEADED agent (default; the model may pass `headed` on tools that can move the pointer) | never | always+ AD_INSTRUCTIONS path of the instructions file (default: ad-instructions.md next to this file)+"""++import base64+import json+import os+import re+import subprocess+import sys++HEADED = os.environ.get("AD_HEADED", "agent")+INSTR = os.environ.get(+ "AD_INSTRUCTIONS",+ os.path.join(os.path.dirname(os.path.abspath(__file__)), "ad-instructions.md"),+)+S = lambda d: {"type": "string", "description": d}+INT = lambda d: {"type": "integer", "description": d}+B = lambda d: {"type": "boolean", "description": d}+REF = S("Qualified ref from snapshot (@<snapshot_id>:eN)")+APP, WIN = S("Application name"), S("Window ID from list-windows")+# tool: (cli command, description, positional params, {param: (flag, kind, schema)}, takes_headed)+T = {+ "snapshot": (+ "snapshot",+ "Capture accessibility tree as structured JSON with @ref IDs",+ [],+ {+ "app": ("--app", "s", APP),+ "window_id": ("--window-id", "s", WIN),+ "surface": ("--surface", "s", S("window|focused|menu|menubar|sheet|popover|alert")),+ "root": ("--root", "s", S("Start from this ref")),+ "interactive_only": ("-i", "f", B("Interactive elements only")),+ "compact": ("--compact", "f", B("Collapse single-child unnamed nodes")),+ "skeleton": ("--skeleton", "f", B("Shallow overview")),+ "max_depth": ("--max-depth", "s", INT("Max depth (default 10)")),+ "include_bounds": ("--include-bounds", "f", B("Include element bounds")),+ "timeout_ms": ("--timeout-ms", "s", INT("Observation deadline ms")),+ },+ False,+ ),+ "find": (+ "find",+ "Search elements by role, name, value, or text content",+ [],+ {+ "app": ("--app", "s", APP),+ "window_id": ("--window-id", "s", WIN),+ "role": ("--role", "s", S("Accessibility role")),+ "name": ("--name", "s", S("Accessible name")),+ "value": ("--value", "s", S("Current value")),+ "text": ("--text", "s", S("Text in name/value/title/description")),+ "exact": ("--exact", "f", B("Exact match")),+ "root": ("--root", "s", S("Search inside this ref")),+ "surface": ("--surface", "s", S("Surface")),+ "first": ("--first", "f", B("First match only")),+ "limit": ("--limit", "s", INT("Max matches")),+ },+ False,+ ),+ "get": (+ "get",+ "Read an element property (text, value, title, bounds, role, states)",+ ["ref"],+ {+ "ref": ("", "p", REF),+ "property": ("--property", "s", S("text|value|title|bounds|role|states")),+ },+ False,+ ),+ "is": (+ "is",+ "Check element state (visible, enabled, checked, focused, expanded, selected)",+ ["ref"],+ {"ref": ("", "p", REF), "property": ("--property", "s", S("State"))},+ False,+ ),+ "screenshot": (+ "screenshot",+ "Take a PNG screenshot of an application window",+ [],+ {+ "app": ("--app", "s", APP),+ "window_id": ("--window-id", "s", WIN),+ "screen": ("--screen", "s", INT("Display index")),+ },+ False,+ ),+ "click": (+ "click",+ "Click element via accessibility press action",+ ["ref"],+ {"ref": ("", "p", REF)},+ True,+ ),+ "double_click": (+ "double-click",+ "Physically double-click element; requires headed",+ ["ref"],+ {"ref": ("", "p", REF)},+ True,+ ),+ "right_click": (+ "right-click",+ "Open a context menu semantically, or physically with headed",+ ["ref"],+ {"ref": ("", "p", REF)},+ True,+ ),+ "type": (+ "type",+ "Insert text into a text target",+ ["ref", "text"],+ {"ref": ("", "p", REF), "text": ("", "p", S("Text to type"))},+ True,+ ),+ "set_value": (+ "set-value",+ "Set element value directly via accessibility attribute",+ ["ref", "value"],+ {"ref": ("", "p", REF), "value": ("", "p", S("Value"))},+ False,+ ),+ "clear": (+ "clear",+ "Clear element value to empty string",+ ["ref"],+ {"ref": ("", "p", REF)},+ True,+ ),+ "focus": ("focus", "Set keyboard focus on element", ["ref"], {"ref": ("", "p", REF)}, False),+ "select": (+ "select",+ "Select an option in a list or dropdown",+ ["ref", "value"],+ {"ref": ("", "p", REF), "value": ("", "p", S("Option"))},+ False,+ ),+ "toggle": ("toggle", "Toggle a checkbox or switch", ["ref"], {"ref": ("", "p", REF)}, False),+ "check": (+ "check",+ "Set checkbox or switch to checked state (idempotent)",+ ["ref"],+ {"ref": ("", "p", REF)},+ False,+ ),+ "uncheck": (+ "uncheck",+ "Set checkbox or switch to unchecked state (idempotent)",+ ["ref"],+ {"ref": ("", "p", REF)},+ False,+ ),+ "expand": (+ "expand",+ "Expand a disclosure triangle or tree item",+ ["ref"],+ {"ref": ("", "p", REF)},+ False,+ ),+ "collapse": (+ "collapse",+ "Collapse a disclosure triangle or tree item",+ ["ref"],+ {"ref": ("", "p", REF)},+ False,+ ),+ "scroll": (+ "scroll",+ "Scroll element (--direction up/down/left/right, --amount N)",+ ["ref"],+ {+ "ref": ("", "p", REF),+ "direction": ("--direction", "s", S("up|down|left|right")),+ "amount": ("--amount", "s", INT("Scroll units (default 3)")),+ },+ True,+ ),+ "scroll_to": (+ "scroll-to",+ "Scroll element into visible area",+ ["ref"],+ {"ref": ("", "p", REF)},+ False,+ ),+ "press": (+ "press",+ "Send a key combo: return, escape, cmd+c, shift+tab ...",+ ["combo"],+ {"combo": ("", "p", S("Key combo")), "window_id": ("--window-id", "s", WIN)},+ False,+ ),+ "hover": (+ "hover",+ "Move cursor to element center or coordinates (requires headed)",+ [],+ {"ref": ("", "o", REF), "xy": ("--xy", "s", S("x,y"))},+ "force",+ ),+ "drag": (+ "drag",+ "Drag from one element or point to another (requires headed)",+ [],+ {+ "from": ("--from", "s", REF),+ "from_xy": ("--from-xy", "s", S("x,y")),+ "to": ("--to", "s", REF),+ "to_xy": ("--to-xy", "s", S("x,y")),+ "duration": ("--duration", "s", INT("ms")),+ "drop_delay": ("--drop-delay", "s", INT("ms")),+ },+ "force",+ ),+ "mouse_move": (+ "mouse-move",+ "Move cursor to absolute screen coordinates (requires headed)",+ [],+ {"xy": ("--xy", "s", S("x,y"))},+ "force",+ ),+ "mouse_click": (+ "mouse-click",+ "Click at absolute screen coordinates (requires headed)",+ [],+ {+ "xy": ("--xy", "s", S("x,y")),+ "button": ("--button", "s", S("left|right|middle")),+ "count": ("--count", "s", INT("Clicks")),+ },+ "force",+ ),+ "mouse_wheel": (+ "mouse-wheel",+ "Scroll the mouse wheel at absolute coordinates (requires headed)",+ [],+ {+ "x": ("--x", "s", INT("X")),+ "y": ("--y", "s", INT("Y")),+ "dy": ("--dy", "s", INT("Vertical lines")),+ },+ "force",+ ),+ "launch": (+ "launch",+ "Launch application and return once its process is running; --activate waits for a window",+ ["app"],+ {+ "app": ("", "p", S("App name or bundle ID")),+ "activate": ("--activate", "f", B("Wait for a window")),+ },+ False,+ ),+ "close_app": (+ "close-app",+ "Quit an application gracefully (--force to terminate)",+ ["app"],+ {"app": ("", "p", APP), "force": ("--force", "f", B("Terminate"))},+ False,+ ),+ "list_windows": (+ "list-windows",+ "List all visible windows (--app to filter by application)",+ [],+ {"app": ("--app", "s", APP)},+ False,+ ),+ "list_apps": (+ "list-apps",+ "List all running GUI applications (--app to filter)",+ [],+ {"app": ("--app", "s", APP)},+ False,+ ),+ "focus_window": (+ "focus-window",+ "Bring a window to front and confirm OS focus",+ [],+ {+ "window_id": ("--window-id", "s", WIN),+ "app": ("--app", "s", APP),+ "title": ("--title", "s", S("Window title")),+ },+ False,+ ),+ "resize_window": (+ "resize-window",+ "Resize application window",+ [],+ {+ "app": ("--app", "s", APP),+ "window_id": ("--window-id", "s", WIN),+ "width": ("--width", "s", INT("px")),+ "height": ("--height", "s", INT("px")),+ },+ False,+ ),+ "move_window": (+ "move-window",+ "Move application window to new position",+ [],+ {+ "app": ("--app", "s", APP),+ "window_id": ("--window-id", "s", WIN),+ "x": ("--x", "s", INT("X")),+ "y": ("--y", "s", INT("Y")),+ },+ False,+ ),+ "clipboard_get": (+ "clipboard-get",+ "Read plain-text or typed clipboard contents",+ [],+ {},+ False,+ ),+ "clipboard_set": (+ "clipboard-set",+ "Write text to the clipboard",+ ["text"],+ {"text": ("", "p", S("Text"))},+ False,+ ),+ "wait": (+ "wait",+ "Wait for time (ms), element presence, text, or window appearance",+ ["ms"],+ {+ "ms": ("", "o", INT("Milliseconds to pause")),+ "element": ("--element", "s", REF),+ "text": ("--text", "s", S("Text")),+ "window": ("--window", "s", S("Window title")),+ "predicate": ("--predicate", "s", S("exists|enabled|visible|actionable|value")),+ "app": ("--app", "s", APP),+ "timeout": ("--timeout", "s", INT("ms")),+ },+ False,+ ),+ "batch": (+ "batch",+ "Execute a bounded, sequential, non-atomic JSON command batch",+ ["json"],+ {"json": ("", "p", S("JSON array of {command, args} objects"))},+ False,+ ),+}+# Not exposed (parity with the other arms' tool sets; no shell, no host side effects): skills, session, trace, cursor-overlay,+# permissions, status, notification commands, open-system-surface, list-surfaces, minimize/maximize/restore (add if cua-driver's set_window_frame is judged equal).+++def argv_for(name, a):+ cmd, _, pos, params, hd = T[name]+ out = []+ if (+ HEADED == "always"+ or hd == "force"+ or (HEADED == "agent" and hd is True and a.get("headed"))+ ):+ out.append("--headed")+ out.append(cmd)+ for k, (flag, kind, _) in params.items():+ v = a.get(k)+ if v is None or v is False:+ continue+ if kind in ("p", "o"):+ continue+ if kind == "f":+ out.append(flag)+ else:+ out += [flag + "=" + str(v)] if str(v).startswith("-") else [flag, str(v)]+ out += [str(a[k]) for k in pos if a.get(k) is not None]+ return out+++def tools():+ res = []+ for n, (cmd, desc, pos, params, hd) in T.items():+ props = {k: v[2] for k, v in params.items()}+ if hd is True and HEADED == "agent":+ props["headed"] = B(+ "Physical delivery (moves the pointer/focus). Default is headless semantic delivery."+ )+ res.append(+ {+ "name": n,+ "description": desc,+ "inputSchema": {+ "type": "object",+ "properties": props,+ "required": [k for k in pos if params[k][1] == "p"],+ },+ }+ )+ return res+++class Backend:+ def __init__(self):+ self.exe = os.environ.get("AD_BIN") or "agent-desktop"++ def run(self, argv, timeout=120):+ try:+ r = subprocess.run([self.exe] + argv, capture_output=True, timeout=timeout)+ except subprocess.TimeoutExpired:+ return 124, b"timed out"+ return r.returncode, (r.stdout + r.stderr)+++def to_content(rc, raw):+ text = raw.decode("utf-8", "replace")+ imgs = []++ def strip(m):+ imgs.append(m.group(0))+ return "<image %d>" % len(imgs)++ text = re.sub(r"[A-Za-z0-9+/=]{2000,}", strip, text)+ out = [{"type": "text", "text": text}]+ out += [{"type": "image", "data": i, "mimeType": "image/png"} for i in imgs]+ return out, rc != 0 and not text.lstrip().startswith("{")+++def serve():+ be = Backend()+ instr = open(INSTR).read() if os.path.exists(INSTR) else ""+ for line in sys.stdin:+ m = json.loads(line)+ mid, meth = m.get("id"), m.get("method")++ def send(r):+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": mid, **r}) + "\n")+ sys.stdout.flush()++ if meth == "initialize":+ send(+ {+ "result": {+ "protocolVersion": "2024-11-05",+ "capabilities": {"tools": {}},+ "serverInfo": {"name": "agentdesktop", "version": "bench-adapter"},+ "instructions": instr,+ }+ }+ )+ elif meth == "tools/list":+ send({"result": {"tools": tools()}})+ elif meth == "tools/call":+ p = m["params"]+ try:+ if p["name"] not in T:+ raise KeyError(p["name"])+ content, err = to_content(*be.run(argv_for(p["name"], p.get("arguments") or {})))+ send({"result": {"content": content, "isError": err}})+ except Exception as e:+ send(+ {+ "result": {+ "content": [{"type": "text", "text": "adapter error: %s" % e}],+ "isError": True,+ }+ }+ )+ elif mid is not None:+ send({"result": {}})+++if __name__ == "__main__":+ serve()diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/tools/browser_use_harness/bu_mcp.py b/libs/cua-driver-bench/automated-eval/macos_bench/tools/browser_use_harness/bu_mcp.pynew file mode 100644index 0000000000..ad7503e6cd--- /dev/null+++ b/libs/cua-driver-bench/automated-eval/macos_bench/tools/browser_use_harness/bu_mcp.py@@ -0,0 +1,243 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++"""Minimal stdlib MCP adapter for browser-use/macos-harness 0.2.1 (bench arm `cc-browser-use`).++macos-harness is a shell CLI whose work is done by a per-user helper daemon (started on the first call). The vendor+skill teaches a shell ("actions you are sure of, then one read, joined with &&"). Bench v2 gives the model no shell, so+this adapter exposes the vendor's own surface unchanged through ONE tool:++ macos_harness(command) e.g. macos-harness click --app "TextEdit" --element_index 12 && macos-harness get_app_state --app "TextEdit"+ view_screenshot(path) stand-in for the Read tool the skill assumes ("open the file on the Screenshot line")++The command string is parsed here (shlex, no shell): only the vendor tools and `skill`, joined by `&&`, with one optional+trailing heredoc for paste/type_text/set_value. Pipes, `;`, `||`, redirects and `doctor`, `install`, `approve`, `helper`+and the like are refused. The server instructions are the output of `macos-harness skill` (the vendor SKILL.md), so the+text always matches the installed version. view_screenshot only opens files that macos-harness printed on a Screenshot line.++Environment:+ BU_BIN path of the macos-harness executable (default: `macos-harness` on PATH)+ BU_SHOT ondemand (default, vendor-faithful) | always (attach the screenshot to every get_app_state)+ BU_IMG_MAX optional longest-side downscale in pixels (uses macOS `sips`); 0 = off+"""++import base64+import json+import os+import re+import shlex+import subprocess+import sys+import tempfile++BIN = os.environ.get("BU_BIN") or "macos-harness"+SHOT = os.environ.get("BU_SHOT", "ondemand")+IMG_MAX = int(os.environ.get("BU_IMG_MAX", "0") or 0)+ALLOWED = {+ "list_apps",+ "get_app_state",+ "click",+ "perform_secondary_action",+ "set_value",+ "select_text",+ "scroll",+ "drag",+ "press_key",+ "type_text",+ "paste",+ "skill",+}+HEREDOC = re.compile(r"<<-?\s*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\1[ \t]*\n(.*?)\n\2[ \t]*\Z", re.S)+SHOT_RE = re.compile(r"^Screenshot \(\d+x\d+ px\): (.+)$", re.M)+++def parse(command):+ """-> list of (argv, stdin|None). Raises ValueError with a message the model can act on."""+ command = command.strip()+ stdin = None+ m = HEREDOC.search(command)+ if m:+ stdin, command = m.group(3), command[: m.start()].rstrip()+ lex = shlex.shlex(command, posix=True, punctuation_chars=True)+ lex.whitespace_split = True+ segs, cur = [], []+ for t in lex:+ if t == "&&":+ segs.append(cur)+ cur = []+ elif set(t) <= set("();<>|&"):+ raise ValueError(+ "only `macos-harness ...` commands joined by && are allowed (got %r)" % t+ )+ else:+ cur.append(t)+ segs.append(cur)+ out = []+ for i, s in enumerate(segs):+ if s[:1] == ["macos-harness"]:+ s = s[1:]+ if not s or s[0] not in ALLOWED:+ raise ValueError(+ "unknown or not allowed command %r; use only the commands on the skill page"+ % (s[:1] or "")+ )+ out.append((s, stdin if i == len(segs) - 1 else None))+ return out+++class Backend:+ def __init__(self):+ self.seen = set() # screenshot paths macos-harness printed++ def cli(self, argv, stdin):+ try:+ r = subprocess.run(+ [BIN, *argv],+ input=stdin.encode() if stdin is not None else None,+ capture_output=True,+ timeout=150,+ )+ except subprocess.TimeoutExpired:+ return 124, b"timed out"+ return r.returncode, r.stdout + r.stderr++ def cat(self, path):+ if path not in self.seen:+ return 1, b"only screenshots that macos-harness wrote can be opened"+ try:+ with open(path, "rb") as f:+ return 0, f.read()+ except OSError as e:+ return 1, str(e).encode()+++def shrink(data):+ if not IMG_MAX:+ return data+ with tempfile.TemporaryDirectory() as d:+ p = os.path.join(d, "s.jpeg")+ open(p, "wb").write(data)+ subprocess.run(["/usr/bin/sips", "-Z", str(IMG_MAX), p], capture_output=True)+ return open(p, "rb").read()+++def img(data):+ return {+ "type": "image",+ "data": base64.b64encode(shrink(data)).decode(),+ "mimeType": "image/jpeg",+ }+++def run_command(be, command):+ try:+ steps = parse(command)+ except ValueError as e:+ return [{"type": "text", "text": "usage error: %s" % e}], True+ texts, content, last_shot, err = [], [], None, False+ for argv, stdin in steps:+ rc, raw = be.cli(argv, stdin)+ t = raw.decode("utf-8", "replace")+ texts.append(t)+ m = SHOT_RE.search(t)+ if m:+ last_shot = m.group(1).strip()+ be.seen.add(last_shot)+ if rc != 0:+ err = True+ break # && semantics+ content.append({"type": "text", "text": "\n".join(texts)})+ if SHOT == "always" and last_shot and not err and steps[-1][0][0] == "get_app_state":+ rc, raw = be.cat(last_shot)+ if rc == 0:+ content.append(img(raw))+ return content, err+++def tools():+ t = [+ {+ "name": "macos_harness",+ "description": "Run macos-harness commands, exactly as the skill teaches (instructions). One call may chain commands with &&; it stops at the first failure. For paste/type_text/set_value with quotes or several lines, end the command with a heredoc (<<'EOF' ... EOF). No other shell syntax.",+ "inputSchema": {+ "type": "object",+ "properties": {+ "command": {+ "type": "string",+ "description": 'e.g. macos-harness click --app "TextEdit" --element_index 12 && macos-harness get_app_state --app "TextEdit"',+ }+ },+ "required": ["command"],+ },+ },+ {+ "name": "view_screenshot",+ "description": "Open a screenshot file named on a `Screenshot (WxH px): <path>` line (the skill's 'open the file'). Only files macos-harness wrote.",+ "inputSchema": {+ "type": "object",+ "properties": {"path": {"type": "string"}},+ "required": ["path"],+ },+ },+ ]+ return t+++def call(be, name, a):+ if name == "macos_harness":+ return run_command(be, a.get("command", ""))+ if name == "view_screenshot":+ rc, raw = be.cat(a.get("path", ""))+ return (+ ([img(raw)], False)+ if rc == 0+ else ([{"type": "text", "text": raw.decode("utf-8", "replace")}], True)+ )+ raise KeyError(name)+++def serve():+ be = Backend()+ instr = be.cli(["skill"], None)[1].decode("utf-8", "replace")+ for line in sys.stdin:+ m = json.loads(line)+ mid, meth = m.get("id"), m.get("method")++ def send(r):+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": mid, **r}) + "\n")+ sys.stdout.flush()++ if meth == "initialize":+ send(+ {+ "result": {+ "protocolVersion": "2024-11-05",+ "capabilities": {"tools": {}},+ "serverInfo": {"name": "browseruse", "version": "bench-adapter"},+ "instructions": instr,+ }+ }+ )+ elif meth == "tools/list":+ send({"result": {"tools": tools()}})+ elif meth == "tools/call":+ p = m["params"]+ try:+ c, e = call(be, p["name"], p.get("arguments") or {})+ send({"result": {"content": c, "isError": e}})+ except Exception as ex:+ send(+ {+ "result": {+ "content": [{"type": "text", "text": "adapter error: %s" % ex}],+ "isError": True,+ }+ }+ )+ elif mid is not None:+ send({"result": {}})+++if __name__ == "__main__":+ serve()diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/tools/browser_use_harness/wh_mcp.py b/libs/cua-driver-bench/automated-eval/macos_bench/tools/browser_use_harness/wh_mcp.pynew file mode 100644index 0000000000..9e580e9003--- /dev/null+++ b/libs/cua-driver-bench/automated-eval/macos_bench/tools/browser_use_harness/wh_mcp.py@@ -0,0 +1,157 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++"""Minimal stdlib MCP adapter for browser-use/windows-harness 0.2.2 (commit 46a37cf1d411c7816adffc274d5bdc2cca2bd9f0).++Same shape as the macOS adapter (bu_mcp.py): one tool carrying the vendor CLI syntax, the vendor skill as the server+instructions, and view_screenshot for image files the harness itself wrote. No shell: argv is parsed with shlex and only+the harness's own subcommands `apps`, `see`, `state`, `exec` and `skill` are run (`run` and `repl` need files or a+terminal and are not offered). Run it inside the interactive desktop session of the user the trial runs as.++Environment:+ WH_BIN path of windows-harness.exe (default: `windows-harness` on PATH)+"""++import base64+import json+import os+import re+import shlex+import subprocess+import sys++WH = os.environ.get("WH_BIN") or "windows-harness"+ALLOWED = {"apps", "see", "state", "exec", "skill"}+NOWIN = 0x08000000+seen_images = set()+++def run(argv, timeout=150):+ try:+ r = subprocess.run(+ [WH, *argv],+ capture_output=True,+ timeout=timeout,+ creationflags=NOWIN if os.name == "nt" else 0,+ )+ return r.returncode, (r.stdout + r.stderr).decode("utf-8", "replace")+ except subprocess.TimeoutExpired:+ return 124, "timed out"+++SKILL = run(["skill"])[1]+++def command(cmd):+ cmd = cmd.strip()+ if cmd.startswith("windows-harness"):+ cmd = cmd[len("windows-harness") :].strip()+ try:+ argv = shlex.split(cmd, posix=True)+ except ValueError as e:+ return {"content": [{"type": "text", "text": f"parse error: {e}"}], "isError": True}+ if not argv or argv[0] not in ALLOWED:+ return {+ "content": [+ {+ "type": "text",+ "text": f"allowed subcommands: {sorted(ALLOWED)} (run/repl need files or a terminal and are not offered)",+ }+ ],+ "isError": True,+ }+ rc, out = run(argv)+ for m in re.findall(r"[A-Za-z]:\\[^\s\"'<>|]+?\.(?:png|jpg|jpeg)", out):+ if os.path.isfile(m):+ seen_images.add(os.path.normcase(m))+ return {"content": [{"type": "text", "text": f"exit {rc}\n{out[-60000:]}"}], "isError": rc != 0}+++def view(path):+ if os.path.normcase(path) not in seen_images:+ return {+ "content": [+ {+ "type": "text",+ "text": "only screenshots that windows-harness wrote can be viewed",+ }+ ],+ "isError": True,+ }+ data = open(path, "rb").read()+ mime = "image/png" if path.lower().endswith(".png") else "image/jpeg"+ return {+ "content": [{"type": "image", "data": base64.b64encode(data).decode(), "mimeType": mime}]+ }+++TOOLS = [+ {+ "name": "windows_harness",+ "description": "Run one windows-harness CLI command, exactly as the skill shows, without the leading program name or with it: apps | see '<app>' | state '<app>' | exec '<python>' | skill. Python passed to exec has win, browser, Path and subprocess preloaded.",+ "inputSchema": {+ "type": "object",+ "properties": {"command": {"type": "string"}},+ "required": ["command"],+ },+ },+ {+ "name": "view_screenshot",+ "description": "Return a screenshot file that windows-harness wrote (a path it printed) as an image.",+ "inputSchema": {+ "type": "object",+ "properties": {"path": {"type": "string"}},+ "required": ["path"],+ },+ },+]+++def main():+ out = sys.stdout.buffer+ for raw in sys.stdin.buffer:+ try:+ msg = json.loads(raw)+ except Exception:+ continue+ mid, method = msg.get("id"), msg.get("method")+ if mid is None:+ continue+ if method == "initialize":+ res = {+ "protocolVersion": msg["params"].get("protocolVersion", "2025-06-18"),+ "capabilities": {"tools": {}},+ "serverInfo": {"name": "windows-harness", "version": "bench-adapter"},+ "instructions": SKILL,+ }+ elif method == "tools/list":+ res = {"tools": TOOLS}+ elif method == "tools/call":+ p = msg["params"]+ a = p.get("arguments") or {}+ res = (+ command(a.get("command", ""))+ if p["name"] == "windows_harness"+ else view(a.get("path", ""))+ )+ else:+ out.write(+ (+ json.dumps(+ {+ "jsonrpc": "2.0",+ "id": mid,+ "error": {"code": -32601, "message": "unknown"},+ }+ )+ + "\n"+ ).encode()+ )+ out.flush()+ continue+ out.write((json.dumps({"jsonrpc": "2.0", "id": mid, "result": res}) + "\n").encode())+ out.flush()+++main()diff --git a/libs/cua-driver-bench/automated-eval/macos_bench/tools/codex_cu/codex_cu_filter.py b/libs/cua-driver-bench/automated-eval/macos_bench/tools/codex_cu/codex_cu_filter.pynew file mode 100644index 0000000000..8f2b8cd7fa--- /dev/null+++ b/libs/cua-driver-bench/automated-eval/macos_bench/tools/codex_cu/codex_cu_filter.py@@ -0,0 +1,246 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.++"""Stdio filter between Claude Code and OpenAI's computer-use `cua_repl` MCP server (bench arm `cc-codex-cu`).++OpenAI's plugin is written for the ChatGPT/Codex app as its client. Claude Code is a different client, so four+differences are bridged here and nothing else is touched (no tool is added, removed or reworded, except item 4):++1. `tools/call` gets the `codex/sandbox-state-meta` metadata the plugin expects (`sandboxCwd`, and a disabled+ permission profile because the bench machine is the sandbox). Claude Code sends no such metadata.+2. `elicitation/create` is the plugin's per-app approval prompt. It is accepted only for the exact text+ `Allow Computer Use to use "<App>"?` (or `Allow Codex to use ...`) where <App> is on the allowlist, and declined+ otherwise. No human answers during a trial.+3. `server/discover` (sent first by newer Claude Code builds) is answered locally with -32601 so the plugin's+ Rust MCP layer, which aborts on any first message but `initialize`, never sees it.+4. Windows app 26.1029 only: the `js` tool's input schema is a top-level `oneOf`, which the Anthropic API rejects, so+ Claude Code drops the tool. The schema is flattened to one object with the same properties, none required.++Usage:+ codex_cu_filter.py --allow "Calculator,Finder" [--cwd DIR] [--log FILE] -- <server command> [args...]+ codex_cu_filter.py --allow "BenchLab" [--cwd DIR] [--log FILE] --windows-app "<...>\\resources"++`--windows-app` builds the server command and environment for the Windows ChatGPT/Codex app package from its+`resources` directory (cua_node\\bin\\node.exe running @oai\\cua-repl\\bin\\cua-repl.mjs). On macOS use the server entry+from the plugin's own `.mcp.json` (see make_codex_cu_mcp.py) as the command after `--`.+No credentials are read here; the plugin uses the ChatGPT sign-in of the user the trial runs as.+"""++from __future__ import annotations++import argparse+import json+import os+import re+import subprocess+import sys+import threading+import time+from pathlib import Path++KEY = "codex/sandbox-state-meta"+ELICIT_APP = re.compile(r'Allow (?:Computer Use|Codex) to use "?([^"?]+)"?\?')+++class Filter:+ def __init__(self, allow: set[str], cwd: str, log_path: str | None = None):+ self.allow = {a.strip().lower() for a in allow if a.strip()}+ self.cwd = cwd+ self.log_path = log_path++ def log(self, message: str) -> None:+ if self.log_path:+ with open(self.log_path, "a", encoding="utf-8") as f:+ f.write(time.strftime("%H:%M:%S ") + message + "\n")++ def cwd_uri(self) -> str:+ return Path(self.cwd).absolute().as_uri()++ def rewrite_up(self, line: bytes) -> bytes:+ """Client -> server: inject the sandbox metadata on tools/call."""+ if b'"tools/call"' not in line:+ return line+ try:+ msg = json.loads(line)+ if msg.get("method") == "tools/call":+ meta = msg.setdefault("params", {}).setdefault("_meta", {}).setdefault(KEY, {})+ meta["sandboxCwd"] = self.cwd_uri()+ meta["permissionProfile"] = {"type": "disabled"}+ return json.dumps(msg, separators=(",", ":")).encode() + b"\n"+ except ValueError as error:+ self.log(f"inject failed {error!r}")+ return line++ def discover_reply(self, line: bytes) -> bytes | None:+ if b"server/discover" not in line:+ return None+ try:+ msg = json.loads(line)+ except ValueError:+ return None+ if msg.get("method") != "server/discover" or "id" not in msg:+ return None+ self.log("server/discover answered -32601")+ reply = {+ "jsonrpc": "2.0",+ "id": msg["id"],+ "error": {"code": -32601, "message": "Method not found"},+ }+ return json.dumps(reply, separators=(",", ":")).encode() + b"\n"++ def elicit_reply(self, line: bytes) -> bytes | None:+ """Server -> client elicitation, answered here. Returns the reply for the server, or None."""+ if b"elicitation/create" not in line:+ return None+ try:+ msg = json.loads(line)+ except ValueError:+ return None+ if msg.get("method") != "elicitation/create" or "id" not in msg:+ return None+ text = (msg.get("params") or {}).get("message") or ""+ found = ELICIT_APP.match(text)+ ok = bool(found) and found.group(1).strip().lower() in self.allow+ result = (+ {"action": "accept", "content": {}, "_meta": {"persist": "session"}}+ if ok+ else {"action": "decline"}+ )+ self.log(f"elicitation {text!r} -> {result['action']}")+ return (+ json.dumps(+ {"jsonrpc": "2.0", "id": msg["id"], "result": result}, separators=(",", ":")+ ).encode()+ + b"\n"+ )++ def flatten_down(self, line: bytes) -> bytes:+ """Server -> client: flatten a top-level oneOf input schema in a tools/list result."""+ if b'"oneOf"' not in line or b'"tools"' not in line:+ return line+ try:+ msg = json.loads(line)+ changed = False+ for tool in (msg.get("result") or {}).get("tools") or []:+ schema = tool.get("inputSchema") or {}+ if "oneOf" in schema:+ props = dict(schema.get("properties") or {})+ for branch in schema["oneOf"]:+ props.update(branch.get("properties") or {})+ tool["inputSchema"] = {+ "type": "object",+ "additionalProperties": False,+ "properties": props,+ }+ changed = True+ self.log(f"flattened oneOf schema of {tool.get('name')}")+ if changed:+ return json.dumps(msg, separators=(",", ":")).encode() + b"\n"+ except ValueError as error:+ self.log(f"flatten failed {error!r}")+ return line+++def windows_command(+ resources: str, home: str | None = None, work: str | None = None+) -> tuple[list[str], dict[str, str]]:+ """Server command and environment for the Windows ChatGPT/Codex app, from its `resources` directory."""+ res = Path(resources)+ node = res / "cua_node" / "bin"+ mods = node / "node_modules"+ user = Path(home or os.environ.get("USERPROFILE") or Path.home())+ env = dict(os.environ)+ env.update(+ {+ "NODE_REPL_NATIVE_PIPE_CONNECT_TIMEOUT_MS": "1000",+ "NODE_REPL_NODE_MODULE_DIRS": str(mods),+ "NODE_REPL_NODE_PATH": str(node / "node.exe"),+ "NODE_REPL_TRUSTED_CODE_PATHS": f"{user / '.codex'};{mods}",+ "CODEX_HOME": str(user / ".codex"),+ "NODE_REPL_INSTRUCTIONS_USE_CASE_COMPUTER_USE": "Control desktop apps on Windows through Computer Use.",+ "NODE_REPL_TRUSTED_SERVICES": json.dumps({"sky": "@oai/sky/service"}),+ "SKY_CUA_SERVICE_PATH": str(+ mods / "@oai" / "sky" / "bin" / "windows" / "codex-computer-use.exe"+ ),+ "CODEX_CLI_PATH": str(res / "codex.exe"),+ "CUA_REPL_NODE_REPL_PATH": str(node / "node_repl.exe"),+ "CUA_REPL_ENABLED_SURFACES": "computer",+ }+ )+ return [str(node / "node.exe"), str(mods / "@oai" / "cua-repl" / "bin" / "cua-repl.mjs")], env+++def run(flt: Filter, command: list[str], env: dict[str, str] | None, cwd: str) -> int:+ Path(cwd).mkdir(parents=True, exist_ok=True)+ proc = subprocess.Popen(+ command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env, cwd=cwd, bufsize=0+ )+ flt.log(f"spawned pid={proc.pid} allow={sorted(flt.allow)}")+ write_lock, out_lock = threading.Lock(), threading.Lock()++ def down() -> None:+ out = sys.stdout.buffer+ for line in iter(proc.stdout.readline, b""):+ reply = flt.elicit_reply(line)+ if reply is not None:+ with write_lock:+ proc.stdin.write(reply)+ proc.stdin.flush()+ continue+ with out_lock:+ out.write(flt.flatten_down(line))+ out.flush()++ thread = threading.Thread(target=down, daemon=True)+ thread.start()+ try:+ for line in iter(sys.stdin.buffer.readline, b""):+ reply = flt.discover_reply(line)+ if reply is not None:+ with out_lock:+ sys.stdout.buffer.write(reply)+ sys.stdout.buffer.flush()+ continue+ with write_lock:+ proc.stdin.write(flt.rewrite_up(line))+ proc.stdin.flush()+ except OSError:+ pass+ try:+ proc.stdin.close()+ except OSError:+ pass+ code = proc.wait()+ thread.join(timeout=5)+ flt.log(f"exit {code}")+ return code+++def main(argv: list[str] | None = None) -> int:+ argv = list(sys.argv[1:] if argv is None else argv)+ command: list[str] = []+ if "--" in argv:+ split = argv.index("--")+ argv, command = argv[:split], argv[split + 1 :]+ ap = argparse.ArgumentParser(+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter+ )+ ap.add_argument(+ "--allow", default="", help="comma-separated apps whose approval prompt is accepted"+ )+ ap.add_argument("--cwd", default=str(Path.home() / ".cache" / "cua-bench-h2h" / "codex-cu-cwd"))+ ap.add_argument("--log")+ ap.add_argument("--windows-app", help="`resources` directory of the Windows ChatGPT/Codex app")+ args = ap.parse_args(argv)+ env = None+ if args.windows_app:+ command, env = windows_command(args.windows_app)+ if not command:+ ap.error("give a server command after `--` or --windows-app")+ flt = Filter(set(args.allow.split(",")), args.cwd, args.log)+ return run(flt, command, env, args.cwd)+++if __name__ == "__main__":+ sys.exit(main())