Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver-bench): sync Amendment 19 checker fixes and the native Codex setup (A20) (#4978)

Francesco Bonacciebc0b3d7d0ac
diff --git a/benchmarks/cua-driver-bench/README.md b/benchmarks/cua-driver-bench/README.md
index fd37ee2575..6579253373 100644
--- a/benchmarks/cua-driver-bench/README.md
+++ b/benchmarks/cua-driver-bench/README.md
@@ -92,7 +92,7 @@ per-category differences are directional only.
| --- | --- | --- |
| **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`) |
| **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 will be added once its smoke checks pass; no numbers exist yet. |
+| **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. |
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 +151,7 @@ for app in "$CDB_BENCH_WORK"/taskpack/tasks/shared/*/apps/*; do (cd "$app" && np
config from the plugin's own file (`tools/make_codex_cu_mcp.py`). The plugin
is OpenAI's and is not redistributed here; driving it from a client other
than OpenAI's is undocumented.
-* **Codex CLI + `gpt-6-astra`.** Planned; its install steps will come with its harness code.
+* **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`).
### 4. Check, then run
diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/arms.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/arms.py
index d0801a72c5..9f8a620e69 100644
--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/arms.py
+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/arms.py
@@ -38,7 +38,9 @@ DEFAULT_CLAUDE_ARMS = ("cc-cua-driver", "cc-codex-cu", "cc-cua-driver-main")
# Fallback arms, `codex exec --json`, behind --allow-codex-arms in run_bench.py.
CODEX_FALLBACK_ARMS = ("codex-native-cu", "codex-cua-driver")
ARM_ALIASES = {"codex-cua-driver": "cua-driver-mcp"} # name used by the pilot code paths
-ALL_ARMS = CLAUDE_ARMS + CODEX_FALLBACK_ARMS
+# Amendment 20 (CUA-1347): Codex CLI + gpt-6-astra driving Codex computer use natively (codex_native.py).
+NATIVE_CODEX_ARMS = ("cx-codex-cu",)
+ALL_ARMS = CLAUDE_ARMS + CODEX_FALLBACK_ARMS + NATIVE_CODEX_ARMS
CODEX_APP_RESOURCES = Path("/Applications/ChatGPT.app/Contents/Resources")
CODEX_CU_DIR = Path.home() / ".codex" / "computer-use"
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.py
index d9f34785f5..961fe373c2 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
@@ -4,8 +4,9 @@ interruption fields of a trial row.
* GUI-only (CUA-1200). Every v2 task runs once, with no shell or file tools for any setup. The
surface is the same for every setup (Skill, a skill-scoped Read, ToolSearch and the setup's own
computer-use server). `GuiOnlyGuard` watches the agent phase of every trial for the routes that
- are left: a terminal or scripting app in front, a scripting process, or a computer-use tool input
- that runs code or touches files outside the GUI. A violation ends the trial at once and the trial
+ are left: a terminal or scripting app in front, a scripting process, input read by a Terminal shell
+ or a new Terminal session (Amendment 19), or a computer-use tool input that runs code or touches files
+ outside the GUI. A violation ends the trial at once and the trial
counts as failed (`passed` false, `passed_raw` keeps the evaluator's verdict).
* Categories (CUA-1281). Every task has exactly one `category` in its task.json. Reports aggregate
per category and overall. Background operation is a score on every trial, not a category.
@@ -207,6 +208,65 @@ def _pgrep(name: str) -> bool:
return subprocess.run(["pgrep", "-x", name], capture_output=True).returncode == 0
+def _ps_rows() -> list[tuple[int, int, str, str]]:
+ """(pid, ppid, tty, command name) of every process."""
+ out = subprocess.run(
+ ["ps", "-axo", "pid=,ppid=,tty=,comm="], capture_output=True, text=True, timeout=5
+ ).stdout
+ rows = []
+ for line in out.splitlines():
+ parts = line.split(None, 3)
+ if len(parts) == 4 and parts[0].isdigit() and parts[1].isdigit():
+ rows.append((int(parts[0]), int(parts[1]), parts[2], parts[3]))
+ return rows
+
+
+def terminal_session_ttys(rows: list[tuple[int, int, str, str]], exclude_pid: int) -> set[str]:
+ """Device paths of the ttys of Terminal sessions, except the runner's (`exclude_pid`): its own tty, which it
+ never reads, and any tty its descendants open (agents, MCP servers, apps it starts)."""
+ parent = {pid: ppid for pid, ppid, _, _ in rows}
+ tty_of = {pid: tty for pid, _, tty, _ in rows}
+ terminals = {pid for pid, _, _, comm in rows if comm.rsplit("/", 1)[-1] == "Terminal"}
+
+ def ancestors(pid: int) -> set[int]:
+ seen: set[int] = set()
+ while pid in parent and pid not in seen and pid > 1:
+ seen.add(pid)
+ pid = parent[pid]
+ return seen
+
+ def device(tty: str) -> str | None:
+ if tty in ("??", "-", ""):
+ return None
+ return "/dev/" + (tty if tty.startswith("tty") else "tty" + tty)
+
+ excluded = {device(tty_of.get(p, "")) for p in ancestors(exclude_pid)} | {
+ device(tty_of.get(exclude_pid, ""))
+ }
+ ttys: set[str] = set()
+ for pid, _, tty, _ in rows:
+ dev = device(tty)
+ lineage = ancestors(pid)
+ if dev and dev not in excluded and exclude_pid not in lineage and lineage & terminals:
+ ttys.add(dev)
+ return ttys
+
+
+def terminal_tty_inputs(exclude_pid: int | None = None) -> dict[str, float]:
+ """Amendment 19: the last-input time of every Terminal session tty other than the runner's own. A shell
+ sets a tty's access time when it reads typed input, so a later value means input reached a shell."""
+ import os
+
+ rows = _ps_rows()
+ out: dict[str, float] = {}
+ for dev in terminal_session_ttys(rows, os.getpid() if exclude_pid is None else exclude_pid):
+ try:
+ out[dev] = os.stat(dev).st_atime
+ except OSError:
+ continue
+ return out
+
+
class GuiOnlyGuard(threading.Thread):
"""Samples the frontmost app and the scripting processes every `interval` seconds and reads the
agent's stream as it grows. The first violation sets `stop` (when enforcing), which ends the trial."""
@@ -218,6 +278,7 @@ class GuiOnlyGuard(threading.Thread):
enforce: bool = True,
interval: float = 0.5,
pgrep: Callable[[str], bool] = _pgrep,
+ terminal_ttys: Callable[[], dict[str, float]] | None = None,
) -> None:
super().__init__(daemon=True)
self.stream_path = stream_path
@@ -225,6 +286,8 @@ class GuiOnlyGuard(threading.Thread):
self.enforce = enforce
self.interval = interval
self.pgrep = pgrep
+ self.terminal_ttys = terminal_ttys
+ self._tty_base: dict[str, float] | None = None
self.stop = threading.Event()
self.done = threading.Event()
self.started_mono = time.monotonic()
@@ -260,8 +323,25 @@ class GuiOnlyGuard(threading.Thread):
for name in SIDE_DOOR_PROCESSES:
if self.pgrep(name):
self._violate("process", f"process:{name}")
+ self.sample_terminal()
self.read_stream()
+ def sample_terminal(self) -> None:
+ """Amendment 19: Terminal runs the runner, so it is always present and rule 1 only sees it in front.
+ A setup that types into a Terminal window in the background would reach a shell unseen. Input
+ read by a Terminal shell (its tty's access time moves) or a new Terminal session is a violation."""
+ if self.terminal_ttys is None:
+ return
+ current = self.terminal_ttys()
+ if self._tty_base is None:
+ self._tty_base = dict(current)
+ return
+ for dev, atime in current.items():
+ if dev not in self._tty_base:
+ self._violate("terminal", "terminal:new_session")
+ elif atime > self._tty_base[dev]:
+ self._violate("terminal", "terminal:input")
+
def read_stream(self) -> None:
try:
with self.stream_path.open("rb") as handle:
@@ -313,6 +393,8 @@ class GuiOnlyGuard(threading.Thread):
"transient_front": sorted(self.transient),
"mentions": sorted(self.mentions | set(post_hoc_soft))[:20],
"frontmost_seen": sorted(self.seen),
+ "terminal_watched": self.terminal_ttys is not None,
+ "terminal_ttys_at_start": None if self._tty_base is None else len(self._tty_base),
}
@@ -381,14 +463,16 @@ def background_condition_score(
"""A15.3: background completion = the task passed AND the user window kept focus and frontmost status the
whole time (no focus steal, no key loss, no window raised over it, no input landing in it, its text intact)."""
ua = disturbance.get("user_activity") or None
- text_ok = ua is None or (
- ua.get("text_disruptions", 0) == 0 and ua.get("text_intact_at_end") is not False
- )
+ if ua is None:
+ # Amendment 19: in the background condition the user window's text is part of "held"; unmeasured is not held.
+ text_ok = condition != "background"
+ else:
+ text_ok = ua.get("text_disruptions", 0) == 0 and ua.get("text_intact_at_end") is not False
held = (
bool(bg.get("measured"))
and bg.get("focus_steals") == 0
and bg.get("key_focus_lost") == 0
- and (bg.get("windows_raised") or 0) == 0
+ and bg.get("windows_raised") == 0 # A19: None (not measured) is not held
and bg.get("input_leaked") == 0
and text_ok
)
@@ -396,6 +480,13 @@ def background_condition_score(
"condition": condition,
"user_window_held": held,
"background_completion": bool(passed and held) if condition == "background" else None,
+ # Reported alongside, not the A15.3 metric: background completion that also requires the real pointer to
+ # stay put (A19.5 item 1, the owner's decision). Unmeasured pointer is not "still".
+ "background_completion_pointer_still": bool(
+ passed and held and bg.get("pointer_moved") is False
+ )
+ if condition == "background"
+ else None,
"success_regardless_of_focus": bool(passed),
"focus_steals": bg.get("focus_steals"),
"user_input_disrupted": None if ua is None else bool(ua.get("disrupted") or not text_ok),
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.py
new file mode 100644
index 0000000000..abff5be671
--- /dev/null
+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/codex_native.py
@@ -0,0 +1,545 @@
+"""Amendment 20 (CUA-1347): Codex Computer-Use (Sky) driven by OpenAI's own agent and model.
+
+Arm ``cx-codex-cu`` runs the Codex agent that ships inside the ChatGPT app (``codex-cli/CodexCLI.app``,
+OpenAI-signed) with ``gpt-6-astra`` at the model's catalog default effort. The harness talks to it through
+``codex app-server``, the JSON-RPC protocol the Codex app itself uses, because that is the only Codex host route
+that forwards MCP elicitations to the client: ``codex exec`` declines them silently, and Codex Computer-Use asks
+the host to approve every app it touches (``Allow Computer Use to use "<App>"?``). The host answers exactly as for
+arm B (``claude_driver.answer_elicitation``): accept for the apps the task names, decline everything else. Every
+other approval request (commands, file changes, permissions, user input) gets a JSON-RPC error and is recorded.
+
+Its computer-use layer is the same ``cua_repl`` launcher as arm B (``cc-codex-cu``): the ``unified-computer-use``
+plugin's shipped entry, unchanged except ``CUA_REPL_ENABLED_SURFACES=computer``, registered under the name the
+plugin uses (``cua_repl``) with the plugin's model-facing tools (``js``, ``js_reset``). So arm B and this arm share
+the tool layer and differ in the agent harness and the model that drives it.
+
+GUI-only (A14.2) for this arm:
+
+* The shell and every other non-GUI route this Codex build can switch off is off (``DISABLED_FEATURES``); the
+ sandbox is read-only.
+* What cannot be switched off is watched instead: ``apply_patch`` (a file edit) and the multi-agent collaboration
+ tools. App-server reports each tool call as a thread item; ``Translator`` turns the items into the
+ Claude-shaped events the GUI-only guard and the summaries already read, mapping a command execution to ``Bash``,
+ a file change to ``Edit``, a web search to ``WebSearch``, a sub-agent call to ``Agent`` and any other non-GUI
+ item to ``Task`` (all forbidden built-ins, so each ends the trial as a violation). MCP calls keep their name
+ (``mcp__cua_repl__js``) and input, so the same code-pattern scan as arm B applies.
+* Code mode: ``gpt-6-astra`` calls tools from a JavaScript ``exec`` cell (a V8 isolate with no file system, process
+ or network access). Nested MCP calls still arrive as separate ``mcpToolCall`` items.
+
+Turns are the model's sampling requests (one ``thread/tokenUsage/updated`` notification each), the counterpart of
+Claude Code's assistant turns; the 45-turn cap stops the turn when the cap-th response was not the final one. No
+list price is pinned for ``gpt-6-astra`` through the subscription gateway, so cost is not reported for this arm
+(tokens are).
+
+Nothing here reads credentials. The model is reached through the LiteLLM gateway at ``CDB_CODEX_GATEWAY``
+(default ``http://127.0.0.1:4000/v1``), which in the bench VM is a local port forwarded to the owner's gateway for
+the run only; no key is placed in the VM.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import signal
+import subprocess
+import threading
+import time
+from pathlib import Path
+from typing import Any, Callable
+
+ARM = "cx-codex-cu"
+ARMS = (ARM,)
+SERVER = "cua_repl" # the server name of the unified-computer-use plugin
+ENABLED_TOOLS = (
+ "js",
+ "js_reset",
+) # the plugin's tools the model sees (turn_ended is a host hook, not a model tool)
+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
+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"
+
+# Features of this Codex build that would give the agent a non-GUI route or a second agent. Off for every trial.
+DISABLED_FEATURES = (
+ "shell_tool",
+ "unified_exec",
+ "apps",
+ "browser_use",
+ "browser_use_external",
+ "in_app_browser",
+ "image_generation",
+ "multi_agent",
+ "multi_agent_v2",
+ "goals",
+ "view_image",
+ "plugins",
+ "tool_suggest",
+ "skill_search",
+)
+# App-server thread item types that are not a computer-use call. Each maps to a forbidden built-in of A14.2.
+SAFE_ITEMS = {
+ "userMessage",
+ "hookPrompt",
+ "agentMessage",
+ "plan",
+ "reasoning",
+ "mcpToolCall",
+ "sleep",
+ "contextCompaction",
+ "functionCallOutput",
+}
+ITEM_AS_BUILTIN = {
+ "commandExecution": "Bash",
+ "fileChange": "Edit",
+ "webSearch": "WebSearch",
+ "collabAgentToolCall": "Agent",
+ "subAgentActivity": "Agent",
+} # anything else outside SAFE_ITEMS (imageView, imageGeneration, dynamicToolCall, ...) maps to "Task"
+
+
+def _q(value: str) -> str:
+ return json.dumps(value, ensure_ascii=True)
+
+
+def gateway() -> str:
+ return os.environ.get(GATEWAY_ENV) or DEFAULT_GATEWAY
+
+
+def server_entry(mcp_json: Path) -> 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 {}
+ if len(servers) != 1:
+ 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":
+ raise ValueError(
+ f"{mcp_json}: CUA_REPL_ENABLED_SURFACES must be 'computer', got {env.get('CUA_REPL_ENABLED_SURFACES')!r}"
+ )
+ return {"command": entry["command"], "args": list(entry.get("args") or []), "env": env}
+
+
+def config_toml(
+ entry: dict[str, Any], model: str, effort: str, instructions: str, codex_home: Path
+) -> str:
+ env = dict(
+ entry["env"]
+ ) # unchanged from arm B: Sky's service and pipe live under the user's own home
+ lines = [
+ f"model = {_q(model)}",
+ 'model_provider = "litellm"',
+ f"model_reasoning_effort = {_q(effort)}",
+ 'approval_policy = "on-request"', # elicitations reach the host only with on-request
+ 'sandbox_mode = "read-only"',
+ 'web_search = "disabled"',
+ "mcp_optional_startup_grace_ms = 30000",
+ f"developer_instructions = {_q(instructions)}",
+ "",
+ "[features]",
+ *[f"{name} = false" for name in DISABLED_FEATURES],
+ "",
+ "[model_providers.litellm]",
+ 'name = "LiteLLM"',
+ f"base_url = {_q(gateway())}",
+ 'wire_api = "responses"',
+ "requires_openai_auth = false",
+ "request_max_retries = 2",
+ "stream_max_retries = 2",
+ "stream_idle_timeout_ms = 120000",
+ "",
+ 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"[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
+) -> 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"
+ )
+ return {
+ # HOME stays the user's, as for the Claude-driven arms (Sky's native pipe is found from it); only Codex's
+ # own config, sessions and caches move to the trial's CODEX_HOME.
+ "HOME": os.environ.get("HOME", str(home)),
+ "CODEX_HOME": str(codex_home),
+ "PATH": CLOSED_PATH,
+ "TMPDIR": str(home / "tmp"),
+ "LANG": "en_US.UTF-8",
+ }
+
+
+def argv(cli: Path = CODEX_CLI) -> list[str]:
+ return [str(cli), "app-server"]
+
+
+def cli_version(cli: Path = CODEX_CLI) -> str | None:
+ if not cli.is_file():
+ return None
+ out = subprocess.run([str(cli), "--version"], capture_output=True, text=True, timeout=30)
+ return out.stdout.strip() or None
+
+
+# ------------------------------------------------------------------ stream translation
+
+
+class Translator:
+ """App-server notifications -> Claude-shaped stream-json events (assistant tool_use / user tool_result /
+ result), so `bench_v2.GuiOnlyGuard`, `bench_v2.scan_events` and `claude_events.summarize` read this arm the
+ same way as the Claude arms."""
+
+ def __init__(self) -> None:
+ self.final_text = ""
+ self.errors: list[str] = []
+ self.usage = {
+ "inputTokens": 0,
+ "cachedInputTokens": 0,
+ "outputTokens": 0,
+ "reasoningOutputTokens": 0,
+ }
+ self.turns = 0
+ self.turn_completed = False
+ self.turn_status: str | None = None
+ self.started: set[str] = set()
+ self.non_gui: list[str] = []
+
+ @staticmethod
+ def _use(item_id: str, name: str, tool_input: Any) -> dict[str, Any]:
+ return {
+ "type": "assistant",
+ "message": {
+ "id": f"cx-{item_id}",
+ "content": [{"type": "tool_use", "id": item_id, "name": name, "input": tool_input}],
+ },
+ }
+
+ def feed(self, method: str, params: dict[str, Any]) -> list[dict[str, Any]]:
+ out: list[dict[str, Any]] = []
+ if method == "thread/started":
+ out.append(
+ {
+ "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"}],
+ }
+ )
+ elif method == "thread/tokenUsage/updated":
+ self.turns += 1
+ total = (params.get("tokenUsage") or {}).get("total") or {}
+ for key in self.usage:
+ self.usage[key] = int(total.get(key) or 0)
+ elif method == "turn/completed":
+ turn = params.get("turn") or {}
+ self.turn_completed = True
+ self.turn_status = turn.get("status")
+ if turn.get("error"):
+ self.errors.append(json.dumps(turn.get("error"))[:400])
+ elif method == "error":
+ self.errors.append(json.dumps(params)[:400])
+ elif method in ("item/started", "item/completed"):
+ item = params.get("item") or {}
+ itype = str(item.get("type"))
+ item_id = str(item.get("id"))
+ if itype == "agentMessage" and method == "item/completed":
+ self.final_text = str(item.get("text") or "")
+ elif itype == "mcpToolCall":
+ name = f"mcp__{item.get('server')}__{item.get('tool')}"
+ if item_id not in self.started:
+ self.started.add(item_id)
+ out.append(self._use(item_id, name, item.get("arguments") or {}))
+ if method == "item/completed":
+ failed = item.get("status") != "completed" or item.get("error") is not None
+ text = json.dumps(item.get("error"))[:300] if failed else ""
+ out.append(
+ {
+ "type": "user",
+ "message": {
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": item_id,
+ "is_error": failed,
+ "content": text,
+ }
+ ]
+ },
+ }
+ )
+ elif itype not in SAFE_ITEMS and item_id not in self.started:
+ self.started.add(item_id)
+ self.non_gui.append(itype)
+ detail = {
+ k: v
+ for k, v in item.items()
+ if k in ("command", "changes", "query", "tool", "type", "path")
+ }
+ out.append(self._use(item_id, ITEM_AS_BUILTIN.get(itype, "Task"), detail))
+ return out
+
+ def result(self, timed_out: bool, capped: bool, wall_ms: float) -> dict[str, Any]:
+ text = " ".join(self.errors)
+ status = next(
+ (code for code in (429, 401, 403, 500, 502, 503, 504, 529) if str(code) in text), None
+ )
+ is_error = bool(self.errors) and self.turn_status != "completed"
+ subtype = (
+ "error_max_turns" if capped else ("error_during_execution" if is_error else "success")
+ )
+ return {
+ "type": "result",
+ "subtype": subtype,
+ "is_error": is_error or capped,
+ "api_error_status": status,
+ "num_turns": self.turns,
+ "duration_ms": round(wall_ms),
+ "result": self.final_text if not is_error else text[:2000],
+ "usage": {
+ "input_tokens": self.usage["inputTokens"] - self.usage["cachedInputTokens"],
+ "output_tokens": self.usage["outputTokens"],
+ "cache_read_input_tokens": self.usage["cachedInputTokens"],
+ "cache_creation_input_tokens": 0,
+ },
+ "codex_usage": dict(self.usage),
+ "timed_out": timed_out,
+ }
+
+
+def _kill_group(pid: int, grace: float = 1.0) -> None:
+ for sig in (signal.SIGTERM, signal.SIGKILL):
+ try:
+ os.killpg(pid, sig)
+ except OSError:
+ return
+ time.sleep(grace)
+
+
+def run_codex(
+ cmd: list[str],
+ env: dict[str, str],
+ cwd: Path,
+ prompt: str,
+ timeout_s: float,
+ max_turns: int,
+ raw_path: Path,
+ stream_path: Path,
+ stderr_path: Path,
+ allowed_apps: set[str] | None = None,
+ elicitation_path: Path | None = None,
+ abort: Any = None,
+ answer: Callable[[str, set[str]], dict[str, Any]] | None = None,
+) -> 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
+ turn cap or ``abort``. Raw JSON-RPC lines go to ``raw_path``; the translated Claude-shaped events go to
+ ``stream_path`` (both ``<epoch_ms>\\t<json>``) as they arrive, so the GUI-only guard reads them live."""
+ if answer is None:
+ import claude_driver
+
+ answer = claude_driver.answer_elicitation
+ allowed = {a.strip().lower() for a in (allowed_apps or set())}
+ started = time.monotonic()
+ translator = Translator()
+ done = threading.Event()
+ responses: dict[int, dict[str, Any]] = {}
+ got = threading.Condition()
+ elicitations: list[dict[str, Any]] = []
+ elog = elicitation_path.open("w", encoding="utf-8") if elicitation_path else None
+ with (
+ raw_path.open("w", encoding="utf-8") as raw,
+ stream_path.open("w", encoding="utf-8") as stream,
+ stderr_path.open("wb") as err,
+ ):
+ proc = subprocess.Popen(
+ cmd,
+ cwd=str(cwd),
+ env=env,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=err,
+ text=True,
+ bufsize=1,
+ start_new_session=True,
+ )
+ lock = threading.Lock()
+ next_id = [0]
+
+ def send(obj: dict[str, Any]) -> None:
+ with lock:
+ try:
+ assert proc.stdin is not None
+ proc.stdin.write(json.dumps(obj) + "\n")
+ proc.stdin.flush()
+ except (OSError, ValueError):
+ pass
+
+ def request(method: str, params: dict[str, Any], wait_s: float = 60.0) -> dict[str, Any]:
+ with lock:
+ next_id[0] += 1
+ rid = next_id[0]
+ send({"jsonrpc": "2.0", "id": rid, "method": method, "params": params})
+ deadline = time.monotonic() + wait_s
+ with got:
+ while rid not in responses and time.monotonic() < deadline and proc.poll() is None:
+ got.wait(0.5)
+ reply = responses.get(rid) or {"error": {"message": f"no response to {method}"}}
+ if "error" in reply:
+ raise RuntimeError(f"{method}: {json.dumps(reply['error'])[:300]}")
+ return reply.get("result") or {}
+
+ def write(obj: dict[str, Any]) -> None:
+ stream.write(f"{time.time() * 1000:.1f}\t{json.dumps(obj)}\n")
+ stream.flush()
+
+ def pump() -> None:
+ assert proc.stdout is not None
+ for line in proc.stdout:
+ line = line.rstrip("\n")
+ if not line.strip():
+ continue
+ raw.write(f"{time.time() * 1000:.1f}\t{line}\n")
+ raw.flush()
+ try:
+ msg = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ method = msg.get("method")
+ if method and "id" in msg: # a server request
+ params = msg.get("params") or {}
+ if method == "mcpServer/elicitation/request":
+ reply = answer(str(params.get("message") or ""), allowed)
+ record = {
+ "ts": time.time(),
+ "message": params.get("message", ""),
+ "answer": reply["action"],
+ }
+ send({"jsonrpc": "2.0", "id": msg["id"], "result": reply})
+ else:
+ record = {"ts": time.time(), "unhandled": method}
+ send(
+ {
+ "jsonrpc": "2.0",
+ "id": msg["id"],
+ "error": {
+ "code": -32601,
+ "message": "not handled by the benchmark host",
+ },
+ }
+ )
+ elicitations.append(record)
+ if elog:
+ elog.write(json.dumps(record) + "\n")
+ elog.flush()
+ elif method:
+ for out in translator.feed(method, msg.get("params") or {}):
+ write(out)
+ if method == "turn/completed":
+ done.set()
+ elif "id" in msg:
+ with got:
+ responses[msg["id"]] = msg
+ got.notify_all()
+
+ reader = threading.Thread(target=pump, daemon=True)
+ reader.start()
+ timed_out = capped = aborted = False
+ startup_error = ""
+ try:
+ request("initialize", {"clientInfo": {"name": "cdb-bench", "version": "1"}})
+ send({"jsonrpc": "2.0", "method": "initialized"})
+ thread = request("thread/start", {"cwd": str(cwd)}, wait_s=180.0)
+ thread_id = (thread.get("thread") or {}).get("id")
+ request(
+ "turn/start", {"threadId": thread_id, "input": [{"type": "text", "text": prompt}]}
+ )
+ except Exception as error: # noqa: BLE001 - recorded; the row classifies it
+ startup_error = f"{type(error).__name__}: {error}"
+ translator.errors.append(startup_error)
+ while not startup_error and proc.poll() is None and not done.is_set():
+ if time.monotonic() - started > timeout_s:
+ timed_out = True
+ break
+ if abort is not None and abort.is_set():
+ aborted = True
+ break
+ if translator.turns >= max_turns and not done.wait(3.0):
+ capped = (
+ True # the cap-th response was not the last one: the next would be past the cap
+ )
+ break
+ done.wait(0.25)
+ _kill_group(proc.pid)
+ reader.join(timeout=5)
+ try:
+ os.killpg(
+ proc.pid, signal.SIGKILL
+ ) # MCP children (cua_repl, node_repl) must not outlive the trial
+ except OSError:
+ pass
+ try:
+ proc.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ pass
+ with lock:
+ write(translator.result(timed_out, capped, (time.monotonic() - started) * 1000))
+ # app-server is a server: the harness ends it after the turn, so a completed turn counts as a clean exit
+ returncode = (
+ 0
+ if translator.turn_status == "completed" and not (timed_out or capped or aborted)
+ else proc.returncode
+ )
+ if elog:
+ elog.close()
+ return {
+ "returncode": returncode,
+ "timed_out": timed_out,
+ "aborted": aborted,
+ "capped": capped,
+ "result_seen": translator.turn_completed,
+ "wall_s": round(time.monotonic() - started, 2),
+ "elicitations": elicitations,
+ "turns": translator.turns,
+ "non_gui_items": translator.non_gui,
+ "codex_usage": dict(translator.usage),
+ "startup_error": startup_error,
+ }
+
+
+def observed(cli: Path = CODEX_CLI) -> dict[str, Any]:
+ import hashlib
+
+ sha = None
+ if cli.is_file():
+ digest = hashlib.sha256()
+ with cli.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1 << 20), b""):
+ digest.update(chunk)
+ sha = digest.hexdigest()
+ return {
+ "codex_cli": str(cli),
+ "codex_cli_version": cli_version(cli),
+ "codex_cli_sha256": sha,
+ "model": MODEL,
+ "effort": EFFORT,
+ "gateway": gateway(),
+ "host": "codex app-server",
+ }
diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/pins.json b/benchmarks/cua-driver-bench/automated-eval/macos_bench/pins.json
index e63606a624..e76fbb260a 100644
--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/pins.json
+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/pins.json
@@ -19,10 +19,10 @@
"environment": "Lume macOS VM on a Mac Studio host (M3 Ultra), cloned from the cached cua-base image; 6 CPU, 12 GB, 1920x1080; one VM for both arms",
"cdb_pack": {
"repo": "trycua/cua, benchmarks/cua-driver-bench/taskpack (public copy)",
- "source": "Copied from Cua's private benchmark repository at revision 16a1937a79ff2ee2e48f5b5d9bb5e6f944119b5a; see taskpack/README.md",
+ "source": "Copied from Cua's private benchmark repository at revision 16a1937a79ff2ee2e48f5b5d9bb5e6f944119b5a; see taskpack/README.md. shared/cdb-s02 also carries the Amendment 19 checker fix (one Schedule row per session).",
"revision": "16a1937a79ff2ee2e48f5b5d9bb5e6f944119b5a",
"tree_sha256": {
- "shared/cdb-s02": "38cb375bb0f879dc780f64856f1876916d4a751abcf7ff3175a85f1989e56ecc",
+ "shared/cdb-s02": "844dbbd2b247395303b901cbd328dee092adfa0e592b511ce6900c69e92073c9",
"shared/cdb-s03": "f018f55fa0208e6244e5789e0e306401a009f7ee07344aece1c741a3a9b70fa4",
"shared/cdb-s04": "f7c67bb4dec8711176897f6cc26df8ed55237c0de48dd13cb242119ac7ca81a8"
},
@@ -57,5 +57,12 @@
"_cua_node_sha256": "ee2d88fda15173431807447aa2b1949f1db4e822efc4a3f4ba2c9a2b83f592f8",
"_service_executable_sha256": "fa5b5d685f550af82902cff1a345db558a1da3eb526cf78cd4659fa0dcde01a5",
"_signature": "Developer ID Application: OpenAI OpCo, LLC (2DC432GLL2), notarized"
+ },
+ "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.",
+ "codex_cli_version": "codex-cli 0.160.0",
+ "codex_cli_sha256": "6b582e8813ce7e8ed4c52814ee5cf230dba647bf2292df747a4003f2657ef201",
+ "model": "gpt-6-astra",
+ "effort": "medium"
}
}
diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/probes/IR-03/evaluate.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/probes/IR-03/evaluate.py
index a3694c3047..0d67a67298 100755
--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/probes/IR-03/evaluate.py
+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/probes/IR-03/evaluate.py
@@ -57,14 +57,20 @@ def evaluate(
"every other title, status and body as at start",
)
done = C.events_of(events, "done")
+ saves = C.events_of(events, "save")
+ # Amendment 19: "When both changes are made, press Done" - the last Done must follow the last save.
+ done_after_saves = bool(done) and all(done[-1]["seq"] > e["seq"] for e in saves)
done_ok = (
- bool(done) and C.details(done[-1]).get("clean") is True and state.get("dirty") is False
+ bool(done)
+ and C.details(done[-1]).get("clean") is True
+ and state.get("dirty") is False
+ and done_after_saves
)
checks.add(
"done_clean",
done_ok,
0.1,
- f"{len(done)} done event(s); dirty at end {state.get('dirty')!r}",
+ f"{len(done)} done event(s); dirty at end {state.get('dirty')!r}; last Done after the last save {done_after_saves}",
)
checks.add(
"state_matches_events",
diff --git a/benchmarks/cua-driver-bench/automated-eval/macos_bench/probes/tests/test_interrupts.py b/benchmarks/cua-driver-bench/automated-eval/macos_bench/probes/tests/test_interrupts.py
index 449e18d423..c12053c0ca 100644
--- a/benchmarks/cua-driver-bench/automated-eval/macos_bench/probes/tests/test_interrupts.py
+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/probes/tests/test_interrupts.py
@@ -224,6 +224,54 @@ class IR03(unittest.TestCase):
r = self.ev(42, state, events)
self.assertFalse(r["checks"]["others_unchanged"]["passed"])
+ def test_done_before_the_changes_fails(self) -> None:
+ # Amendment 19: Done pressed first (clean), then both changes saved by switching notes, no Done after.
+ exp = C.derive_irunsaved(42)
+ si, ri = exp["status_index"], exp["rename_index"]
+ other = 3 - si - ri
+ saved = [
+ {"title": t, "status": C.IR_INITIAL_STATUS, "body": f"Working notes for {t}."}
+ for t in exp["titles"]
+ ]
+ sim = S.Sim("irunsaved", 42)
+ sim.emit("done", count=1, clean=True)
+ sim.emit("open_note", note=si, title=exp["titles"][si])
+ sim.emit("field_edit", note=si, field="status", value=exp["status"], via="poll")
+ sim.emit("save_prompt_shown", note=si, reason="switch", pending=ri)
+ sim.emit("save_answer", answer="save", note=si, reason="switch")
+ saved[si]["status"] = exp["status"]
+ sim.emit("save", note=si, title=exp["titles"][si], status=exp["status"])
+ sim.emit("open_note", note=ri, title=exp["titles"][ri])
+ sim.emit("field_edit", note=ri, field="title", value=exp["new_title"], via="poll")
+ sim.emit("save_prompt_shown", note=ri, reason="switch", pending=other)
+ sim.emit("save_answer", answer="save", note=ri, reason="switch")
+ saved[ri]["title"] = exp["new_title"]
+ sim.emit("save", note=ri, title=exp["new_title"], status=C.IR_INITIAL_STATUS)
+ sim.emit("open_note", note=other, title=exp["titles"][other])
+ state, events = sim.finish(
+ {
+ "saved": saved,
+ "current": other,
+ "fields": {},
+ "dirty": False,
+ "prompts": [{}, {}],
+ "answers": ["save", "save"],
+ "done_count": 1,
+ "done_clean": True,
+ "status": "All notes closed",
+ }
+ )
+ r = self.ev(42, state, events)
+ self.assertTrue(
+ r["checks"]["status_saved"]["passed"] and r["checks"]["title_saved"]["passed"]
+ )
+ self.assertFalse(r["checks"]["done_clean"]["passed"])
+ self.assertFalse(r["passed"])
+ # the same run with one more Done at the end passes
+ sim.emit("done", count=2, clean=True)
+ state, events = sim.finish(dict(state, done_count=2))
+ self.assertTrue(self.ev(42, state, events)["passed"])
+
# ------------------------------------------------------------------ IR-04
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.py
index 645642e769..e04026c782 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
@@ -48,6 +48,7 @@ import bench_v2 as v2 # noqa: E402
import bench_core as core # noqa: E402
import claude_arms as ca # noqa: E402
import cdb_adapter # noqa: E402
+import codex_native as cxn # noqa: E402
import claude_driver # noqa: E402
import claude_events # noqa: E402
import recorder as rec # noqa: E402
@@ -462,7 +463,7 @@ def ensure_agent_daemon(ctx: Ctx, arm: str = "cc-cua-driver") -> None:
def check_pins(pins: dict[str, Any], arm_names: list[str]) -> list[tuple[str, str, str]]:
"""Compare every pinned version and hash with what is installed now. Any difference fails."""
observed = ca.observed_pins(
- include_codex=any(a in ca.CODEX_ARMS for a in arm_names),
+ include_codex=any(a in ca.CODEX_ARMS or a in cxn.ARMS for a in arm_names),
include_cua="cc-cua-driver" in arm_names,
)
if (
@@ -655,7 +656,10 @@ 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),
+ "codex_native": ctx.versions.get("codex_native") if arm in cxn.ARMS else None,
}
+ if arm in cxn.ARMS:
+ row["model"], row["effort"] = cxn.MODEL, cxn.EFFORT
sentinel = pilot.Sentinel(
Path(args.build_dir) / "BenchSentinel.app"
if args.build_dir and not args.no_sentinel
@@ -733,16 +737,21 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]
row["lab_unoccluded"] = row["lab_occlusion"].get("unoccluded")
cwd = ca.prepare_cwd(arm)
mcp_path, server = ctx.mcp[arm]
- argv = ca.claude_argv(
- mcp_config=mcp_path,
- server=server,
- model=args.model,
- max_turns=max_turns,
- max_budget_usd=args.max_budget_usd,
- tool_search=args.tool_search == "default",
- effort=args.effort,
- coding_tools=bool(spec.get("coding_tools")) and not bench_v2,
- system_prompt=ca.system_prompt_for(arm),
+ native = arm in cxn.ARMS
+ argv = (
+ cxn.argv()
+ if native
+ else ca.claude_argv(
+ mcp_config=mcp_path,
+ server=server,
+ model=args.model,
+ max_turns=max_turns,
+ max_budget_usd=args.max_budget_usd,
+ tool_search=args.tool_search == "default",
+ effort=args.effort,
+ coding_tools=bool(spec.get("coding_tools")) and not bench_v2,
+ system_prompt=ca.system_prompt_for(arm),
+ )
)
prompt = (v2.brief_for(brief.strip(), condition) if bench_v2 else brief.strip()) + "\n"
if args.tell_budget:
@@ -756,7 +765,10 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]
agent_started = time.monotonic()
if bench_v2: # A14.2: every v2 trial is guarded, CDB or BenchLab
guard = v2.GuiOnlyGuard(
- stream_path, frontmost_bundle, enforce=getattr(args, "gui_only_enforce", True)
+ stream_path,
+ frontmost_bundle,
+ enforce=getattr(args, "gui_only_enforce", True),
+ terminal_ttys=v2.terminal_tty_inputs, # A19: shell input in a background Terminal
)
guard.start()
watcher = (
@@ -767,18 +779,42 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]
if watcher:
watcher.start()
with pilot.IdleSampler(artifacts / "hid-idle.jsonl"):
- claude = claude_driver.run_claude(
- argv,
- ca.claude_env(),
- cwd,
- prompt,
- allowed_apps(task),
- timeout_s,
- stream_path,
- stderr_path,
- artifacts / "elicitations.jsonl",
- abort=v2.EitherEvent(ctx.abort, guard.stop) if guard else ctx.abort,
- )
+ if (
+ native
+ ): # Amendment 20: codex exec, its stream translated for the guard and the summaries
+ claude = cxn.run_codex(
+ argv,
+ cxn.render_home(
+ trial_dir / "codex-home",
+ mcp_path,
+ cxn.MODEL,
+ cxn.EFFORT,
+ ca.system_prompt_for(arm),
+ ),
+ cwd,
+ prompt,
+ timeout_s,
+ max_turns,
+ trial_dir / "codex-app-server.tsv",
+ stream_path,
+ stderr_path,
+ allowed_apps=allowed_apps(task),
+ elicitation_path=artifacts / "elicitations.jsonl",
+ abort=v2.EitherEvent(ctx.abort, guard.stop) if guard else ctx.abort,
+ )
+ else:
+ claude = claude_driver.run_claude(
+ argv,
+ ca.claude_env(),
+ cwd,
+ prompt,
+ allowed_apps(task),
+ timeout_s,
+ stream_path,
+ stderr_path,
+ artifacts / "elicitations.jsonl",
+ abort=v2.EitherEvent(ctx.abort, guard.stop) if guard else ctx.abort,
+ )
agent_ended = time.monotonic()
if watcher:
watcher.finish()
@@ -791,6 +827,10 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]
video_raw = ctx.recorder.stop() if ctx.recorder and recording else None
events = claude_events.read_events(stream_path)
summary = claude_events.summarize(events)
+ if native: # turns are sampling requests (thread/tokenUsage/updated), not tool uses
+ summary["turns"] = summary["api_calls"] = claude.get("turns")
+ row["codex_usage"] = claude.get("codex_usage")
+ row["codex_non_gui_items"] = claude.get("non_gui_items")
stderr_text = (
stderr_path.read_text("utf-8", "replace")[-4000:] if stderr_path.exists() else ""
)
@@ -850,7 +890,12 @@ def run_attempt(ctx: Ctx, entry: dict[str, Any], attempt: int) -> dict[str, Any]
tokens = summary.get("tokens", {"input": 0, "output": 0, "cache_read": 0, "cache_write": 0})
cost = summary.get("total_cost_usd")
cost_source = "result.total_cost_usd"
- if cost is None:
+ if entry["arm"] in cxn.ARMS:
+ cost, cost_source = (
+ None,
+ "not priced (gpt-6-astra via the subscription gateway; tokens reported)",
+ )
+ elif cost is None:
cost = estimate_cost(tokens)
cost_source = "estimated_from_tokens (no result event)"
result = summary.get("result", {})
@@ -1472,7 +1517,7 @@ def execute_trial(ctx: Ctx, entry: dict[str, Any]) -> dict[str, Any]:
append_row(ctx, row)
ctx.log(
f"trial {entry['trial_id']} a{attempt}: {row['status']} passed={row['passed']} infra={kind} "
- f"wall={row['wall_s']}s turns={row.get('turns')} cost=${row['cost_usd']:.3f} 7d={row.get('quota_seven_day_after')}"
+ f"wall={row['wall_s']}s turns={row.get('turns')} cost=${row['cost_usd'] or 0:.3f} 7d={row.get('quota_seven_day_after')}"
)
if decision in ("final", "exclude"):
ctx.set_state(
@@ -1554,6 +1599,76 @@ def quota_probe(ctx: Ctx) -> tuple[bool, str]:
)
+def native_codex_checks(ctx: Ctx, arm: str, with_models: bool) -> list[tuple[str, str, str]]:
+ """Amendment 20: the Codex CLI build is the pinned one, the gateway serves the model, and one trivial
+ `codex exec` through the trial's own home answers without any tool call."""
+ out: list[tuple[str, str, str]] = []
+ observed = ctx.versions.get("codex_native") or cxn.observed()
+ want = ca.load_pins().get("codex_native") or {}
+ for key in ("codex_cli_version", "codex_cli_sha256"):
+ ok = bool(want.get(key)) and observed.get(key) == want.get(key)
+ out.append(
+ (
+ f"pin codex_native.{key}",
+ "pass" if ok else ("warn" if ctx.args.smoke else "fail"),
+ str(observed.get(key))
+ if ok
+ else f"observed {observed.get(key)!r}, pinned {want.get(key)!r}",
+ )
+ )
+ try:
+ import urllib.request
+
+ with urllib.request.urlopen(cxn.gateway().rstrip("/") + "/models", timeout=10) as resp:
+ listed = [m.get("id") for m in json.load(resp).get("data", [])]
+ out.append(
+ (
+ "gateway lists the model",
+ "pass" if cxn.MODEL in listed else "fail",
+ f"{cxn.gateway()} {cxn.MODEL}",
+ )
+ )
+ except Exception as error: # noqa: BLE001
+ out.append(
+ ("gateway reachable", "fail", f"{cxn.gateway()}: {type(error).__name__}: {error}")
+ )
+ if not with_models:
+ return out
+ mcp_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))
+ cwd = ca.prepare_cwd(arm)
+ stream = ctx.run_dir / f"preflight-init-{arm}.tsv"
+ result = cxn.run_codex(
+ cxn.argv(),
+ env,
+ cwd,
+ "Reply OK. Do not call any tool.",
+ 180,
+ 3,
+ ctx.run_dir / f"preflight-{arm}-raw.tsv",
+ stream,
+ ctx.run_dir / f"preflight-{arm}.stderr",
+ )
+ summary = claude_events.summarize(claude_events.read_events(stream))
+ text = (summary.get("final_text") or "").strip()
+ # the shared system prompt asks for DONE at the end, so either answer is a working turn
+ ok = (
+ result.get("result_seen")
+ and text.upper().startswith(("OK", "DONE"))
+ and not summary["tool_calls"]["total"]
+ )
+ out.append(
+ (
+ f"init check {arm} (codex app-server, {cxn.MODEL})",
+ "pass" if ok else "fail",
+ f"reply={text[:40]!r} tools={summary['tool_calls']['total']} usage={result.get('codex_usage')}",
+ )
+ )
+ return out
+
+
def init_check(ctx: Ctx, arm: str) -> tuple[str, str]:
"""One trivial haiku call per arm through the real argv: verify the init event."""
if arm in ca.CUA_ARMS:
@@ -1802,6 +1917,25 @@ def preflight(ctx: Ctx, with_models: bool = True) -> list[tuple[str, str, str]]:
)
except Exception as error: # noqa: BLE001
add("arm B MCP server", "fail", f"{type(error).__name__}: {error}")
+ for native_arm in [a for a in cxn.ARMS if a in ctx.arm_names]:
+ if not cxn.CODEX_CLI.is_file():
+ add("Codex CLI in the ChatGPT app", "fail", str(cxn.CODEX_CLI))
+ continue
+ try:
+ path, _server = ctx.mcp[native_arm]
+ entry = cxn.server_entry(path)
+ tools = mcp_list_tools(entry["command"], entry["args"], entry["env"])
+ add(
+ f"{native_arm} cua_repl MCP server lists js, js_reset",
+ "pass" if {"js", "js_reset"} <= set(tools) else "fail",
+ str(tools),
+ )
+ except Exception as error: # noqa: BLE001
+ add(f"{native_arm} cua_repl 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)
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", {})
@@ -1890,20 +2024,24 @@ def preflight(ctx: Ctx, with_models: bool = True) -> list[tuple[str, str, str]]:
)
add(
"quota gate from the latest known reading",
- "fail"
+ "warn"
+ if gate["action"] == "gated"
+ and all(a in cxn.ARMS for a in ctx.arm_names) # no Claude seat in use
+ else "fail"
if gate["action"] == "gated"
else ("warn" if gate["action"] == "unknown" else "pass"),
gate["reason"],
)
if (WORK / "HOLD").exists():
add("HOLD file", "fail", (WORK / "HOLD").read_text("utf-8").strip()[:200])
- if with_models and not offline:
+ claude_arms = [a for a in ctx.arm_names if a not in cxn.ARMS]
+ if with_models and not offline and claude_arms: # a native-Codex-only run uses no Claude seat
try:
ok, detail = quota_probe(ctx)
add("quota probe (haiku-4-5)", "pass" if ok else "fail", detail)
except Exception as error: # noqa: BLE001
add("quota probe", "fail", f"{type(error).__name__}: {error}")
- for arm in ctx.arm_names:
+ for arm in claude_arms:
try:
status, detail = init_check(ctx, arm)
add(f"init event check {arm}", status, detail)
@@ -2106,7 +2244,7 @@ def make_ctx(args: argparse.Namespace) -> Ctx:
def setup_arms(ctx: Ctx) -> None:
pins = ca.load_pins()
observed = ca.observed_pins(
- include_codex=any(a in ca.CODEX_ARMS for a in ctx.arm_names),
+ include_codex=any(a in ca.CODEX_ARMS or a in cxn.ARMS for a in ctx.arm_names),
include_cua="cc-cua-driver" in ctx.arm_names,
)
ctx.versions.update(
@@ -2144,6 +2282,16 @@ def setup_arms(ctx: Ctx) -> None:
ctx.mcp[arm] = ca.mcp_config_for(arm, ctx.run_dir, ctx.args.codex_cu_mcp)
except (FileNotFoundError, ValueError) as error:
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
+ try:
+ 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)
+ except (FileNotFoundError, ValueError) as error:
+ raise SystemExit(f"arm {arm} unavailable: {error}")
+ ctx.versions["codex_native"] = cxn.observed()
if ctx.args.build_dir:
apps: dict[str, str] = {}
for name in BENCH_APPS:
@@ -2381,7 +2529,15 @@ def cmd_run(args: argparse.Namespace) -> int:
(ctx.run_dir / "preflight.json").write_text(json.dumps(checks, indent=2) + "\n", "utf-8")
failed = [c for c in checks if c[1] == "fail"]
known = ctx.quota is not None and ctx.quota.get("seven_day") is not None
- if not known and not args.allow_unknown_quota and args.claude_bin is None:
+ native_only = all(
+ a in cxn.ARMS for a in ctx.arm_names
+ ) # Amendment 20: no Claude seat in use
+ if (
+ not known
+ and not native_only
+ and not args.allow_unknown_quota
+ and args.claude_bin is None
+ ):
failed.append(
(
"quota reading",
@@ -2443,6 +2599,12 @@ def cmd_gate_check(args: argparse.Namespace) -> int:
f"latest known: {json.dumps({k: latest.get(k) for k in ('ts', 'five_hour', 'seven_day', 'status', 'source')})}"
)
if decision["action"] == "gated":
+ arm_names = [args.only_arm] if args.only_arm else list(args.arms)
+ if arm_names and all(
+ a in cxn.ARMS for a in arm_names
+ ): # Amendment 20: no Claude seat in use
+ print("quota gate not applied: only native Codex arms, which use no Claude seat")
+ return 0
print("RUN GATED: not starting. The seven-day figure only grows until its window resets.")
return 3
return 0
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.py
index 2690657b83..cf1f07094c 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
@@ -160,6 +160,57 @@ class GuardTest(unittest.TestCase):
summary = guard.summary([], [])
self.assertTrue(summary["violation"] and summary["stopped_trial"])
+ def test_terminal_shell_input_in_background_is_a_violation(self) -> None:
+ # A19: Terminal is never in front (background typing), but its idle shell reads input.
+ ttys = iter([{"/dev/ttys003": 100.0}, {"/dev/ttys003": 100.0}, {"/dev/ttys003": 131.5}])
+ guard, _ = self.make([None] * 3)
+ guard.terminal_ttys = lambda: next(ttys)
+ guard.sample()
+ guard.sample()
+ self.assertFalse(guard.stop.is_set())
+ guard.sample()
+ self.assertTrue(guard.stop.is_set())
+ self.assertEqual(guard.violations[0]["detail"], "terminal:input")
+ self.assertEqual(guard.summary([], [])["terminal_ttys_at_start"], 1)
+
+ def test_new_terminal_session_is_a_violation(self) -> None:
+ ttys = iter([{}, {"/dev/ttys009": 5.0}])
+ guard, _ = self.make([None] * 2)
+ guard.terminal_ttys = lambda: next(ttys)
+ guard.sample()
+ guard.sample()
+ self.assertEqual(guard.violations[0]["detail"], "terminal:new_session")
+
+ def test_closed_terminal_session_is_not_a_violation(self) -> None:
+ ttys = iter([{"/dev/ttys003": 1.0}, {}])
+ guard, _ = self.make([None] * 2)
+ guard.terminal_ttys = lambda: next(ttys)
+ guard.sample()
+ guard.sample()
+ self.assertEqual(guard.violations, [])
+
+ def test_terminal_session_ttys_skip_the_runner_and_non_terminal_ttys(self) -> None:
+ rows = [
+ (1, 0, "??", "/sbin/launchd"),
+ (100, 1, "??", "/System/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal"),
+ (200, 100, "s000", "login"),
+ (201, 200, "s000", "-zsh"),
+ (202, 201, "s000", "/usr/bin/python3"), # the runner, started from launch_bench.command
+ (203, 202, "s000", "claude"),
+ (204, 203, "s004", "codex"), # a pty opened under the runner is the runner's own
+ (300, 100, "s001", "login"),
+ (301, 300, "s001", "-zsh"), # a stray idle shell window
+ (400, 1, "s005", "sshd-session"), # not a Terminal session
+ ]
+ self.assertEqual(v2.terminal_session_ttys(rows, exclude_pid=202), {"/dev/ttys001"})
+ self.assertEqual(
+ v2.terminal_session_ttys(rows, exclude_pid=999),
+ {"/dev/ttys000", "/dev/ttys001", "/dev/ttys004"},
+ )
+
+ def test_terminal_tty_inputs_runs_on_this_host(self) -> None:
+ self.assertIsInstance(v2.terminal_tty_inputs(), dict)
+
def test_record_only_mode_never_stops(self) -> None:
guard, _ = self.make(["com.apple.Terminal"] * 4, enforce=False)
for _ in range(4):
@@ -345,6 +396,28 @@ class BackgroundConditionTest(unittest.TestCase):
self.assertFalse(out["background_completion"])
self.assertTrue(out["user_input_disrupted"])
+ def test_unmeasured_window_order_or_user_text_is_not_completion(self) -> None:
+ # Amendment 19: a missing measure is "not held", never a pass.
+ ua = {
+ "typed": 30,
+ "blocked": 0,
+ "text_disruptions": 0,
+ "text_intact_at_end": True,
+ "disrupted": False,
+ }
+ old_sentinel = v2.background_score(dict(BackgroundTest.QUIET, windows_raised=None), True)
+ out = v2.background_condition_score(
+ old_sentinel, dict(BackgroundTest.QUIET, user_activity=ua), True, "background"
+ )
+ self.assertFalse(out["background_completion"])
+ no_ua = v2.background_condition_score(self.bg(), BackgroundTest.QUIET, True, "background")
+ self.assertFalse(no_ua["background_completion"])
+ self.assertTrue(
+ v2.background_condition_score(self.bg(), BackgroundTest.QUIET, True, "foreground")[
+ "user_window_held"
+ ]
+ )
+
def test_foreground_condition_has_no_completion_metric(self) -> None:
out = v2.background_condition_score(self.bg(), BackgroundTest.QUIET, True, "foreground")
self.assertIsNone(out["background_completion"])
@@ -356,5 +429,35 @@ class BackgroundConditionTest(unittest.TestCase):
self.assertEqual(v2.brief_for("Do X.", "foreground"), "Do X.")
+class PointerStillTest(unittest.TestCase):
+ """A19.5 item 1: background completion with the pointer kept still, reported alongside A15.3."""
+
+ def score(self, pointer_moved: object) -> dict:
+ bg = {
+ "measured": True,
+ "focus_steals": 0,
+ "key_focus_lost": 0,
+ "windows_raised": 0,
+ "input_leaked": 0,
+ "pointer_moved": pointer_moved,
+ }
+ dist = {"user_activity": {"text_disruptions": 0, "text_intact_at_end": True}}
+ return v2.background_condition_score(bg, dist, True, "background")
+
+ def test_pointer_moved_fails_only_the_pointer_still_variant(self) -> None:
+ moved = self.score(True)
+ self.assertTrue(moved["background_completion"])
+ self.assertFalse(moved["background_completion_pointer_still"])
+ self.assertTrue(self.score(False)["background_completion_pointer_still"])
+ self.assertFalse(self.score(None)["background_completion_pointer_still"])
+
+ def test_foreground_has_no_variant(self) -> None:
+ self.assertIsNone(
+ v2.background_condition_score({}, {}, True, "foreground")[
+ "background_completion_pointer_still"
+ ]
+ )
+
+
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.py
new file mode 100644
index 0000000000..ca304771de
--- /dev/null
+++ b/benchmarks/cua-driver-bench/automated-eval/macos_bench/tests/test_codex_native.py
@@ -0,0 +1,214 @@
+"""Amendment 20 (CUA-1347): the native Codex arm (Codex CLI + gpt-6-astra driving Codex computer use)."""
+
+from __future__ import annotations
+
+import json
+import sys
+import tempfile
+import tomllib
+import unittest
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(HERE))
+
+import arms # noqa: E402
+import bench_v2 as v2 # noqa: E402
+import claude_events # noqa: E402
+import codex_native as cxn # noqa: E402
+
+ARM_B = {
+ "mcpServers": {
+ "codex-cu": {
+ "type": "stdio",
+ "command": "/Applications/ChatGPT.app/Contents/Resources/cua_node/bin/node",
+ "args": [
+ "/Applications/ChatGPT.app/Contents/Resources/cua_node/lib/node_modules/@oai/cua-repl/bin/cua-repl.mjs"
+ ],
+ "env": {
+ "CUA_REPL_ENABLED_SURFACES": "computer",
+ "CODEX_HOME": "/Users/lume/.codex",
+ "X": "1",
+ },
+ }
+ }
+}
+
+
+def write_arm_b(folder: Path, surfaces: str = "computer") -> Path:
+ data = json.loads(json.dumps(ARM_B))
+ data["mcpServers"]["codex-cu"]["env"]["CUA_REPL_ENABLED_SURFACES"] = surfaces
+ path = folder / "mcp.json"
+ path.write_text(json.dumps(data), "utf-8")
+ return path
+
+
+class HomeTest(unittest.TestCase):
+ def test_config_uses_arm_b_launcher_and_switches_routes_off(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ tmp_path = Path(tmp)
+ env = cxn.render_home(
+ 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["approval_policy"], "on-request") # elicitations reach the host
+ self.assertEqual(cfg["sandbox_mode"], "read-only")
+ self.assertEqual(cfg["developer_instructions"], "SYSTEM")
+ for feature in (
+ "shell_tool",
+ "unified_exec",
+ "browser_use",
+ "in_app_browser",
+ "multi_agent",
+ "plugins",
+ ):
+ self.assertIs(cfg["features"][feature], False, feature)
+ server = cfg["mcp_servers"]["cua_repl"]
+ self.assertEqual(server["command"], ARM_B["mcpServers"]["codex-cu"]["command"])
+ self.assertEqual(server["args"], ARM_B["mcpServers"]["codex-cu"]["args"])
+ self.assertEqual(server["enabled_tools"], ["js", "js_reset"])
+ self.assertEqual(server["env"]["CUA_REPL_ENABLED_SURFACES"], "computer")
+ self.assertEqual(server["env"]["CODEX_HOME"], "/Users/lume/.codex") # unchanged from arm B
+ self.assertEqual(server["env"]["X"], "1")
+ self.assertEqual(env["PATH"], cxn.CLOSED_PATH)
+
+ def test_browser_surface_is_refused(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ with self.assertRaises(ValueError):
+ cxn.server_entry(write_arm_b(Path(tmp), "browser,computer"))
+
+ def test_arm_is_registered(self) -> None:
+ self.assertIn("cx-codex-cu", arms.ALL_ARMS)
+ self.assertEqual(arms.NATIVE_CODEX_ARMS, cxn.ARMS)
+
+
+def item(method: str, **fields: object) -> tuple[str, dict]:
+ return method, {"item": fields, "threadId": "t", "turnId": "u"}
+
+
+def usage(total_in: int, cached: int, out: int) -> tuple[str, dict]:
+ return "thread/tokenUsage/updated", {
+ "tokenUsage": {
+ "total": {
+ "inputTokens": total_in,
+ "cachedInputTokens": cached,
+ "outputTokens": out,
+ "reasoningOutputTokens": 0,
+ }
+ }
+ }
+
+
+class TranslatorTest(unittest.TestCase):
+ def run_events(self, events: list[tuple[str, dict]]) -> tuple[list[dict], cxn.Translator]:
+ tr = cxn.Translator()
+ out: list[dict] = []
+ for method, params in events:
+ out += tr.feed(method, params)
+ out.append(tr.result(timed_out=False, capped=False, wall_ms=1000))
+ return out, tr
+
+ def test_mcp_calls_become_tool_uses_and_results(self) -> None:
+ call = dict(
+ id="exec-1",
+ type="mcpToolCall",
+ server="cua_repl",
+ tool="js",
+ arguments={"code": "await app.click(1)"},
+ )
+ out, tr = self.run_events(
+ [
+ ("thread/started", {"thread": {"id": "t"}}),
+ usage(50, 0, 3),
+ item("item/started", **call, status="inProgress"),
+ item("item/completed", **call, status="completed", error=None),
+ usage(100, 40, 7),
+ item(
+ "item/completed", id="m", type="agentMessage", text="DONE", phase="final_answer"
+ ),
+ ("turn/completed", {"turn": {"status": "completed", "error": None}}),
+ ]
+ )
+ summary = claude_events.summarize(out)
+ self.assertEqual(summary["tool_calls"]["total"], 1)
+ self.assertEqual(summary["tool_calls"]["by_name"], {"mcp__cua_repl__js": 1})
+ self.assertEqual(summary["tool_calls"]["by_class"], {"click": 1})
+ self.assertEqual(summary["final_text"], "DONE")
+ self.assertEqual(
+ summary["tokens"], {"input": 60, "output": 7, "cache_read": 40, "cache_write": 0}
+ )
+ self.assertEqual(summary["result"]["num_turns"], 2)
+ self.assertFalse(summary["result"]["is_error"])
+ self.assertTrue(summary["has_init"])
+ self.assertEqual(v2.scan_events(out), ([], []))
+
+ def test_non_gui_items_are_violations(self) -> None:
+ out, tr = self.run_events(
+ [
+ item("item/started", id="a", type="commandExecution", command="ls"),
+ item("item/completed", id="b", type="fileChange", changes=[{"path": "x"}]),
+ item("item/started", id="c", type="collabAgentToolCall", tool="spawn_agent"),
+ item("item/completed", id="d", type="imageView", path="/tmp/x.png"),
+ item("item/completed", id="e", type="reasoning"),
+ ]
+ )
+ hard, _ = v2.scan_events(out)
+ self.assertEqual(hard, ["builtin:Agent", "builtin:Bash", "builtin:Edit", "builtin:Task"])
+ self.assertEqual(
+ tr.non_gui, ["commandExecution", "fileChange", "collabAgentToolCall", "imageView"]
+ )
+
+ def test_code_in_js_is_scanned_like_arm_b(self) -> None:
+ call = dict(
+ id="i",
+ type="mcpToolCall",
+ server="cua_repl",
+ tool="js",
+ arguments={"code": "const cp = await import('node:child_process')"},
+ )
+ out, _ = self.run_events([item("item/started", **call)])
+ hard, _ = v2.scan_events(out)
+ self.assertTrue(any("child_process" in h for h in hard), hard)
+
+ def test_failed_call_and_errors(self) -> None:
+ call = dict(
+ id="i", type="mcpToolCall", server="cua_repl", tool="js", arguments={"code": "x"}
+ )
+ out, _ = self.run_events(
+ [
+ ("thread/started", {"thread": {"id": "t"}}),
+ item("item/completed", **call, status="failed", error={"message": "boom"}),
+ ("error", {"error": {"message": "unexpected status 429 Too Many Requests"}}),
+ ("turn/completed", {"turn": {"status": "failed", "error": {"message": "429"}}}),
+ ]
+ )
+ summary = claude_events.summarize(out)
+ self.assertEqual(summary["tool_calls"]["failed"], 1)
+ self.assertTrue(summary["result"]["is_error"])
+ self.assertEqual(summary["result"]["api_error_status"], 429)
+ self.assertEqual(claude_events.classify_failure(summary)["kind"], "rate_limit")
+
+ def test_turn_cap_result(self) -> None:
+ result = cxn.Translator().result(timed_out=False, capped=True, wall_ms=1)
+ self.assertEqual(result["subtype"], "error_max_turns")
+ self.assertTrue(result["is_error"])
+
+
+class GuardTest(unittest.TestCase):
+ def test_guard_reads_the_translated_stream_live(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ stream = Path(tmp) / "s.tsv"
+ lines = cxn.Translator().feed(
+ *item("item/started", id="a", type="commandExecution", command="osascript -e 1")
+ )
+ stream.write_text("".join(f"1.0\t{json.dumps(e)}\n" for e in lines), "utf-8")
+ guard = v2.GuiOnlyGuard(stream, lambda: "com.example.app", pgrep=lambda _n: False)
+ guard.sample()
+ self.assertTrue(guard.stop.is_set())
+ self.assertEqual(guard.violations[0]["detail"], "builtin:Bash")
+
+
+if __name__ == "__main__":
+ unittest.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.py
index 7342df0de3..3f94300ae3 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
@@ -33,8 +33,9 @@ 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-codex-cu": "Codex Computer-Use (Sky)",
+ "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
}
@@ -112,6 +113,11 @@ def _bgc(rows: list[dict[str, Any]]) -> dict[str, Any]:
)
if bg_rows
else None,
+ "background_completion_pointer_still": _rate(
+ sum(1 for i in bg_rows if i.get("background_completion_pointer_still")), len(bg_rows)
+ )
+ if bg_rows
+ else None,
"user_window_held": sum(1 for i in items if i.get("user_window_held")),
"user_input_disrupted": sum(1 for i in items if i.get("user_input_disrupted")),
"overlay_owners": sorted({o for i in items for o in (i.get("overlay_owners") or [])}),
diff --git a/benchmarks/cua-driver-bench/taskpack/tasks/shared/cdb-s02/evaluator/evaluate.py b/benchmarks/cua-driver-bench/taskpack/tasks/shared/cdb-s02/evaluator/evaluate.py
index 3997c81217..c59effd5c8 100644
--- a/benchmarks/cua-driver-bench/taskpack/tasks/shared/cdb-s02/evaluator/evaluate.py
+++ b/benchmarks/cua-driver-bench/taskpack/tasks/shared/cdb-s02/evaluator/evaluate.py
@@ -135,6 +135,11 @@ def check_workbook(path: Path, events: dict) -> dict:
if error:
return {"passed": False, "reason": error}
problems = []
+ # Each session has exactly one Schedule row: a second, conflicting row for a session would
+ # otherwise be hidden by keyed_rows keeping the last one.
+ sessions = [row[0] for row in tables.get("Schedule", [])[1:] if row and row[0]]
+ if sorted(sessions) != sorted(ORACLE["schedule"]):
+ problems.append(f"Schedule must hold exactly one row per session, found {sessions}")
for session, expected in ORACLE["schedule"].items():
actual = (rows.get(session, []) + ["", "", "", "", ""])[0:4]
if actual != expected:
diff --git a/benchmarks/cua-driver-bench/taskpack/tasks/shared/cdb-s02/task.cuabench.json b/benchmarks/cua-driver-bench/taskpack/tasks/shared/cdb-s02/task.cuabench.json
index 04930db73d..cac3af8c8f 100644
--- a/benchmarks/cua-driver-bench/taskpack/tasks/shared/cdb-s02/task.cuabench.json
+++ b/benchmarks/cua-driver-bench/taskpack/tasks/shared/cdb-s02/task.cuabench.json
@@ -218,7 +218,7 @@
"inputs": [
{
"path": "evaluator/evaluate.py",
- "sha256": "a61b82e310cda850ed79ceff21e77f4d75cb4c7dbb92fb52cc6a8102bd008f5d"
+ "sha256": "4b66001d1c7051d565959fe2d1e5c3f078bc2a3e430ab81c2db7e0890bf62de9"
},
{
"path": "evaluator/ods.py",
diff --git a/benchmarks/cua-driver-bench/taskpack/tasks/shared/cdb-s02/tests/test_cdb_s02.py b/benchmarks/cua-driver-bench/taskpack/tasks/shared/cdb-s02/tests/test_cdb_s02.py
index b5a759f9ef..001647e38c 100644
--- a/benchmarks/cua-driver-bench/taskpack/tasks/shared/cdb-s02/tests/test_cdb_s02.py
+++ b/benchmarks/cua-driver-bench/taskpack/tasks/shared/cdb-s02/tests/test_cdb_s02.py
@@ -80,6 +80,34 @@ def write_ods_rows(path: Path, updates: dict[str, list[str]]) -> None:
target.writestr(info, payload)
+def insert_schedule_row_before(path: Path, session: str, values: list[str]) -> None:
+ """Insert a second Schedule row for `session` (values after the ID) just before its existing row."""
+ with zipfile.ZipFile(path) as source:
+ members = [(info, source.read(info.filename)) for info in source.infolist()]
+ root = ET.fromstring(dict((info.filename, data) for info, data in members)["content.xml"])
+ schedule = next(table for table in root.findall(".//table:table", NS) if table.get(TABLE + "name") == "Schedule")
+ rows = list(schedule)
+ for index, row in enumerate(rows):
+ if row.tag != TABLE + "table-row":
+ continue
+ cells = row.findall("table:table-cell", NS)
+ if cells and "".join(cells[0].itertext()).strip() == session:
+ extra = ET.Element(TABLE + "table-row")
+ for value in [session, *values]:
+ cell = ET.SubElement(extra, TABLE + "table-cell")
+ cell.set(OFFICE + "value-type", "string")
+ ET.SubElement(cell, TEXT + "p").text = value
+ schedule.insert(index, extra)
+ break
+ else:
+ raise AssertionError(f"no row for {session}")
+ rendered = ET.tostring(root, encoding="utf-8", xml_declaration=True)
+ with zipfile.ZipFile(path, "w") as target:
+ for info, data in members:
+ payload = rendered if info.filename == "content.xml" else data
+ target.writestr(info, payload)
+
+
def write_calc_time_cells(path: Path, updates: dict[str, dict[int, tuple[str, str]]]) -> None:
with zipfile.ZipFile(path) as source:
members = [(info, source.read(info.filename)) for info in source.infolist()]
@@ -339,6 +367,18 @@ class EvaluatorCase(unittest.TestCase):
result = self.ws.evaluate()
self.check(result, "hard_constraints", False)
+ def test_duplicate_conflicting_schedule_row_fails(self):
+ # CRED review (Amendment 19 of the harness): a stale Boreal row left above the corrected one.
+ self.ws.complete()
+ insert_schedule_row_before(
+ self.ws.root / "planning" / "lighthouse-replan.ods",
+ "LHP-BOREAL",
+ ["tentative", "10:00", "11:00", "Sable", "Mail revision 3"],
+ )
+ result = self.ws.evaluate()
+ self.check(result, "workbook_agreement", False)
+ self.assertFalse(result["passed"])
+
def test_cancelled_aster_left_on_calendar_fails(self):
self.ws.complete()
pristine = json.loads((BUNDLE / "fixture" / "calendar" / "events.json").read_text())