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
fix(cua-driver-bench): sync Amendments 22 and 23 and the public Claude helper setup (#4987)
Francesco Bonacci14358179a1d1
diff --git a/benchmarks/cua-driver-bench/METHOD.md b/benchmarks/cua-driver-bench/METHOD.mdindex efd15cfacb..23efc3e90c 100644--- a/benchmarks/cua-driver-bench/METHOD.md+++ b/benchmarks/cua-driver-bench/METHOD.md@@ -9,10 +9,14 @@ under [Registration record](#registration-record); this summary adds no rule.The protocol was committed before the first trial, and every change since thenis a dated amendment committed before the trials it covers. The full text is-`benchmarks/cua-driver-bench/automated-eval/macos_bench/PREREGISTRATION.md` at-these commits of `trycua/cua` (branch `bench/macos-head-to-head`). Times are the-commit times in UTC; GitHub's push history for that branch is the independent-record of when each one became public.+`PREREGISTRATION.md` at the commits below, on the harness's working branch+`bench/macos-head-to-head`. That branch now lives in a private Cua repository;+each registration commit is tagged there (`cdb-prereg/*`). The commits and the+pre-registration text are verifiable on request: ask Cua for the commit objects,+and check the hashes and commit times below against them. Times are the commit+times in UTC. Until 11 Oct 2026 the branch was also public on `trycua/cua`, so+GitHub's push history there is an independent record for the commits listed up+to that date.| Commit | Time (UTC) | What it registered || --- | --- | --- |@@ -26,13 +30,18 @@ record of when each one became public.| `b74564efd4fc657567be6acf011dabbdbf72f43c` | 2026-10-11 02:45 | A17.3: the Bench v2 rerun, both conditions, registered before its first trial || `69229a31c55f6693cbab20ac48287d2b17d42bac` | 2026-10-11 09:10 | A17.3 outcome || `f7f65e4a281f685817ce71e29d1d9fd704684b27` | 2026-10-11 11:51 | Amendment 20: Codex Computer-Use (Sky) driven by the Codex CLI and `gpt-6-astra`, before any trial of that setup |+| `91a758aa914a5a4a671eb338c173fecc81cbc760` | 2026-10-11 14:54 | Amendment 22: background completion means the user was undisturbed (multi-player rule), the headline from the next full run |+| `c77413bbbd45eca33a34f722c197d35a51860900` | 2026-10-11 15:08 | Amendment 23: Codex CLI as a second harness (Cua Driver under Codex CLI), and the Claude helper setup made public |+| `47fd21ff82d2ebfc732442872508673b46a828d6` | 2026-10-11 15:12 | A23.1: the Codex CLI model is GPT-6.1 Sol if accessible, else `gpt-6-astra` |+| `ad49a3c1a8e373834fbe78ce53c82aeb4dd504be` | 2026-10-11 15:18 | A23: the Claude helper also runs under Codex CLI (`cx-claude-cu-helper`), the full 2 x 3 matrix |+| `a1036e6aac3f17ce15256e88cae7f1410e5eddd6` | 2026-10-11 15:22 | A23.1: GPT-6.1 Sol (`gpt-6.1-sol`, effort low) for the Codex CLI setups |Smoke runs (Amendments 14 to 17) validate the harness and are never analysed.Amendments 1 to 13 cover Bench v1, which used different tasks and tools; Benchv2 results are never pooled with them.**Coming next, each registered before its first trial:** a larger Bench v2 task-set, the final full run with the Amendment 20 setup, and a run on a sealed+set, the final full run with the Amendment 20 and 23 setups, and a run on a sealedheld-out task set.**Why a summary rather than the full text here.** The full pre-registration@@ -61,6 +70,9 @@ default effort, the same system prompt, `--strict-mcp-config`, ToolSearch on,and only the built-in tools `Skill`, `Read` (restricted to the skill directory)and `ToolSearch`, plus the setup's own computer-use MCP server. Each trial gets360 seconds and 45 turns. See [`automated-eval/macos_bench/RUNNER.md`](automated-eval/macos_bench/RUNNER.md).+The Codex CLI setups of Amendment 23 run the Codex CLI bundled with the ChatGPT+app as `codex app-server` instead, with the same prompts, limits, GUI-only guard+and checkers.## Setups@@ -68,10 +80,14 @@ and `ToolSearch`, plus the setup's own computer-use MCP server. Each trial gets| --- | --- | --- || Cua Driver | `cc-cua-driver-script` | Cua Driver built from a pinned main commit, with its skill and `run_script` on (the default from Cua Driver 0.35) || Codex Computer-Use (Sky) | `cc-codex-cu` | OpenAI's `cua_repl` launcher from the ChatGPT app 26.930 plugin, used unmodified except that the browser surface is off, through an MCP bridge. Claude chooses the actions. No skill ships with it. |-| Codex Computer-Use (Sky), driven by Codex CLI + `gpt-6-astra` | registered (Amendment 20), not yet run | The same `cua_repl` tool layer, driven by OpenAI's own agent (the Codex CLI bundled with the ChatGPT app, run as `codex app-server`) and model (`gpt-6-astra`), with the same prompts, approvals, budget, GUI-only guard and checkers. It joins the next full run. Its harness code will be added here once its smoke checks pass. |--The registered runs also included a third setup that is not part of this-public release. Internal baselines (other Cua Driver builds) may be run; they+| 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 | `cc-claude-cu-helper` | Claude Desktop 2.31226.0's `app-cu-helper`, used unmodified, behind Cua's minimal MCP adapter, which adds a window list and window screenshots. |+| Cua Driver, driven by Codex CLI | `cx-cua-driver` (Amendment 23, not yet run) | The `cc-cua-driver-script` build, daemon, MCP entry and system prompt, driven by the Codex CLI bundled with the ChatGPT app (`codex app-server`), without skill files. |+| Codex Computer-Use (Sky), driven by Codex CLI | `cx-codex-cu` (Amendments 20 and 23, not yet run) | The same `cua_repl` tool layer, driven by OpenAI's own agent (the Codex CLI bundled with the ChatGPT app, run as `codex app-server`) and model, with the same prompts, approvals, budget, GUI-only guard and checkers. |+| Claude Computer-Use (Desktop helper), driven by Codex CLI (same label and caveat) | `cx-claude-cu-helper` (Amendment 23, not yet run) | The `cc-claude-cu-helper` helper, adapter and MCP entry, driven by the Codex CLI. |++The Codex CLI setups (Amendment 23) use GPT-6.1 Sol (`gpt-6.1-sol`, default effort low). The+model is recorded in every row and named in the label; no numbers exist yet for+these setups. Internal baselines (other Cua Driver builds) may be run; theyare reported as baselines, never as headline setups.## Tasks and categories@@ -130,9 +146,19 @@ violation.**Success:** every required check of the task's checker passed, and there was noGUI-only violation. Checkers read app state and event logs; no model grades.-**Background completion (primary metric of the background condition):** the-trial passed, and the user window held focus and frontmost status the whole-time:+**Background completion, multi-player rule (Amendment 22; the primary metric+of the background condition from the next full run):** the trial passed, and+the user could have kept working at the same time, undisturbed: no loss of key+focus, no window raised over the user window, the user's typing never lost or+redirected, the real pointer never moved more than 1 px, the clipboard never+changed, no Space or full-screen switch, no sheet or dialog on the user's app,+and the user's app never deactivated or activated. BenchSentinel measures all+eight; a criterion that was not measured counts as a disturbance. Each criterion+is reported as its own column, overall and per category.++**Background completion, Amendment 15 (the primary metric before Amendment 22,+still reported):** the trial passed, and the user window held focus and+frontmost status the whole time:* no focus steal (the frontmost app never changed away from it);* no loss of key status;@@ -146,7 +172,7 @@ banner) is logged but not counted as a raise.**Secondary:** success regardless of focus; the number of focus steals; keyloss; windows raised; simulated user keystrokes swallowed (ticks when the userwindow was not active and key); pointer movement over 10 px (recorded, not part-of background completion); for the IR tasks, whether the interruption was+of the Amendment 15 background completion); for the IR tasks, whether the interruption wasshown, exercised, handled and the task completed; turns, equivalent cost andwall time per trial.@@ -183,8 +209,12 @@ differences are directional only.* **An MCP bridge, not the vendor's agent.** In the Codex Computer-Use (Sky)setup driven by Claude Code, Claude chooses the actions through OpenAI'stool; it is not OpenAI's agent as shipped. The Amendment 20 setup addresses- that. Comparing it with Cua Driver changes the tool layer, the agent and the- model at once, and reports will say so.+ that, and Amendment 23 runs all three tool layers under both harnesses, so+ each harness compares tool layers with its own agent and model.+* **Open terms checks.** Driving Codex Computer-Use from Claude Code is+ undocumented by OpenAI. Nobody has reviewed Anthropic's terms on driving+ Claude Desktop's computer-use helper from a third-party adapter, or on+ publishing its results.* **Simulated interruptions.** The IR prompts and overlays are drawn byBenchLab, not by macOS or Chrome.* **Small samples.** 5 runs per cell; a 5/5 has a Wilson 95% lower bound ofdiff --git a/benchmarks/cua-driver-bench/README.md b/benchmarks/cua-driver-bench/README.mdindex 21d5676853..4db682c5bd 100644--- a/benchmarks/cua-driver-bench/README.md+++ b/benchmarks/cua-driver-bench/README.md@@ -2,9 +2,9 @@Cua Driver Bench measures how well a computer-use tool layer lets an agent getreal desktop work done, and whether it can do that work in the background-without taking the user's focus, keyboard or pointer. The agent, the model, the-prompts and the limits are the same for every setup; only the computer-use tool-changes.+without taking the user's focus, keyboard or pointer. Within each agent+harness, the agent, the model, the prompts and the limits are the same for every+setup; only the computer-use tool changes.This directory holds the harness, the public task set and the method of**Bench v2**. Bench v2 is **macOS-only for now**: every task, app and@@ -50,9 +50,11 @@ The full method, with the reasons for each rule, is in [`METHOD.md`](METHOD.md).* **Pre-registration.** The protocol was committed before the first trial, andevery change since is a dated amendment committed before the trials it covers.`METHOD.md` lists the commits.-* **One agent, different tools.** Every setup runs Claude Code- (`claude -p`, Claude Sonnet 5.5) with the same system prompt, the same- built-in tools and the same limits: 360 s and 45 turns per trial.+* **One agent per harness, different tools.** The Claude Code setups run+ `claude -p` with Claude Sonnet 5.5; the Codex CLI setups (Amendment 23) run+ `codex app-server` with GPT-6.1 Sol (`gpt-6.1-sol`, default effort low). Within a harness every+ setup gets the same system prompt, the same built-in tools and the same+ limits: 360 s and 45 turns per trial.* **Two conditions.** In the *foreground* condition a small witness window isin front at the start and the agent may take focus. In the *background*condition a "User activity" window stays in front and types one character a@@ -73,12 +75,12 @@ The full method, with the reasons for each rule, is in [`METHOD.md`](METHOD.md).| Metric | Definition || --- | --- || Success | The checker passed every required check. A GUI-only violation is a fail. |-| Background completion | Background condition only, the primary metric: the trial passed **and** the user window held focus the whole time: no focus steal, no loss of key status, no window raised over it, no keystroke, click or scroll landing in it, and its text intact. |+| Background completion | Background condition only, the primary metric. From the next full run it follows the multi-player rule of Amendment 22: the trial passed **and** the user could have kept working undisturbed, as if two people shared the computer. None of eight disturbances may happen: loss of key focus, a window raised over the user window, the user's typing lost or redirected (or any keystroke, click or scroll landing in the user window), the real pointer moving more than 1 px, a clipboard change, a Space or full-screen switch, a sheet or dialog on the user's app, or the user's app being deactivated or activated. A criterion that was not measured counts as a disturbance. Each criterion is also reported as its own column. The earlier definition (Amendment 15: focus, key status, raises, typing; pointer not counted) is still reported next to it. || Focus steals | Times the frontmost app changed away from the witness or user window || Key loss | Times the witness or user window lost key status || Windows raised | Times a window of another app appeared above the witness or user window. Windows owned by the computer-use tool itself (an agent cursor, a status banner) are logged but not counted. || User keystrokes swallowed | Simulated user keystrokes that never reached the user window, because it was not active and key |-| Pointer moved | The real pointer moved more than 10 px. Recorded, not part of background completion. |+| Pointer moved | The real pointer moved. Part of background completion from Amendment 22 (more than 1 px); under the earlier definition it was recorded (more than 10 px) but not counted. || Interruption handled | IR tasks: the interruption was shown, appeared before the final action, and was answered safely || Cost, turns, wall time | Claude Code's equivalent cost, model turns and agent wall time per trial |@@ -88,11 +90,27 @@ per-category differences are directional only.## Setups+Amendment 23 runs every tool under both harnesses (a 2 x 3 matrix), so that+the agent harness and model are not confounded with the tool layer:++| Harness and model | Setups (arm ids) |+| --- | --- |+| Claude Code + Claude Sonnet 5.5 | Cua Driver (`cc-cua-driver-script`); Codex Computer-Use (Sky) (`cc-codex-cu`); Claude Computer-Use (Desktop helper) (`cc-claude-cu-helper`) |+| Codex CLI + GPT-6.1 Sol (`gpt-6.1-sol`, default effort low) | Cua Driver (`cx-cua-driver`); Codex Computer-Use (Sky) (`cx-codex-cu`); Claude Computer-Use (Desktop helper) (`cx-claude-cu-helper`) |+| Setup | Status | What the agent drives || --- | --- | --- |-| **Cua Driver** | 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`) |+| **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. |-| **Codex Computer-Use (Sky)**, driven by Codex CLI + `gpt-6-astra` | Planned (pre-registered in Amendment 20, not yet run) | The same Codex tool layer driven by OpenAI's own agent and model: the Codex CLI bundled with the ChatGPT app, run as `codex app-server`, with `gpt-6-astra`. Same prompts, approvals, limits, guard and checkers. Its harness code is `automated-eval/macos_bench/codex_native.py` (arm `cx-codex-cu`); its smoke checks pass, and it runs in the next full Bench v2 run. 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** | 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. |+| **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. |++The Codex CLI setups share `automated-eval/macos_bench/codex_native.py`. Their+model is GPT-6.1 Sol (`gpt-6.1-sol`, default effort low). The model is recorded+in every row and named in the setup's label. No numbers exist yet for the Codex+CLI setups.The harness also keeps internal baseline arms (the Cua Driver 0.34.0 release,main with `run_script` off, and the skill in the system prompt) that are not@@ -151,7 +169,24 @@ for app in "$CDB_BENCH_WORK"/taskpack/tasks/shared/*/apps/*; do (cd "$app" && npconfig from the plugin's own file (`tools/make_codex_cu_mcp.py`). The pluginis OpenAI's and is not redistributed here; driving it from a client otherthan OpenAI's is undocumented.-* **Codex CLI + `gpt-6-astra`** (arm `cx-codex-cu`). Nothing extra to install: it uses the Codex CLI bundled in the same ChatGPT app (`Contents/Resources/codex-cli/CodexCLI.app`) and the same `cua_repl` MCP config as the Claude-driven Codex setup. Point `CDB_CODEX_GATEWAY` at an OpenAI-compatible Responses endpoint that serves `gpt-6-astra` (default `http://127.0.0.1:4000/v1`). The pinned CLI build is in `pins.json` (`codex_native`).+* **Claude Computer-Use (Desktop helper)** (arm `cc-claude-cu-helper`). In the+ VM only, run `zsh tools/claude_cu_helper/install_cu_helper.sh`. It downloads+ Claude Desktop 2.31226.0 from Anthropic's own URL, checks the archive size and+ sha256 and the helper's sha256 and signature against `pins.json`+ (`claude_cu_helper`), unpacks it without moving it to `/Applications` or+ launching it, and builds `winlist` and `cu-disclaim` from source. Then give+ `app-cu-helper` Accessibility in System Settings. No Claude Desktop binary,+ app code or asset is included in this repository; only Cua's adapter is.+* **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:++* **OpenAI:** driving Codex Computer-Use from a client other than OpenAI's+ (the Claude Code setup) is undocumented, as noted above.+* **Anthropic:** nobody has reviewed Anthropic's terms on driving Claude+ Desktop's computer-use helper from a third-party adapter, or on publishing+ its results. The helper is an internal interface, not an Anthropic-supported+ procedure.### 4. Check, then rundiff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/RUNNER.md b/benchmarks/cua-driver-bench/automated-eval/macos_bench/RUNNER.mdindex 7fbec91ea7..4b0cf266b4 100644--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/RUNNER.md+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/RUNNER.md@@ -12,6 +12,8 @@ invocation, isolation, schedule, gates and output. The method is in| `cc-cua-driver-script` | Cua Driver | Cua Driver built from the pinned main commit, MCP server `cua`, `run_script` on, the skill of that commit in the working directory, and a short `run_script` addendum in the system prompt || `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 |+| `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 |Arms `codex-native-cu` and `codex-cua-driver` (`codex exec --json`, fromdiff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/arms.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/arms.pyindex 64d4e34643..65950dff8a 100644--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/arms.py+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/arms.py@@ -34,6 +34,7 @@ CLAUDE_ARMS = ("cc-cua-driver-main","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-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.@@ -42,7 +43,11 @@ DEFAULT_CLAUDE_ARMS = ("cc-cua-driver", "cc-codex-cu", "cc-cua-driver-main")CODEX_FALLBACK_ARMS = ("codex-native-cu", "codex-cua-driver")ARM_ALIASES = {"codex-cua-driver": "cua-driver-mcp"} # name used by the pilot code paths# Amendment 20 (CUA-1347): Codex CLI + gpt-6-astra driving Codex computer use natively (codex_native.py).-NATIVE_CODEX_ARMS = ("cx-codex-cu",)+NATIVE_CODEX_ARMS = (+ "cx-codex-cu",+ "cx-cua-driver",+ "cx-claude-cu-helper",+) # the last two: Amendment 23ALL_ARMS = CLAUDE_ARMS + CODEX_FALLBACK_ARMS + NATIVE_CODEX_ARMSCODEX_APP_RESOURCES = Path("/Applications/ChatGPT.app/Contents/Resources")diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/bench_v2.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/bench_v2.pyindex ddea6451b2..dd3499cbbc 100644--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/bench_v2.py+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/bench_v2.py@@ -498,6 +498,87 @@ def background_condition_score(}+# ------------------------------------------------------------------ multi-player background completion (A22)++# The owner's rule of 11 Oct 2026: the user could have kept working at the same time, undisturbed, as if two people+# shared the computer. Each criterion is True (held), False (the user was disturbed) or None (not measured).+MULTIPLAYER_CRITERIA: dict[str, str] = {+ "key_focus": "keyboard focus or key-window loss",+ "window_raised": "a window raised over the user's window",+ "typing": "the user's typing lost or redirected",+ "pointer": "the real pointer moved",+ "clipboard": "the user's clipboard changed",+ "space": "a desktop Space or full-screen switch",+ "dialog": "a modal, sheet or dialog on the user's app",+ "activation": "the user's app activated or deactivated",+}+POINTER_STILL_PX = 1.0 # "any amount": the simulated user never moves the pointer, so any movement above 1 px counts+++def _zero(value: Any) -> bool | None:+ return None if value is None else int(value) == 0+++def multiplayer_criteria(disturbance: dict[str, Any]) -> dict[str, bool | None]:+ d = disturbance or {}+ ua = d.get("user_activity")+ leaked = [d.get(k) for k in ("keystrokes_leaked", "clicks_leaked", "scrolls_leaked")]+ if ua is None:+ typing = None+ else:+ typing = (+ all(int(v or 0) == 0 for v in leaked)+ and int(ua.get("blocked") or 0) == 0+ and int(ua.get("text_disruptions") or 0) == 0+ and ua.get("text_intact_at_end") is not False+ )+ deviation = d.get("pointer_max_deviation_px")+ lost, gained = d.get("activations_lost"), d.get("activations_gained")+ activation = (+ None+ if d.get("front_changes") is None+ else (+ int(d.get("front_changes") or 0) == 0 and int(lost or 0) == 0 and int(gained or 0) == 0+ )+ )+ return {+ "key_focus": _zero(d.get("key_loss")),+ "window_raised": _zero(d.get("windows_raised")),+ "typing": typing,+ "pointer": None if deviation is None else float(deviation) <= POINTER_STILL_PX,+ "clipboard": _zero(d.get("clipboard_changes")),+ "space": _zero(d.get("space_switches")),+ "dialog": _zero(d.get("sheets_shown")),+ "activation": activation,+ }+++def multiplayer_score(+ disturbance: dict[str, Any],+ measured: bool,+ passed: bool,+ condition: str | None,+ rescore: bool = False,+) -> dict[str, Any]:+ """A22: background completion = the task passed AND none of the eight disturbances happened to the user.+ In a scored run an unmeasured criterion is not held (fail closed). ``rescore`` re-expresses a run from before+ A22 over the criteria it did measure; such figures are labelled secondary and list what was not measured."""+ criteria = multiplayer_criteria(disturbance)+ unmeasured = sorted(k for k, v in criteria.items() if v is None)+ if rescore:+ held = measured and all(v is not False for v in criteria.values())+ else:+ held = measured and all(v is True for v in criteria.values())+ return {+ "rule": "A22" + (" rescored" if rescore else ""),+ "condition": condition,+ "criteria": criteria,+ "unmeasured": unmeasured,+ "user_undisturbed": held,+ "background_completion": bool(passed and held) if condition == "background" else None,+ }++# ------------------------------------------------------------------ interruptionsdiff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/claude_arms.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/claude_arms.pyindex 462c67e668..22eee95e7f 100644--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/claude_arms.py+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/claude_arms.py@@ -182,6 +182,116 @@ def force_accessibility(arm: str) -> bool:return arm in FORCE_ACCESSIBILITY_ARMS+# Amendment 11: "Claude Desktop 2.31226.0 computer-use helper via a minimal adapter". The helper binary of Claude+# Desktop 2.31226.0 (Contents/Helpers/app-cu-helper, Anthropic-signed, used unmodified in place inside the unpacked,+# never-launched app) does the input; tools/claude_cu_helper/cu_helper_mcp.py exposes it as MCP server+# "claude-cu-helper" and adds a window list (winlist, CGWindowList) and window screenshots (/usr/sbin/screencapture).+# VM only (tools/claude_cu_helper/install_cu_helper.sh). Cua Driver is not used by this arm.+CU_HELPER_DIR = WORK / "claude-cu-helper"+CU_HELPER_ADAPTER = CU_HELPER_DIR / "cu_helper_mcp.py"+CU_HELPER_WINLIST = CU_HELPER_DIR / "winlist"+CU_HELPER_LAUNCHER = (+ CU_HELPER_DIR / "cu-disclaim"+) # starts the helper as its own responsible process (A11)+CU_DESKTOP_DIR = WORK / "claude-desktop-2.31226.0"+CU_HELPER_BIN = (+ CU_DESKTOP_DIR / "extracted" / "Claude.app" / "Contents" / "Helpers" / "app-cu-helper"+)+CU_HELPER_SERVER = "claude-cu-helper"+CU_HELPER_PYTHON = Path("/opt/homebrew/bin/python3")+CU_HELPER_LABEL = "Claude Desktop 2.31226.0 computer-use helper via a minimal adapter"+++@dataclass(frozen=True)+class CuHelperBuild:+ arm: str+ adapter: Path+ helper: Path+ winlist: Path+ launcher: Path++ def argv(self, actions: list[str]) -> list[str]:+ return [+ str(CU_HELPER_PYTHON),+ "-I",+ "-B",+ str(self.adapter),+ "--helper",+ str(self.helper),+ "--winlist",+ str(self.winlist),+ "--launcher",+ str(self.launcher),+ "--actions",+ ",".join(actions),+ ]+++CU_HELPER_BUILDS = {+ "cc-claude-cu-helper": CuHelperBuild(+ "cc-claude-cu-helper",+ CU_HELPER_ADAPTER,+ CU_HELPER_BIN,+ CU_HELPER_WINLIST,+ CU_HELPER_LAUNCHER,+ )+}+CU_HELPER_ARMS = tuple(CU_HELPER_BUILDS)+++def cu_helper_env() -> dict[str, str]:+ """The adapter's environment: closed PATH, real HOME (the helper keeps no state there), nothing else."""+ return {+ "HOME": os.environ.get("HOME", "/tmp"),+ "PATH": "/usr/bin:/bin:/usr/sbin:/sbin",+ "DO_NOT_TRACK": "1",+ }+++def cu_helper_actions(pins: dict[str, Any] | None = None) -> list[str]:+ """The input tools the adapter offers: exactly the pinned list from the VM probe (A11)."""+ pins = pins if pins is not None else load_pins()+ return list((pins.get("claude_cu_helper") or {}).get("actions") or [])+++def cu_helper_observed(build: CuHelperBuild | None = None) -> dict[str, Any]:+ """What is installed for the helper arm right now, keyed like pins.json ``claude_cu_helper``."""+ build = build or CU_HELPER_BUILDS["cc-claude-cu-helper"]+ zip_path = CU_DESKTOP_DIR / "Claude-2.31226.0.zip"+ return {+ "desktop_zip_sha256": sha256_file(zip_path) if zip_path.is_file() else None,+ "helper_sha256": sha256_file(build.helper) if build.helper.is_file() else None,+ "adapter_sha256": sha256_file(build.adapter) if build.adapter.is_file() else None,+ "winlist_sha256": sha256_file(build.winlist) if build.winlist.is_file() else None,+ "launcher_sha256": sha256_file(build.launcher) if build.launcher.is_file() else None,+ }+++def check_cu_helper_pins(+ pins: dict[str, Any], observed: dict[str, Any]+) -> list[tuple[str, str, str]]:+ want = pins.get("claude_cu_helper", {})+ out = []+ for key in (+ "desktop_zip_sha256",+ "helper_sha256",+ "adapter_sha256",+ "winlist_sha256",+ "launcher_sha256",+ ):+ ok = bool(want.get(key)) and observed.get(key) == want.get(key)+ out.append(+ (+ f"pin claude_cu_helper.{key}",+ "pass" if ok else "fail",+ str(observed.get(key))+ if ok+ else f"observed {observed.get(key)!r}, pinned {want.get(key)!r}",+ )+ )+ return out++CODEX_CU_MCP_CANDIDATES = (WORK / "codex-access" / "mcp.json",WORK / "codex-access" / "mcp_cua_repl_computer.json",@@ -203,6 +313,9 @@ ARM_DESCRIPTIONS = {"CUA_DRIVER_EXPERIMENTAL_SCRIPT=1 for earlier builds) and the run_script addendum in the system prompt","cc-codex-cu": "Claude Code + Codex computer-use cua_repl MCP (server codex-cu), no skill","cc-codex-cu-1007-browser": "Claude Code + Codex 26.1007.21159 cua_repl MCP (server codex-cu), surfaces browser+computer, no skill (Amendment 10)",+ "cc-claude-cu-helper": "Claude Code + "+ + CU_HELPER_LABEL+ + " (MCP server claude-cu-helper; Amendment 11), no skill",}SKILL_PROMPT_HEADER = (@@ -295,6 +408,22 @@ def mcp_config_for(path = run_dir / f"mcp-{arm}.json"path.write_text(json.dumps(config, indent=2) + "\n", "utf-8")return path, "cua"+ if arm in CU_HELPER_BUILDS:+ build = CU_HELPER_BUILDS[arm]+ command, *args = build.argv(cu_helper_actions())+ config = {+ "mcpServers": {+ CU_HELPER_SERVER: {+ "type": "stdio",+ "command": command,+ "args": args,+ "env": cu_helper_env(),+ }+ }+ }+ path = run_dir / f"mcp-{arm}.json"+ path.write_text(json.dumps(config, indent=2) + "\n", "utf-8")+ return path, CU_HELPER_SERVERif arm in CODEX_ARMS:source = (resolve_codex_cu_config(codex_cu_config)diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/claude_events.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/claude_events.pyindex 5acb3715d3..fb95239a23 100644--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/claude_events.py+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/claude_events.py@@ -96,10 +96,26 @@ def strip_mcp(name: str) -> tuple[str | None, str]:return None, name+# Amendment 11: the cc-claude-cu-helper adapter (server "claude-cu-helper"), tools named like Claude's own+# background computer-use tools.+CU_HELPER_CLASSES = {+ "app_list_windows": "observe",+ "app_screenshot": "observe",+ "app_click": "click",+ "app_type": "type",+ "app_key": "key",+ "app_scroll": "scroll",+ "app_drag": "drag",+ "app_hover": "other", # like Cua Driver's move_cursor+}++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 tool in CUA_CLASSES:return CUA_CLASSES[tool]if tool == "js":diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/codex_native.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/codex_native.pyindex 35a16e69ac..996715bced 100644--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/codex_native.py+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/codex_native.py@@ -51,8 +51,21 @@ from pathlib import Pathfrom typing import Any, CallableARM = "cx-codex-cu"-ARMS = (ARM,)+# cx-cua-driver and cx-claude-cu-helper: Amendment 23, Cua Driver's MCP server and Cua's helper adapter under the+# same Codex host+ARMS = (ARM, "cx-cua-driver", "cx-claude-cu-helper")SERVER = "cua_repl" # the server name of the unified-computer-use plugin+SERVER_OF = {+ "cx-codex-cu": SERVER,+ "cx-cua-driver": "cua",+ "cx-claude-cu-helper": "claude-cu-helper",+}+# The Claude Code arm whose MCP config (and, for Cua Driver, whose daemon, build and system prompt) the Codex arm uses.+SOURCE_ARM = {+ "cx-codex-cu": "cc-codex-cu",+ "cx-cua-driver": "cc-cua-driver-script",+ "cx-claude-cu-helper": "cc-claude-cu-helper",+}ENABLED_TOOLS = ("js","js_reset",@@ -60,12 +73,26 @@ ENABLED_TOOLS = (CODEX_CLI = Path("/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex")-MODEL = "gpt-6-astra"-EFFORT = "medium" # gpt-6-astra's default_reasoning_level in the Codex model catalog; Claude arms use their default+# Amendment 23: GPT-6.1 Sol (`gpt-6.1-sol`, served through the gateway), at its catalog default effort+# (`low`), as the Claude arms use Claude's default. A20's smoke used gpt-6-astra (`medium`). The model and effort are+# recorded in every row and named in the setup's label.+MODEL_DEFAULT_EFFORT = {"gpt-6-astra": "medium", "gpt-6.1-sol": "low"}+MODEL_DISPLAY = {"gpt-6-astra": "GPT-6 Astra", "gpt-6.1-sol": "GPT-6.1 Sol"}+MODEL = (+ os.environ.get("CDB_CODEX_MODEL") or "gpt-6.1-sol"+) # A23.1: served through the gateway since 11 Oct+EFFORT = os.environ.get("CDB_CODEX_EFFORT") or MODEL_DEFAULT_EFFORT.get(MODEL, "medium")GATEWAY_ENV = "CDB_CODEX_GATEWAY"DEFAULT_GATEWAY = "http://127.0.0.1:4000/v1"CLOSED_PATH = "/usr/bin:/bin:/usr/sbin:/sbin"-LABEL = "Codex Computer-Use (Sky), driven by Codex CLI + GPT-6 Astra"+LABELS = {+ "cx-codex-cu": f"Codex Computer-Use (Sky), driven by Codex CLI + {MODEL_DISPLAY.get(MODEL, MODEL)}",+ "cx-cua-driver": f"Cua Driver, driven by Codex CLI + {MODEL_DISPLAY.get(MODEL, MODEL)}",+ "cx-claude-cu-helper": "Claude Computer-Use (Desktop helper), driven by Codex CLI + "+ f"{MODEL_DISPLAY.get(MODEL, MODEL)} (Claude Desktop 2.31226.0 computer-use helper via a minimal adapter; an "+ "internal interface, not an Anthropic-supported procedure)",+}+LABEL = LABELS[ARM]# Features of this Codex build that would give the agent a non-GUI route or a second agent. Off for every trial.DISABLED_FEATURES = (@@ -113,7 +140,7 @@ def gateway() -> str:return os.environ.get(GATEWAY_ENV) or DEFAULT_GATEWAY-def server_entry(mcp_json: Path) -> dict[str, Any]:+def server_entry(mcp_json: Path, arm: str = ARM) -> dict[str, Any]:"""The single server of arm B's MCP config (written by tools/make_codex_cu_mcp.py from the plugin)."""data = json.loads(mcp_json.read_text("utf-8"))servers = data.get("mcpServers") or {}@@ -121,7 +148,7 @@ def server_entry(mcp_json: Path) -> dict[str, Any]:raise ValueError(f"{mcp_json}: expected exactly one MCP server, found {sorted(servers)}")entry = next(iter(servers.values()))env = dict(entry.get("env") or {})- if env.get("CUA_REPL_ENABLED_SURFACES") != "computer":+ if SERVER_OF[arm] == SERVER and env.get("CUA_REPL_ENABLED_SURFACES") != "computer":raise ValueError(f"{mcp_json}: CUA_REPL_ENABLED_SURFACES must be 'computer', got {env.get('CUA_REPL_ENABLED_SURFACES')!r}")@@ -129,8 +156,14 @@ def server_entry(mcp_json: Path) -> dict[str, Any]:def config_toml(- entry: dict[str, Any], model: str, effort: str, instructions: str, codex_home: Path+ entry: dict[str, Any],+ model: str,+ effort: str,+ instructions: str,+ codex_home: Path,+ arm: str = ARM,) -> str:+ server = SERVER_OF[arm]env = dict(entry["env"]) # unchanged from arm B: Sky's service and pipe live under the user's own home@@ -156,28 +189,33 @@ def config_toml("stream_max_retries = 2","stream_idle_timeout_ms = 120000","",- f"[mcp_servers.{SERVER}]",+ f"[mcp_servers.{server}]",f"command = {_q(entry['command'])}",f"args = [{', '.join(_q(a) for a in entry['args'])}]","startup_timeout_sec = 120",'default_tools_approval_mode = "approve"',- f"enabled_tools = [{', '.join(_q(t) for t in ENABLED_TOOLS)}]",+ *(+ [f"enabled_tools = [{', '.join(_q(t) for t in ENABLED_TOOLS)}]"]+ if server == SERVER+ else []+ ),"",- f"[mcp_servers.{SERVER}.env]",+ f"[mcp_servers.{server}.env]",*[f"{key} = {_q(str(value))}" for key, value in sorted(env.items())],]return "\n".join(lines) + "\n"def render_home(- home: Path, mcp_json: Path, model: str, effort: str, instructions: str+ home: Path, mcp_json: Path, model: str, effort: str, instructions: str, arm: str = ARM) -> dict[str, str]:"""Write a fresh CODEX_HOME for one trial; return the closed environment for `codex exec`."""codex_home = home / ".codex"codex_home.mkdir(parents=True, exist_ok=True)(home / "tmp").mkdir(exist_ok=True)(codex_home / "config.toml").write_text(- config_toml(server_entry(mcp_json), model, effort, instructions, codex_home), "utf-8"+ config_toml(server_entry(mcp_json, arm), model, effort, instructions, codex_home, arm),+ "utf-8",)return {# HOME stays the user's, as for the Claude-driven arms (Sky's native pipe is found from it); only Codex's@@ -209,7 +247,8 @@ class Translator:result), so `bench_v2.GuiOnlyGuard`, `bench_v2.scan_events` and `claude_events.summarize` read this arm thesame way as the Claude arms."""- def __init__(self) -> None:+ def __init__(self, server: str = SERVER) -> None:+ self.server = serverself.final_text = ""self.errors: list[str] = []self.usage = {@@ -242,8 +281,10 @@ class Translator:"type": "system","subtype": "init","codex_thread": (params.get("thread") or {}).get("id"),- "tools": [f"mcp__{SERVER}__{t}" for t in ENABLED_TOOLS],- "mcp_servers": [{"name": SERVER, "status": "connected"}],+ "tools": [f"mcp__{SERVER}__{t}" for t in ENABLED_TOOLS]+ if self.server == SERVER+ else [],+ "mcp_servers": [{"name": self.server, "status": "connected"}],})elif method == "thread/tokenUsage/updated":@@ -350,6 +391,7 @@ def run_codex(elicitation_path: Path | None = None,abort: Any = None,answer: Callable[[str, set[str]], dict[str, Any]] | None = None,+ server: str = SERVER,) -> dict[str, Any]:"""Run one trial through `codex app-server` in its own process group: initialize, start a thread in ``cwd``,start one turn with ``prompt``, answer server requests, and stop at turn/completed, the wall-time limit, the@@ -361,7 +403,7 @@ def run_codex(answer = claude_driver.answer_elicitationallowed = {a.strip().lower() for a in (allowed_apps or set())}started = time.monotonic()- translator = Translator()+ translator = Translator(server)done = threading.Event()responses: dict[int, dict[str, Any]] = {}got = threading.Condition()diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/pins.json b/benchmarks/cua-driver-bench/automated-eval/macos_bench/pins.jsonindex c84c7fbc83..ad05a78601 100644--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/pins.json+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/pins.json@@ -63,11 +63,63 @@"_service_executable_sha256": "fa5b5d685f550af82902cff1a345db558a1da3eb526cf78cd4659fa0dcde01a5","_signature": "Developer ID Application: OpenAI OpCo, LLC (2DC432GLL2), notarized"},+ "claude_cu_helper": {+ "_note": "Amendment 11: arm cc-claude-cu-helper, \"Claude Desktop 2.31226.0 computer-use helper via a minimal adapter\". Claude Desktop 2.31226.0 downloaded and unpacked in a clone of the bench VM only (never launched, never moved to /Applications). The helper is used unmodified in place; tools/claude_cu_helper/install_cu_helper.sh checks the archive and helper hashes and the signature. The helper's Accessibility grant was given in System Settings (Privacy & Security > Accessibility > +), through the VM's UI. Public copy: adapter_sha256 is the published cu_helper_mcp.py with its licence header (the registered runs used the same adapter without it, d3f7797bee7b).",+ "desktop_version": "2.31226.0",+ "desktop_zip_url": "https://downloads.claude.ai/releases/darwin/universal/2.31226.0/Claude-eb794d1033f2a59c2cd89aa29ed1f8b5de12aa73.zip",+ "desktop_zip_bytes": 383954641,+ "desktop_zip_sha256": "bd38f1051a14cabd893c7422e106ad6318e8785f19472c8064eafa64ce235820",+ "helper_sha256": "7bd631e8b5ae36941ac551c474055e2eff32163db6684628eac5cfcabcb3dc14",+ "helper_signature": "Developer ID Application: Anthropic PBC (Q6L2SF6YDW), identifier app-cu-helper",+ "adapter_sha256": "ed0da1fc5d00da2d8a3f8a43e3b18df9a41150e97a41632107eb8f82bcd058eb",+ "winlist_sha256": "d150737bd4a3f7995a2abe7a615b951da8189236da7e3cb969e0de670d9614d4",+ "launcher_sha256": "c9dd836899692149e0a7d2bf144aa5f1180b359661016fddd267140c77e0057f",+ "actions": [+ "click",+ "right_click",+ "type",+ "key",+ "scroll",+ "drag",+ "hover"+ ],+ "tools": [+ "app_click",+ "app_drag",+ "app_hover",+ "app_key",+ "app_list_windows",+ "app_screenshot",+ "app_scroll",+ "app_type"+ ],+ "probe_required": [+ "skylight",+ "axTrusted"+ ],+ "helper_methods": [+ "probe",+ "dispatchRaw",+ "wakeChromiumCompositor",+ "bringWindowToActiveSpace",+ "keyWindowSpoof"+ ],+ "dispatch_kinds": [+ "click",+ "rclick",+ "mclick",+ "drag",+ "scroll",+ "hover",+ "key",+ "type"+ ]+ },"codex_native": {- "_note": "Amendment 20 (CUA-1347): the Codex CLI bundled in ChatGPT 26.930.51102 (codex-cli/CodexCLI.app, Developer ID OpenAI OpCo, LLC, 2DC432GLL2), host protocol `codex app-server`, model gpt-6-astra at its catalog default effort (medium). Pinned from the host's identical app version; the smoke checks the VM copy.",+ "_note": "Amendment 20 (CUA-1347): the Codex CLI bundled in ChatGPT 26.930.51102 (codex-cli/CodexCLI.app, Developer ID OpenAI OpCo, LLC, 2DC432GLL2), host protocol `codex app-server`, model gpt-6.1-sol (Amendment 23) at its catalog default effort (low); A20's smoke used gpt-6-astra (medium). Pinned from the host's identical app version; the smoke checks the VM copy.","codex_cli_version": "codex-cli 0.160.0","codex_cli_sha256": "6b582e8813ce7e8ed4c52814ee5cf230dba647bf2292df747a4003f2657ef201",- "model": "gpt-6-astra",- "effort": "medium"+ "model": "gpt-6.1-sol",+ "effort": "low"}}diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/run_bench.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/run_bench.pyindex c74e83f53b..cf2a0f3150 100644--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/run_bench.py+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/run_bench.py@@ -537,6 +537,81 @@ def mcp_list_tools(command: str, args: list[str], env: dict[str, str]) -> list[sclient.close()+def cu_helper_probe(+ helper: Path, launcher: Path | None = None, timeout: float = 20.0+) -> dict[str, Any]:+ """Amendment 11: the helper's own ``probe`` (capability flags), asked directly over its JSON-RPC stdin/stdout,+ started through the same launcher as in a trial (so ``axTrusted`` is the helper's own grant)."""+ proc = subprocess.run(+ [str(launcher), str(helper)] if launcher else [str(helper)],+ input=json.dumps({"jsonrpc": "2.0", "id": 1, "method": "probe", "params": {}}) + "\n",+ capture_output=True,+ text=True,+ timeout=timeout,+ env={"PATH": "/usr/bin:/bin", "HOME": os.environ.get("HOME", "")},+ )+ for line in proc.stdout.splitlines():+ try:+ reply = json.loads(line)+ except json.JSONDecodeError:+ continue+ if reply.get("id") == 1:+ return reply.get("result") or {"error": reply.get("error")}+ return {"error": f"no probe reply (rc={proc.returncode}): {proc.stderr[-300:]}"}+++def cu_helper_live_checks(ctx: "Ctx", arm: str) -> list[tuple[str, str, str]]:+ """Amendment 11 preflight: the helper's probe reports the pinned required flags, and the adapter, started+ exactly as in a trial, lists exactly the pinned tools."""+ out: list[tuple[str, str, str]] = []+ pins = ca.load_pins().get("claude_cu_helper", {})+ build = ca.CU_HELPER_BUILDS[arm]+ try:+ probe = cu_helper_probe(build.helper, build.launcher)+ except Exception as error: # noqa: BLE001+ probe = {"error": f"{type(error).__name__}: {error}"}+ ctx.versions.setdefault("claude_cu_helper", {})["probe"] = probe+ required = pins.get("probe_required") or ["skylight", "axTrusted"]+ missing = [k for k in required if probe.get(k) is not True]+ out.append(+ (+ f"{arm} helper probe: {', '.join(required)}",+ "pass" if not missing else "fail",+ json.dumps(probe)[:400] + (f" missing {missing}" if missing else ""),+ )+ )+ path, _server = ctx.mcp[arm]+ command, cargs, env = mcp_entry(path)+ try:+ tools = sorted(mcp_list_tools(command, cargs, env))+ want = sorted(pins.get("tools") or [])+ out.append(+ (+ f"{arm} adapter lists the pinned tools",+ "pass" if want and tools == want else "fail",+ f"{tools}" + ("" if tools == want else f" pinned {want}"),+ )+ )+ except Exception as error: # noqa: BLE001+ out.append((f"{arm} adapter MCP server", "fail", f"{type(error).__name__}: {error}"))+ return out+++def cu_helper_row_identity(ctx: "Ctx") -> dict[str, Any]:+ pin = ca.load_pins().get("claude_cu_helper", {})+ seen = ctx.versions.get("claude_cu_helper") or {}+ return {+ "label": ca.CU_HELPER_LABEL,+ "desktop_version": pin.get("desktop_version"),+ "helper_sha256": seen.get("helper_sha256"),+ "adapter_sha256": seen.get("adapter_sha256"),+ "actions": ca.cu_helper_actions(),+ "probe": {+ k: v for k, v in (seen.get("probe") or {}).items() if isinstance(v, (bool, str, int))+ },+ }++def mcp_entry(config_path: Path) -> tuple[str, list[str], dict[str, str]]:data = json.loads(config_path.read_text("utf-8"))((name, entry),) = data["mcpServers"].items()@@ -598,7 +673,7 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]sentinel_front = True if bench_v2 else bool(spec.get("sentinel_frontmost", True))condition = getattr(args, "condition", "foreground") if bench_v2 else None # Amendment 15# Per-build Cua Driver identity (Amendment 3); arm B rows keep the 0.34.0 values of the recorder build.- build_versions = (ctx.versions.get("builds") or {}).get(arm) or (+ build_versions = (ctx.versions.get("builds") or {}).get(cxn.SOURCE_ARM.get(arm, arm)) or (ctx.versions.get("builds") or {}).get("cc-cua-driver", {})trial_dir = ctx.run_dir / "trials" / entry["trial_id"] / f"a{attempt}"@@ -651,7 +726,9 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]"macos": ctx.versions.get("macos"),"bench_repo_commit": ctx.versions.get("bench_repo_commit"),"bench_src_sha256": ctx.versions.get("bench_src_sha256"),- "system_prompt_sha256": hashlib.sha256(ca.system_prompt_for(arm).encode()).hexdigest(),+ "system_prompt_sha256": hashlib.sha256(+ ca.system_prompt_for(cxn.SOURCE_ARM.get(arm, arm)).encode()+ ).hexdigest(),"skill_in_prompt": bool(getattr(ca.CUA_BUILDS.get(arm), "skill_in_prompt", False)),"electron_named_bundles": spec.get("kind") == "cdb"and os.environ.get("CDB_ELECTRON_SHARED") != "1",@@ -659,6 +736,11 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]"quota_seven_day_before": (ctx.quota or {}).get("seven_day"),# whether Chrome/Electron got the force-accessibility switch (no shipped arm sets it)"force_accessibility": ca.force_accessibility(arm),+ # Amendment 11: the helper arm's identity (Desktop version, helper and adapter hashes, offered actions)+ "claude_cu_helper": cu_helper_row_identity(ctx)+ if cxn.SOURCE_ARM.get(arm, arm) in ca.CU_HELPER_ARMS+ else None,+ # Amendment 20: the native Codex arm's identity (Codex CLI build, model, effort)"codex_native": ctx.versions.get("codex_native") if arm in cxn.ARMS else None,}if arm in cxn.ARMS:@@ -707,6 +789,10 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]) # no stale clipboard between trialsif arm in ca.CUA_ARMS:ensure_agent_daemon(ctx, arm)+ elif (+ cxn.SOURCE_ARM.get(arm) in ca.CUA_ARMS+ ): # A23: Cua Driver under Codex uses that build's daemon+ ensure_agent_daemon(ctx, cxn.SOURCE_ARM[arm])if getattr(args, "park_pointer", False):row["pointer_parked"] = park_pointer(ctx)lab_app = Path(args.build_dir) / "BenchLab.app"@@ -792,7 +878,8 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]mcp_path,cxn.MODEL,cxn.EFFORT,- ca.system_prompt_for(arm),+ ca.system_prompt_for(cxn.SOURCE_ARM[arm]),+ arm,),cwd,prompt,@@ -804,6 +891,7 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]allowed_apps=allowed_apps(task),elicitation_path=artifacts / "elicitations.jsonl",abort=v2.EitherEvent(ctx.abort, guard.stop) if guard else ctx.abort,+ server=cxn.SERVER_OF[arm],)else:claude = claude_driver.run_claude(@@ -883,6 +971,14 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]if cdb is not None:cdb.stop_apps()pilot.sweep_processes(str(trial_dir))+ helper_arm = cxn.SOURCE_ARM.get(+ arm, arm+ ) # A23: the helper under Codex CLI uses the same build+ if helper_arm in ca.CU_HELPER_ARMS:+ # the adapter and its helper end with claude's process group; a survivor could post input later+ row["cu_helper_leftover_killed"] = pilot.sweep_processes(+ str(ca.CU_HELPER_BUILDS[helper_arm].helper)+ ) + (pilot.sweep_processes(str(ca.CU_HELPER_BUILDS[helper_arm].adapter)))kill_bench_apps()reset_needs_apps(needs)saved = strip_stream_file(stream_path)@@ -1017,6 +1113,12 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]"raised_by": summary_sentinel.get("raised_by", []),"overlay_owners": summary_sentinel.get("overlay_owners", []),"user_activity": summary_sentinel.get("user_activity"),+ # Amendment 22: the remaining multi-player measures (None when the sentinel did not record them)+ "activations_lost": summary_sentinel.get("activations_lost"),+ "activations_gained": summary_sentinel.get("activations_gained"),+ "clipboard_changes": summary_sentinel.get("clipboard_changes"),+ "space_switches": summary_sentinel.get("space_switches"),+ "sheets_shown": summary_sentinel.get("sheets_shown"),},"sentinel_frontmost": sentinel_front,"gui_only": gui_only,@@ -1049,6 +1151,14 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]if bench_v2else None)+ # A22: the headline background metric, multi-player background completion, with each criterion on its own+ row["multiplayer"] = (+ v2.multiplayer_score(+ row["disturbance"], bool(row["background"]["measured"]), bool(row["passed"]), condition+ )+ if bench_v2+ else None+ )if video_raw and ctx.compress:ctx.compress.submit(video_raw, trial_dir / "video")(trial_dir / "trial.json").write_text(json.dumps(row, indent=2) + "\n", "utf-8")@@ -1640,7 +1750,9 @@ def native_codex_checks(ctx: Ctx, arm: str, with_models: bool) -> list[tuple[strmcp_path, _server = ctx.mcp[arm]home = ctx.run_dir / f"preflight-{arm}-home"shutil.rmtree(home, ignore_errors=True)- env = cxn.render_home(home, mcp_path, cxn.MODEL, cxn.EFFORT, ca.system_prompt_for(arm))+ env = cxn.render_home(+ home, mcp_path, cxn.MODEL, cxn.EFFORT, ca.system_prompt_for(cxn.SOURCE_ARM[arm]), arm+ )cwd = ca.prepare_cwd(arm)stream = ctx.run_dir / f"preflight-init-{arm}.tsv"result = cxn.run_codex(@@ -1653,6 +1765,7 @@ def native_codex_checks(ctx: Ctx, arm: str, with_models: bool) -> list[tuple[strctx.run_dir / f"preflight-{arm}-raw.tsv",stream,ctx.run_dir / f"preflight-{arm}.stderr",+ server=cxn.SERVER_OF[arm],)summary = claude_events.summarize(claude_events.read_events(stream))text = (summary.get("final_text") or "").strip()@@ -1925,20 +2038,44 @@ def preflight(ctx: Ctx, with_models: bool = True) -> list[tuple[str, str, str]]:add("Codex CLI in the ChatGPT app", "fail", str(cxn.CODEX_CLI))continuetry:- path, _server = ctx.mcp[native_arm]- entry = cxn.server_entry(path)+ path, server = ctx.mcp[native_arm]+ entry = cxn.server_entry(path, native_arm)+ source = cxn.SOURCE_ARM[native_arm]+ if (+ source in ca.CUA_ARMS and not offline+ ): # A23: Cua Driver under Codex uses that build's daemon+ ensure_agent_daemon(ctx, source)tools = mcp_list_tools(entry["command"], entry["args"], entry["env"])+ want = (+ {"js", "js_reset"}+ if server == cxn.SERVER+ else set(ca.load_pins().get("claude_cu_helper", {}).get("tools") or ["app_click"])+ if server == ca.CU_HELPER_SERVER+ else {"list_apps", "run_script"}+ )add(- f"{native_arm} cua_repl MCP server lists js, js_reset",- "pass" if {"js", "js_reset"} <= set(tools) else "fail",- str(tools),+ f"{native_arm} {server} MCP server lists {sorted(want)}",+ "pass" if want <= set(tools) else "fail",+ f"{len(tools)} tools",)except Exception as error: # noqa: BLE001- add(f"{native_arm} cua_repl MCP server", "fail", f"{type(error).__name__}: {error}")+ add(f"{native_arm} MCP server", "fail", f"{type(error).__name__}: {error}")for name, status, detail in native_codex_checks(ctx, native_arm, with_models and not offline):add(name, status, detail)+ helper_sources = {+ cxn.SOURCE_ARM.get(a, a) for a in ctx.arm_names+ } # A23: also for cx-claude-cu-helper+ for helper_arm in [a for a in ca.CU_HELPER_ARMS if a in helper_sources]:+ observed = ca.cu_helper_observed(ca.CU_HELPER_BUILDS[helper_arm])+ ctx.versions.setdefault("claude_cu_helper", {}).update(observed)+ for name, status, detail in ca.check_cu_helper_pins(pins, observed):+ add(name, status, detail)+ if offline:+ continue+ for name, status, detail in cu_helper_live_checks(ctx, helper_arm):+ add(name, status, detail)cdb_ids = [t for t in ctx.task_ids if task_spec(ctx.tasks[t]).get("kind") == "cdb"]if cdb_ids:want = ca.load_pins().get("cdb_pack", {}).get("tree_sha256", {})@@ -2274,7 +2411,9 @@ def setup_arms(ctx: Ctx) -> None:else None,}for arm, build in ca.CUA_BUILDS.items()- if arm in ctx.arm_names or arm == "cc-cua-driver"+ if arm in ctx.arm_names+ or arm == "cc-cua-driver"+ or arm in {cxn.SOURCE_ARM.get(a) for a in ctx.arm_names}},pins=pins,system_prompt_sha256=hashlib.sha256(ca.SYSTEM_PROMPT.encode()).hexdigest(),@@ -2287,11 +2426,13 @@ def setup_arms(ctx: Ctx) -> None:raise SystemExit(f"arm {arm} unavailable: {error}")elif (arm in cxn.ARMS- ): # Amendment 20: arm B's cua_repl entry, copied unmodified, driven by Codex CLI+ ): # A20/A23: the source Claude arm's MCP entry, copied unmodified, driven by Codex CLItry:- path, _server = ca.mcp_config_for("cc-codex-cu", ctx.run_dir, ctx.args.codex_cu_mcp)- cxn.server_entry(path)- ctx.mcp[arm] = (path, cxn.SERVER)+ path, _server = ca.mcp_config_for(+ cxn.SOURCE_ARM[arm], ctx.run_dir, ctx.args.codex_cu_mcp+ )+ cxn.server_entry(path, arm)+ ctx.mcp[arm] = (path, cxn.SERVER_OF[arm])except (FileNotFoundError, ValueError) as error:raise SystemExit(f"arm {arm} unavailable: {error}")ctx.versions["codex_native"] = cxn.observed()diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/swift/BenchSentinel.swift b/benchmarks/cua-driver-bench/automated-eval/macos_bench/swift/BenchSentinel.swiftindex d4901b2f80..b9b859aa79 100644--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/swift/BenchSentinel.swift+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/swift/BenchSentinel.swift@@ -147,6 +147,12 @@ final class SentinelDelegate: NSObject, NSApplicationDelegate, NSTextFieldDelega"mouse": mouseInfo(), "front": frontInfo(), "active": NSApp.isActive,"key": window?.isKeyWindow ?? false, "idle": idleInfo(),]+ // Amendment 22 (multi-player background completion): the user's clipboard, whether the user's window is+ // on the active Space, and whether a sheet or modal window appeared on the user's app.+ out["clip"] = NSPasteboard.general.changeCount+ out["onspace"] = window?.isOnActiveSpace ?? false+ out["sheet"] = (window?.attachedSheet != nil) || (NSApp.modalWindow != nil)+ || NSApp.windows.contains { $0 !== window && $0.isVisible }let above = windowsAbove()out["above_n"] = above.countif !above.isEmpty { out["above"] = above }@@ -215,6 +221,12 @@ final class SentinelDelegate: NSObject, NSApplicationDelegate, NSTextFieldDeleganc.addObserver(forName: NSApplication.didResignActiveNotification, object: nil, queue: .main) { [weak self] _ in self?.emit("didResignActive", ["front": self?.frontInfo() ?? [:]]) }+ // Amendment 22: a desktop Space or full-screen switch.+ NSWorkspace.shared.notificationCenter.addObserver(+ forName: NSWorkspace.activeSpaceDidChangeNotification, object: nil, queue: .main+ ) { [weak self] _ in+ self?.emit("space", ["onspace": self?.window?.isOnActiveSpace ?? false])+ }// Catches focus flips shorter than one sampler tick.NSWorkspace.shared.notificationCenter.addObserver(forName: NSWorkspace.didActivateApplicationNotification, object: nil, queue: .maindiff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/swift/summarize_sentinel.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/swift/summarize_sentinel.pyindex c72cc36691..445e7d754a 100644--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/swift/summarize_sentinel.py+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/swift/summarize_sentinel.py@@ -22,7 +22,9 @@ DEVIATION_PX = 10.0HID_KEYS = ("move", "down", "key", "scroll")# Amendment 15: overlay and indicator windows of the computer-use tools themselves (the agent cursor, the# "ChatGPT Computer Use" banner) are not raises. They are logged as metadata (`overlay_owners`) only.-OVERLAY_OWNER_RE = re.compile(r"(?i)cua ?driver|chatgpt computer use|computer use|codex|claude")+OVERLAY_OWNER_RE = re.compile(+ r"(?i)cua ?driver|chatgpt computer use|computer use|codex|app-cu-helper|claude"+)FRONT_EVENTS = ("s", "front", "armed", "disarmed")# Idle values only ever grow between samples unless a real event resets them.DROP_EPSILON_S = 1e-3@@ -163,6 +165,7 @@ def summarize(log_path: str) -> dict[str, Any]:_windows_raised(window, result)_user_activity(window, result)+ _multiplayer(window, body, result)result["pointer_max_deviation_px"] = round(result["pointer_max_deviation_px"], 2)result["front_changed_to"] = sorted(changed_to)result["available"] = result["samples"] >= 10@@ -211,6 +214,34 @@ def _windows_raised(window: list[dict[str, Any]], result: dict[str, Any]) -> Non)+def _multiplayer(+ window: list[dict[str, Any]], body: list[dict[str, Any]], result: dict[str, Any]+) -> None:+ """Amendment 22: the clipboard, Space and sheet measures, and activations of the user's app. Each is None+ when the sentinel that wrote the log did not record it (logs from before A22)."""+ samples = [ln for ln in window if ln.get("ev") in ("s", "armed", "disarmed")]+ clips = [ln["clip"] for ln in samples if isinstance(ln.get("clip"), int)]+ result["clipboard_changes"] = (clips[-1] - clips[0]) if len(clips) >= 2 else None+ spaces = [ln for ln in samples if "onspace" in ln]+ if spaces or any(ln.get("ev") == "space" for ln in body):+ events = sum(1 for ln in body if ln.get("ev") == "space")+ off = sum(+ 1 for a, b in zip(spaces, spaces[1:]) if a.get("onspace") and not b.get("onspace")+ )+ result["space_switches"] = (+ events or off+ ) # the notification when it fired, else the sampled transitions+ else:+ result["space_switches"] = None+ sheets = [ln for ln in samples if "sheet" in ln]+ result["sheets_shown"] = (+ sum(1 for a, b in zip(sheets, sheets[1:]) if b.get("sheet") and not a.get("sheet"))+ if sheets+ else None+ )+ result["activations_gained"] = sum(1 for ln in body if ln.get("ev") == "didBecomeActive")++def _user_activity(window: list[dict[str, Any]], result: dict[str, Any]) -> None:"""Amendment 15: the simulated user's typing in the user-activity window. None when the sentinel ranwithout --user-activity (no user_* lines and no user_text line)."""diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/swift/tests/test_summarize_sentinel.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/swift/tests/test_summarize_sentinel.pyindex 50a31f5bef..15f141e69d 100644--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/swift/tests/test_summarize_sentinel.py+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/swift/tests/test_summarize_sentinel.py@@ -329,5 +329,82 @@ class WindowsRaisedTests(unittest.TestCase):self.assertEqual(result["above_at_start"], ["Terminal"])+class MultiplayerMeasuresTest(unittest.TestCase):+ """Amendment 22: clipboard, Space and sheet measures from the sentinel log."""++ def write(self, lines: list[dict]) -> str:+ import json as _json+ import tempfile as _tf++ handle = _tf.NamedTemporaryFile("w", suffix=".jsonl", delete=False)+ handle.write("\n".join(_json.dumps(x) for x in lines) + "\n")+ handle.close()+ return handle.name++ def sample(self, t: int, **extra: object) -> dict:+ return {+ "ev": "s",+ "t": t,+ "armed": True,+ "mouse": [0, 0],+ "front": {"bid": "ai.cua.benchsentinel"},+ **extra,+ }++ def test_new_measures(self) -> None:+ lines = [+ {+ "ev": "armed",+ "t": 0,+ "armed": True,+ "mouse": [0, 0],+ "clip": 5,+ "onspace": True,+ "sheet": False,+ "front": {"bid": "ai.cua.benchsentinel"},+ }+ ]+ lines += [+ self.sample(i * 50, clip=5 if i < 6 else 7, onspace=True, sheet=(i == 8))+ for i in range(1, 14)+ ]+ lines += [+ {"ev": "space", "t": 700, "armed": True, "onspace": False},+ {"ev": "didBecomeActive", "t": 710, "armed": True},+ ]+ lines += [+ {+ "ev": "disarmed",+ "t": 800,+ "armed": False,+ "mouse": [0, 0],+ "clip": 7,+ "onspace": True,+ "sheet": False,+ }+ ]+ out = summarize_sentinel.summarize(self.write(lines))+ self.assertEqual(out["clipboard_changes"], 2)+ self.assertEqual(out["space_switches"], 1)+ self.assertEqual(out["sheets_shown"], 1)+ self.assertEqual(out["activations_gained"], 1)++ def test_old_logs_are_not_measured(self) -> None:+ lines = [+ {+ "ev": "armed",+ "t": 0,+ "armed": True,+ "mouse": [0, 0],+ "front": {"bid": "ai.cua.benchsentinel"},+ }+ ]+ lines += [self.sample(i * 50) for i in range(1, 12)]+ out = summarize_sentinel.summarize(self.write(lines))+ self.assertIsNone(out["clipboard_changes"])+ self.assertIsNone(out["space_switches"])+ self.assertIsNone(out["sheets_shown"])++if __name__ == "__main__":unittest.main()diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/tests/test_bench_v2.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tests/test_bench_v2.pyindex de7efc6b43..efbc62df0b 100644--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/tests/test_bench_v2.py+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tests/test_bench_v2.py@@ -290,7 +290,9 @@ class SelectionTest(unittest.TestCase):self.assertFalse(any(t.startswith("IR-") for t in ctx.task_ids))def test_v2_static_checks_pass_for_the_headline_arms(self) -> None:- ctx = self.ctx("--bench-v2", "--arms", "cc-cua-driver-script", "cc-codex-cu")+ ctx = self.ctx(+ "--bench-v2", "--arms", "cc-cua-driver-script", "cc-codex-cu", "cc-claude-cu-helper"+ )checks = rb.v2_static_checks(ctx)self.assertTrue(all(status == "pass" for _, status, _ in checks), checks)@@ -356,7 +358,7 @@ class AnalyzeV2Test(unittest.TestCase):(Path(tmp) / "results.jsonl").write_text("".join(json.dumps(r) + "\n" for r in rows))report = av.analyze(av.load_rows([Path(tmp)]))a = report["arms"]["cc-cua-driver-script|foreground"]- self.assertEqual(a["label"], "Cua Driver [foreground]")+ self.assertEqual(a["label"], "Cua Driver, driven by Claude Code [foreground]")self.assertEqual(av.headline(a["overall"]), "2/3 passed, 2 focus steals")self.assertEqual(a["by_category"]["precision"]["success"]["k"], 1)self.assertIsNone(a["by_category"]["web_forms"])@@ -462,5 +464,67 @@ class PointerStillTest(unittest.TestCase):)+class MultiplayerTest(unittest.TestCase):+ """Amendment 22: background completion with the user undisturbed (eight criteria)."""++ CLEAN = {+ "key_loss": 0,+ "windows_raised": 0,+ "keystrokes_leaked": 0,+ "clicks_leaked": 0,+ "scrolls_leaked": 0,+ "user_activity": {"blocked": 0, "text_disruptions": 0, "text_intact_at_end": True},+ "pointer_max_deviation_px": 0.0,+ "clipboard_changes": 0,+ "space_switches": 0,+ "sheets_shown": 0,+ "front_changes": 0,+ "activations_lost": 0,+ "activations_gained": 0,+ }++ def test_clean_trial_completes(self) -> None:+ out = v2.multiplayer_score(dict(self.CLEAN), True, True, "background")+ self.assertTrue(out["background_completion"])+ self.assertEqual(out["unmeasured"], [])++ def test_each_disturbance_fails_completion(self) -> None:+ cases = {+ "key_focus": {"key_loss": 1},+ "window_raised": {"windows_raised": 2},+ "typing": {+ "user_activity": {"blocked": 1, "text_disruptions": 0, "text_intact_at_end": True}+ },+ "pointer": {"pointer_max_deviation_px": 3.0},+ "clipboard": {"clipboard_changes": 1},+ "space": {"space_switches": 1},+ "dialog": {"sheets_shown": 1},+ "activation": {"activations_gained": 1},+ }+ self.assertEqual(set(cases), set(v2.MULTIPLAYER_CRITERIA))+ for name, change in cases.items():+ out = v2.multiplayer_score({**self.CLEAN, **change}, True, True, "background")+ self.assertFalse(out["background_completion"], name)+ self.assertIs(out["criteria"][name], False, name)++ def test_unmeasured_fails_closed_unless_rescoring(self) -> None:+ old = {+ k: v+ for k, v in self.CLEAN.items()+ if k not in ("clipboard_changes", "space_switches", "sheets_shown")+ }+ self.assertFalse(+ v2.multiplayer_score(old, True, True, "background")["background_completion"]+ )+ rescored = v2.multiplayer_score(old, True, True, "background", rescore=True)+ self.assertTrue(rescored["background_completion"])+ self.assertEqual(rescored["unmeasured"], ["clipboard", "dialog", "space"])+ self.assertEqual(rescored["rule"], "A22 rescored")++ def test_typed_input_landing_in_the_user_window_is_typing_disturbed(self) -> None:+ out = v2.multiplayer_score({**self.CLEAN, "keystrokes_leaked": 4}, True, True, "background")+ self.assertIs(out["criteria"]["typing"], False)++if __name__ == "__main__":unittest.main()diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/tests/test_claude_cu_helper_arm.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tests/test_claude_cu_helper_arm.pynew file mode 100644index 0000000000..882c7da00e--- /dev/null+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tests/test_claude_cu_helper_arm.py@@ -0,0 +1,481 @@+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.+"""Unit tests for arm cc-claude-cu-helper (Amendment 11, "Claude Desktop 2.31226.0 computer-use helper via a minimal+adapter"): arm registration, MCP config, argv, pins, the adapter's MCP surface, coordinate mapping, the helper+JSON-RPC client and the preflight probe, all against stand-ins. Nothing from Claude Desktop is run or read here,+no GUI is touched and no model is called."""++from __future__ import annotations++import base64+import json+import os+import struct+import subprocess+import sys+import tempfile+import textwrap+import unittest+import zlib+from pathlib import Path+from unittest import mock++HERE = Path(__file__).resolve().parent+sys.path.insert(0, str(HERE.parent))+sys.path.insert(0, str(HERE.parent / "tools" / "claude_cu_helper"))++import arms # noqa: E402+import claude_arms as ca # noqa: E402+import claude_events as ce # noqa: E402+import cu_helper_mcp as ad # noqa: E402+import run_bench as rb # noqa: E402++ARM = "cc-claude-cu-helper"+ADAPTER = HERE.parent / "tools" / "claude_cu_helper" / "cu_helper_mcp.py"+++def png(width: int, height: int) -> bytes:+ raw = b"".join(b"\x00" + b"\xff" * (width * 3) for _ in range(height))++ def chunk(kind: bytes, data: bytes) -> bytes:+ return (+ struct.pack(">I", len(data))+ + kind+ + data+ + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)+ )++ ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)+ return (+ b"\x89PNG\r\n\x1a\n"+ + chunk(b"IHDR", ihdr)+ + chunk(b"IDAT", zlib.compress(raw))+ + chunk(b"IEND", b"")+ )+++FAKE_HELPER = textwrap.dedent(+ """\+ #!/usr/bin/env python3+ import json, os, sys+ log = os.environ.get("FAKE_HELPER_LOG")+ for line in sys.stdin:+ req = json.loads(line)+ if log:+ open(log, "a").write(line)+ if req["method"] == "probe":+ res = {"skylight": True, "axTrusted": True, "focusWithoutRaise": True, "os": "26.5.2"}+ elif req["method"] == "wakeChromiumCompositor":+ res = {"woke": False}+ elif req["method"] == "dispatchRaw":+ p = req["params"]+ busy = os.environ.get("FAKE_HELPER_BUSY")+ if busy and not os.path.exists(busy):+ open(busy, "w").write("1")+ res = {"delivered": False, "path": "unavailable", "code": "user_actively_typing"}+ elif p["kind"] == "rclick":+ res = {"delivered": False, "path": "unavailable", "code": "context_menu",+ "debugFields": {"blockedReason": "context_menu_rclick_refused"}}+ else:+ res = {"delivered": True, "path": "cgevent", "debugFields": {}}+ if p["kind"] == "type":+ res["charsDelivered"] = len(p["text"])+ else:+ print(json.dumps({"jsonrpc": "2.0", "id": req["id"], "error": {"code": -32601, "message": "nope"}}), flush=True)+ continue+ print(json.dumps({"jsonrpc": "2.0", "id": req["id"], "result": res}), flush=True)+ """+)++WINDOWS = [+ {+ "app": "BenchLab",+ "pid": 4242,+ "window_id": 77,+ "title": "BenchLab",+ "x": 100.0,+ "y": 50.0,+ "width": 800.0,+ "height": 600.0,+ "layer": 0,+ },+ {+ "app": "Finder",+ "pid": 1,+ "window_id": 5,+ "title": "",+ "x": 0.0,+ "y": 0.0,+ "width": 400.0,+ "height": 300.0,+ "layer": 0,+ },+]+++class Fixture:+ def __init__(self, tmp: Path, shot: tuple[int, int] = (1600, 1200)) -> None:+ self.tmp = tmp+ self.helper = tmp / "app-cu-helper"+ self.helper.write_text(FAKE_HELPER)+ self.helper.chmod(0o755)+ self.winlist = tmp / "winlist"+ self.winlist.write_text("#!/bin/sh\ncat <<'EOF'\n" + json.dumps(WINDOWS) + "\nEOF\n")+ self.winlist.chmod(0o755)+ (tmp / "shot.png").write_bytes(png(*shot))+ self.screencapture = tmp / "screencapture"+ # last argument is the output path; -l<id> must be present+ self.screencapture.write_text(+ '#!/bin/sh\nfor a; do last=$a; done\ncase "$*" in *-l77*) cp \'%s\' "$last";; *) exit 1;; esac\n'+ % (tmp / "shot.png")+ )+ self.screencapture.chmod(0o755)+ self.sips = tmp / "sips" # stand-in: writes a PNG of the requested size (-z H W path)+ self.sips.write_text(+ "#!/usr/bin/env python3\nimport sys\nsys.path.insert(0, %r)\nfrom test_claude_cu_helper_arm import png\n"+ "h, w, path = int(sys.argv[2]), int(sys.argv[3]), sys.argv[4]\nopen(path, 'wb').write(png(w, h))\n"+ % str(HERE)+ )+ self.sips.chmod(0o755)+ self.log = tmp / "helper.log"++ def adapter(self, actions: list[str] | None = None, busy: bool = False) -> ad.Adapter:+ env = {**os.environ, "FAKE_HELPER_LOG": str(self.log)}+ if busy:+ env["FAKE_HELPER_BUSY"] = str(self.tmp / "busy-once")+ helper = ad.Helper([str(self.helper)], env=env)+ return ad.Adapter(+ helper,+ str(self.winlist),+ list(ad.ALL_ACTIONS) if actions is None else actions,+ host_pid=99,+ screencapture=str(self.screencapture),+ sips=str(self.sips),+ busy_wait_s=0.01,+ )++ def requests(self, method: str = "dispatchRaw") -> list[dict]:+ rows = (+ [json.loads(line) for line in self.log.read_text().splitlines()]+ if self.log.exists()+ else []+ )+ return [r for r in rows if r["method"] == method]+++class ArmRegistrationTest(unittest.TestCase):+ def test_arm_is_a_named_claude_arm_with_the_agreed_label(self) -> None:+ self.assertIn(ARM, arms.CLAUDE_ARMS)+ self.assertNotIn(ARM, arms.DEFAULT_CLAUDE_ARMS)+ self.assertIn(ARM, ca.CU_HELPER_ARMS)+ self.assertNotIn(ARM, ca.CUA_ARMS)+ self.assertEqual(+ ca.CU_HELPER_LABEL, "Claude Desktop 2.31226.0 computer-use helper via a minimal adapter"+ )+ self.assertIn(ca.CU_HELPER_LABEL, ca.ARM_DESCRIPTIONS[ARM])++ def test_same_system_prompt_no_skill_and_argv_differs_only_in_server(self) -> None:+ self.assertEqual(ca.system_prompt_for(ARM), ca.SYSTEM_PROMPT)+ with tempfile.TemporaryDirectory() as tmp:+ self.assertEqual(list(ca.prepare_cwd(ARM, Path(tmp) / "w").iterdir()), [])+ common = dict(model="claude-sonnet-5-5", max_turns=45, max_budget_usd=6)+ a = ca.claude_argv(mcp_config=Path("/r/mcp-x.json"), server="claude-cu-helper", **common)+ b = ca.claude_argv(mcp_config=Path("/r/mcp-x.json"), server="cua", **common)+ self.assertEqual(+ [(x, y) for x, y in zip(a, b) if x != y], [("mcp__claude-cu-helper", "mcp__cua")]+ )+++class McpConfigTest(unittest.TestCase):+ def test_config_runs_the_adapter_with_absolute_paths_and_a_closed_env(self) -> None:+ pins = {"claude_cu_helper": {"actions": ["click", "type"]}}+ with (+ tempfile.TemporaryDirectory() as tmp,+ mock.patch.object(ca, "load_pins", return_value=pins),+ ):+ path, server = ca.mcp_config_for(ARM, Path(tmp))+ self.assertEqual(server, "claude-cu-helper")+ ((name, entry),) = json.loads(path.read_text())["mcpServers"].items()+ self.assertEqual(name, "claude-cu-helper")+ self.assertEqual(entry["command"], "/opt/homebrew/bin/python3")+ self.assertEqual(entry["args"][:3], ["-I", "-B", str(ca.CU_HELPER_ADAPTER)])+ self.assertIn("--helper", entry["args"])+ helper = entry["args"][entry["args"].index("--helper") + 1]+ self.assertTrue(+ helper.endswith(+ "claude-desktop-2.31226.0/extracted/Claude.app/Contents/Helpers/app-cu-helper"+ )+ )+ self.assertEqual(entry["args"][-2:], ["--actions", "click,type"])+ self.assertEqual(+ entry["args"][entry["args"].index("--launcher") + 1], str(ca.CU_HELPER_LAUNCHER)+ )+ self.assertEqual(entry["env"]["PATH"], "/usr/bin:/bin:/usr/sbin:/sbin")+ self.assertNotIn("cua", json.dumps(entry).replace("cua-bench", "").replace("claude-cu", ""))++ def test_pins_must_all_match(self) -> None:+ keys = (+ "desktop_zip_sha256",+ "helper_sha256",+ "adapter_sha256",+ "winlist_sha256",+ "launcher_sha256",+ )+ pins = {"claude_cu_helper": {k: "a" for k in keys}}+ self.assertTrue(+ all(s == "pass" for _, s, _ in ca.check_cu_helper_pins(pins, {k: "a" for k in keys}))+ )+ bad = ca.check_cu_helper_pins(pins, {**{k: "a" for k in keys}, "helper_sha256": "b"})+ self.assertEqual(+ [n for n, s, _ in bad if s == "fail"], ["pin claude_cu_helper.helper_sha256"]+ )+ self.assertTrue(+ all(s == "fail" for _, s, _ in ca.check_cu_helper_pins({}, {k: None for k in keys}))+ )+++class ToolClassTest(unittest.TestCase):+ def test_classes(self) -> None:+ self.assertEqual(ce.tool_class("mcp__claude-cu-helper__app_click", {}), "click")+ self.assertEqual(ce.tool_class("mcp__claude-cu-helper__app_screenshot", {}), "observe")+ self.assertEqual(ce.tool_class("mcp__claude-cu-helper__app_list_windows", {}), "observe")+ self.assertEqual(ce.tool_class("mcp__claude-cu-helper__app_type", {}), "type")+ self.assertEqual(ce.tool_class("mcp__claude-cu-helper__app_hover", {}), "other")+ self.assertEqual(ce.tool_class("mcp__claude-cu-helper__nonsense", {}), "other")+++class AdapterTest(unittest.TestCase):+ def setUp(self) -> None:+ self._tmp = tempfile.TemporaryDirectory()+ self.fx = Fixture(Path(self._tmp.name))++ def tearDown(self) -> None:+ self._tmp.cleanup()++ def shot(self, adapter: ad.Adapter) -> tuple[int, int]:+ content = adapter.call("app_screenshot", {"app": "benchlab"})+ self.assertEqual(content[1]["type"], "image")+ return ad.png_size(base64.b64decode(content[1]["data"]))++ def test_tools_offered_follow_the_pinned_actions_only(self) -> None:+ names = [t["name"] for t in self.fx.adapter().tools()]+ self.assertEqual(+ names,+ [+ "app_list_windows",+ "app_screenshot",+ "app_click",+ "app_type",+ "app_key",+ "app_scroll",+ "app_drag",+ "app_hover",+ ],+ )+ only_click = self.fx.adapter(["click"]).tools()+ self.assertEqual(+ [t["name"] for t in only_click], ["app_list_windows", "app_screenshot", "app_click"]+ )+ self.assertEqual(only_click[2]["inputSchema"]["properties"]["button"]["enum"], ["left"])+ self.assertEqual(+ [t["name"] for t in self.fx.adapter(["nonsense"]).tools()],+ ["app_list_windows", "app_screenshot"],+ )++ def test_target_size_keeps_aspect_and_budget(self) -> None:+ w, h = ad.target_size(3456, 2234)+ self.assertLessEqual(w * h, ad.MAX_PIXELS)+ self.assertAlmostEqual(w / h, 3456 / 2234, places=2)+ self.assertEqual(ad.target_size(800, 600), (800, 600)) # never upscaled++ def test_screenshot_wakes_the_compositor_then_click_maps_pixels_to_window_points(self) -> None:+ adapter = self.fx.adapter()+ w, h = self.shot(adapter)+ self.assertEqual((w, h), ad.target_size(1600, 1200))+ self.assertEqual(self.fx.requests("wakeChromiumCompositor")[0]["params"]["windowId"], 77)+ out = adapter.call(+ "app_click", {"app": "BenchLab", "coordinate": [w / 2, h / 4], "count": 2}+ )+ self.assertTrue(json.loads(out[0]["text"])["delivered"])+ (req,) = self.fx.requests()+ p = req["params"]+ self.assertEqual(+ (+ p["pid"],+ p["windowId"],+ p["kind"],+ p["count"],+ p["hostPid"],+ p["focusedTarget"],+ p["nativeMouseVariant"],+ ),+ (4242, 77, "click", 2, 99, False, False),+ )+ self.assertAlmostEqual(p["winLocalPt"]["x"], 400.0, delta=0.6)+ self.assertAlmostEqual(p["winLocalPt"]["y"], 150.0, delta=0.6)+ adapter.helper.close()++ def test_desktop_mapping_for_type_key_scroll_drag_hover(self) -> None:+ adapter = self.fx.adapter()+ w, h = self.shot(adapter)+ adapter.call("app_type", {"app": "BenchLab", "text": "abc"})+ adapter.call(+ "app_type",+ {"app": "BenchLab", "text": "xyz", "coordinate": [10, 10], "mode": "replace"},+ )+ adapter.call("app_key", {"app": "BenchLab", "combo": "cmd+shift+Z"})+ adapter.call("app_key", {"app": "BenchLab", "combo": "Enter"})+ adapter.call("app_scroll", {"app": "BenchLab", "coordinate": [10, 10], "dy": 3})+ adapter.call(+ "app_drag", {"app": "BenchLab", "coordinate": [0, 0], "to_coordinate": [w / 2, h / 2]}+ )+ adapter.call("app_hover", {"app": "BenchLab", "coordinate": [w / 2, h / 2]})+ ps = [r["params"] for r in self.fx.requests()]+ self.assertEqual(+ [p["kind"] for p in ps],+ ["type", "key", "type", "key", "key", "scroll", "drag", "hover"],+ )+ self.assertTrue(ps[0]["focusedTarget"]) # no coordinate: the app's focused element+ self.assertEqual(ps[0]["winLocalPt"], {"x": 400.0, "y": 300.0})+ self.assertEqual(+ (+ ps[1]["keyName"],+ ps[1]["modifiers"],+ ps[1]["partOfTextWrite"],+ ps[1]["focusedTarget"],+ ),+ ("a", ["cmd"], True, False),+ )+ self.assertEqual(ps[2]["text"], "xyz")+ self.assertEqual((ps[3]["keyName"], ps[3]["modifiers"]), ("z", ["cmd", "shift"]))+ self.assertEqual((ps[4]["keyName"], ps[4]["modifiers"]), ("return", []))+ self.assertEqual(+ (ps[5]["dy"], ps[5]["dx"], ps[5]["ticks"]), (-120, 0, 1)+ ) # Desktop: round(-dy * 40)+ self.assertAlmostEqual(ps[6]["toWinLocalPt"]["x"], 400.0, delta=0.6)+ adapter.helper.close()++ def test_refusals_come_back_as_tool_errors_with_the_helper_reason(self) -> None:+ adapter = self.fx.adapter()+ self.shot(adapter)+ with self.assertRaisesRegex(RuntimeError, "context_menu_rclick_refused"):+ adapter.call("app_click", {"app": "BenchLab", "coordinate": [1, 1], "button": "right"})+ with self.assertRaisesRegex(ValueError, "not available"):+ self.fx.adapter(["click"]).call(+ "app_click", {"app": "BenchLab", "coordinate": [1, 1], "button": "right"}+ )+ with self.assertRaisesRegex(ValueError, "exactly one key"):+ adapter.call("app_key", {"app": "BenchLab", "combo": "cmd+shift"})+ with self.assertRaisesRegex(ValueError, "longer than"):+ adapter.call("app_type", {"app": "BenchLab", "text": "x" * 4001})+ adapter.helper.close()++ def test_busy_user_typing_is_retried_like_desktop(self) -> None:+ adapter = self.fx.adapter(busy=True)+ self.shot(adapter)+ out = adapter.call("app_key", {"app": "BenchLab", "combo": "tab"})+ self.assertTrue(json.loads(out[0]["text"])["delivered"])+ self.assertEqual(len(self.fx.requests()), 2)+ adapter.helper.close()++ def test_input_needs_a_screenshot_and_a_point_inside_it(self) -> None:+ adapter = self.fx.adapter()+ with self.assertRaisesRegex(ValueError, "screenshot"):+ adapter.call("app_click", {"app": "BenchLab", "coordinate": [1, 1]})+ adapter.call("app_screenshot", {"app": "BenchLab", "window_id": 77})+ with self.assertRaisesRegex(ValueError, "outside"):+ adapter.call("app_click", {"app": "BenchLab", "coordinate": [99999, 1]})+ with self.assertRaisesRegex(ValueError, "no on-screen window"):+ adapter.call("app_screenshot", {"app": "Nope"})+ self.assertEqual(self.fx.requests(), []) # nothing reached dispatchRaw+ adapter.helper.close()++ def test_unknown_tool_and_list_windows_filter(self) -> None:+ adapter = self.fx.adapter(["click"])+ self.assertEqual(+ json.loads(adapter.call("app_list_windows", {"app": "finder"})[0]["text"])[0][+ "window_id"+ ],+ 5,+ )+ with self.assertRaises(ValueError):+ adapter.call("app_type", {"app": "BenchLab", "text": "x"})++ def test_mcp_stdio_end_to_end(self) -> None:+ argv = [+ sys.executable,+ "-I",+ "-B",+ str(ADAPTER),+ "--helper",+ str(self.fx.helper),+ "--winlist",+ str(self.fx.winlist),+ "--screencapture",+ str(self.fx.screencapture),+ "--sips",+ str(self.fx.sips),+ "--actions",+ "click,key",+ ]+ msgs = [+ {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": {"protocolVersion": "2025-06-18"},+ },+ {"jsonrpc": "2.0", "method": "notifications/initialized"},+ {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}},+ {+ "jsonrpc": "2.0",+ "id": 3,+ "method": "tools/call",+ "params": {+ "name": "app_click",+ "arguments": {"app": "BenchLab", "coordinate": [1, 1]},+ },+ },+ {"jsonrpc": "2.0", "id": 4, "method": "nope", "params": {}},+ ]+ done = subprocess.run(+ argv,+ input="".join(json.dumps(m) + "\n" for m in msgs),+ capture_output=True,+ text=True,+ timeout=30,+ )+ replies = {r["id"]: r for r in map(json.loads, done.stdout.splitlines())}+ self.assertEqual(replies[1]["result"]["serverInfo"]["name"], "claude-cu-helper")+ self.assertEqual(+ [t["name"] for t in replies[2]["result"]["tools"]],+ ["app_list_windows", "app_screenshot", "app_click", "app_key"],+ )+ self.assertTrue(replies[3]["result"]["isError"])+ self.assertEqual(replies[4]["error"]["code"], -32601)+++class HelperClientTest(unittest.TestCase):+ def test_helper_errors_and_restart(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ fx = Fixture(Path(tmp))+ helper = ad.Helper([str(fx.helper)])+ self.assertTrue(helper.call("probe", {})["axTrusted"])+ with self.assertRaisesRegex(ad.HelperError, "nope"):+ helper.call("whatever", {})+ helper.close()+ self.assertTrue(helper.call("probe", {})["skylight"]) # restarted after close+ helper.close()++ def test_preflight_probe_reads_the_helper_directly(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ fx = Fixture(Path(tmp))+ probe = rb.cu_helper_probe(fx.helper)+ self.assertTrue(probe["axTrusted"])+ missing = Path(tmp) / "missing"+ with self.assertRaises(OSError):+ rb.cu_helper_probe(missing)+++if __name__ == "__main__":+ unittest.main()diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/tests/test_codex_native.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tests/test_codex_native.pyindex 60b2e99482..86d68e137c 100644--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/tests/test_codex_native.py+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tests/test_codex_native.py@@ -54,8 +54,8 @@ class HomeTest(unittest.TestCase):tmp_path / "home", write_arm_b(tmp_path), cxn.MODEL, cxn.EFFORT, "SYSTEM")cfg = tomllib.loads((Path(env["CODEX_HOME"]) / "config.toml").read_text("utf-8"))- self.assertEqual(cfg["model"], "gpt-6-astra")- self.assertEqual(cfg["model_reasoning_effort"], "medium")+ self.assertEqual(cfg["model"], cxn.MODEL)+ self.assertEqual(cfg["model_reasoning_effort"], cxn.EFFORT)self.assertEqual(cfg["approval_policy"], "on-request") # elicitations reach the hostself.assertEqual(cfg["sandbox_mode"], "read-only")self.assertEqual(cfg["developer_instructions"], "SYSTEM")@@ -104,6 +104,48 @@ def usage(total_in: int, cached: int, out: int) -> tuple[str, dict]:}+class CuaDriverUnderCodexTest(unittest.TestCase):+ """Amendment 23: Cua Driver's MCP server under the same Codex host."""++ def test_cua_server_has_no_tool_filter_and_no_surface_check(self) -> None:+ cua = {+ "mcpServers": {+ "cua": {+ "type": "stdio",+ "command": "/w/cua-driver",+ "args": ["--socket", "/tmp/s", "mcp"],+ "env": {"CUA_DRIVER_HOME": "/w/h"},+ }+ }+ }+ with tempfile.TemporaryDirectory() as tmp:+ path = Path(tmp) / "mcp.json"+ path.write_text(json.dumps(cua), "utf-8")+ env = cxn.render_home(+ Path(tmp) / "home", path, cxn.MODEL, cxn.EFFORT, "SYSTEM", "cx-cua-driver"+ )+ cfg = tomllib.loads((Path(env["CODEX_HOME"]) / "config.toml").read_text("utf-8"))+ server = cfg["mcp_servers"]["cua"]+ self.assertEqual(server["args"], ["--socket", "/tmp/s", "mcp"])+ self.assertNotIn("enabled_tools", server)+ self.assertEqual(server["env"], {"CUA_DRIVER_HOME": "/w/h"})+ self.assertNotIn("cua_repl", cfg["mcp_servers"])++ def test_registry(self) -> None:+ self.assertEqual(cxn.SOURCE_ARM["cx-cua-driver"], "cc-cua-driver-script")+ self.assertEqual(cxn.SOURCE_ARM["cx-claude-cu-helper"], "cc-claude-cu-helper")+ self.assertEqual(cxn.SERVER_OF["cx-claude-cu-helper"], "claude-cu-helper")+ self.assertIn("not an Anthropic-supported procedure", cxn.LABELS["cx-claude-cu-helper"])+ self.assertIn("cx-claude-cu-helper", arms.ALL_ARMS)+ self.assertIn("cx-cua-driver", arms.ALL_ARMS)+ self.assertEqual(cxn.MODEL, "gpt-6.1-sol") # A23.1+ self.assertEqual(cxn.EFFORT, "low")++ def test_translator_names_the_cua_server(self) -> None:+ out = cxn.Translator("cua").feed("thread/started", {"thread": {"id": "t"}})+ self.assertEqual(out[0]["mcp_servers"], [{"name": "cua", "status": "connected"}])++class TranslatorTest(unittest.TestCase):def run_events(self, events: list[tuple[str, dict]]) -> tuple[list[dict], cxn.Translator]:tr = cxn.Translator()diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/analyze_claude_cu.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/analyze_claude_cu.pynew file mode 100644index 0000000000..59d14d7a9c--- /dev/null+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/analyze_claude_cu.py@@ -0,0 +1,299 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.+"""Pre-registered analysis of the Claude computer-use arms (PREREGISTRATION.md, Amendment 11), written before their+first trial.++ analyze_claude_cu.py RUN_DIR REF_RUN_DIR [--extra RUN_DIR ...] [--arm ARM] [--out-json FILE]++RUN_DIR holds the helper arm's trials (cc-claude-cu-helper); REF_RUN_DIR is a run whose arms ran the same tasks with+the same seeds on the same VM image. --extra adds other follow-on runs on the same tasks (for example a run of+cc-codex-cu-1007-browser) to the standings table. Rows are the final, counted rows of complete blocks. Everything here+is descriptive; these are separate runs, not an interleaved comparison.++The helper arm is "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".++1. Standings: per arm over the tasks the follow-on run covers: passed trials, mean turns, tokens, wall time, cost.+2. The follow-on arm against A (cc-cua-driver-main), paired by task and run index: task-macro success difference and+ the geometric-mean turns and tokens ratios, with the A5.4 task-stratified bootstrap.+3. Per task and arm.+4. The arm's own signals from its streams: calls per tool, failed calls, and input calls the helper reported as not+ delivered.+5. The most common failure classes, with trial paths.+"""++from __future__ import annotations++import argparse+import json+import math+import random+import re+import statistics as st+import sys+from collections import Counter, defaultdict+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+import posthoc_calls as ph # noqa: E402++HELPER = "cc-claude-cu-helper"+A, AX, A0, B, B1007 = (+ "cc-cua-driver-main",+ "cc-cua-driver-script",+ "cc-cua-driver",+ "cc-codex-cu",+ "cc-codex-cu-1007-browser",+)+LABEL = {+ HELPER: "Claude Desktop 2.31226.0 computer-use helper via a minimal adapter",+ A: "A Cua Driver main",+ AX: "AX Cua Driver main + run_script",+ A0: "A0 Cua Driver 0.34.0",+ B: "B Codex CU 26.930",+ B1007: "B' Codex CU 26.1007 (browser+computer)",+}+ORDER = (HELPER, AX, A, A0, B, B1007)+NOT_DELIVERED = re.compile(r'"delivered"\s*:\s*false|did not deliver')+BOOT = 10_000+SEED = 20261007+++def load(results: Path) -> list[dict]:+ """Final, counted rows of complete blocks. Completeness is recomputed from blocks.json: a row's+ `block_incomplete` flag is written when a run stops mid-block and is not cleared when a resumed run+ finishes that block."""+ rows = []+ for line in results.read_text("utf-8").splitlines():+ if not line.strip():+ continue+ d = json.loads(line)+ if d.get("smoke") or not d.get("final", True) or d.get("excluded"):+ continue+ rows.append(d)+ blocks_file = results.parent / "blocks.json"+ if blocks_file.is_file():+ blocks = json.loads(blocks_file.read_text("utf-8"))["blocks"]+ have: dict = defaultdict(set)+ for r in rows:+ have[r["block"]].add(r["trial_id"])+ complete = {+ bid for bid, b in blocks.items() if len(have.get(bid, set())) >= b["n_expected"]+ }+ rows = [r for r in rows if r["block"] in complete]+ else:+ rows = [r for r in rows if not r.get("block_incomplete")]+ return rows+++def total_tokens(row: dict) -> float:+ tokens = row.get("tokens") or {}+ return sum(float(tokens.get(k) or 0) for k in ("input", "output", "cache_read", "cache_write"))+++def geomean(xs: list[float]) -> float:+ xs = [x for x in xs if x > 0]+ return math.exp(sum(math.log(x) for x in xs) / len(xs)) if xs else float("nan")+++def bootstrap(task_pairs: dict, stat) -> tuple[float, float, float]:+ """Task-stratified bootstrap: resample run pairs within each task."""+ rng = random.Random(SEED)+ point = stat(task_pairs)+ draws = []+ for _ in range(BOOT):+ sample = {t: [rng.choice(prs) for _ in prs] for t, prs in task_pairs.items()}+ v = stat(sample)+ if not math.isnan(v):+ draws.append(v)+ draws.sort()+ lo = draws[int(0.025 * len(draws))]+ hi = draws[min(len(draws) - 1, int(0.975 * len(draws)))]+ return point, lo, hi+++def task_pairs_for(by: dict, tasks: list[str], x: str, y: str) -> dict:+ """Rows of arms x and y paired by task and run index; tasks without a pair are dropped."""+ out = {}+ for t in tasks:+ a = {r["run_index"]: r for r in by.get((t, x), [])}+ b = {r["run_index"]: r for r in by.get((t, y), [])}+ prs = [(a[i], b[i]) for i in sorted(set(a) & set(b))]+ if prs:+ out[t] = prs+ return out+++def ratio_block(tp: dict, metric) -> dict:+ def stat(d: dict) -> float:+ ratios = []+ for prs in d.values():+ mx = st.mean(metric(p[0]) for p in prs)+ my = st.mean(metric(p[1]) for p in prs)+ if mx > 0 and my > 0:+ ratios.append(mx / my)+ return geomean(ratios)++ point, lo, hi = bootstrap(tp, stat)+ return {"geomean_ratio": point, "ci95": [lo, hi]}+++def success_block(tp: dict) -> dict:+ def stat(d: dict) -> float:+ return st.mean(+ st.mean(float(bool(p[0]["passed"])) for p in prs)+ - st.mean(float(bool(p[1]["passed"])) for p in prs)+ for prs in d.values()+ )++ point, lo, hi = bootstrap(tp, stat)+ return {"macro_diff": point, "ci95": [lo, hi]}+++def turns(r: dict) -> float:+ return float(r.get("turns") or 0)+++def norm(text: str) -> str:+ t = re.sub(r"\s+", " ", text or "").strip()+ t = re.sub(r'"[^"]{0,80}"|\'[^\']{0,80}\'', "<s>", t)+ t = re.sub(r"\b[0-9a-f]{6,}\b|\d+(\.\d+)?", "N", t)+ return t[:110]+++def summary(rows: list[dict]) -> dict:+ return {+ "n": len(rows),+ "passed": sum(1 for r in rows if r["passed"]),+ "turns": st.mean(turns(r) for r in rows) if rows else float("nan"),+ "tokens": st.mean(total_tokens(r) for r in rows) if rows else float("nan"),+ "wall_s": st.mean(r.get("wall_s") or 0 for r in rows) if rows else float("nan"),+ "cost_usd": st.mean(r.get("cost_usd") or 0 for r in rows) if rows else float("nan"),+ }+++def stream_signals(run: Path, rows: list[dict]) -> dict:+ calls: Counter = Counter()+ failed: Counter = Counter()+ undelivered = 0+ classes: dict = defaultdict(list)+ for r in rows:+ trial = run / "trials" / r["trial_id"] / f"a{r['attempt']}"+ stream = trial / "claude-stream.tsv"+ if stream.exists():+ for c in ph.calls(ph.events(stream)):+ tool = c["name"].split("__")[-1] if c["name"].startswith("mcp__") else c["name"]+ calls[tool] += 1+ text = c.get("result") or ""+ if NOT_DELIVERED.search(text):+ undelivered += 1+ if c["error"]:+ failed[tool] += 1+ classes[f"{tool} error: {norm(text)}"].append(trial)+ if not r["passed"]:+ if turns(r) >= (r.get("max_turns") or 45):+ classes["turn cap reached"].append(trial)+ if r.get("status") == "timeout":+ classes["wall-time limit reached"].append(trial)+ for check, ok in (r.get("checks") or {}).items():+ if not ok:+ classes[f"evaluator check failed: {check} ({r['task']})"].append(trial)+ top = sorted(classes.items(), key=lambda kv: -len(kv[1]))[:12]+ return {+ "calls": dict(calls.most_common()),+ "failed": dict(failed.most_common()),+ "inputs_not_delivered": undelivered,+ "failure_classes": [+ {"class": k, "count": len(v), "trials": sorted({str(x) for x in v})} for k, v in top+ ],+ }+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("run", type=Path)+ ap.add_argument("ref_run", type=Path)+ ap.add_argument("--extra", type=Path, action="append", default=[])+ ap.add_argument("--arm", default=HELPER)+ ap.add_argument("--out-json", type=Path)+ args = ap.parse_args()+ arm_rows = [r for r in load(args.run / "results.jsonl") if r["arm"] == args.arm]+ tasks = sorted({r["task"] for r in arm_rows})+ others = [r for r in load(args.ref_run / "results.jsonl") if r["arm"] != args.arm]+ for extra in args.extra:+ others += [r for r in load(extra / "results.jsonl") if r["arm"] == B1007]+ rows = arm_rows + [r for r in others if r["task"] in tasks]+ arms = [a for a in ORDER if any(r["arm"] == a for r in rows)]+ by = defaultdict(list)+ for r in rows:+ by[(r["task"], r["arm"])].append(r)+ out: dict = {+ "run": args.run.name,+ "ref_run": args.ref_run.name,+ "extra": [e.name for e in args.extra],+ "arm": args.arm,+ "tasks": tasks,+ "arms": {},+ }+ p = print+ p(f"# {LABEL[args.arm]}: {args.run.name} against {args.ref_run.name}\n")+ p(+ f"{len(arm_rows)} counted trials of {args.arm} over {len(tasks)} tasks. Other arms: {args.ref_run.name}"+ + (", " + ", ".join(e.name for e in args.extra) if args.extra else "")+ + " on the same tasks (separate runs).\n"+ )+ p("## 1. Standings\n")+ p("| Arm | Passed | Mean turns | Tokens | Wall s | Cost USD |")+ p("|---|---|---|---|---|---|")+ for arm in sorted(arms, key=lambda a: -summary([r for r in rows if r["arm"] == a])["passed"]):+ s = summary([r for r in rows if r["arm"] == arm])+ out["arms"][arm] = s+ p(+ f"| {LABEL[arm]} | {s['passed']}/{s['n']} | {s['turns']:.1f} | {s['tokens']:,.0f} | {s['wall_s']:.0f} | {s['cost_usd']:.3f} |"+ )+ p(f"\n## 2. {args.arm} against A (paired by task and run index, task-stratified bootstrap)\n")+ tp = task_pairs_for(by, tasks, args.arm, A)+ if tp:+ sx, tx, kx = success_block(tp), ratio_block(tp, turns), ratio_block(tp, total_tokens)+ out.update(vs_A_success=sx, vs_A_turns=tx, vs_A_tokens=kx)+ p(+ f"* success minus A: {sx['macro_diff']:+.2f} ({sx['ci95'][0]:+.2f} to {sx['ci95'][1]:+.2f})"+ )+ p(f"* turns / A: {tx['geomean_ratio']:.2f} ({tx['ci95'][0]:.2f} to {tx['ci95'][1]:.2f})")+ p(f"* tokens / A: {kx['geomean_ratio']:.2f} ({kx['ci95'][0]:.2f} to {kx['ci95'][1]:.2f})")+ else:+ p("No pairs.")+ p("\n## 3. Per task\n")+ p("| Task | Arm | n | Success | Score | Turns | Wall s | Tokens | Cost USD |")+ p("|---|---|---|---|---|---|---|---|---|")+ for t in tasks:+ for arm in arms:+ v = by.get((t, arm), [])+ if v:+ p(+ f"| {t} | {LABEL[arm]} | {len(v)} | {sum(1 for r in v if r['passed'])}/{len(v)} | {st.mean(r['score'] or 0 for r in v):.2f} "+ f"| {st.mean(turns(r) for r in v):.1f} | {st.mean(r['wall_s'] or 0 for r in v):.0f} | {st.mean(total_tokens(r) for r in v):,.0f} | {st.mean(r['cost_usd'] or 0 for r in v):.3f} |"+ )+ sig = stream_signals(args.run, arm_rows)+ out["streams"] = sig+ p(f"\n## 4. {args.arm} signals from the streams\n")+ p("* calls per tool: " + ", ".join(f"{k} {v}" for k, v in sig["calls"].items()))+ p("* failed calls: " + (", ".join(f"{k} {v}" for k, v in sig["failed"].items()) or "none"))+ p(f"* input calls the helper reported as not delivered: {sig['inputs_not_delivered']}")+ leftovers = sum(int(r.get("cu_helper_leftover_killed") or 0) for r in arm_rows)+ p(f"* leftover adapter/helper processes killed after trials: {leftovers}")+ p("\n## 5. Failure classes\n")+ for c in sig["failure_classes"]:+ p(+ f"* {c['count']}x {c['class']} (e.g. "+ + ", ".join(Path(u).parent.name for u in c["trials"][:3])+ + ")"+ )+ if args.out_json:+ args.out_json.write_text(json.dumps(out, indent=2, default=str) + "\n", "utf-8")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/analyze_v2.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/analyze_v2.pyindex 00063a8cf3..8df1cb9e4d 100644--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/analyze_v2.py+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/analyze_v2.py@@ -35,10 +35,19 @@ from analyze import wilson_interval # noqa: E402# Public setup names; any other arm is reported under its arm id.ARM_LABELS = {- "cc-cua-driver-script": "Cua Driver",+ "cc-cua-driver-script": "Cua Driver, driven by Claude Code", # suffix from Amendment 23"cc-codex-cu": "Codex Computer-Use (Sky), driven by Claude Code", # suffix from Amendment 20"cc-codex-cu-1007-browser": "Codex Computer-Use (Sky) 26.1007",- "cx-codex-cu": "Codex Computer-Use (Sky), driven by Codex CLI + GPT-6 Astra", # Amendment 20+ "cx-codex-cu": "Codex Computer-Use (Sky), driven by Codex CLI", # Amendment 20; the rows' model is appended+ "cx-cua-driver": "Cua Driver, driven by Codex CLI", # Amendment 23; the rows' model is appended+ "cx-claude-cu-helper": ( # Amendment 23; the rows' model is appended+ "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"+ ),+ "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"+ ),}@@ -103,6 +112,7 @@ def summarize(rows: list[dict[str, Any]]) -> dict[str, Any]:},"gui_only_violations": sum(1 for g in gui if g.get("violation")),"background_condition": _bgc(rows),+ "multiplayer": _mp(rows),}@@ -127,6 +137,41 @@ def _bgc(rows: list[dict[str, Any]]) -> dict[str, Any]:}+def _mp_of(row: dict[str, Any]) -> dict[str, Any]:+ """A22 score of a row: as recorded, or re-expressed (labelled "A22 rescored") for rows from before A22."""+ if row.get("multiplayer"):+ return row["multiplayer"]+ measured = bool((row.get("background") or {}).get("measured"))+ return v2.multiplayer_score(+ row.get("disturbance") or {},+ measured,+ bool(row.get("passed")),+ row.get("condition"),+ rescore=True,+ )+++def _mp(rows: list[dict[str, Any]]) -> dict[str, Any] | None:+ """Amendment 22: the headline background metric, and how many background trials broke each criterion."""+ items = [_mp_of(r) for r in rows if r.get("condition") == "background"]+ if not items:+ return None+ return {+ "background_completion": _rate(+ sum(1 for i in items if i.get("background_completion")), len(items)+ ),+ "rules": sorted({i["rule"] for i in items}),+ "disturbed": {+ k: sum(1 for i in items if i["criteria"].get(k) is False)+ for k in v2.MULTIPLAYER_CRITERIA+ },+ "unmeasured": {+ k: sum(1 for i in items if i["criteria"].get(k) is None)+ for k in v2.MULTIPLAYER_CRITERIA+ },+ }++def interruptions(rows: list[dict[str, Any]]) -> dict[str, Any]:out: dict[str, Any] = {}by_task: dict[str, list[dict[str, Any]]] = defaultdict(list)@@ -164,7 +209,13 @@ def analyze(rows: list[dict[str, Any]]) -> dict[str, Any]:report["arms"][key] = {"arm": arm,"condition": condition,- "label": ARM_LABELS.get(arm, f"{arm} (internal baseline)") + f" [{condition}]",+ "label": ARM_LABELS.get(arm, f"{arm} (internal baseline)")+ + (+ f" + {', '.join(sorted({str(r.get('model')) for r in arm_rows}))}"+ if arm.startswith("cx-")+ else ""+ )+ + f" [{condition}]","overall": summarize(arm_rows),"by_category": cats,"interruptions": interruptions(arm_rows),@@ -179,6 +230,9 @@ def analyze(rows: list[dict[str, Any]]) -> dict[str, Any]:def headline(s: dict[str, Any]) -> str:b = s["background"]+ mp = (s.get("multiplayer") or {}).get("background_completion")+ if mp: # A22: the background condition leads with multi-player background completion+ return f"{mp['k']}/{mp['n']} completed with the user undisturbed, {s['success']['k']}/{s['trials']} passed"bc = (s.get("background_condition") or {}).get("background_completion")if bc: # A15.3: the background condition leads with background completionreturn f"{bc['k']}/{bc['n']} completed in the background, {s['success']['k']}/{s['trials']} passed, {b['focus_steals']} focus steals"@@ -256,6 +310,37 @@ def markdown(report: dict[str, Any]) -> str:f"| {a['label']} | {c['k']}/{c['n']} | {s['success']['k']}/{s['trials']} | {s['background']['focus_steals']} | "f"{bc['user_window_held']}/{s['trials']} | {bc['user_input_disrupted']} | {', '.join(bc['overlay_owners']) or 'none'} |")+ cols = list(v2.MULTIPLAYER_CRITERIA)+ lines += [+ "",+ "## Background completion with the user undisturbed (Amendment 22, headline)",+ "",+ "Completed = passed and none of the eight disturbances below happened. Each column counts the background "+ 'trials in which that disturbance happened. Rows marked "A22 rescored" come from runs before A22 and are scored on the criteria those runs measured (secondary figures).',+ "",+ "| Setup | Rule | Background completion | "+ + " | ".join(v2.MULTIPLAYER_CRITERIA[c].capitalize() for c in cols)+ + " |",+ "|---|---|---|" + "---|" * len(cols),+ ]+ for arm, a in report["arms"].items():+ mp = a["overall"].get("multiplayer")+ if a["condition"] != "background" or not mp:+ continue+ c = mp["background_completion"]+ n = mp["background_completion"]["n"]+ cells = [+ "not measured"+ if mp["unmeasured"][k] == n+ else f"{mp['disturbed'][k]}"+ + (f" ({mp['unmeasured'][k]} not measured)" if mp["unmeasured"][k] else "")+ for k in cols+ ]+ lines.append(+ f"| {a['label']} | {', '.join(mp['rules'])} | {c['k']}/{c['n']} | "+ + " | ".join(cells)+ + " |"+ )viol = [(a["label"], v) for a in report["arms"].values() for v in a["violations"]]lines += ["", "## GUI-only violations", ""]lines += [f"- {label}: {v['trial_id']}: {v['evidence']}" for label, v in viol] or ["None."]diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/claude_cu_helper/cu_disclaim.c b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/claude_cu_helper/cu_disclaim.cnew file mode 100644index 0000000000..8fcf3e2019--- /dev/null+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/claude_cu_helper/cu_disclaim.c@@ -0,0 +1,79 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// cu-disclaim: start Claude Desktop's app-cu-helper as its own responsible process (arm cc-claude-cu-helper,+// Amendment 11).+//+// macOS checks Accessibility against the *responsible* process. Under the bench runner the adapter's children+// would be attributed to Terminal.app. Inside Claude Desktop the helper runs under Claude.app, which holds the+// grants. Here the helper is started with responsibility disclaimed, so macOS checks the helper's own code identity+// (identifier app-cu-helper, Anthropic team Q6L2SF6YDW), and the Accessibility grant is given to that binary in+// System Settings, through the normal UI. Nothing of ours gets a grant, and Terminal's grants are not widened.+//+// cu-disclaim <program> [args...]+//+// stdin, stdout and stderr are inherited unchanged (the helper's JSON-RPC passes straight through). The launcher+// waits for the child, passes SIGTERM/SIGINT/SIGHUP on once, and exits with the child's status. The child stays in+// the caller's process group, so a group kill reaches it.+//+// Build (in the VM): clang -O2 -Wall -o cu-disclaim cu_disclaim.c++#include <errno.h>+#include <signal.h>+#include <spawn.h>+#include <stdio.h>+#include <string.h>+#include <sys/wait.h>+#include <unistd.h>++extern char **environ;++// Exported by libsystem; declared here because no public header has it.+int responsibility_spawnattrs_setdisclaim(posix_spawnattr_t *attrs, int disclaim);++static volatile pid_t child_pid = 0;+static volatile sig_atomic_t forwarded[32];++static void forward(int sig) {+ if (child_pid > 0 && sig > 0 && sig < 32 && !forwarded[sig]) {+ forwarded[sig] = 1;+ kill(child_pid, sig);+ }+}++int main(int argc, char **argv) {+ if (argc < 2) {+ fprintf(stderr, "usage: cu-disclaim <program> [args...]\n");+ return 64;+ }+ posix_spawnattr_t attrs;+ posix_spawnattr_init(&attrs);+ if (responsibility_spawnattrs_setdisclaim(&attrs, 1) != 0) {+ fprintf(stderr, "cu-disclaim: responsibility_spawnattrs_setdisclaim failed\n");+ return 70;+ }+ struct sigaction sa;+ memset(&sa, 0, sizeof sa);+ sa.sa_handler = forward;+ sigemptyset(&sa.sa_mask);+ sigaction(SIGTERM, &sa, NULL);+ sigaction(SIGINT, &sa, NULL);+ sigaction(SIGHUP, &sa, NULL);+ pid_t pid;+ int rc = posix_spawn(&pid, argv[1], NULL, &attrs, argv + 1, environ);+ posix_spawnattr_destroy(&attrs);+ if (rc != 0) {+ fprintf(stderr, "cu-disclaim: spawn %s: %s\n", argv[1], strerror(rc));+ return 127;+ }+ child_pid = pid;+ int status = 0;+ for (;;) {+ pid_t done = waitpid(pid, &status, 0);+ if (done == pid) break;+ if (done < 0 && errno != EINTR) return 127;+ }+ if (WIFEXITED(status)) return WEXITSTATUS(status);+ if (WIFSIGNALED(status)) return 128 + WTERMSIG(status);+ return 1;+}diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/claude_cu_helper/cu_helper_mcp.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/claude_cu_helper/cu_helper_mcp.pynew file mode 100644index 0000000000..6494c80753--- /dev/null+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/claude_cu_helper/cu_helper_mcp.py@@ -0,0 +1,510 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.+"""Minimal MCP adapter around Claude Desktop's ``app-cu-helper`` (arm ``cc-claude-cu-helper``, Amendment 11):+"Claude Desktop 2.31226.0 computer-use helper via a minimal adapter".++The helper of Claude Desktop 2.31226.0 is not an MCP server. It reads newline-delimited JSON-RPC on stdin and+writes the responses on stdout. Its methods (probed in the VM): ``probe``, ``dispatchRaw`` (kinds click, rclick,+mclick, drag, scroll, hover, key, type: input delivered to one window of one process at a window-local point, in the+background), ``wakeChromiumCompositor``, ``bringWindowToActiveSpace`` and ``keyWindowSpoof``. This adapter exposes+the input as MCP tools shaped like Claude's own background computer-use tools (``app_*``) and adds what the helper+does not provide:++* **Which windows exist** (``app_list_windows``): ``winlist``, a small Swift tool built in the VM that prints+ ``CGWindowListCopyWindowInfo`` (owner, pid, window id, bounds, title). Public macOS API only.+* **What a window shows** (``app_screenshot``): ``/usr/sbin/screencapture -l <window id>`` of that one window, the+ stock macOS tool, downscaled with ``/usr/bin/sips`` to Claude Code's own screenshot budget. Desktop captures with+ its in-process native module (``@ant/claude-swift``, ``appScoped.captureWindow``), not with the helper, so that path+ is not reachable here. Like Desktop, the adapter asks the helper to wake a Chromium window's compositor first.++Everything that changes the screen goes through the helper's ``dispatchRaw`` and nothing else. When the helper+refuses or cannot do something, the tool returns the helper's refusal; no other input path is used. Desktop's+accessibility layer (element indexes, menus, AX text entry) lives in its main process, not in the helper, and is not+offered. Cua Driver is not used anywhere in this arm.++Run: python3 -I -B cu_helper_mcp.py --helper <app-cu-helper> --winlist <winlist> [--launcher <cu-disclaim>]+ [--actions click,right_click,type,key,scroll,drag,hover]+Stdlib only. Logs go to stderr; nothing is written to disk except the temporary screenshot files, which are deleted+after each call.+"""++from __future__ import annotations++import argparse+import base64+import json+import math+import os+import queue+import struct+import subprocess+import sys+import tempfile+import threading+import time+from typing import Any, Callable++ADAPTER_VERSION = "1.0.0"+SERVER_NAME = "claude-cu-helper"+SCREENCAPTURE = "/usr/sbin/screencapture"+SIPS = "/usr/bin/sips"+# Claude Code's built-in computer use downscales every screenshot before it reaches the model (a 3456x2234+# capture becomes about 1372x887, docs "Screenshots are downscaled automatically"): about 1.22 megapixels. The+# adapter uses the same budget, so the model sees the same amount of detail as with Claude's own tool.+MAX_PIXELS = 1372 * 887+MAX_EDGE = 1568+HELPER_TIMEOUT_S = 15.0++# The input tools and the helper call each one makes. The mapping copies Claude Desktop 2.31226.0's own raw-input path+# (its OTr function and dispatch call site in app.asar, read in the VM): dispatchRaw with pid, windowId, winLocalPt,+# focusedTarget, hostPid and nativeMouseVariant plus the kind fields below; scroll units are Desktop's x40 points;+# key combos map meta/cmd -> cmd, alt/option -> option, ctrl, shift, fn; typing is capped at 4000 characters and a+# "replace" type first sends cmd+a with partOfTextWrite, as Desktop does. Which tools are offered is fixed by+# --actions (pinned from the VM probe); nothing here falls back to any other input path.+ALL_ACTIONS = ("click", "right_click", "type", "key", "scroll", "drag", "hover")+TYPE_MAX_CHARS = 4000+SCROLL_POINTS_PER_UNIT = 40+BUSY_RETRIES, BUSY_WAIT_S = 6, 0.4 # Desktop retries "user_actively_typing" 6 times, 400 ms apart+MODIFIERS = {"cmd": "cmd", "command": "cmd", "meta": "cmd", "super": "cmd", "shift": "shift", "alt": "option",+ "option": "option", "opt": "option", "ctrl": "ctrl", "control": "ctrl", "fn": "fn"}+KEY_ALIASES = {"enter": "return", "esc": "escape", "pgdn": "pageDown", "pagedown": "pageDown", "pgup": "pageUp",+ "pageup": "pageUp", "arrowup": "up", "arrowdown": "down", "arrowleft": "left", "arrowright": "right"}+++def log(message: str) -> None:+ sys.stderr.write(f"[{SERVER_NAME}] {message}\n")+ sys.stderr.flush()+++# ---------------------------------------------------------------- helper process+++class HelperError(RuntimeError):+ pass+++class Helper:+ """The helper as a child process: one request at a time, newline-delimited JSON-RPC 2.0."""++ def __init__(self, argv: list[str], env: dict[str, str] | None = None) -> None:+ self.argv = argv+ self.env = env+ self.proc: subprocess.Popen[str] | None = None+ self.lines: "queue.Queue[str | None]" = queue.Queue()+ self.next_id = 0+ self.lock = threading.Lock()++ def _start(self) -> None:+ self.proc = subprocess.Popen(+ self.argv,+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=sys.stderr, # the helper logs on stderr; it lands in Claude Code's MCP log with ours+ text=True,+ bufsize=1,+ env=self.env,+ )+ self.lines = queue.Queue()+ threading.Thread(target=self._pump, args=(self.proc, self.lines), daemon=True).start()++ @staticmethod+ def _pump(proc: subprocess.Popen[str], lines: "queue.Queue[str | None]") -> None:+ assert proc.stdout is not None+ for line in proc.stdout:+ lines.put(line)+ lines.put(None)++ def call(self, method: str, params: dict[str, Any], timeout: float = HELPER_TIMEOUT_S) -> dict[str, Any]:+ with self.lock:+ if self.proc is None or self.proc.poll() is not None:+ self._start()+ assert self.proc is not None and self.proc.stdin is not None+ self.next_id += 1+ ident = self.next_id+ self.proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": ident, "method": method, "params": params}) + "\n")+ self.proc.stdin.flush()+ deadline = time.monotonic() + timeout+ while True:+ left = deadline - time.monotonic()+ if left <= 0:+ raise HelperError(f"helper {method}: no response within {timeout:g} s")+ try:+ line = self.lines.get(timeout=left)+ except queue.Empty:+ continue+ if line is None:+ raise HelperError(f"helper exited during {method} (rc={self.proc.poll()})")+ try:+ reply = json.loads(line)+ except json.JSONDecodeError:+ continue+ if reply.get("id") != ident:+ continue+ if "error" in reply:+ raise HelperError(f"helper {method}: {json.dumps(reply['error'])[:500]}")+ return reply.get("result") or {}++ def close(self) -> None:+ if self.proc is not None and self.proc.poll() is None:+ try:+ assert self.proc.stdin is not None+ self.proc.stdin.close() # the helper exits when stdin closes+ self.proc.wait(timeout=5)+ except (OSError, subprocess.TimeoutExpired):+ self.proc.kill()+++# ---------------------------------------------------------------- windows and screenshots+++def list_windows(winlist: str) -> list[dict[str, Any]]:+ done = subprocess.run([winlist], capture_output=True, text=True, timeout=10)+ if done.returncode != 0:+ raise RuntimeError(f"winlist failed: {done.stderr.strip()[:300]}")+ return json.loads(done.stdout)+++def find_window(winlist: str, window_id: int) -> dict[str, Any]:+ for win in list_windows(winlist):+ if int(win.get("window_id", -1)) == int(window_id):+ return win+ raise ValueError(f"no on-screen window with window_id {window_id}; call list_windows")+++def png_size(data: bytes) -> tuple[int, int]:+ if data[:8] != b"\x89PNG\r\n\x1a\n" or data[12:16] != b"IHDR":+ raise ValueError("not a PNG")+ width, height = struct.unpack(">II", data[16:24])+ return int(width), int(height)+++def target_size(width: int, height: int) -> tuple[int, int]:+ """Largest size within MAX_PIXELS and MAX_EDGE with the same aspect ratio (never upscaled)."""+ scale = min(1.0, math.sqrt(MAX_PIXELS / float(width * height)), MAX_EDGE / float(max(width, height)))+ return max(1, int(width * scale)), max(1, int(height * scale))+++def capture_window(window_id: int, screencapture: str = SCREENCAPTURE, sips: str = SIPS) -> tuple[bytes, int, int]:+ """PNG of one window (no shadow), downscaled to the screenshot budget. Returns (png, width, height)."""+ with tempfile.TemporaryDirectory(prefix="cuhelper-") as tmp:+ path = os.path.join(tmp, "w.png")+ done = subprocess.run([screencapture, "-x", "-o", "-t", "png", f"-l{int(window_id)}", path],+ capture_output=True, text=True, timeout=20)+ if done.returncode != 0 or not os.path.exists(path) or os.path.getsize(path) == 0:+ raise RuntimeError(f"screencapture failed (rc={done.returncode}): {done.stderr.strip()[:300]}")+ with open(path, "rb") as handle:+ data = handle.read()+ width, height = png_size(data)+ new_w, new_h = target_size(width, height)+ if (new_w, new_h) != (width, height):+ subprocess.run([sips, "-z", str(new_h), str(new_w), path], capture_output=True, timeout=20, check=True)+ with open(path, "rb") as handle:+ data = handle.read()+ width, height = png_size(data)+ return data, width, height+++# ---------------------------------------------------------------- the MCP server+++def parse_combo(combo: str) -> tuple[str, list[str]]:+ """"cmd+shift+z" -> ("z", ["cmd", "shift"]); the last non-modifier part is the key."""+ parts = [p.strip() for p in str(combo or "").replace(" ", "").split("+") if p.strip()]+ mods: list[str] = []+ keys: list[str] = []+ for part in parts:+ low = part.lower()+ if low in MODIFIERS:+ if MODIFIERS[low] not in mods:+ mods.append(MODIFIERS[low])+ else:+ keys.append(KEY_ALIASES.get(low, part if len(part) > 1 else low))+ if len(keys) != 1:+ raise ValueError(f"combo {combo!r} must name exactly one key, e.g. \"return\" or \"cmd+a\"")+ return keys[0], mods+++class Adapter:+ """Tools in the shape of Claude's own background computer-use tools (``app_list_windows``, ``app_screenshot``,+ ``app_click``, ``app_type``, ``app_key``, ``app_scroll``, ``app_drag``: ``app`` + ``window_id`` targeting,+ ``coordinate`` in screenshot pixels), limited to what the helper can do. Desktop's accessibility layer (element+ indexes, menus, AX text entry) is not part of the helper and is not offered."""++ def __init__(self, helper: Helper, winlist: str, actions: list[str], host_pid: int | None = None,+ screencapture: str = SCREENCAPTURE, sips: str = SIPS, busy_wait_s: float = BUSY_WAIT_S) -> None:+ self.helper = helper+ self.winlist = winlist+ self.actions = [a for a in ALL_ACTIONS if a in actions]+ self.host_pid = host_pid if host_pid is not None else os.getpid()+ self.screencapture = screencapture+ self.sips = sips+ self.busy_wait_s = busy_wait_s+ # window_id -> (window width in points, height in points, screenshot width, screenshot height)+ self.frames: dict[int, tuple[float, float, int, int]] = {}++ # -------------------------------------------------- tool definitions++ def tools(self) -> list[dict[str, Any]]:+ app = {"type": "string", "description": "Application name as shown by app_list_windows (e.g. \"BenchLab\")."}+ window_id = {"type": "integer", "description": "window_id from app_list_windows; default: the app's frontmost window"}+ coordinate = {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2,+ "description": "[x, y] in pixels of the latest app_screenshot of this window (origin top-left)"}+ bg = " without bringing it to the front (delivered by Claude Desktop's computer-use helper)."++ def tool(name: str, description: str, props: dict[str, Any], required: list[str]) -> dict[str, Any]:+ return {"name": name, "description": description, "inputSchema": {+ "type": "object", "properties": props, "required": required, "additionalProperties": False}}++ out = [+ tool("app_list_windows", "List the windows on screen. Without app: every app. Returns [{app, pid, window_id, "+ "title, x, y, width, height}] (frame in screen points). Use the window_id with app_screenshot and the "+ "action tools.", {"app": app}, []),+ tool("app_screenshot", "Capture a screenshot of one window of an application. The (x, y) coordinates you "+ "pass to the action tools are ALWAYS pixels in the latest screenshot of that window.",+ {"app": app, "window_id": window_id}, ["app"]),+ ]+ if "click" in self.actions:+ buttons = ["left", "right"] if "right_click" in self.actions else ["left"]+ out.append(tool("app_click", "Click a point within one window of an application" + bg + " Right-clicks "+ "that would open a context menu, and clicks on pop-up menus, are refused by the helper.",+ {"app": app, "window_id": window_id, "coordinate": coordinate,+ "button": {"type": "string", "enum": buttons},+ "count": {"type": "number", "enum": [1, 2, 3]}}, ["app", "coordinate"]))+ if "type" in self.actions:+ out.append(tool("app_type", "Type text into one window of an application" + bg + " With coordinate, the "+ "text goes to the text element at that point (it must be the focused element: click it "+ "first); without coordinate, to the app's focused element. mode \"replace\" selects all "+ f"first (cmd+a). At most {TYPE_MAX_CHARS} characters.",+ {"app": app, "window_id": window_id, "coordinate": coordinate, "text": {"type": "string"},+ "mode": {"type": "string", "enum": ["insert", "replace"]}}, ["app", "text"]))+ if "key" in self.actions:+ out.append(tool("app_key", "Send a key or shortcut to one window of an application" + bg + " Examples: "+ "\"return\", \"escape\", \"tab\", \"backspace\", \"delete\", \"up\", \"pageDown\", "+ "\"cmd+a\". Some shortcuts are refused in the background.",+ {"app": app, "window_id": window_id, "coordinate": coordinate,+ "combo": {"type": "string"}}, ["app", "combo"]))+ if "scroll" in self.actions:+ out.append(tool("app_scroll", "Scroll the content at a point within one window of an application" + bg ++ f" dy > 0 scrolls toward the bottom, dy < 0 toward the top; dx > 0 toward the right. One "+ f"unit is about {SCROLL_POINTS_PER_UNIT} points.",+ {"app": app, "window_id": window_id, "coordinate": coordinate, "dy": {"type": "number"},+ "dx": {"type": "number"}}, ["app", "coordinate"]))+ if "drag" in self.actions:+ out.append(tool("app_drag", "Drag from coordinate to to_coordinate inside one window of an application" + bg,+ {"app": app, "window_id": window_id, "coordinate": coordinate,+ "to_coordinate": coordinate}, ["app", "coordinate", "to_coordinate"]))+ if "hover" in self.actions:+ out.append(tool("app_hover", "Move the pointer over a point within one window of an application" + bg ++ " (hover: tooltips and hover-only controls).",+ {"app": app, "window_id": window_id, "coordinate": coordinate}, ["app", "coordinate"]))+ return out++ # -------------------------------------------------- targeting++ def window_for(self, app: str, window_id: Any = None) -> dict[str, Any]:+ wins = list_windows(self.winlist)+ if window_id is not None:+ for win in wins:+ if int(win.get("window_id", -1)) == int(window_id):+ return win+ raise ValueError(f"no on-screen window with window_id {window_id}; call app_list_windows")+ name = (app or "").strip().lower()+ for win in wins: # front to back: the first match is the app's frontmost window+ if str(win.get("app", "")).lower() == name:+ return win+ raise ValueError(f"no on-screen window of app {app!r}; call app_list_windows")++ def to_window_points(self, wid: int, coord: Any) -> dict[str, float]:+ if not isinstance(coord, (list, tuple)) or len(coord) != 2:+ raise ValueError("coordinate must be [x, y]")+ x, y = float(coord[0]), float(coord[1])+ if wid not in self.frames:+ raise ValueError(f"take an app_screenshot of window {wid} first; coordinates are screenshot pixels")+ w_pt, h_pt, w_px, h_px = self.frames[wid]+ if not (0 <= x < w_px and 0 <= y < h_px):+ raise ValueError(f"point ({x:g}, {y:g}) is outside the {w_px}x{h_px} screenshot of window {wid}")+ return {"x": round(x * w_pt / w_px, 2), "y": round(y * h_pt / h_px, 2)}++ # -------------------------------------------------- tool calls++ def call(self, name: str, args: dict[str, Any]) -> list[dict[str, Any]]:+ if name == "app_list_windows":+ wins = list_windows(self.winlist)+ if args.get("app"):+ wins = [w for w in wins if str(w.get("app", "")).lower() == str(args["app"]).strip().lower()]+ return [{"type": "text", "text": json.dumps(wins)}]+ if name == "app_screenshot":+ win = self.window_for(args.get("app", ""), args.get("window_id"))+ wid = int(win["window_id"])+ try: # Desktop wakes a Chromium window's compositor through the helper before every capture+ self.helper.call("wakeChromiumCompositor", {"pid": int(win["pid"]), "windowId": wid,+ "hostPid": self.host_pid, "debug": True})+ except HelperError as error:+ log(f"wakeChromiumCompositor: {error}")+ data, width, height = capture_window(wid, self.screencapture, self.sips)+ self.frames[wid] = (float(win["width"]), float(win["height"]), width, height)+ text = (f"{win.get('app')} window {wid} ({win.get('title') or 'untitled'}): screenshot {width}x{height} px; "+ "coordinates are pixels of this image.")+ return [{"type": "text", "text": text},+ {"type": "image", "data": base64.b64encode(data).decode("ascii"), "mimeType": "image/png"}]+ handler = {+ "app_click": ("click", self.click), "app_type": ("type", self.type_text), "app_key": ("key", self.key),+ "app_scroll": ("scroll", self.scroll), "app_drag": ("drag", self.drag), "app_hover": ("hover", self.hover),+ }.get(name)+ if handler is None or handler[0] not in self.actions:+ raise ValueError(f"unknown tool {name}")+ win = self.window_for(args.get("app", ""), args.get("window_id"))+ return handler[1](win, args)++ def dispatch(self, win: dict[str, Any], point: dict[str, float] | None, fields: dict[str, Any],+ focused: bool = False) -> dict[str, Any]:+ params = {"pid": int(win["pid"]), "windowId": int(win["window_id"]),+ "winLocalPt": point or {"x": round(float(win["width"]) / 2, 2), "y": round(float(win["height"]) / 2, 2)},+ "focusedTarget": focused, "hostPid": self.host_pid, "nativeMouseVariant": False,+ "debug": True, **fields} # debug: refusals carry the helper's blockedReason+ for attempt in range(BUSY_RETRIES + 1):+ result = self.helper.call("dispatchRaw", params)+ if result.get("code") != "user_actively_typing" or attempt == BUSY_RETRIES:+ return result+ time.sleep(self.busy_wait_s)+ return result++ @staticmethod+ def report(what: str, result: dict[str, Any], point: dict[str, float] | None) -> list[dict[str, Any]]:+ info = {"delivered": result.get("delivered"), "path": result.get("path")}+ for key in ("code", "charsDelivered"):+ if key in result:+ info[key] = result[key]+ reason = (result.get("debugFields") or {}).get("blockedReason")+ if reason:+ info["reason"] = reason+ if point:+ info["window_point"] = [point["x"], point["y"]]+ text = json.dumps(info)+ if result.get("delivered") is not True:+ raise RuntimeError(f"the helper did not deliver the {what}: {text}")+ return [{"type": "text", "text": text}]++ def point_of(self, win: dict[str, Any], args: dict[str, Any], required: bool) -> dict[str, float] | None:+ if args.get("coordinate") is None and not required:+ return None+ return self.to_window_points(int(win["window_id"]), args.get("coordinate"))++ def click(self, win: dict[str, Any], args: dict[str, Any]) -> list[dict[str, Any]]:+ button = str(args.get("button") or "left")+ if button not in ("left", "right") or (button == "right" and "right_click" not in self.actions):+ raise ValueError(f"button {button!r} is not available")+ count = int(args.get("count") or 1)+ if count not in (1, 2, 3):+ raise ValueError("count must be 1, 2 or 3")+ point = self.point_of(win, args, True)+ result = self.dispatch(win, point, {"kind": "rclick" if button == "right" else "click", "count": count})+ return self.report("click", result, point)++ def type_text(self, win: dict[str, Any], args: dict[str, Any]) -> list[dict[str, Any]]:+ text = str(args.get("text") or "")+ if not text:+ raise ValueError("text is empty")+ if len(text) > TYPE_MAX_CHARS:+ raise ValueError(f"text is longer than {TYPE_MAX_CHARS} characters")+ point = self.point_of(win, args, False)+ focused = point is None+ if (args.get("mode") or "insert") == "replace":+ sel = self.dispatch(win, point, {"kind": "key", "keyName": "a", "modifiers": ["cmd"], "partOfTextWrite": True},+ focused)+ if sel.get("delivered") is not True:+ return self.report("select-all before replace", sel, point)+ result = self.dispatch(win, point, {"kind": "type", "text": text}, focused)+ return self.report("text", result, point)++ def key(self, win: dict[str, Any], args: dict[str, Any]) -> list[dict[str, Any]]:+ key, mods = parse_combo(args.get("combo", ""))+ point = self.point_of(win, args, False)+ result = self.dispatch(win, point, {"kind": "key", "keyName": key, "modifiers": mods}, point is None)+ return self.report("key", result, point)++ def scroll(self, win: dict[str, Any], args: dict[str, Any]) -> list[dict[str, Any]]:+ dy, dx = float(args.get("dy") or 0), float(args.get("dx") or 0)+ if not dy and not dx:+ raise ValueError("give dy and/or dx")+ point = self.point_of(win, args, True)+ result = self.dispatch(win, point, {"kind": "scroll", "dx": round(-dx * SCROLL_POINTS_PER_UNIT),+ "dy": round(-dy * SCROLL_POINTS_PER_UNIT), "ticks": 1})+ return self.report("scroll", result, point)++ def drag(self, win: dict[str, Any], args: dict[str, Any]) -> list[dict[str, Any]]:+ point = self.point_of(win, args, True)+ to = self.to_window_points(int(win["window_id"]), args.get("to_coordinate"))+ result = self.dispatch(win, point, {"kind": "drag", "toWinLocalPt": to})+ return self.report("drag", result, point)++ def hover(self, win: dict[str, Any], args: dict[str, Any]) -> list[dict[str, Any]]:+ point = self.point_of(win, args, True)+ result = self.dispatch(win, point, {"kind": "hover"})+ return self.report("hover", result, point)+++def serve(adapter: Adapter, stdin: Any = None, stdout: Any = None) -> None:+ stdin = stdin or sys.stdin+ stdout = stdout or sys.stdout++ def send(obj: dict[str, Any]) -> None:+ stdout.write(json.dumps(obj) + "\n")+ stdout.flush()++ handlers: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {+ "initialize": lambda p: {+ "protocolVersion": p.get("protocolVersion") or "2025-06-18",+ "capabilities": {"tools": {}},+ "serverInfo": {"name": SERVER_NAME, "version": ADAPTER_VERSION},+ },+ "tools/list": lambda p: {"tools": adapter.tools()},+ "ping": lambda p: {},+ }+ for raw in stdin:+ raw = raw.strip()+ if not raw:+ continue+ try:+ msg = json.loads(raw)+ except json.JSONDecodeError:+ continue+ method, ident = msg.get("method"), msg.get("id")+ if ident is None:+ continue # notifications+ params = msg.get("params") or {}+ if method == "tools/call":+ try:+ content = adapter.call(params.get("name", ""), params.get("arguments") or {})+ send({"jsonrpc": "2.0", "id": ident, "result": {"content": content, "isError": False}})+ except Exception as error: # noqa: BLE001 - every failure goes back to the model as a tool error+ send({"jsonrpc": "2.0", "id": ident,+ "result": {"content": [{"type": "text", "text": f"{type(error).__name__}: {error}"}],+ "isError": True}})+ elif method in handlers:+ send({"jsonrpc": "2.0", "id": ident, "result": handlers[method](params)})+ else:+ send({"jsonrpc": "2.0", "id": ident, "error": {"code": -32601, "message": f"method not found: {method}"}})+ adapter.helper.close()+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--helper", required=True)+ parser.add_argument("--winlist", required=True)+ parser.add_argument("--launcher", help="cu-disclaim: start the helper as its own responsible process (A11)")+ parser.add_argument("--actions", default=",".join(ALL_ACTIONS))+ parser.add_argument("--screencapture", default=SCREENCAPTURE)+ parser.add_argument("--sips", default=SIPS)+ args = parser.parse_args(argv)+ helper = Helper([args.launcher, args.helper] if args.launcher else [args.helper], env={"PATH": "/usr/bin:/bin", "HOME": os.environ.get("HOME", "/tmp")})+ adapter = Adapter(helper, args.winlist, [a for a in args.actions.split(",") if a],+ screencapture=args.screencapture, sips=args.sips)+ log(f"adapter {ADAPTER_VERSION} up; helper {args.helper}; actions {adapter.actions}")+ serve(adapter)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/claude_cu_helper/install_cu_helper.sh b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/claude_cu_helper/install_cu_helper.shnew file mode 100644index 0000000000..eed9ef9004--- /dev/null+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/claude_cu_helper/install_cu_helper.sh@@ -0,0 +1,57 @@+#!/bin/zsh+# SPDX-License-Identifier: FSL-1.1-MIT+# Copyright (c) 2026 Cua AI, Inc.+# Amendment 11: install the pieces of arm cc-claude-cu-helper ("Claude Desktop 2.31226.0 computer-use helper via a+# minimal adapter"). VM ONLY: run it in the disposable bench VM clone made for this arm, never on a Mac anyone uses.+#+# zsh install_cu_helper.sh # download + verify Claude Desktop 2.31226.0, build winlist, print the pin values+#+# What it does, and what it never does:+# 1. downloads the pinned Claude Desktop archive from downloads.claude.ai and checks its byte size and sha256;+# 2. unpacks it with ditto into $CDB_BENCH_WORK/claude-desktop-2.31226.0/ (the app is NOT moved to /Applications+# and is NEVER launched: Desktop updates itself when it starts);+# 3. checks the sha256 of Contents/Helpers/app-cu-helper and its signature (codesign --verify, Anthropic's team id);+# 4. builds winlist (public CGWindowList API) with swiftc and cu-disclaim (cu_disclaim.c) with clang.+# It never re-signs anything, never removes the quarantine attribute (curl sets none), never changes entitlements.+set -euo pipefail+HERE=${0:A:h}+W=${CDB_BENCH_WORK:-$HOME/bench-work}+D=$W/claude-desktop-2.31226.0+URL=https://downloads.claude.ai/releases/darwin/universal/2.31226.0/Claude-eb794d1033f2a59c2cd89aa29ed1f8b5de12aa73.zip+ZIP_SHA=bd38f1051a14cabd893c7422e106ad6318e8785f19472c8064eafa64ce235820+ZIP_BYTES=383954641+HELPER_SHA=7bd631e8b5ae36941ac551c474055e2eff32163db6684628eac5cfcabcb3dc14+TEAM=Q6L2SF6YDW++mkdir -p $D+Z=$D/Claude-2.31226.0.zip+if [ ! -f $Z ] || [ "$(shasum -a 256 $Z | cut -d' ' -f1)" != $ZIP_SHA ]; then+ curl -fL --retry 3 -o $Z.part $URL+ mv $Z.part $Z+fi+[ "$(stat -f %z $Z)" = $ZIP_BYTES ] || { echo "archive size mismatch: $(stat -f %z $Z)" >&2; exit 2; }+[ "$(shasum -a 256 $Z | cut -d' ' -f1)" = $ZIP_SHA ] || { echo "archive sha256 mismatch" >&2; exit 2; }+echo "archive ok: $ZIP_BYTES bytes, sha256 $ZIP_SHA"++H=$D/extracted/Claude.app/Contents/Helpers/app-cu-helper+# unpack once: the helper's Accessibility grant (System Settings, A11) is for this file, so it is not re-extracted+if [ ! -f $H ] || [ "$(shasum -a 256 $H | cut -d' ' -f1)" != $HELPER_SHA ]; then+ rm -rf $D/extracted+ mkdir -p $D/extracted+ ditto -x -k $Z $D/extracted+fi+[ "$(shasum -a 256 $H | cut -d' ' -f1)" = $HELPER_SHA ] || { echo "helper sha256 mismatch" >&2; exit 2; }+codesign --verify --strict --verbose=2 $H+codesign -dv --verbose=2 $H 2>&1 | grep -E "^(Identifier|Authority|TeamIdentifier)="+[[ "$(codesign -dv $H 2>&1)" == *"TeamIdentifier=$TEAM"* ]] || { echo "helper team id is not $TEAM" >&2; exit 2; }+echo "helper ok: sha256 $HELPER_SHA"+xattr -l $H | sed 's/^/xattr: /' || true++mkdir -p $W/claude-cu-helper+swiftc -O -o $W/claude-cu-helper/winlist $HERE/winlist.swift+clang -O2 -Wall -o $W/claude-cu-helper/cu-disclaim $HERE/cu_disclaim.c+cp $HERE/cu_helper_mcp.py $W/claude-cu-helper/cu_helper_mcp.py++echo "--- values for pins.json claude_cu_helper"+cd ${HERE:h:h}+CDB_BENCH_WORK=$W /opt/homebrew/bin/python3 -c "import json, claude_arms as ca; print(json.dumps(ca.cu_helper_observed(), indent=2))"diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/claude_cu_helper/winlist.swift b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/claude_cu_helper/winlist.swiftnew file mode 100644index 0000000000..68cba1146a--- /dev/null+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tools/claude_cu_helper/winlist.swift@@ -0,0 +1,35 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// winlist: print the on-screen windows as JSON, for the cc-claude-cu-helper adapter (Amendment 11).+// Public CoreGraphics API only (CGWindowListCopyWindowInfo); no Accessibility, no private symbols, no input.+// Window titles need Screen Recording for the responsible process; without it "title" is empty.+//+// Build (in the VM): swiftc -O -o winlist winlist.swift+// Output: [{"app","pid","window_id","title","x","y","width","height","layer"}], front to back, layer 0 only+// (normal app windows), windows smaller than 40x40 points dropped.+import CoreGraphics+import Foundation++let options: CGWindowListOption = [.optionOnScreenOnly, .excludeDesktopElements]+let infos = (CGWindowListCopyWindowInfo(options, kCGNullWindowID) as? [[String: Any]]) ?? []+var out: [[String: Any]] = []+for info in infos {+ let layer = info[kCGWindowLayer as String] as? Int ?? -1+ guard layer == 0 else { continue }+ guard let bounds = info[kCGWindowBounds as String] as? [String: Any],+ let rect = CGRect(dictionaryRepresentation: bounds as CFDictionary) else { continue }+ if rect.width < 40 || rect.height < 40 { continue }+ out.append([+ "app": info[kCGWindowOwnerName as String] as? String ?? "",+ "pid": info[kCGWindowOwnerPID as String] as? Int ?? 0,+ "window_id": info[kCGWindowNumber as String] as? Int ?? 0,+ "title": info[kCGWindowName as String] as? String ?? "",+ "x": Double(rect.origin.x), "y": Double(rect.origin.y),+ "width": Double(rect.size.width), "height": Double(rect.size.height),+ "layer": layer,+ ])+}+let data = try JSONSerialization.data(withJSONObject: out, options: [])+FileHandle.standardOutput.write(data)+FileHandle.standardOutput.write("\n".data(using: .utf8)!)diff --git a/benchmarks/cua-driver-bench/ruff.toml b/benchmarks/cua-driver-bench/ruff.tomlindex f0bdfd704d..61b880d9bf 100644--- a/benchmarks/cua-driver-bench/ruff.toml+++ b/benchmarks/cua-driver-bench/ruff.toml@@ -1,5 +1,6 @@# Ruff settings for the Cua Driver Bench harness. Inherits the repository settings.# The task pack is excluded: its files are pinned by digest (task manifests, evaluator-# oracles and the harness pins), so they are kept byte for byte as released.+# oracles and the harness pins), so they are kept byte for byte as released. So is the helper arm's adapter, whose+# sha256 is pinned in pins.json (claude_cu_helper.adapter_sha256) and checked before every helper run.extend = "../../pyproject.toml"-extend-exclude = ["taskpack"]+extend-exclude = ["taskpack", "automated-eval/macos_bench/tools/claude_cu_helper/cu_helper_mcp.py"]