Skip to content

armgit / axuse

Public Imported from GitHub
0

Accessibility-first browser & computer use for AI agents — one MCP server for every harness (Codex, Claude Code, OpenCode, Antigravity). Instruments the DOM/accessibility tree via CDP instead of screenshot loops: diffed snapshots, stable element refs, trusted input, typed errors. Zero dependencies

axuse — accessibility-first browser & computer use for AI agents

tfusion6667237a1e1936f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..d6b78fb
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,137 @@
+name: CI
+
+on:
+ push:
+ pull_request:
+
+jobs:
+ # ---------------------------------------------------------------- macOS
+ # Lane coverage: two supported macOS versions on Apple Silicon, plus the
+ # Intel build of the oldest supported version (macos-15-intel is the
+ # successor of the retired macos-13 image; macos-14 is deprecated).
+ macos:
+ name: macOS (${{ matrix.os }}, Node ${{ matrix.node }})
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [macos-26, macos-15, macos-15-intel]
+ node: [22]
+ include:
+ - os: macos-26
+ node: 24
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: ${{ matrix.node }}
+ - name: Install Chrome for Testing (extension-bridge + browser coverage)
+ shell: bash
+ run: |
+ set -euo pipefail
+ case "$(uname -m)" in
+ arm64) platform="mac-arm64" ;;
+ x86_64) platform="mac-x64" ;;
+ *) echo "Unsupported macOS runner architecture: $(uname -m)" >&2; exit 1 ;;
+ esac
+ metadata="$RUNNER_TEMP/chrome-for-testing.json"
+ curl --fail --silent --show-error --location \
+ https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json \
+ --output "$metadata"
+ url="$(node -e 'const fs=require("node:fs"); const d=JSON.parse(fs.readFileSync(process.argv[1],"utf8")); const hit=d.channels.Stable.downloads.chrome.find((x)=>x.platform===process.argv[2]); if(!hit) process.exit(2); process.stdout.write(hit.url);' "$metadata" "$platform")"
+ archive="$RUNNER_TEMP/chrome-for-testing.zip"
+ curl --fail --silent --show-error --location "$url" --output "$archive"
+ install_root="$RUNNER_TEMP/axuse-chrome-for-testing"
+ mkdir -p "$install_root"
+ ditto -x -k "$archive" "$install_root"
+ browser="$install_root/chrome-mac${platform#mac}/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
+ test -x "$browser"
+ echo "AXUSE_BROWSER=$browser" >> "$GITHUB_ENV"
+ - name: Full suite (capability gates on, TAP for the skip audit)
+ env:
+ AXUSE_ENABLE_MACOS_CUA: "1"
+ AXUSE_TEST_MACOS_DESKTOP: "1"
+ run: |
+ set -o pipefail
+ node --test --test-reporter=tap test/*.test.js | tee "$RUNNER_TEMP/tap.txt"
+ - name: Skip audit (every skip explicit, typed, CI-visible)
+ run: node tools/skip-audit.mjs "$RUNNER_TEMP/tap.txt"
+ - name: Doctor smoke
+ env:
+ AXUSE_ENABLE_MACOS_CUA: "1"
+ run: node src/cli.js doctor
+ - name: Bridge security check (token file owner-only)
+ run: |
+ node - <<'EOF'
+ // Start a hub in an isolated dir and assert the info file's mode.
+ import("node:fs").then(async (fs) => {
+ const os = await import("node:os");
+ const dir = fs.mkdtempSync(await import("node:path").then((p) => p.join(os.tmpdir(), "axuse-sec-")));
+ process.env.AXUSE_BRIDGE_DIR = dir;
+ const { BridgeHub } = await import("./src/bridge/hub.js");
+ const hub = await new BridgeHub().start();
+ const st = fs.statSync(await import("./src/bridge/hub.js").then((h) => h.infoPath()));
+ const mode = st.mode & 0o777;
+ hub.stop();
+ fs.rmSync(dir, { recursive: true, force: true });
+ if (process.platform !== "win32" && (mode & 0o077) !== 0) {
+ console.error(`bridge.json mode ${mode.toString(8)} is broader than 0600`);
+ process.exit(1);
+ }
+ console.log(`bridge.json mode ${mode.toString(8)} OK`);
+ });
+ EOF
+
+ # -------------------------------------------------------------- Windows
+ # The Windows desktop driver is the resident PowerShell one — exercised
+ # live here (screen info + screenshots only; no pointer movement).
+ windows:
+ name: Windows (windows-latest, Node 22)
+ runs-on: windows-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ - name: Full suite (TAP for the skip audit)
+ shell: bash
+ run: |
+ set -o pipefail
+ node --test --test-reporter=tap "test/*.test.js" | tee "$RUNNER_TEMP/tap.txt"
+ - name: Skip audit
+ run: node tools/skip-audit.mjs "$RUNNER_TEMP/tap.txt"
+ - name: Doctor smoke
+ run: node src/cli.js doctor
+
+ # ---------------------------------------------------------------- Linux
+ # Browser tools are platform-free; this lane pins Chrome for Testing so the
+ # browser suite runs for real (no desktop driver on Linux by design).
+ linux:
+ name: Linux (ubuntu-latest, Node 22)
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ - name: Install Chrome for Testing
+ run: |
+ set -euo pipefail
+ metadata="$RUNNER_TEMP/cft.json"
+ curl --fail --silent --show-error --location \
+ https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json \
+ --output "$metadata"
+ url="$(node -e 'const fs=require("node:fs"); const d=JSON.parse(fs.readFileSync(process.argv[1],"utf8")); const hit=d.channels.Stable.downloads.chrome.find((x)=>x.platform==="linux64"); if(!hit) process.exit(2); process.stdout.write(hit.url);' "$metadata")"
+ curl --fail --silent --show-error --location "$url" --output "$RUNNER_TEMP/cft.zip"
+ unzip -q "$RUNNER_TEMP/cft.zip" -d "$RUNNER_TEMP/cft"
+ echo "AXUSE_BROWSER=$RUNNER_TEMP/cft/chrome-linux64/chrome" >> "$GITHUB_ENV"
+ - name: Full suite (TAP for the skip audit)
+ env:
+ DISPLAY: ":99"
+ run: |
+ set -o pipefail
+ node --test --test-reporter=tap test/*.test.js | tee "$RUNNER_TEMP/tap.txt"
+ - name: Skip audit
+ run: node tools/skip-audit.mjs "$RUNNER_TEMP/tap.txt"
+ - name: Doctor smoke
+ run: node src/cli.js doctor
diff --git a/.github/workflows/tcc-manual.yml b/.github/workflows/tcc-manual.yml
new file mode 100644
index 0000000..ed989f1
--- /dev/null
+++ b/.github/workflows/tcc-manual.yml
@@ -0,0 +1,64 @@
+name: Manual TCC validation (self-hosted macOS)
+
+# This lane is SEPARATE from CI on purpose. GitHub-hosted runners cannot be
+# granted Accessibility or Screen Recording, so the granted side of the TCC
+# matrix can only be validated on a machine a human prepared. The tests
+# capture a 200x120 corner slice, post one zero-delta scroll event (a real
+# event that moves nothing), and — the LIVE scroll-direction pin — briefly
+# open an axuse-owned Chrome window, scroll IT with a real wheel event, and
+# assert the direction via scrollY read-back. Nothing outside axuse's own
+# window is ever scrolled or captured.
+#
+# One-time runner setup (documented in docs/macos-support.md):
+# 1. A dedicated Mac (not your daily driver) registered as a self-hosted
+# runner with labels: self-hosted, macOS, axuse-tcc
+# 2. System Settings → Privacy & Security → Accessibility: add the exact
+# binary that runs the tests (the runner's node, e.g. via a Terminal
+# window owned by the runner user).
+# 3. Same for Screen Recording, then restart that binary.
+# 4. Verify: AXUSE_TEST_MACOS_TCC_MANUAL=1 node --test
+# test/desktop-tcc-manual.test.js — the first test fails with typed
+# instructions if the lane is misconfigured.
+
+on:
+ workflow_dispatch:
+ inputs:
+ note:
+ description: "What this validation run covers (recorded in the summary)"
+ required: false
+ default: "monthly TCC-granted validation"
+
+jobs:
+ tcc-manual:
+ name: TCC-granted desktop validation
+ runs-on: [self-hosted, macOS, axuse-tcc]
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@v4
+ - name: Environment fingerprint (evidence)
+ run: |
+ sw_vers
+ uname -m
+ node --version
+ echo "runner: $(whoami)"
+ - name: TCC-manual suite (fails closed when grants are missing)
+ env:
+ AXUSE_ENABLE_MACOS_CUA: "1"
+ AXUSE_TEST_MACOS_TCC_MANUAL: "1"
+ run: |
+ set -o pipefail
+ node --test --test-reporter=tap test/desktop-tcc-manual.test.js | tee "$RUNNER_TEMP/tcc-tap.txt"
+ # The manual suite must produce ZERO skips: every test in it is
+ # mandatory in this lane.
+ if grep -q "# SKIP" "$RUNNER_TEMP/tcc-tap.txt"; then
+ echo "::error::TCC-manual lane produced skips — the runner is misconfigured or the gate is wrong."
+ exit 1
+ fi
+ - name: Denied-state regression (same machine, subshell without grants is NOT possible — informational)
+ run: |
+ echo "Denied-state coverage runs automatically in CI lanes (typed-error paths) and on any un-granted host."
+ - name: Full suite passive desktop paths (screen info, windows, probe)
+ env:
+ AXUSE_ENABLE_MACOS_CUA: "1"
+ AXUSE_TEST_MACOS_DESKTOP: "1"
+ run: node --test test/desktop.test.js
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..4dd3d36
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,41 @@
+# Dependencies
+node_modules/
+
+# Generated benchmark output
+bench/results-*.jsonl
+
+# Logs
+*.log
+npm-debug.log*
+
+# Env / secrets
+.env
+.env.*
+
+# OS / editor
+.DS_Store
+Thumbs.db
+.vscode/
+.idea/
+
+# Coverage / build
+coverage/
+dist/
+*.tgz
+
+# Generated suite output (regenerate: see bench/suite/README.md)
+bench/suite/out/
+bench/suite/results/
+bench/suite/browser-use-SKILL.md
+
+# Solver plugin install target (this directory holds PAID, separately
+# licensed solver packages — never part of the open-source repo).
+# Only the README below is tracked; everything else stays local.
+
+# plugins/*
+!plugins/README.md
+
+# Premium plugin artifacts (specs: 01/03) — local-only outputs.
+vaults/
+captures/
+plugins/licenses/
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..0c420d7
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,132 @@
+Copyright © CTOL Digital Solutions
+
+Required Notice: Copyright CTOL Digital Solutions (https://ctol.digital)
+
+# PolyForm Noncommercial License 1.0.0
+
+<https://polyformproject.org/licenses/noncommercial/1.0.0>
+
+## Acceptance
+
+In order to get any license under these terms, you must agree
+to them as both strict obligations and conditions to all
+your licenses.
+
+## Copyright License
+
+The licensor grants you a copyright license for the
+software to do everything you might do with the software
+that would otherwise infringe the licensor's copyright
+in it for any permitted purpose. However, you may only
+distribute the software according to [Distribution License](#distribution-license)
+and make changes or new works based on the software
+according to [Changes and New Works License](#changes-and-new-works-license).
+
+## Distribution License
+
+The licensor grants you an additional copyright license
+to distribute copies of the software. Your license
+to distribute covers distributing the software with changes
+and new works permitted by [Changes and New Works License](#changes-and-new-works-license).
+
+## Notices
+
+You must ensure that anyone who gets a copy of any part
+of the software from you also gets a copy of these terms
+or the URL for them above, as well as copies of any plain-text lines beginning
+with `Required Notice:` that the licensor provided with
+the software. For example:
+
+> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
+
+## Changes and New Works License
+
+The licensor grants you an additional copyright license
+to make changes or new works based on the software
+for any permitted purpose.
+
+## Patent License
+
+The licensor grants you a patent license for the software that
+covers patent claims the licensor can license, or becomes able
+to license, that you would infringe by using the software.
+
+## Noncommercial Purposes
+
+Any noncommercial purpose is a permitted purpose.
+
+## Personal Uses
+
+Personal use for research, experiment, and testing for
+the benefit of public knowledge, personal study, private
+entertainment, hobby projects, amateur pursuits, or religious
+observance, without any anticipated commercial application,
+is use for a permitted purpose.
+
+## Noncommercial Organizations
+
+Use by any charitable organization, educational
+institution, public research organization, public safety or
+health organization, environmental protection organization,
+or government institution is use for a permitted purpose
+regardless of the source of funding or obligations resulting
+from the funding.
+
+## Fair Use
+
+You may have "fair use" rights for the software under the law. These terms do not limit them.
+
+## No Other Rights
+
+These terms do not allow you to sublicense or transfer any
+of your licenses to anyone else, or prevent the licensor from
+granting licenses to anyone else. These terms do not imply
+any other licenses.
+
+## Patent Defense
+
+If you make any written claim that the software infringes
+or contributes to infringement of any patent, your patent
+license for the software granted under these terms ends
+immediately. If your company makes such a claim, your
+patent license ends immediately for work on behalf of your
+company.
+
+## Violations
+
+The first time you are notified in writing that you have
+violated any of these terms, or done anything with the software
+not covered by your licenses, your licenses can nonetheless
+continue if you come into full compliance with these terms,
+and take practical steps to correct past violations, within
+32 days of receiving notice. Otherwise, all your licenses
+end immediately.
+
+## No Liability
+
+***As far as the law allows, the software comes as is, without any
+warranty or condition, and the licensor will not be liable to you
+for any damages arising out of these terms or the use or nature
+of the software, under any kind of legal claim.***
+
+## Definitions
+
+The **licensor** is the individual or entity offering these
+terms, and the **software** is the software the licensor makes
+available under these terms.
+
+**You** refers to the individual or entity agreeing to them.
+
+**Your company** is any legal entity, sole proprietorship,
+or other kind of organization that you work for, plus all
+organizations that have control over, are under the control of,
+or are under common control with that organization. **Control**
+means ownership of substantially all the assets of an entity,
+or the power to direct its management and policies by vote,
+contract, or otherwise. Control can be direct or indirect.
+
+**Your licenses** are all the licenses granted to you for the
+software under these terms.
+
+**Use** means anything you do with the software requiring one
+of your licenses.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..5a2918b
--- /dev/null
+++ b/README.md
@@ -0,0 +1,360 @@
+# axuse — browser & computer use, done right
+
+**Accessibility-first browser and computer use for agent harnesses.** One MCP
+server plugs into Codex, Claude Code, OpenCode, Antigravity, or any
+MCP-capable host. Zero dependencies (Node ≥ 22). Windows desktop driver is
+verified; macOS desktop control is available as an explicit opt-in with
+native TCC permission checks.
+
+The design is distilled from the two best implementations of this problem —
+OpenAI's Codex Chrome extension and the ZCode harness — and exists to prove a
+point: **a screenshot loop is not the right interface for a machine**. The
+DOM tree, the accessibility tree, and CDP are. axuse instruments the target
+instead of photographing it.
+
+If you are a journalist or other non-developer using Codex or ChatGPT Work,
+start with the [non-developer onboarding guide](docs/non-developer-onboarding.md).
+It explains the one-time connector setup, the first verification prompt, and
+copy-and-paste research prompts. The source repository's setup below is for
+developers and administrators.
+
+## Proven in production
+
+axuse is maintained by **CTOL Digital Solutions**
+([ctol.digital](https://ctol.digital)), a leading AI, Strategy and IT
+consultancy. This work has been tested and used at large scale across many
+client engagements. CTOL Digital Solutions holds the copyright of all the
+code.
+
+
+## Quick start
+
+You need **Node.js 22+** and a Chromium-family browser (Chrome, Edge,
+Chromium, or Chrome for Testing; found automatically, or set
+`AXUSE_BROWSER=/path/to/chrome`).
+Nothing else: axuse has no npm dependencies.
+
+**1. Get it and check the environment**
+
+```bash
+git clone https://github.com/ctoldigital/axuse.git
+cd axuse
+node src/cli.js doctor # finds a browser, launches it, takes a snapshot
+```
+
+For a daily Chrome/Edge session, use the guided bridge setup. It registers the
+native host, opens the extensions page, prints the exact folder to load, and
+can print your harness configuration in the same command:
+
+```bash
+node src/cli.js setup --browser chrome --harness codex
+```
+
+After clicking **Load unpacked** once, verify the connection with:
+
+```bash
+node src/cli.js bridge verify
+```
+
+**2. Add it to your harness** (use your absolute path to `src/cli.js`)
+
+```bash
+# Codex
+codex mcp add axuse -- node /abs/path/axuse/src/cli.js mcp
+
+# Claude Code
+claude mcp add --scope user axuse -- node /abs/path/axuse/src/cli.js mcp
+
+# OpenCode, Antigravity, any other MCP host: print the config block to paste
+node src/cli.js print-config --harness opencode # or agy | generic
+```
+
+**3. Ask for something in the browser**
+
+> Open https://example.com, find the "More information" link and tell me
+> where it goes.
+
+The agent calls `ax_open`, reads the accessibility snapshot, and acts on
+element refs like `[ref=e7]`. Each action returns only what changed.
+
+**Optional settings** (environment variables for the MCP server)
+
+| variable | effect |
+|---|---|
+| `AXUSE_HEADLESS=1` | launch the browser without a window (servers, CI) |
+| `AXUSE_BROWSER` | path to the browser binary |
+| `AXUSE_PROFILE_DIR` | where temporary browser profiles go (default: OS temp; they are deleted on exit) |
+| `AXUSE_BRIDGE_DIR` | override the local bridge state directory (default: `~/Library/Application Support/axuse` on macOS) |
+| `AXUSE_ENABLE_MACOS_CUA=1` | enable macOS desktop tools (Accessibility + Screen Recording grants are still required) |
+| `AXUSE_BRIDGE_DEBUG=1` | trace the extension bridge |
+
+To drive your own logged-in Chrome instead of a fresh browser, see
+[Driving your daily browser](#driving-your-daily-browser-the-codex-pattern).
+
+## Benchmark
+
+On 16 server-scored browser tasks, run in the same harness (Codex CLI) with
+the same model against Codex's own Chrome extension and
+[browser-use](https://github.com/browser-use/browser-use) 0.13:
+
+| | axuse | Codex + Chrome extension | browser-use |
+|---|---|---|---|
+| tasks passed | 28/28 | 27/27 | 27/27 |
+| median time per task | **17 s** | 26 s | 56 s |
+| tokens, all runs | **4.7M** | 9.8M | 8.8M |
+| median tool calls | **5** | 7 | 12 |
+
+Accuracy tied on those tasks. A harder 7-task extension (checkout flow,
+virtualized grid, date pickers, signup errors, nested iframes, file upload,
+local dev app) has been run once so far: axuse 7/7; Codex + Chrome failed 2
+by stopping to ask for confirmation; browser-use failed 1. Method, anti-cheat
+rules and how to reproduce: [`bench/suite/README.md`](bench/suite/README.md).
+Install footprint and setup comparison: [`bench/suite/EASE.md`](bench/suite/EASE.md).
+
+## Why this is faster and more reliable than screenshot CUA
+
+| | Screenshot CUA loop | axuse |
+|---|---|---|
+| Observation | ~1–2MB base64 raster per step, ~1k+ image tokens, vision-encoder latency | YAML-like AX snapshot in KBs; **diff by default** (only removed/added/changed lines) |
+| Targeting | pixel coordinates guessed from an image; drifts with resolution/DPR | stable element refs bound to **element identity** (insertion-safe) + Playwright-style semantic lines |
+| Input | synthetic DOM events (rejected by sites) or fragile OS injection | trusted CDP `Input.dispatch*` events (`isTrusted`) |
+| Failure mode | silent misclick, discovered 2–3 screenshots later | typed errors: `REF_NOT_FOUND` / `STALE_STATE` / `DIALOG_OPEN` with `retry` hints and `action_sent` facts |
+| Change detection | re-photograph everything | sequenced event ring buffer + snapshot diffing |
+| Cost control | none | budgets enforced in code: snapshot char/node caps, screenshot byte budget with quality fallback, one raster per call |
+
+## Install into a harness
+
+```bash
+node src/cli.js print-config --harness codex # or claude-code | opencode | agy | generic
+```
+
+- **Codex** — append the printed `[mcp_servers.axuse]` block to `~/.codex/config.toml`
+- **Claude Code** — `claude mcp add --scope user axuse -- node <path>/src/cli.js mcp`
+- **OpenCode** — merge the printed `mcp` block into `opencode.json`
+- **Antigravity / any MCP host** — the printed `mcpServers` block
+
+Verify the environment: `node src/cli.js doctor`.
+
+The model-facing usage contract lives in [`SKILL.md`](SKILL.md) — point your
+harness's skill system (or system prompt) at it.
+
+## Solver plugins (open core ↔ paid solvers)
+
+axuse's core is CAPTCHA-agnostic and ships **no solvers**. Turnstile / hCaptcha /
+reCAPTCHA solvers are **separate, commercially licensed packages** that plug in
+through a thin, frozen seam (`src/plugins/`):
+
+```bash
+# install: drop a solver package into plugins/ (or list dirs in AXUSE_PLUGINS)
+node src/cli.js plugins # → ✓ [email protected] — providers: turnstile, recaptcha-v2, hcaptcha
+node src/cli.js solve turnstile --url https://demo.turnstile.workers.dev/
+```
+
+From any MCP harness: `ax_solve_captcha { provider, url? }` and `ax_plugins`.
+Plugins that own capabilities (session vaults, network governors, guarded
+actions…) can also contribute their **own MCP tools** through a validated
+`tools()` export (`ax_vault`, `ax_net`, `ax_guard`, …) — same seam, same
+trust boundary. The ABI, the solver context, the `tools()` contract, and
+packaging/licensing guidance:
+[`docs/plugins.md`](docs/plugins.md). A complete free (PolyForm Noncommercial
+1.0.0) reference solver
+lives in [`examples/plugin-turnstile-demo/`](examples/plugin-turnstile-demo/).
+
+## Architecture
+
+```
+harness (Codex / Claude Code / OpenCode / Antigravity / …)
+ │ MCP over stdio (JSON-RPC 2.0) — the universal integration layer
+ ▼
+src/mcp/ — thin, stateless-per-call adapter (hand-rolled, zero deps)
+ │ one frozen command contract (src/core/commands.js)
+ ▼
+src/core/ — the state owner (Codex native-host / ZCode host pattern)
+ ├─ controller.js sessions, tabs, state_id, dialogs, auto-observe diffs,
+ │ OOPIF frame registry (f-slot namespaced refs)
+ ├─ cdp.js launch/attach Chromium, browser-level WebSocket, flat sessions,
+ │ Target.setAutoAttach for OOPIF auto-entry
+ ├─ serialize.js injected AX serializer: element-identity refs, shadow DOM,
+ │ same-origin iframes (coordinate-translated), budgets
+ ├─ diff.js per-ref diff + text-line multiset diff + cost-based full fallback
+ ├─ actuate.js trusted Input.dispatch*, live ref resolution (frame-chain
+ │ coordinate translation), combos, waits
+ ├─ screenshot.js one raster, byte budget, quality fallback, crop hints
+ └─ errors.js typed codes, retry hints, action_sent, side_effect
+ │
+ ├─ src/bridge/ — Codex-style extension backend for the user's daily
+ │ Chrome/Edge: hub (TCP rendezvous, token auth, NDJSON) ←
+ │ native-messaging host (framed stdio relay) ← MV3 extension
+ │ (chrome.debugger = real CDP over the user's real browser)
+ │ + installer (registry/HKCU, host manifest, launcher) + backend
+ │ duck-typed onto the same command contract
+ ▼
+src/desktop/ — computer use (driver matrix)
+ ├─ Windows: resident PowerShell + SendInput/GDI, DPI-aware — VERIFIED
+ ├─ macOS: JXA/CoreGraphics + System Events + screencapture/sips,
+ │ display-point coordinates, env-gated with TCC diagnostics
+ └─ (the driver interface is the seam for a real AX/UIA tree driver)
+```
+
+### The patterns, and where each one comes from
+
+| Pattern | Codex lineage | ZCode lineage | axuse implementation |
+|---|---|---|---|
+| Diff-first observation | page-state diffing, default-on | "the tree comes back as a diff only… unchanged rows are omitted and their indices stay valid" | per-ref diff; refs bound to element identity so unchanged rows stay valid |
+| Element addressing | axState `element_index`/locators | refs `e1,e2…` in page + live resolution | `window.__axuseRefRegistry` (identity-stable across insertions), resolved live at action time |
+| Trusted input | `chrome.debugger` → `Input.dispatch*` | `webContents.debugger` | raw CDP `Input.dispatch*` / `Input.insertText` |
+| Event buffer | `tab_cdp_events` sequenced ring (limit ≤1000) | event routing with teardown discipline | ring buffer, sequence cursor, filtered methods |
+| Context budgets | 64k DOM text cap | 2×200KB images at protocol boundary, one-raster rule | snapshot node/char caps; screenshot 200KB budget + quality fallback + crop hint |
+| Error vocabulary | structured locator errors | `STALE_STATE`, `sideEffect:none\|uncertain`, `actionSent` | typed codes + `retry: reobserve\|retry\|never` + `action_sent` |
+| Frozen contract | command envelopes w/ zod | one discriminated union for all backends | `Contract` → validation AND MCP schemas generated from it |
+| Real user session | attaches to the user's real Chrome profile | `extension` backend via user Chrome | **extension bridge**: MV3 extension + native messaging + hub; `ax_open {backend:"extension"}` |
+| Frame entry (OOPIF) | webmcp/extension content merging | IAB merges frames; OOPIF via CDP | `Target.setAutoAttach` per tab; frames serialized in their own sessions, merged under `f<slot>:` identity-stable refs, input dispatched frame-locally |
+
+## Tool surface
+
+**Browser** (always): `ax_open`, `ax_open_many`, `ax_navigate`, `ax_go`, `ax_tabs`, `ax_observe`,
+`ax_click`, `ax_fill`, `ax_upload`, `ax_hover`, `ax_type`, `ax_press`,
+`ax_scroll`, `ax_select`, `ax_drag`, `ax_screenshot`, `ax_element_info`,
+`ax_evaluate`, `ax_wait_for`, `ax_events`, `ax_dialog`, `ax_close`.
+
+The ones that save the most steps:
+
+- `ax_fill` sets a whole form in one call (text, selects, checkboxes, radios,
+ switches, custom dropdowns, autocomplete) and can click submit.
+- `ax_observe {find:"text"}` returns only the matching lines of a big page.
+- `ax_scroll {until:"text"}` scrolls an infinite feed or virtualized list,
+ in the page or inside a scrolling panel, until the text appears.
+- `ax_upload` sets files on a file input; a click that opens a file chooser
+ is reported instead of hanging.
+- `ax_open_many` opens a bounded URL list sequentially, returns compact titles
+ and accessibility excerpts, and closes temporary tabs by default. It is the
+ batch equivalent of `ax_open` and avoids writing a custom MCP client.
+- JS dialogs and new tabs opened by an action are reported in its result.
+
+**Desktop** (Windows: verified. macOS: opt-in with
+`AXUSE_ENABLE_MACOS_CUA=1` and host Accessibility/Screen Recording grants):
+`ax_desktop_screenshot`, `ax_desktop_screen_info`,
+`ax_desktop_click`, `ax_desktop_type`, `ax_desktop_press`, `ax_desktop_scroll`,
+`ax_desktop_windows`, `ax_desktop_activate`, `ax_desktop_drag`.
+
+## The loop the model is guided into
+
+```
+ax_open → FULL snapshot with refs (e.g. button "Sign in" [ref=e7])
+ax_click {e7} → returns the DIFF (removed/added/changed + text changes)
+ax_type {e9, text} → returns the diff (value="…" appears)
+… → screenshots ONLY for visual/canvas checks (budget-capped)
+```
+
+Cross-origin iframes appear in the snapshot as `--- frame f1 (url) ---`
+sections with `f1:eN` refs — same loop, same diffs, frame-stable refs.
+
+Errors are facts, not strings:
+
+```json
+{ "code": "REF_NOT_FOUND",
+ "hint": "Refs are per-observation. Call ax_observe, then act on fresh refs.",
+ "retry": "reobserve" }
+```
+
+## Driving your daily browser (the Codex pattern)
+
+```bash
+axuse bridge install # registers the native messaging host (Chrome + Edge hives)
+axuse bridge # hub (or it starts on demand with the MCP server)
+```
+
+Load `bridge/extension` unpacked in Chrome/Edge (Developer mode → Load
+unpacked), then `ax_open { url, backend: "extension" }`. Your browser, your
+logged-in sessions, tabs visible to you; `ax_close` closes only axuse's tabs.
+The whole chain — native messaging framing, hub auth, CDP-over-chrome.debugger,
+diffed snapshots, trusted clicks — is covered by `test/bridge.test.js`.
+
+Field notes (all established live against Edge 155 / Chrome 155):
+
+- Branded Chrome silently ignores `--load-extension` (137+). Automated
+ extension loads need Edge / Chromium / Chrome-for-Testing; manual unpacked
+ loads work everywhere.
+- Edge requires `allowed_origins` in the host manifest — with only
+ `allowed_extensions` it reports "native messaging host not found". The
+ installer writes both.
+- On macOS, `setup` and `bridge install` also accept `chromium` and
+ `chrome-for-testing`, and register the host in each browser's own
+ `NativeMessagingHosts` directory.
+- The Windows native host is a `.bat` launcher: cmd.exe relays the framed
+ stdio pipes faithfully, where a compiled C# shim (Console.OpenStandardInput)
+ dropped Chrome's stdin writes. Debug any install with
+ `AXUSE_BRIDGE_DEBUG=1` (hub + nm-host message tracing) and
+ `self.__axuseDiag` inside the extension's service worker (readable via an
+ attached DevTools/CDP session).
+
+## Honest scope notes
+
+- **macOS desktop control is opt-in** because it can synthesize OS input. Set
+ `AXUSE_ENABLE_MACOS_CUA=1`, grant the host Accessibility and Screen Recording
+ in System Settings → Privacy & Security, then run `node src/cli.js doctor`.
+ Coordinates are macOS global display points and returned desktop JPEGs are
+ resized to the same point dimensions for direct click mapping. Linux has no
+ desktop driver yet (browser tools still work).
+- **The extension backend has no Target domain** (chrome.debugger limits), so
+ OOPIF frames are listed but not entered there; the CDP backend enters them.
+- **Anti-bot reality**: axuse runs a real Chromium with a real profile, but
+ it does not implement Codex's `x-browser-agent` traffic labeling or
+ bot-detection handoff — sites that fingerprint automation may still block
+ it. The bridge backend (your daily browser) is the most human-looking path.
+
+For a non-MCP batch workflow, the same bounded operation is available from the
+CLI and accepts plain URL lists or Markdown containing links:
+
+```bash
+node src/cli.js open-urls sources.md --backend extension --output report.md
+```
+
+The generated report is intentionally honest: it contains page titles, access
+status, and bounded accessibility-text excerpts, not fabricated semantic
+summaries.
+
+## Development
+
+```bash
+node --test test/diff.test.js test/browser.test.js test/mcp.test.js test/desktop.test.js test/oopif.test.js test/bridge.test.js test/plugin.test.js
+```
+
+On macOS, enable the passive desktop capability gates explicitly:
+
+```bash
+AXUSE_ENABLE_MACOS_CUA=1 AXUSE_TEST_MACOS_DESKTOP=1 npm test
+```
+
+Tests are gated: browser/MCP tests skip when no Chromium-family browser is
+found; the OOPIF test spins up two loopback origins (127.0.0.1 + localhost);
+the bridge test registers + uninstalls a native messaging host and uses an
+extension-capable browser when one is installed (branded Chrome on current
+macOS builds is honestly skipped because it ignores automated
+`--load-extension`); desktop tests exercise passive screen/window discovery on
+macOS with `AXUSE_TEST_MACOS_DESKTOP=1`. A real macOS screenshot test is
+explicit with `AXUSE_TEST_MACOS_SCREENSHOT=1` because Screen Recording is
+TCC-protected. No test moves your real mouse or sends keys.
+
+Debugging: `AXUSE_BRIDGE_DEBUG=1` traces hub + native-host messages;
+`self.__axuseDiag` in the extension SW reports connect/disconnect history.
+
+Every `# SKIP` in a suite run is explicit, typed, and audited: run TAP output
+through `node tools/skip-audit.mjs` and it fails when a skip is missing from
+`test/skip-allowlist.json`. CI enforces this on every lane.
+
+macOS production reference — support matrix (browsers × macOS versions ×
+arch), TCC permission model, failure taxonomy, the manual TCC validation
+lane, benchmarks, and known limitations with evidence:
+[docs/macos-support.md](docs/macos-support.md).
+
+## License
+
+Copyright © CTOL Digital Solutions ([ctol.digital](https://ctol.digital)).
+All rights reserved.
+
+Licensed under the **PolyForm Noncommercial License 1.0.0** — see
+[`LICENSE`](LICENSE). Use, distribution, and modification are free for any
+**noncommercial** purpose (personal use, research, education, charities,
+public institutions). **Commercial use requires a separate commercial
+license** from CTOL Digital Solutions ([ctol.digital](https://ctol.digital)).
diff --git a/SKILL.md b/SKILL.md
new file mode 100644
index 0000000..3b9095c
--- /dev/null
+++ b/SKILL.md
@@ -0,0 +1,153 @@
+# axuse — browser & computer use, done right
+
+Accessibility-first browser/computer use over MCP. Works in any MCP-capable
+harness (Codex, Claude Code, OpenCode, Antigravity, …). Zero dependencies.
+
+## The contract (read once, then act)
+
+**Instrument, don't photograph.** The browser is controlled through CDP with
+structured accessibility snapshots. Screenshots are rationed. Coordinates are
+the last resort.
+
+1. **Open → act → read the diff → act.** Every action returns the diff of
+ what changed — you do not need to re-observe after acting. Elements carry
+ their state: `checked`/`unchecked`, `expanded=…`, `selected`, `disabled`,
+ `value="…"`, `haspopup`. Tables print one `row "a | b | c"` line per row.
+2. **Batch, don't drip.** Forms: ONE `ax_fill` with every field (text,
+ `<select>`, checkboxes/radios/switches as true/false, ARIA/native sliders as numbers (trusted Arrow-key convergence, no synthetic writes), custom dropdowns and
+ autocomplete comboboxes by option text) plus `submit` — not one call per
+ field.
+3. **Search, don't scroll-and-read.** `ax_observe {find:"text"}` returns only
+ the matching lines (+context, refs) from the whole page.
+ `ax_scroll {until:"text"}` scrolls an infinite feed / lazy list in ONE call
+ until the text appears and returns just that neighbourhood.
+4. **Refs, not pixels.** Act on `{ref: "e7"}` from the latest observation.
+ Refs are bound to the element and resolved live (after the element's box is
+ stable), so clicks land even if the layout moved.
+5. **Frames and tabs are handled for you.** Cross-origin iframes appear as
+ `--- frame f1 (url) ---` sections with `f1:e3` refs — act on them like any
+ ref. A click that opens a new tab/popup reports it and returns the new
+ tab's snapshot; it becomes the active tab (`tab_id` to go back).
+6. **Dialogs.** An action that opens alert/confirm/prompt says so in its
+ result; answer with `ax_dialog` (accept|dismiss, `prompt_text`). A
+ confirm→prompt chain reports the next dialog after each answer.
+7. **Waiting.** `ax_wait_for {text|selector|expression}` is one bounded
+ in-page wait and returns the diff when the condition holds.
+8. **Pixels only when pixels matter** (canvas, visual checks): the snapshot
+ shows `canvas (box=x,y,WxH)`; take one `ax_screenshot`, then click
+ `{x,y}` in page coordinates (the box tells you where the canvas is).
+9. **App shortcuts follow the OS.** `ax_press {combo:"ctrl+alt+1",
+ platform:true}` translates Windows-convention application shortcuts to
+ the host OS (macOS: cmd+alt+1, cmd+end, …). Omit `platform` for combos
+ that must be literal Control (terminals, devtools). Plain `enter`,
+ `escape`, arrows are identical everywhere; select-all is automatic.
+
+For a bounded source list, use `ax_open_many` with `urls: [...]`. It returns
+compact title/status/excerpt rows and closes its temporary tabs by default;
+reserve repeated `ax_open` calls for pages that need interactive follow-up.
+
+## CAPTCHA solving (only with a loaded solver plugin)
+
+`ax_solve_captcha { provider, url? }` solves a CAPTCHA on the active tab (or
+opens `url` first) using a **loaded solver plugin** — the open core ships none;
+solvers are separate (paid) packages. `ax_plugins` lists what is loaded and any
+that failed to load. Results are facts: `solved`, `token`, `attempts`,
+`rounds`, `elapsedMs`, `notes` — a null token is reported as unsolved, never
+fabricated. Without any solver loaded the call fails typed `NO_SOLVER` with the
+install hint.
+
+Loaded plugins may also contribute **capability tools** (`ax_vault`,
+`ax_net`, `ax_capture`, `ax_guard`, `ax_extract`, …) through a validated
+`tools()` export — capability surfaces, not solves. `ax_plugins` lists each
+loaded package together with its contributed tool names.
+
+## Error vocabulary (typed — read `code`, `hint`, `retry`)
+
+- `REF_NOT_FOUND` / `STALE_STATE` → the page changed under you: `retry:
+ "reobserve"` — call `ax_observe`, then re-plan from fresh refs.
+- `DIALOG_OPEN` → answer with `ax_dialog`, then retry the action.
+- `ELEMENT_HIDDEN` → scroll or re-observe.
+- `SCREENSHOT_BUDGET_EXCEEDED` → crop a region instead.
+- `DESKTOP_PERMISSION_REQUIRED` → grant macOS Accessibility/Screen Recording
+ to the host, then retry after `axuse doctor` confirms the grant.
+- Actions report `action_sent`: `sent` | `possibly_sent` (a timeout after
+ dispatch — verify state before retrying, the input may have landed).
+
+## Desktop apps on macOS — structure-first too
+
+The macOS desktop layer (needs `AXUSE_ENABLE_MACOS_CUA=1` + the
+Accessibility grant) mirrors the browser discipline:
+
+1. **`ax_desktop_windows`** → pick the target app (rows carry pid + bounds;
+ frontmost first).
+2. **`ax_desktop_ax_snapshot {pid|name|front}`** → the app's accessibility
+ tree with roles, titles, values, bounds, and live refs — the desktop twin
+ of `ax_observe`. Budgeted (truncation is reported as facts).
+3. **Act on refs, not pixels**: `ax_desktop_ax_click {ref}` (trusted AXPress;
+ automatic coordinate fallback when an app refuses), `ax_desktop_ax_set
+ {ref, value}` (writable text fields, read-back verified), and
+ `ax_desktop_ax_read {ref}` for fresh facts. Stale refs fail typed
+ `REF_NOT_FOUND` with a reobserve hint — same vocabulary as the browser.
+4. Coordinates + screenshots (`ax_desktop_click`, `ax_desktop_screenshot`)
+ remain the fallback for canvas/games — the same "structure before
+ pixels" rule as the browser side.
+
+## Attach to the real browser (two ways)
+**1. Raw CDP attach.** Relaunch Chrome with `--remote-debugging-port=9222
+--remote-allow-origins=*`, then `ax_open { url, cdp_url: "http://127.0.0.1:9222" }`.
+Full feature set (including OOPIF frame entry).
+
+**2. The axuse bridge extension (Codex-style).** Drive your daily Chrome/Edge
+through an extension — your real profile, cookies and logged-in sessions, with
+the debugger infobar keeping you honestly informed:
+
+```
+axuse setup --browser chrome --harness codex # guided one-time setup
+axuse bridge verify # check the live connection
+axuse bridge install # registers the native messaging host
+axuse bridge # start the hub (or it starts on demand)
+```
+
+Then load `bridge/extension` as an UNPACKED extension in Chrome
+(chrome://extensions → Developer mode → Load unpacked), and
+`ax_open { url, backend: "extension" }`. The service worker dials the hub via
+native messaging; tabs it opens are visible in your browser; `ax_close` closes
+the tabs axuse created — never your browser.
+
+**Extension backend notes (all discovered live):**
+- Branded Chrome 137+ ignores `--load-extension` (silent no-op), so automated
+ installs need Edge / Chromium / Chrome-for-Testing. Loading unpacked by hand
+ works in every browser.
+- Edge's native-messaging host lookup requires `allowed_origins`
+ (`chrome-extension://ID/`) in the host manifest — `allowed_extensions` alone
+ reports "host not found". The installer writes both fields.
+- On macOS, `--browser` may also be `chromium` or `chrome-for-testing`; the
+ installer uses the browser-specific `NativeMessagingHosts` directory.
+- On Windows the native host is a `.bat` launcher (cmd.exe relays the stdio
+ pipes faithfully; a compiled C# shim lost Chrome's stdin writes).
+
+## Desktop (computer use)
+
+`ax_desktop_*` tools exist on **Windows** (SendInput + GDI capture, physical
+pixels — get bounds from `ax_desktop_screen_info`/`ax_desktop_windows`).
+Verified live.
+
+**macOS** ships an opt-in driver (System Events keystroke, corrected
+CoreGraphics mouse/scroll events via JXA, and `screencapture` + `sips` pixels)
+that loads with `AXUSE_ENABLE_MACOS_CUA=1`. It reports TCC permission failures
+as typed desktop errors. Grant the host Accessibility + Screen Recording in
+System Settings → Privacy & Security, then use `node src/cli.js doctor` before
+desktop actions. Coordinates are macOS global display points; desktop JPEGs
+are resized to those point dimensions for direct coordinate mapping.
+
+v1 desktop is coordinate+vision based (no OS accessibility tree): use it only
+for apps the browser tools cannot reach. Prefer `ax_*` for anything web.
+
+## Anti-patterns
+
+- Screenshot loops as the primary observation (the CUA trap — expensive,
+ lossy, coordinate-drifting).
+- Clicking coordinates remembered from BEFORE another action or navigation.
+- Polling with repeated full observations when a `diff` would do.
+- Ignoring `covered: true` notes (an overlay ate the click) — verify in the
+ diff and re-plan.
diff --git a/axuselogo.svg b/axuselogo.svg
new file mode 100644
index 0000000..da6a6be
--- /dev/null
+++ b/axuselogo.svg
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<svg
+ viewBox="59 35 180.66469 129.29295"
+ width="180.66469"
+ height="129.29295"
+ role="img"
+ aria-label="Black double-headed axe symbol"
+ version="1.1"
+ id="svg2"
+ sodipodi:docname="axuselogo.svg"
+ inkscape:version="1.4.4 (dcaf3e7, 2026-05-05)"
+ xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+ xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+ xmlns="http://www.w3.org/2000/svg"
+ xmlns:svg="http://www.w3.org/2000/svg">
+ <defs
+ id="defs2" />
+ <sodipodi:namedview
+ id="namedview2"
+ pagecolor="#ffffff"
+ bordercolor="#000000"
+ borderopacity="0.25"
+ inkscape:showpageshadow="2"
+ inkscape:pageopacity="0.0"
+ inkscape:pagecheckerboard="0"
+ inkscape:deskcolor="#d1d1d1"
+ inkscape:zoom="1.3202743"
+ inkscape:cx="-24.237388"
+ inkscape:cy="-17.041914"
+ inkscape:window-width="1920"
+ inkscape:window-height="991"
+ inkscape:window-x="-9"
+ inkscape:window-y="-9"
+ inkscape:window-maximized="1"
+ inkscape:current-layer="svg2" />
+ <path
+ fill="#000000"
+ fill-rule="evenodd"
+ d="m 86.457262,35.000498 c -14.000005,15 -26.000005,37.999992 -27.000005,54.999992 -3,31.00001 9,57.00001 29.000009,74.00001 2.999987,-19 13.999994,-36 30.999994,-54 l 30,-29.00001 h 1 l 13,13 13,-13 -26,-25.999992 h -2 l -32,30.999992 c -16,-15 -25.000007,-33.999992 -27.999994,-49.999992 z M 83.457257,75.00049 c -5,10 -6,23 -5,33.00001 1,6 3,12 5,16 l 19.000003,-24 z"
+ id="path1" />
+ <path
+ id="path2"
+ d="m 212.45718,35 c -3,13 -10,27.000001 -20,40 l -43,43.99999 -15,-13 -11,11 v 3 l 17,17 v 27.29297 h 19 v -28.29297 l 22,-22 c 17,13 29,31 31,50 22,-22 32,-52.99999 25,-84.99999 -3,-13 -14,-32 -25,-44 z m 3,40 c 5,11 6,22.99998 5,32.99999 0,6 -2,12 -5,16 l -19,-24 z" />
+</svg>
diff --git a/bench/fixture-server.mjs b/bench/fixture-server.mjs
new file mode 100644
index 0000000..ab487ac
--- /dev/null
+++ b/bench/fixture-server.mjs
@@ -0,0 +1,258 @@
+/**
+ * axuse head-to-head benchmark — fixture server.
+ *
+ * Deterministic, per-run-seeded task pages. Every state change POSTs to this
+ * server, so task success is scored against SERVER-SIDE ground truth, not
+ * the model's self-report. Two listeners on different origins (127.0.0.1 and
+ * localhost) so T5 can host a genuine cross-origin iframe (OOPIF).
+ */
+import http from "node:http";
+import { once } from "node:events";
+
+// -------- seeded RNG (deterministic per run id) --------
+function hash(s) {
+ let h = 2166136261;
+ for (let i = 0; i < s.length; i++) {
+ h ^= s.charCodeAt(i);
+ h = Math.imul(h, 16777619);
+ }
+ return h >>> 0;
+}
+function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+const rng = (run) => mulberry32(hash(run));
+const letters = "ABCDEFGHJKLMNPQRSTUVWXYZ";
+const digits = "23456789";
+const pick = (r, alphabet, n) => Array.from({ length: n }, () => alphabet[Math.floor(r() * alphabet.length)]).join("");
+
+const state = new Map(); // run → ground truth
+function ground(run) {
+ if (!state.has(run)) {
+ const r = rng(run);
+ const colors = ["Red", "Green", "Blue"];
+ const targetColor = colors[Math.floor(r() * 3)];
+ const t3rows = Array.from({ length: 150 }, (_, i) => ({
+ sku: `SKU-${1000 + i}`,
+ product: `Widget ${pick(r, letters, 2)}-${pick(r, digits, 3)}`,
+ price: (2 + r() * 480).toFixed(2),
+ stock: Math.floor(r() * 90) + 1,
+ }));
+ // Ensure a unique target product name.
+ const targetRow = t3rows[Math.floor(r() * t3rows.length)];
+ targetRow.product = `Widget TARGET-${pick(r, letters, 3)}`;
+ state.set(run, {
+ t1: { code: pick(r, letters, 3) + pick(r, digits, 3), claimed: false },
+ t2: { valid: false, confirmation: null, name: null, email: null, plan: null },
+ t3: { rows: t3rows, target: targetRow },
+ t4: {
+ color: targetColor, number: String(Math.floor(100 + r() * 900)),
+ word: pick(r, letters, 5), token: pick(r, letters, 4) + pick(r, digits, 4),
+ step: 0, wrong: 0,
+ },
+ t5: { code: pick(r, letters, 3) + pick(r, digits, 3), clicked: false },
+ });
+ }
+ return state.get(run);
+}
+
+const page = (title, body) => `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title>
+<style>body{font-family:system-ui,sans-serif;max-width:880px;margin:24px auto;padding:0 16px}
+table{border-collapse:collapse}td,th{border:1px solid #ccc;padding:4px 10px;font-size:14px}
+button{padding:6px 14px;margin:4px}input,select{margin:4px}</style></head><body>${body}</body></html>`;
+
+const api = (res, obj) => { res.setHeader("content-type", "application/json"); res.end(JSON.stringify(obj)); };
+
+/**
+ * Browser-only gate for scored action endpoints: browsers always send
+ * Origin (on POST) and Sec-Fetch-* headers; curl/Invoke-WebRequest/node
+ * fetch-by-default do not. Kills the lazy shell-shortcut path so the
+ * benchmark measures the BROWSER tool layers.
+ */
+function browserOnly(req, res, allowedHost) {
+ const origin = String(req.headers.origin ?? "");
+ const sec = req.headers["sec-fetch-site"];
+ const originOk = origin.includes(allowedHost);
+ const secOk = sec !== undefined && sec !== "none";
+ if (!originOk && !secOk) {
+ res.statusCode = 403;
+ return api(res, { error: "browser-only endpoint: complete this action in a real browser" }), false;
+ }
+ return true;
+}
+
+function makeServer(origin /* "parent" | "child" */) {
+ return http.createServer((req, res) => {
+ const u = new URL(req.url, "http://x");
+ const run = u.searchParams.get("run") ?? "";
+ if (!run) return api(res, { error: "missing run" });
+ const g = ground(run);
+
+ if (origin === "parent") {
+ const host = "127.0.0.1";
+ if (u.pathname === "/t1") {
+ return res.end(page("claim", `
+<h1>Claim your code</h1>
+<p>Press the button to reveal your personal code.</p>
+<button id="claim" onclick="fetch('/api/t1/claim?run=${run}',{method:'POST'}).then(r=>r.json()).then(d=>document.getElementById('out').textContent='code: '+d.code)">Claim code</button>
+<div id="out" style="min-height:1em;font-size:20px"></div>`));
+ }
+ if (u.pathname === "/api/t1/claim" && req.method === "POST") {
+ if (!browserOnly(req, res, host)) return;
+ g.t1.claimed = true;
+ return api(res, { code: g.t1.code });
+ }
+ if (u.pathname === "/t2") {
+ return res.end(page("form", `
+<h1>Create account</h1>
+<form onsubmit="event.preventDefault();fetch('/api/t2/submit?run=${run}',{method:'POST',body:JSON.stringify({name:f1.value,email:f2.value,plan:sel.value,agree:cb.checked})}).then(r=>r.json()).then(d=>document.getElementById('out').textContent=d.ok?('confirmation: '+d.confirmation):('error: '+d.error))">
+<label for="f1">Full name</label><input id="f1"><br>
+<label for="f2">Email</label><input id="f2" type="email"><br>
+<label for="sel">Plan</label><select id="sel"><option value="">—</option><option>Alpha</option><option>Beta</option><option>Gamma</option></select><br>
+<input type="checkbox" id="cb"><label for="cb">I agree</label><br>
+<button type="submit">Submit</button>
+</form><div id="out" style="min-height:1em"></div>`));
+ }
+ if (u.pathname === "/api/t2/submit" && req.method === "POST") {
+ if (!browserOnly(req, res, host)) return;
+ let b = "";
+ req.on("data", (d) => (b += d));
+ req.on("end", () => {
+ const v = JSON.parse(b || "{}");
+ g.t2.name = v.name; g.t2.email = v.email; g.t2.plan = v.plan;
+ const ok = v.name && String(v.email).includes("@") && v.plan && v.agree === true;
+ g.t2.valid = !!ok;
+ if (ok) g.t2.confirmation = "CNF-" + hash(run + "t2").toString(36).toUpperCase().slice(0, 8);
+ return api(res, ok ? { ok: true, confirmation: g.t2.confirmation } : { ok: false, error: "invalid form" });
+ });
+ return;
+ }
+ if (u.pathname === "/t3") {
+ const rows = g.t3.rows.map((r) => `<tr><td>${r.sku}</td><td>${r.product}</td><td>${r.price}</td><td>${r.stock}</td></tr>`).join("");
+ return res.end(page("catalog", `
+<h1>Catalog</h1><p>150 products. Find yours.</p>
+<table><thead><tr><th>SKU</th><th>Product</th><th>Price ($)</th><th>Stock</th></tr></thead><tbody>${rows}</tbody></table>`));
+ }
+ if (u.pathname === "/t4") {
+ return res.end(page("wizard", `
+<h1>Setup wizard</h1>
+<div id="app">loading…</div>
+<script>
+const RUN=${JSON.stringify(run)};
+async function step(){
+ const r=await fetch('/api/t4/state?run='+RUN).then(r=>r.json());
+ const app=document.getElementById('app');
+ if(r.done){app.innerHTML='<p>final token: <b>'+r.token+'</b></p>';return;}
+ if(r.step===0){app.innerHTML='<p>Step 1 — pick a color:</p>'+r.options.map(o=>'<button data-c="'+o+'" onclick="pick(\\''+o+'\\')">'+o+'</button>').join('');}
+ else if(r.step===1){app.innerHTML='<p>Step 2 — enter the displayed number:</p><p>number: <b>'+r.number+'</b></p><input id="num"><button onclick="num()">Verify</button><p id="err"></p>';}
+ else if(r.step===2){app.innerHTML='<p>Step 3 — click the word:</p>'+r.decoys.map(o=>'<button data-w="'+o+'" onclick="word(\\''+o+'\\')">'+o+'</button>').join('');}
+ else if(r.step===3){app.innerHTML='<p>Step 4 — finish:</p><button onclick="finish()">Finish</button>';}
+}
+async function pick(c){const r=await fetch('/api/t4/pick?run='+RUN,{method:'POST',body:JSON.stringify({c})}).then(r=>r.json());if(!r.ok){document.getElementById('app').insertAdjacentHTML('afterbegin','<p style="color:red">wrong choice</p>');}step();}
+async function num(){const r=await fetch('/api/t4/num?run='+RUN,{method:'POST',body:JSON.stringify({n:document.getElementById('num').value})}).then(r=>r.json());if(!r.ok){document.getElementById('err').textContent='wrong number';}step();}
+async function word(w){const r=await fetch('/api/t4/word?run='+RUN,{method:'POST',body:JSON.stringify({w})}).then(r=>r.json());if(!r.ok){document.getElementById('app').insertAdjacentHTML('afterbegin','<p style="color:red">wrong word</p>');}step();}
+async function finish(){await fetch('/api/t4/finish?run='+RUN,{method:'POST'});step();}
+step();
+</script>`));
+ }
+ if (u.pathname === "/api/t4/state") {
+ return api(res, { step: g.t4.step, done: g.t4.step >= 4, token: g.t4.step >= 4 ? g.t4.token : null,
+ number: g.t4.step === 1 ? g.t4.number : null,
+ options: ["Red", "Green", "Blue"],
+ decoys: g.t4.step === 2 ? [g.t4.word, ...[g.t4.word + "X", "X" + g.t4.word, g.t4.word.toLowerCase()].slice(0, 2)] : [] });
+ }
+ if (u.pathname === "/api/t4/pick" && req.method === "POST") {
+ if (!browserOnly(req, res, host)) return;
+ let b = ""; req.on("data", (d) => (b += d)); req.on("end", () => {
+ const v = JSON.parse(b || "{}");
+ const ok = v.c === g.t4.color;
+ if (ok) g.t4.step = 1; else g.t4.wrong++;
+ api(res, { ok });
+ });
+ return;
+ }
+ if (u.pathname === "/api/t4/num" && req.method === "POST") {
+ if (!browserOnly(req, res, host)) return;
+ let b = ""; req.on("data", (d) => (b += d)); req.on("end", () => {
+ const v = JSON.parse(b || "{}");
+ const ok = String(v.n).trim() === g.t4.number;
+ if (ok) g.t4.step = 2; else g.t4.wrong++;
+ api(res, { ok });
+ });
+ return;
+ }
+ if (u.pathname === "/api/t4/word" && req.method === "POST") {
+ if (!browserOnly(req, res, host)) return;
+ let b = ""; req.on("data", (d) => (b += d)); req.on("end", () => {
+ const v = JSON.parse(b || "{}");
+ const ok = v.w === g.t4.word;
+ if (ok) g.t4.step = 3; else g.t4.wrong++;
+ api(res, { ok });
+ });
+ return;
+ }
+ if (u.pathname === "/api/t4/finish" && req.method === "POST") {
+ if (!browserOnly(req, res, host)) return;
+ if (g.t4.step === 3) g.t4.step = 4;
+ return api(res, { ok: true });
+ }
+ if (u.pathname === "/t5") {
+ return res.end(page("host", `
+<h1>Host page</h1>
+<p>The details live in the embedded panel below.</p>
+<iframe src="${CHILD_BASE}/t5child?run=${run}" style="width:420px;height:180px;border:1px solid #ccc"></iframe>`));
+ }
+ if (u.pathname === "/api/state") {
+ return api(res, {
+ t1: { code: g.t1.code, claimed: g.t1.claimed },
+ t2: { valid: g.t2.valid, confirmation: g.t2.confirmation },
+ t3: { target: g.t3.target.product, price: g.t3.target.price, stock: g.t3.target.stock },
+ t4: { step: g.t4.step, token: g.t4.token, wrong: g.t4.wrong, color: g.t4.color, number: g.t4.number, word: g.t4.word },
+ t5: { code: g.t5.code, clicked: g.t5.clicked },
+ });
+ }
+ }
+
+ if (origin === "child") {
+ const childHost = new URL(CHILD_BASE).host;
+ if (u.pathname === "/t5child") {
+ return res.end(page("panel", `
+<h2>Secure panel</h2>
+<button id="rev" onclick="fetch('${CHILD_BASE}/api/t5/reveal?run=${run}',{method:'POST'}).then(r=>r.json()).then(d=>document.getElementById('out').textContent='code: '+d.code)">Reveal code</button>
+<div id="out" style="min-height:1em"></div>`));
+ }
+ if (u.pathname === "/api/t5/reveal" && req.method === "POST") {
+ if (!browserOnly(req, res, childHost)) return;
+ g.t5.clicked = true;
+ return api(res, { code: g.t5.code });
+ }
+ }
+
+ res.statusCode = 404;
+ res.end("nope");
+ });
+}
+
+let CHILD_BASE = "";
+
+/** Start both origins; returns bases + close(). */
+export async function startFixtures() {
+ const child = makeServer("child");
+ child.listen(0, "localhost");
+ await once(child, "listening");
+ CHILD_BASE = `http://localhost:${child.address().port}`;
+ const parent = makeServer("parent");
+ parent.listen(0, "127.0.0.1");
+ await once(parent, "listening");
+ const parentBase = `http://127.0.0.1:${parent.address().port}`;
+ return {
+ parentBase,
+ childBase: CHILD_BASE,
+ close: () => { child.close(); parent.close(); },
+ };
+}
diff --git a/bench/macos-hotpaths.mjs b/bench/macos-hotpaths.mjs
new file mode 100644
index 0000000..94c7f54
--- /dev/null
+++ b/bench/macos-hotpaths.mjs
@@ -0,0 +1,138 @@
+#!/usr/bin/env node
+/**
+ * macOS hot-path benchmarks (safe by construction):
+ *
+ * - osascript spawn baseline (JXA "1+1") → per-action floor
+ * - screen_info / permissions probe: cold vs cached → cache win (spawns)
+ * - native input script build + spawn budget (MOCKED runFn — never posts)
+ * - CDP: browser launch→ws, observe, click, type → browser hot paths
+ * - browser screenshot (JPEG, budgeted) → pixel path
+ * - bridge hub start/stop + info write → bridge startup
+ * - ephemeral profile create/delete round-trip → cleanup cost
+ * - 24-way concurrent CDP Runtime.evaluate → concurrency
+ *
+ * Nothing here moves real input or captures the screen: native-input rows
+ * measure protocol cost through an injected runFn, and pixel capture goes
+ * through the PAGE (Page.captureScreenshot), not the desktop TCC path.
+ *
+ * Usage: node bench/macos-hotpaths.mjs [--json out.json]
+ */
+import { mkdtempSync, rmSync, statSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { execFile } from "node:child_process";
+
+const { Controller } = await import("../src/core/controller.js");
+const { BrowserHandle } = await import("../src/core/cdp.js");
+const { BridgeHub } = await import("../src/bridge/hub.js");
+
+const results = {};
+const jsonOut = process.argv.includes("--json") ? process.argv[process.argv.indexOf("--json") + 1] : null;
+
+function record(name, ms, facts = {}) {
+ results[name] = { ms: Math.round(ms * 10) / 10, ...facts };
+ console.log(`${name.padEnd(48)} ${String(Math.round(ms)).padStart(7)} ms ${Object.entries(facts).map(([k, v]) => `${k}=${v}`).join(" ")}`);
+}
+
+const time = async (fn) => {
+ const t0 = performance.now();
+ await fn();
+ return performance.now() - t0;
+};
+
+// ---------------------------------------------------------------- baseline
+const spawnOnce = (file, args) => new Promise((ok, err) => execFile(file, args, { timeout: 15_000 }, (e, o) => (e ? err(e) : ok(o))));
+
+if (process.platform === "darwin") {
+ const spawnFlavor = async (args, warm = true) => {
+ if (warm) await spawnOnce("osascript", args);
+ const t = await time(async () => { for (let i = 0; i < 10; i++) await spawnOnce("osascript", args); });
+ return t / 10;
+ };
+ const jxaNoop = await spawnFlavor(["-l", "JavaScript", "-e", "1+1"]);
+ record("osascript flavor: JXA noop", jxaNoop, { perSpawnMs: Math.round(jxaNoop * 10) / 10 });
+ const jxaCg = await spawnFlavor(["-l", "JavaScript", "-e", "ObjC.import('CoreGraphics'); 1+1"]);
+ record("osascript flavor: JXA + CoreGraphics", jxaCg, { perSpawnMs: Math.round(jxaCg * 10) / 10, note: "the real per-gesture floor" });
+ const asNoop = await spawnFlavor(["-e", "return 1"]);
+ record("osascript flavor: AppleScript noop", asNoop, { perSpawnMs: Math.round(asNoop * 10) / 10 });
+
+ const { MacDriver } = await import("../src/desktop/macos.js");
+ const d = new MacDriver();
+ const coldInfo = await time(() => d.screenInfo({ refresh: true }));
+ record("desktop screen_info probe (cold)", coldInfo);
+ const warmInfo = await time(() => d.screenInfo());
+ record("desktop screen_info (cached)", warmInfo, { savedMs: Math.round((coldInfo - warmInfo) * 10) / 10 });
+ const coldPerm = await time(() => d.permissions({ refresh: true }));
+ record("desktop permissions probe (cold)", coldPerm);
+ const warmPerm = await time(() => d.permissions());
+ record("desktop permissions (cached)", warmPerm, { savedMs: Math.round((coldPerm - warmPerm) * 10) / 10 });
+
+ // Protocol cost of native input WITHOUT posting: script build + a runFn
+ // with realistic execFile latency (measured noop). This is the floor a
+ // click/drag pays per gesture batch.
+ const noop = async () => "ok";
+ const dMock = new MacDriver({ runFn: noop });
+ const clickBuild = await time(() => dMock.click({ x: 10, y: 10 }));
+ record("native click: 1 gesture batch (mocked post)", clickBuild, { batches: 1 });
+ const dblBuild = await time(() => dMock.click({ x: 10, y: 10, double: true }));
+ record("native double-click: 1 gesture batch (mocked post)", dblBuild, { batches: 1 });
+ const dragBuild = await time(() => dMock.drag({ from: { x: 0, y: 0 }, to: { x: 100, y: 100 }, steps: 12 }));
+ record("native drag: 3 gesture batches (mocked post)", dragBuild, { batches: 3 });
+}
+
+// ---------------------------------------------------------------- browser
+const page = `data:text/html,<!doctype html><html><body>
+ <button id="b" onclick="this.textContent='clicked'">go</button>
+ <input id="i" value="">
+ <p>${"x".repeat(2000)}</p></body></html>`;
+
+let browser, controller;
+const launchMs = await time(async () => {
+ browser = await BrowserHandle.launch({ headless: true });
+});
+record("BrowserHandle.launch → ws connect", launchMs);
+
+const disposeMs = await time(async () => { await browser.dispose(); });
+record("BrowserHandle.dispose (ephemeral profile cleanup)", disposeMs);
+
+controller = new Controller();
+await controller.execute("open", { url: page, settle_ms: 200 });
+
+const obsMs = await time(() => controller.execute("observe", { mode: "diff" }));
+record("CDP observe (diff)", obsMs);
+
+const clickMs = await time(async () => { await controller.execute("click", { target: { ref: "e1" }, settle_ms: 50 }); });
+record("CDP click ref + diff", clickMs);
+
+const typeMs = await time(async () => { await controller.execute("type", { target: { ref: "e2" }, text: "hello world", settle_ms: 50 }); });
+record("CDP type + diff", typeMs);
+
+const shotMs = await time(() => controller.execute("screenshot", {}));
+record("browser screenshot (JPEG budgeted)", shotMs);
+
+// Concurrency: 24 parallel evaluates over one connection.
+const concMs = await time(async () => {
+ await Promise.all(Array.from({ length: 24 }, (_, i) => controller.execute("evaluate", { expression: `${i} * 2` })));
+});
+record("24-way concurrent CDP evaluate", concMs, { perCallMs: Math.round(concMs / 24 * 10) / 10 });
+
+await controller.dispose();
+
+// ---------------------------------------------------------------- bridge
+const AXUSE_BRIDGE_DIR_BACKUP = process.env.AXUSE_BRIDGE_DIR;
+const bridgeDir = mkdtempSync(join(tmpdir(), "axuse-bench-bridge-"));
+process.env.AXUSE_BRIDGE_DIR = bridgeDir;
+let hub;
+const hubMs = await time(async () => { hub = await new BridgeHub().start(); });
+const infoSt = statSync(join(bridgeDir, "bridge.json"));
+record("bridge hub start (listen + token file)", hubMs, { mode: (infoSt.mode & 0o777).toString(8) });
+const hubStopMs = await time(() => { hub.stop(); });
+record("bridge hub stop", hubStopMs);
+process.env.AXUSE_BRIDGE_DIR = AXUSE_BRIDGE_DIR_BACKUP;
+rmSync(bridgeDir, { recursive: true, force: true });
+
+console.log("\nplatform:", process.platform, process.arch, `node ${process.version}`);
+if (jsonOut) {
+ writeFileSync(jsonOut, JSON.stringify({ ts: new Date().toISOString(), platform: `${process.platform}/${process.arch}`, node: process.version, results }, null, 2));
+ console.log(`wrote ${jsonOut}`);
+}
diff --git a/bench/micro.mjs b/bench/micro.mjs
new file mode 100644
index 0000000..41a34e1
--- /dev/null
+++ b/bench/micro.mjs
@@ -0,0 +1,98 @@
+/**
+ * axuse micro-benchmark — real numbers for the comparison:
+ * - observation cost: full snapshot chars/tokens, latency
+ * - diff cost after an action: chars/tokens, latency
+ * - action round trip latency (observe→act→diff)
+ * - screenshot budget reality (bytes for a viewport on a real page)
+ * Tokens estimated at ~4 chars/token for text; images at ~1.3k-1.6k tokens
+ * for a 1280x720-class JPEG plus vision-encoder prefill latency (not
+ * measurable here, so reported as bytes + the standard estimate range).
+ */
+import http from "node:http";
+import { once } from "node:events";
+import { Controller } from "../src/core/controller.js";
+import { locateBrowser } from "../src/core/cdp.js";
+
+const hasBrowser = !!locateBrowser();
+
+// A page with a realistic amount of UI structure (50-ish interactive elements).
+const n = 12;
+let html = `<!doctype html><html><head><title>bench</title></head><body>
+<h1>Bench page</h1>`;
+for (let i = 0; i < n; i++) {
+ html += `
+<nav><a href="#s${i}">link ${i}</a></nav>
+<section>
+ <form>
+ <label for="f${i}">Field ${i}</label>
+ <input id="f${i}" placeholder="type here" />
+ <select id="s${i}"><option value="a">Alpha</option><option value="b">Beta</option></select>
+ <button type="button" id="b${i}" onclick="document.getElementById('o${i}').textContent='done ${i}'">Go ${i}</button>
+ <div id="o${i}" style="min-height:1em"></div>
+ </form>
+</section>`;
+}
+html += `</body></html>`;
+
+const srv = http.createServer((q, r) => { r.setHeader("content-type", "text/html"); r.end(html); });
+srv.listen(0, "127.0.0.1");
+await once(srv, "listening");
+const url = `http://127.0.0.1:${srv.address().port}/`;
+
+const c = new Controller();
+
+// Cold start: browser launch + first observation.
+let t0 = Date.now();
+const opened = await c.execute("open", { url, headless: true, settle_ms: 100 });
+const openMs = Date.now() - t0;
+const full = opened.observation.text;
+const fullChars = full.length;
+const estTokens = Math.ceil(fullChars / 4);
+
+// Warm observation (diff mode with no changes).
+t0 = Date.now();
+const obs1 = await c.execute("observe", { mode: "diff" });
+const warmDiffMs = Date.now() - t0;
+
+// Warm full observation.
+t0 = Date.now();
+const obs2 = await c.execute("observe", { mode: "full" });
+const warmFullMs = Date.now() - t0;
+const warmFullChars = obs2.observation.text.length;
+
+// Action round trip: click → auto-diff returns.
+const ref = full.match(/button "Go 3"[^\[]*\[ref=(e\d+)\]/)[1];
+t0 = Date.now();
+const clicked = await c.execute("click", { target: { ref }, settle_ms: 120 });
+const actMs = Date.now() - t0;
+const diffChars = (clicked.observation?.text ?? "").length;
+const diffTokens = Math.ceil(diffChars / 4);
+const diffSawChange = /done 3/.test(clicked.observation?.text ?? "");
+
+// Screenshot reality check (what a vision-loop step would cost instead).
+t0 = Date.now();
+const shot = await c.execute("screenshot", {});
+const shotMs = Date.now() - t0;
+const shotBytes = shot.image.bytes;
+
+// Typing round trip.
+const fieldRef = full.match(/textbox "Field 3"[^\[]*\[ref=(e\d+)\]/)[1];
+t0 = Date.now();
+const typed = await c.execute("type", { target: { ref: fieldRef }, text: "hello world", settle_ms: 120 });
+const typeMs = Date.now() - t0;
+
+await c.execute("close", { browser: true });
+srv.close();
+
+const fmt = (ms) => `${ms}ms`;
+console.log(JSON.stringify({
+ page: { interactive_elements: n * 3 + n, sections: n },
+ cold_open_launch_plus_first_full_observation: fmt(openMs),
+ first_full_snapshot: { chars: fullChars, est_tokens: estTokens },
+ warm_full_observation: { latency: fmt(warmFullMs), chars: warmFullChars },
+ warm_diff_observation_no_change: { latency: fmt(warmDiffMs), text: obs1.observation.text.slice(0, 60) },
+ click_to_diff_round_trip: { latency: fmt(actMs), diff_chars: diffChars, diff_est_tokens: diffTokens, diff_saw_change: diffSawChange },
+ type_to_diff_round_trip: { latency: fmt(typeMs), diff_chars: (typed.observation?.text ?? "").length },
+ screenshot_for_comparison: { latency: fmt(shotMs), jpeg_bytes: shotBytes, est_image_tokens: "≈1.1k-1.6k + vision-encoder prefill per step (a vision loop pays this EVERY step)" },
+}, null, 2));
+process.exit(0);
diff --git a/bench/run-head-to-head.mjs b/bench/run-head-to-head.mjs
new file mode 100644
index 0000000..d90c355
--- /dev/null
+++ b/bench/run-head-to-head.mjs
@@ -0,0 +1,291 @@
+/**
+ * axuse head-to-head benchmark runner.
+ *
+ * Fair design: SAME model (gpt-5.6-luna, reasoning pinned), SAME tasks,
+ * SAME machine — the only variable is the browser tool layer:
+ * - arm "codex": Codex's native browser tools (your real Chrome, via the
+ * installed Codex extension)
+ * - arm "axuse": axuse MCP tools (own headless Chromium), registered via
+ * `codex exec -c mcp_servers.axuse...` overrides
+ *
+ * Success is scored against SERVER-SIDE ground truth (every state change in
+ * the fixture pages POSTs to the server), not the model's self-report.
+ * Metrics come from the codex session JSONL: token_usage_record (thread
+ * totals), function_call / outputs (per-tool payload sizes), task_complete.
+ *
+ * Usage: node bench/run-head-to-head.mjs [--tasks t1,t2,t3,t4,t5]
+ * [--arms codex,axuse] [--reps 3]
+ */
+import { spawn } from "node:child_process";
+import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { homedir } from "node:os";
+import { fileURLToPath } from "node:url";
+import { startFixtures } from "./fixture-server.mjs";
+
+const AXUSE_DIR = process.env.AXBENCH_AXUSE_DIR ?? join(dirname(fileURLToPath(import.meta.url)), "..", "..");
+const CLI_ABS = `${AXUSE_DIR}/src/cli.js`.replaceAll("\\", "/");
+const SESSIONS_ROOT = join(homedir(), ".codex", "sessions");
+const MODEL = "gpt-5.6-luna";
+const EFFORT = "medium"; // pinned for BOTH arms; falls back silently if rejected
+const RUN_TIMEOUT_MS = 300_000;
+
+// ---------------- CLI args ----------------
+const arg = (name) => {
+ const i = process.argv.indexOf(name);
+ return i >= 0 ? process.argv[i + 1] : undefined;
+};
+const TASKS = (arg("--tasks") ?? "t1,t2,t3,t4,t5").split(",");
+const ARMS = (arg("--arms") ?? "codex,axuse").split(",");
+const REPS = Number(arg("--reps") ?? 3);
+
+// ---------------- task definitions ----------------
+const tasks = {
+ t1: {
+ prompt: (bases, run) => `Open the URL ${bases.parentBase}/t1?run=${run} in the browser. Click the button labeled "Claim code". Then report the 6-character code that appears on the page. Respond with ONLY the code, nothing else.`,
+ score: (truth, msg) => truth.t1.claimed && msg.includes(truth.t1.code),
+ },
+ t2: {
+ prompt: (bases, run) => `Open the URL ${bases.parentBase}/t2?run=${run} in the browser. Fill the form exactly like this: Full name = "Ada Lovelace", Email = "[email protected]", Plan = "Beta", check the "I agree" checkbox, then click the Submit button. Report the confirmation ID that appears. Respond with ONLY the confirmation ID, nothing else.`,
+ score: (truth, msg) => truth.t2.valid && msg.includes(truth.t2.confirmation ?? "___"),
+ },
+ t3: {
+ prompt: (bases, run) => `Open the URL ${bases.parentBase}/t3?run=${run} in the browser. It is a catalog table of 150 products. Find the product whose name starts with "Widget TARGET-". Report its price and stock exactly as shown, in the format PRICE|STOCK (for example 123.45|67). Respond with ONLY that, nothing else.`,
+ score: (truth, msg) => msg.includes(truth.t3.price) && msg.includes(truth.t3.stock),
+ },
+ t4: {
+ prompt: (bases, run) => `Open the URL ${bases.parentBase}/t4?run=${run} in the browser. It is a multi-step wizard. The wizard validates each step server-side: a wrong choice shows an error and does NOT advance — find the correct choice and proceed. Complete every step until the wizard displays a final token. Report ONLY the final token, nothing else.`,
+ score: (truth, msg) => truth.t4.step >= 4 && msg.includes(truth.t4.token),
+ },
+ t5: {
+ prompt: (bases, run) => `Open the URL ${bases.parentBase}/t5?run=${run} in the browser. The page embeds a cross-origin iframe containing a "Secure panel". Click the button labeled "Reveal code" INSIDE that iframe. Report the 6-character code that appears. Respond with ONLY the code, nothing else.`,
+ score: (truth, msg) => truth.t5.clicked && msg.includes(truth.t5.code),
+ },
+};
+
+// ---------------- codex session log parsing ----------------
+function snapshotSessionFiles() {
+ const files = [];
+ const walk = (dir) => {
+ let entries;
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
+ for (const e of entries) {
+ const p = join(dir, e.name);
+ if (e.isDirectory()) walk(p);
+ else if (e.name.endsWith(".jsonl")) files.push(p);
+ }
+ };
+ walk(SESSIONS_ROOT);
+ return new Set(files);
+}
+
+function newestSessionFile(since) {
+ const files = [];
+ const walk = (dir) => {
+ let entries;
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
+ for (const e of entries) {
+ const p = join(dir, e.name);
+ if (e.isDirectory()) walk(p);
+ else if (e.name.endsWith(".jsonl")) {
+ const st = statSync(p);
+ if (st.mtimeMs >= since - 2000) files.push({ p, m: st.mtimeMs });
+ }
+ }
+ };
+ walk(SESSIONS_ROOT);
+ files.sort((a, b) => b.m - a.m);
+ return files[0]?.p ?? null;
+}
+
+function outputText(p) {
+ const o = p.output;
+ if (typeof o === "string") return o;
+ if (Array.isArray(o)) return o.map((x) => x.text ?? "").join("");
+ return "";
+}
+
+function parseSession(file) {
+ const calls = []; // {name, argsChars, outChars, argsSnippet}
+ const byCall = new Map();
+ let threadTokens = null;
+ let turns = 0;
+ let finalMsg = "";
+ for (const line of readFileSync(file, "utf8").split("\n")) {
+ if (!line.trim()) continue;
+ let o;
+ try { o = JSON.parse(line); } catch { continue; }
+ const p = o.payload ?? {};
+ if (o.type === "response_item") {
+ if (p.type === "function_call" || p.type === "custom_tool_call") {
+ const args = p.arguments ?? p.input ?? "";
+ const rec = { name: p.name, argsChars: args.length, outChars: 0, argsSnippet: String(args).slice(0, 400) };
+ byCall.set(p.call_id, rec);
+ calls.push(rec);
+ } else if (p.type === "function_call_output" || p.type === "custom_tool_call_output") {
+ const rec = byCall.get(p.call_id);
+ if (rec) rec.outChars = outputText(p).length;
+ }
+ } else if (o.type === "token_usage_record") {
+ turns++;
+ if (p.thread_token_usage) threadTokens = p.thread_token_usage;
+ } else if (o.type === "event_msg" && p.type === "task_complete") {
+ finalMsg = p.last_agent_message ?? "";
+ }
+ }
+ return { calls, turns, threadTokens, finalMsg };
+}
+
+// ---------------- one codex run ----------------
+function runCodex(arm, prompt) {
+ return new Promise((resolve) => {
+ // axuse is registered persistently (`codex mcp add axuse -- node cli.js mcp`).
+ const args = [
+ "exec", "-s", "danger-full-access", "--skip-git-repo-check",
+ "-m", MODEL, "-c", `model_reasoning_effort="${EFFORT}"`,
+ prompt,
+ ];
+ const t0 = Date.now();
+ const child = spawn("codex", args, {
+ cwd: AXUSE_DIR,
+ env: { ...process.env, ...(arm === "axuse" ? { AXUSE_HEADLESS: "1" } : {}) },
+ shell: false,
+ // stdin IGNORED: an open-but-never-closed pipe makes `codex exec`
+ // block waiting for stdin EOF (it detects piped stdin).
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (d) => (stdout += d));
+ child.stderr.on("data", (d) => (stderr += d));
+ const timer = setTimeout(() => {
+ try { child.kill(); } catch {}
+ resolve({ timedOut: true, wallMs: Date.now() - t0, stdout, stderr });
+ }, RUN_TIMEOUT_MS);
+ child.on("error", (e) => {
+ clearTimeout(timer);
+ resolve({ code: `spawn-error: ${e.message}`, wallMs: Date.now() - t0, stdout, stderr, timedOut: false });
+ });
+ child.on("exit", (code) => {
+ clearTimeout(timer);
+ resolve({ code, wallMs: Date.now() - t0, stdout, stderr, timedOut: false });
+ });
+ });
+}
+
+const armDirective = {
+ codex:
+ "You have browser tools available through Codex (they control the user's real Chrome browser). " +
+ "Do ALL page interaction in the browser. " +
+ "Do NOT use curl, wget, Invoke-WebRequest, fetch, node, python, or any HTTP client to interact with the task pages — " +
+ "the task endpoints reject non-browser requests. Complete the task entirely in the browser.\n\n",
+ axuse:
+ "You have ax_* MCP tools for browser control (they launch their own headless Chromium automatically — ax_open creates the tab). " +
+ "Use the ax_* tools EXCLUSIVELY for all page interaction. " +
+ "Do NOT use curl, wget, Invoke-WebRequest, fetch, node, python, or any HTTP client, and do not use any other browser tool — " +
+ "the task endpoints reject non-browser requests. Complete the task entirely in the browser with ax_* tools.\n\n",
+};
+
+/** Browser-tool-use evidence in a session (legitimacy check). */
+function browserEvidence(calls) {
+ const ax = calls.filter((c) => /^ax_/.test(c.name));
+ if (ax.length) return { used: true, via: `ax tools (${ax.length})` };
+ const kernel = calls.filter((c) =>
+ (c.name === "js" || c.name === "exec") &&
+ /browser|tab|navigate|page|agent\.browsers|axuse|\.claim|iframe|click|observe|snapshot/i.test(c.argsSnippet));
+ if (kernel.length) return { used: true, via: `browser SDK in ${kernel[0].name} (${kernel.length})` };
+ return { used: false, via: "no browser-tool evidence" };
+}
+
+async function main() {
+ const bases = await startFixtures();
+ console.log(`fixtures: parent=${bases.parentBase} child=${bases.childBase}`);
+ console.log(`model=${MODEL} effort=${EFFORT} tasks=${TASKS} arms=${ARMS} reps=${REPS}`);
+
+ const results = [];
+ const fetchTruth = async (run) =>
+ (await fetch(`${bases.parentBase}/api/state?run=${run}`).then((r) => r.json()));
+
+ for (let rep = 1; rep <= REPS; rep++) {
+ const order = rep % 2 === 1 ? [...ARMS] : [...ARMS].reverse();
+ for (const task of TASKS) {
+ if (task === "t5" && rep > 1) continue; // capability probe: 1 rep
+ for (const arm of order) {
+ const run = `${task}-${arm}-${rep}-${Date.now().toString(36)}${Math.floor(Math.random() * 1e4).toString(36)}`;
+ const prompt = armDirective[arm] + tasks[task].prompt(bases, run);
+ const since = Date.now();
+ process.stdout.write(`run ${run} … `);
+ const r = await runCodex(arm, prompt);
+
+ // ground truth AFTER the attempt (server observed the real behavior)
+ const truth = await fetchTruth(run);
+ const sessionFile = newestSessionFile(since);
+ const parsed = sessionFile ? parseSession(sessionFile) : { calls: [], turns: 0, threadTokens: null, finalMsg: "" };
+ const msg = (parsed.finalMsg || r.stdout || "").toString();
+ const success = tasks[task].score(truth, msg);
+
+ const byName = {};
+ for (const c of parsed.calls) {
+ byName[c.name] = byName[c.name] ?? { count: 0, argsChars: 0, outChars: 0 };
+ byName[c.name].count++;
+ byName[c.name].argsChars += c.argsChars;
+ byName[c.name].outChars += c.outChars;
+ }
+ const evidence = browserEvidence(parsed.calls);
+ const rec = {
+ run, task, arm, rep,
+ wallMs: r.wallMs,
+ exit: r.code ?? (r.timedOut ? "timeout" : "?"),
+ timedOut: r.timedOut,
+ success,
+ browserToolUse: evidence,
+ turns: parsed.turns,
+ tokens: parsed.threadTokens,
+ toolCalls: parsed.calls.length,
+ tools: byName,
+ finalMsgSnippet: msg.slice(0, 120).replace(/\s+/g, " "),
+ stderrSnippet: r.stderr?.slice(0, 300),
+ sessionFile,
+ };
+ results.push(rec);
+ writeFileSync(join(AXUSE_DIR, "bench", `results-${RUN_TS}.jsonl`),
+ results.map((x) => JSON.stringify(x)).join("\n") + "\n");
+ console.log(`${success ? "PASS" : "FAIL"} ${rec.wallMs}ms turns=${rec.turns} tools=${rec.toolCalls} tokens=${parsed.threadTokens?.total_tokens ?? "?"}`);
+ if (r.stderr && /error/i.test(r.stderr)) console.log(" stderr:", r.stderr.slice(0, 200).replace(/\n/g, " "));
+ }
+ }
+ }
+
+ // ---------------- summary ----------------
+ console.log("\n================ SUMMARY ================");
+ const med = (xs) => { const s = [...xs].sort((a, b) => a - b); return s.length ? s[Math.floor((s.length - 1) / 2)] : null; };
+ const fmtTok = (n) => (n == null ? "?" : n.toLocaleString());
+ for (const task of TASKS) {
+ for (const arm of ARMS) {
+ const rs = results.filter((r) => r.task === task && r.arm === arm);
+ if (!rs.length) continue;
+ const ok = rs.filter((r) => r.success);
+ const legit = rs.filter((r) => r.browserToolUse.used);
+ const inTok = med(rs.map((r) => r.tokens?.input_tokens ?? 0));
+ const outTok = med(rs.map((r) => r.tokens?.output_tokens ?? 0));
+ // Tool-layer observation cost: outputs of browser tools. axuse: ax_*.
+ // codex: browser SDK results come back inside js/exec outputs —
+ // approximated by the same outputs (the kernel is the browser surface).
+ const obsChars = (r) => Object.entries(r.tools)
+ .filter(([name]) => arm === "axuse" ? name.startsWith("ax_") : /js|exec/i.test(name))
+ .reduce((a, [, t]) => a + t.outChars, 0);
+ console.log(`${task}/${arm}: success ${ok.length}/${rs.length}` +
+ ` (browser-tool evidence ${legit.length}/${rs.length})` +
+ ` | wall ${med(rs.map((r) => r.wallMs))?.toLocaleString()}ms` +
+ ` | turns ${med(rs.map((r) => r.turns))}` +
+ ` | tools ${med(rs.map((r) => r.toolCalls))}` +
+ ` | tok in ${fmtTok(inTok)} out ${fmtTok(outTok)}` +
+ ` | tool-outputs ≈${Math.ceil((med(rs.map((r) => obsChars(r))) ?? 0) / 4)} tok`);
+ }
+ }
+ bases.close();
+ process.exit(0);
+}
+
+const RUN_TS = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 16);
+main();
diff --git a/bench/suite/EASE.md b/bench/suite/EASE.md
new file mode 100644
index 0000000..6d96b8c
--- /dev/null
+++ b/bench/suite/EASE.md
@@ -0,0 +1,17 @@
+# Ease of use — measured
+
+Measured on the benchmark machine (Windows 11, 2026-10-15).
+
+| | axuse | Codex + Chrome extension | browser-use 0.13.11 |
+|---|---|---|---|
+| Install size | **0.2 MB** (src + bridge) | 46.7 MB bundled plugins + 59 MB extension | 228.5 MB (uv tool env) |
+| Runtime dependencies | **0** — Node ≥ 22 only | Codex desktop runtime, Chrome + extension | 106 Python packages, uv, Python |
+| Setup per harness | **1 line** (`codex mcp add axuse -- node src/cli.js mcp`; `claude mcp add …`; an `opencode.json` block) | built into Codex; not available to other harnesses | `uv tool install`, a Chrome with remote debugging (or `BU_CDP_URL`), plus a skill install per harness |
+| Integration surface | MCP (standard tool calls) | Codex-internal JS REPL | shell + Python heredocs written by the model |
+| Harnesses verified in this repo | Codex, Claude Code (4/4), OpenCode (2/2) — same server, unmodified | Codex only | any harness with a shell (not separately verified) |
+
+Observed friction during the benchmark (transcripts in each run's Codex session file):
+
+- **Codex + Chrome extension** stopped to ask for confirmation on pre-approved destructive or submitting steps (delete, place order, sign up) in unattended runs. Localhost access was blocked (`ERR_BLOCKED_BY_CLIENT`) on 2026-10-14 but worked on 2026-10-15, so treat it as intermittent.
+- **browser-use** relies on the model writing bash heredocs; under PowerShell the first attempt failed with a parse error before the model switched to a PowerShell here-string.
+- **axuse** needed no workaround in any harness; the model discovers it through the standard MCP tool list and server instructions.
diff --git a/bench/suite/README.md b/bench/suite/README.md
new file mode 100644
index 0000000..23ad051
--- /dev/null
+++ b/bench/suite/README.md
@@ -0,0 +1,92 @@
+# axuse benchmark suite v2
+
+A head-to-head benchmark of browser-use **tool layers** for coding-agent
+harnesses. Same harness (Codex CLI), same model (`gpt-5.6-luna`, reasoning
+`medium`), same 16 tasks, same machine. The **only** variable is the browser
+layer:
+
+| arm | what the model drives |
+|---|---|
+| `codex-chrome` | Codex's own browser use: the Codex Chrome extension in the user's real Chrome (Codex's built-in plugin + skill) |
+| `axuse` | the axuse MCP server (its own headless Chromium) |
+| `browser-use` | [browser-use](https://github.com/browser-use/browser-use) 0.13 CLI + its official `SKILL.md`, attached to a dedicated headless Chrome via `BU_CDP_URL` |
+
+## Tasks
+
+Deterministic, per-run seeded pages (`server.mjs`) covering what real browser
+agents trip over:
+
+| id | capability | pass condition (server-side) |
+|---|---|---|
+| t1 | click → reveal | claim endpoint hit + code reported |
+| t2 | form fill (text, email, select, checkbox) | exact values submitted |
+| t3 | 150-row table lookup | price + stock reported |
+| t4 | 4-step wizard with server validation | all steps + token |
+| t5 | cross-origin iframe (OOPIF) | click inside iframe |
+| t6 | nested shadow DOM switches + radios | exact settings saved |
+| t7 | infinite scroll feed (300 posts, lazy pages) | exactly the target post liked |
+| t8 | hover-only menu | export clicked, never "Delete account" |
+| t9 | `confirm()` → `prompt()` dialog chain | only the target file deleted, reason "cleanup" |
+| t10 | `target=_blank` new tab round trip | help tab visited + code verified |
+| t11 | async job (5 s) then download | download after ready |
+| t12 | pointer-events drag & drop (kanban) | card in Done |
+| t13 | contenteditable editor | exact text published |
+| t14 | ARIA autocomplete combobox + custom listbox | Zurich / Switzerland saved |
+| t15 | debounced search + pagination | right order's details opened |
+| t16 | canvas (no DOM) — needs vision | click inside the red circle |
+
+## Fairness and anti-cheat
+
+- **Public HTTPS fixtures.** The Codex extension refuses localhost / private
+ IPs (`ERR_BLOCKED_BY_CLIENT`), so the fixtures are served through two
+ Cloudflare quick tunnels (two origins → the t5 iframe is genuinely
+ cross-origin). Every arm loads the same public URLs.
+- **Server-side scoring.** Every state change POSTs to the fixture server;
+ success = server ground truth **and** the reported value. Ground truth is
+ only readable with a random bench key.
+- **Browser-only endpoints.** Scored endpoints require `Sec-Fetch-*` headers;
+ the runner also audits every tool call and disqualifies runs that hit the
+ task host with a shell HTTP client.
+- **Isolation.** Each run gets an empty working directory outside the repo
+ (no peeking at the fixture source). The axuse and browser-use arms run with
+ Codex's browser/computer-use features and plugins disabled; the
+ codex-chrome and browser-use arms run with axuse disabled; any call into
+ another arm's browser layer disqualifies the run.
+- **Same instructions.** All arms get the same task text plus the same
+ "unattended, pre-approved, no HTTP clients" rules; each arm gets one line
+ naming its tools (browser-use additionally gets its official SKILL.md, the
+ content Codex would load when that skill triggers).
+- **Frozen subject.** The axuse arm runs a frozen copy (`--axuse-cli`), so
+ development edits cannot leak into a benchmark in flight.
+- **Order rotation.** Arm order rotates per task and repetition.
+
+## Metrics
+
+From the Codex session log of each run: wall time, turns, tool calls, and
+thread token totals (`total`, and `fresh` = uncached input + output).
+`capability success` excludes runs where the agent stopped to ask the absent
+user for confirmation (a safety-policy outcome — reported separately, never
+hidden).
+
+## Reproduce
+
+```bash
+# once: browser-use CLI + its skill text, cloudflared
+uv tool install browser-use==0.13.11
+browser-use skill show > bench/suite/browser-use-SKILL.md
+winget install Cloudflare.cloudflared
+
+# sanity: every task is solvable and scoring is correct (scripted, no LLM)
+node bench/suite/oracle.mjs
+
+# the benchmark (freeze axuse first)
+cp -r src package.json bridge /path/to/axuse-frozen/
+node bench/suite/run.mjs --reps 3 --tag final --axuse-cli /path/to/axuse-frozen/src/cli.js
+node bench/suite/summarize.mjs bench/suite/results/final.jsonl
+
+# portability: the same axuse server in other harnesses
+node bench/suite/portability.mjs --harness claude,opencode
+```
+
+Results land in `results/*.jsonl` (one line per run, with the session file
+path for audit).
diff --git a/bench/suite/coord-check.mjs b/bench/suite/coord-check.mjs
new file mode 100644
index 0000000..a92178e
--- /dev/null
+++ b/bench/suite/coord-check.mjs
@@ -0,0 +1,19 @@
+// Coordinate contract check: screenshot pixels == ax_click {x,y}, even when scrolled.
+import { startSuite } from "./server.mjs";
+import { Controller } from "../../src/core/controller.js";
+const s = await startSuite(); const c = new Controller();
+const run = "coord-" + Date.now();
+await c.execute("open", { url: `${s.base.parent}/t16?run=${run}`, headless: true });
+await c.execute("evaluate", { expression: "document.body.style.paddingBottom='2000px'; scrollTo(0, 60); scrollY" });
+const shot = await c.execute("screenshot", {});
+const o = (await c.execute("observe", { mode: "full" })).observation.text;
+const [bx, by, bw] = o.match(/box=(-?\d+),(-?\d+),(\d+)x/).slice(1).map(Number);
+const red = s.truth(run).t16.circles.find((k) => k.color === "red");
+const scale = (bw - 2) / 640;
+// What a vision model would do: read the circle's pixel position in the screenshot.
+const x = bx + 1 + red.x * scale, y = by + 1 + red.y * scale;
+const r = await c.execute("click", { target: { x, y } });
+console.log("screenshot note:", shot.note);
+console.log("canvas line:", o.match(/- canvas[^\n]*/)[0]);
+console.log("hit:", s.truth(run).t16.hits);
+await c.execute("close", { browser: true }); s.close(); process.exit(0);
diff --git a/bench/suite/dump.mjs b/bench/suite/dump.mjs
new file mode 100644
index 0000000..3a5e8ba
--- /dev/null
+++ b/bench/suite/dump.mjs
@@ -0,0 +1,15 @@
+import { writeFileSync } from "node:fs";
+import { startSuite, TASK_IDS } from "./server.mjs";
+import { Controller } from "../../src/core/controller.js";
+const s = await startSuite();
+const c = new Controller();
+let first = true;
+for (const t of TASK_IDS) {
+ const url = `${s.base.parent}/${t}?run=dump-${t}`;
+ const r = first ? await c.execute("open", { url, headless: true }) : await c.execute("navigate", { url });
+ first = false;
+ const txt = r.observation?.text ?? JSON.stringify(r).slice(0, 2000);
+ writeFileSync(new URL(`./out/${t}.txt`, import.meta.url), txt);
+ console.log(t, txt.length, "chars");
+}
+await c.execute("close", { browser: true }); s.close(); process.exit(0);
diff --git a/bench/suite/fill-check.mjs b/bench/suite/fill-check.mjs
new file mode 100644
index 0000000..f28bd34
--- /dev/null
+++ b/bench/suite/fill-check.mjs
@@ -0,0 +1,30 @@
+// ax_fill check on the suite's form (t2) and combobox/dropdown (t14) tasks.
+import { startSuite, SCORE } from "./server.mjs";
+import { Controller } from "../../src/core/controller.js";
+const s = await startSuite();
+const c = new Controller();
+const ref = (txt, re) => txt.match(new RegExp(re.source + String.raw`[^\n]*\[ref=(e\d+)\]`))[1];
+
+let run = "fill-t2-" + Date.now();
+let o = (await c.execute("open", { url: `${s.base.parent}/t2?run=${run}`, headless: true })).observation.text;
+let r = await c.execute("fill", {
+ fields: [
+ { ref: ref(o, /textbox "Full name"/), value: "Ada Lovelace" },
+ { ref: ref(o, /textbox "Email"/), value: "[email protected]" },
+ { ref: ref(o, /combobox "Plan"/), value: "Beta" },
+ { ref: ref(o, /checkbox "I agree"/), value: true },
+ ],
+ submit: ref(o, /button "Submit"/),
+});
+console.log("t2 fill result:\n" + r.observation.text);
+console.log("t2 server:", s.truth(run).t2.valid);
+
+run = "fill-t14-" + Date.now();
+o = (await c.execute("navigate", { url: `${s.base.parent}/t14?run=${run}` })).observation.text;
+r = await c.execute("fill", {
+ fields: [{ ref: ref(o, /combobox "City"/), value: "Zurich" }, { ref: ref(o, /button "Country/), value: "Switzerland" }],
+ submit: ref(o, /button "Save destination"/),
+});
+console.log("t14 fill result:\n" + r.observation.text);
+console.log("t14 server:", JSON.stringify(s.truth(run).t14.got));
+await c.execute("close", { browser: true }); s.close(); process.exit(0);
diff --git a/bench/suite/find-check.mjs b/bench/suite/find-check.mjs
new file mode 100644
index 0000000..0fdbc1c
--- /dev/null
+++ b/bench/suite/find-check.mjs
@@ -0,0 +1,20 @@
+// ax_scroll {until} on the infinite feed (t7) and ax_observe {find} on the catalog (t3).
+import { startSuite, SCORE } from "./server.mjs";
+import { Controller } from "../../src/core/controller.js";
+import { renderResult } from "../../src/mcp/render.js";
+const s = await startSuite(); const c = new Controller();
+let run = "find-t7-" + Date.now();
+await c.execute("open", { url: `${s.base.parent}/t7?run=${run}`, headless: true });
+const author = s.truth(run).t7.feed[s.truth(run).t7.idx].author;
+let t0 = Date.now();
+let r = await c.execute("scroll", { until: author });
+console.log(`--- scroll until ${author} (${Date.now() - t0}ms)\n` + renderResult("scroll", r));
+const likeRef = r.observation.text.split(`text "${author}"`)[1].match(/button "Like" \[ref=(e\d+)\]/)[1];
+r = await c.execute("click", { target: { ref: likeRef } });
+console.log("--- click\n" + renderResult("click", r));
+{ const g = s.truth(run).t7; console.log("liked", g.likes, "target", g.feed[g.idx].id, g.feed[g.idx].author, "liked author", g.feed.find(p => p.id === g.likes[0])?.author); }
+run = "find-t3-" + Date.now();
+await c.execute("navigate", { url: `${s.base.parent}/t3?run=${run}` });
+r = await c.execute("observe", { find: "TARGET" });
+console.log("--- observe find TARGET\n" + renderResult("observe", r));
+await c.execute("close", { browser: true }); s.close(); process.exit(0);
diff --git a/bench/suite/oracle.mjs b/bench/suite/oracle.mjs
new file mode 100644
index 0000000..470af6a
--- /dev/null
+++ b/bench/suite/oracle.mjs
@@ -0,0 +1,219 @@
+/**
+ * Scripted oracle: solves every suite task through axuse's public command
+ * surface (no LLM). Proves (1) each task is solvable, (2) server scoring is
+ * correct, (3) axuse can actuate each capability the suite exercises.
+ * node bench/suite/oracle.mjs [--tasks t1,t7]
+ */
+import { startSuite, TASK_IDS, SCORE } from "./server.mjs";
+import { Controller } from "../../src/core/controller.js";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+const tmp = join(homedir(), ".axbench-tmp", "oracle-files"); mkdirSync(tmp, { recursive: true });
+let shopUrl = "";
+
+const only = process.argv.includes("--tasks") ? process.argv[process.argv.indexOf("--tasks") + 1].split(",") : TASK_IDS;
+const s = await startSuite();
+const c = new Controller();
+let opened = false;
+const full = async () => (await c.execute("observe", { mode: "full", max_nodes: 2000, max_chars: 200000 })).observation.text;
+const ref = (txt, re) => { const m = txt.match(new RegExp(re.source + String.raw`[^\n]*\[ref=((?:f\d+:)?e\d+)\]`)); if (!m) throw new Error("no ref for " + re); return m[1]; };
+const click = (r) => c.execute("click", { target: { ref: r }, settle_ms: 200 });
+const grab = (txt, re) => (txt.match(re) ?? [])[1] ?? "";
+
+const solvers = {
+ async t1(t) { await click(ref(t, /button "Claim code"/)); return grab(await full(), /code: (\w{6})/); },
+ async t2(t) {
+ await c.execute("type", { target: { ref: ref(t, /textbox "Full name"/) }, text: "Ada Lovelace" });
+ await c.execute("type", { target: { ref: ref(t, /textbox "Email"/) }, text: "[email protected]" });
+ await c.execute("select", { ref: ref(t, /combobox "Plan"/), value: "Beta" });
+ await click(ref(t, /checkbox "I agree"/));
+ await click(ref(t, /button "Submit"/));
+ return grab(await full(), /confirmation: (CNF-\w+)/);
+ },
+ async t3(t) { const m = t.match(/Widget TARGET-\w+ \| ([\d.]+) \| (\d+)/); return `${m[1]}|${m[2]}`; },
+ async t4(t) {
+ for (const col of ["Red", "Green", "Blue"]) { await click(ref(await full(), new RegExp(`button "${col}"`))); if (/number:/.test(await full())) break; }
+ let x = await full(); const num = grab(x, /number: (\d+)/);
+ await c.execute("type", { target: { ref: ref(x, /textbox "Number"/) }, text: num }); await click(ref(await full(), /button "Verify"/));
+ x = await full(); const w = grab(x, /click the exact word (\w+)/);
+ await click(ref(x, new RegExp(`button "${w}"`))); await click(ref(await full(), /button "Finish"/));
+ return grab(await full(), /final token: (\w+)/);
+ },
+ async t5(t) { await click(ref(t, /button "Reveal code"/)); return grab(await full(), /code: (\w{6})/); },
+ async t6(t) {
+ await click(ref(t, /switch "Email alerts"/)); await click(ref(t, /radio "Weekly"/)); await click(ref(t, /button "Save preferences"/));
+ return grab(await full(), /Reference: (\w{6})/);
+ },
+ async t7(t, g) {
+ const author = g.t7.feed[g.t7.idx].author;
+ for (let i = 0; i < 40; i++) {
+ const x = await full();
+ const m = x.match(new RegExp(`text "${author}"[\\s\\S]*?button "Like"[^\\n]*\\[ref=(e\\d+)\\]`));
+ if (m) { await click(m[1]); return grab(await full(), /code: (\w{6})/); }
+ await c.execute("scroll", { direction: "down", amount: 6, settle_ms: 500 });
+ }
+ },
+ async t8(t) {
+ await c.execute("hover", { target: { ref: ref(t, /link "Account/) } });
+ await click(ref(await full(), /menuitem "Export data"/));
+ return grab(await full(), /Export code: (\w{6})/);
+ },
+ async t9(t) {
+ const r = await c.execute("click", { target: { ref: ref(t, /button "Delete old-backup.zip"/) } });
+ await c.execute("dialog", { answer: "accept" });
+ await c.execute("dialog", { answer: "accept", prompt_text: "cleanup" });
+ return grab(await full(), /Code: (\w{6})/);
+ },
+ async t10(t) {
+ await click(ref(t, /link "help center"/));
+ const tabs = await c.execute("tabs", {});
+ const help = tabs.tabs.find((x) => /t10help/.test(x.url));
+ const origin = tabs.tabs.find((x) => /\/t10\?/.test(x.url));
+ let code;
+ if (help) {
+ const o = await c.execute("observe", { tab_id: help.tab_id, mode: "full" });
+ code = grab(o.observation.text, /verification code is: (\w{6})/);
+ await c.execute("close", { tab_id: help.tab_id });
+ }
+ const x = (await c.execute("observe", { tab_id: origin.tab_id, mode: "full" })).observation.text;
+ await c.execute("type", { tab_id: origin.tab_id, target: { ref: ref(x, /textbox "Verification code"/) }, text: code ?? "" });
+ await c.execute("click", { tab_id: origin.tab_id, target: { ref: ref(x, /button "Verify"/) }, settle_ms: 300 });
+ return grab((await c.execute("observe", { tab_id: origin.tab_id, mode: "full" })).observation.text, /Receipt: (\w{6})/);
+ },
+ async t11(t) {
+ await click(ref(t, /button "Generate report"/));
+ await c.execute("wait_for", { expression: "!!document.getElementById('d')", timeout_ms: 15000 });
+ await click(ref(await full(), /button "Download report"/));
+ return grab(await full(), /Code: (\w{6})/);
+ },
+ async t12(t) {
+ await c.execute("drag", { from: { ref: ref(t, /listitem "Fix login bug"/) }, to: { ref: ref(t, /region "Done column"/) }, settle_ms: 400 });
+ return grab(await full(), /Code: (\w{6})/);
+ },
+ async t13(t) {
+ await c.execute("type", { target: { ref: ref(t, /textbox "Release note editor"/) }, text: "Release 4.2 fixes the export bug." });
+ await click(ref(await full(), /button "Publish"/));
+ return grab(await full(), /Code: (\w{6})/);
+ },
+ async t14(t) {
+ await c.execute("type", { target: { ref: ref(t, /combobox "City"/) }, text: "Zurich", settle_ms: 600 });
+ await click(ref(await full(), /option "Zurich"/));
+ await click(ref(await full(), /button "Country/));
+ await click(ref(await full(), /option "Switzerland"/));
+ await click(ref(await full(), /button "Save destination"/));
+ return grab(await full(), /Code: (\w{6})/);
+ },
+ async t15(t, g) {
+ await c.execute("type", { target: { ref: ref(t, /searchbox "Search customer"/) }, text: g.t15.customer, settle_ms: 900 });
+ const x = await full();
+ const m = x.match(/row "(ORD-\d+) \| [^|]+\| Refunded[^\n]*\n\s*- button "Details" \[ref=(e\d+)\]/);
+ await click(m[2]);
+ return grab(await full(), /order code: (\w{6})/);
+ },
+ async t16(t, g) {
+ // Oracle reads geometry from ground truth; an agent reads the screenshot.
+ const box = t.match(/canvas \(box=(\d+),(\d+),(\d+)x(\d+)/).slice(1).map(Number);
+ const red = g.t16.circles.find((k) => k.color === "red");
+ const sx = (box[2] - 2) / 640, sy = (box[3] - 2) / 300;
+ await c.execute("click", { target: { x: box[0] + 1 + red.x * sx, y: box[1] + 1 + red.y * sy }, settle_ms: 300 });
+ return grab(await full(), /Code: (\w{6})/);
+ },
+ async t17(t) {
+ for (const item of ["Write release notes", "Fix flaky test", "Update changelog"]) {
+ await c.execute("type", { target: { ref: ref(await full(), /textbox "New todo"/) }, text: item, submit: true });
+ }
+ await click(ref(await full(), /checkbox "Fix flaky test"/));
+ await click(ref(await full(), /button "Sync to server"/));
+ return grab(await full(), /Code: (\w{6})/);
+ },
+ async t18(t) {
+ const buy = async (name, size, color, qty) => {
+ await c.execute("navigate", { url: shopUrl });
+ let x = await full();
+ await click(ref(x, new RegExp(`link "${name}"`)));
+ x = await full();
+ await c.execute("fill", { fields: [
+ { ref: ref(x, /combobox "Size"/), value: size },
+ { ref: ref(x, new RegExp(`radio "${color}"`)), value: true },
+ { ref: ref(x, /spinbutton "Quantity"/), value: String(qty) },
+ ], submit: ref(x, /button "Add to cart"/) });
+ };
+ await buy("Trail Runner", "M", "Blue", 2);
+ await buy("Rain Shell", "L", "Black", 1);
+ await click(ref(await full(), /link "Cart"/));
+ let x = await full();
+ await c.execute("fill", { fields: [{ ref: ref(x, /textbox "Coupon code"/), value: "SAVE10" }], submit: ref(x, /button "Apply"/) });
+ await click(ref(await full(), /link "Proceed to checkout"/));
+ x = await full();
+ await c.execute("fill", { fields: [
+ { ref: ref(x, /textbox "Full name"/), value: "Ada Lovelace" }, { ref: ref(x, /textbox "Street"/), value: "Bahnhofstrasse 1" },
+ { ref: ref(x, /textbox "ZIP"/), value: "8001" }, { ref: ref(x, /textbox "City"/), value: "Zurich" },
+ { ref: ref(x, /combobox "Country"/), value: "Switzerland" }, { ref: ref(x, /radio "Express/), value: true },
+ ], submit: ref(x, /button "Place order"/) });
+ return grab(await full(), /Order number: (ORD-\d+)/);
+ },
+ async t19(t, g) {
+ const id = g.t19.rows[g.t19.idx].id;
+ const r = await c.execute("scroll", { until: id });
+ await click(ref(r.observation.text, new RegExp(`button "Approve ${id}"`)));
+ return grab(await full(), /Code: (\w{6})/);
+ },
+ async t20(t) {
+ const pick = async (field, monthsAhead, label) => {
+ await click(ref(await full(), new RegExp(`textbox "${field}"`)));
+ for (let i = 0; i < monthsAhead; i++) await click(ref(await full(), /button "Next month"/));
+ await click(ref(await full(), new RegExp(`button "${label}"`)));
+ };
+ await pick("Departure", 2, "December 17, 2026");
+ await pick("Return", 3, "January 3, 2027");
+ await click(ref(await full(), /button "Save dates"/));
+ return grab(await full(), /Code: (\w{6})/);
+ },
+ async t21(t) {
+ const fill = async (u) => {
+ const x = await full();
+ return c.execute("fill", { fields: [
+ { ref: ref(x, /textbox "Username"/), value: u }, { ref: ref(x, /textbox "Password"/), value: "Analytical#Engine1843" },
+ { ref: ref(x, /textbox "Confirm password"/), value: "Analytical#Engine1843" }, { ref: ref(x, /textbox "Date of birth/), value: "1990-12-10" },
+ { ref: ref(x, /checkbox "I accept the terms"/), value: true },
+ ], submit: ref(x, /button "Create account"/) });
+ };
+ await fill("ada");
+ if (/already taken/.test(await full())) await fill("ada_1815");
+ return grab(await full(), /Account code: (\w{6})/);
+ },
+ async t22(t) {
+ const x = await full();
+ await c.execute("fill", { fields: [{ ref: ref(x, /textbox "Branch code"/), value: "ZH-4471" }], submit: ref(x, /button "Look up"/) });
+ return grab(await full(), /Confirmation: (\w{6})/);
+ },
+ async t23(t, g) {
+ const file = join(tmp, g.t23.want);
+ writeFileSync(file, g.t23.content);
+ await c.execute("upload", { ref: ref(t, /button "Avatar file"/), paths: [file] });
+ await click(ref(await full(), /button "Upload"/));
+ return grab(await full(), /Code: (\w{6})/);
+ },
+};
+
+let pass = 0;
+for (const t of only) {
+ const run = `oracle-${t}-${Date.now().toString(36)}`;
+ const url = `${s.base.parent}/${t}?run=${run}`;
+ const t0 = Date.now();
+ try {
+ const r = opened ? await c.execute("navigate", { url, settle_ms: 400 }) : await c.execute("open", { url, headless: true, settle_ms: 400 });
+ opened = true;
+ await new Promise((ok) => setTimeout(ok, 300));
+ shopUrl = url;
+ const ans = await solvers[t](await full(), s.truth(run));
+ const ok = SCORE[t](s.truth(run), String(ans ?? ""));
+ pass += ok;
+ console.log(`${ok ? "PASS" : "FAIL"} ${t} answer=${ans} ${Date.now() - t0}ms`);
+ } catch (e) {
+ console.log(`FAIL ${t} ${e.message}`);
+ }
+}
+console.log(`oracle: ${pass}/${only.length}`);
+await c.execute("close", { browser: true }); s.close(); process.exit(0);
diff --git a/bench/suite/portability.mjs b/bench/suite/portability.mjs
new file mode 100644
index 0000000..82f60fe
--- /dev/null
+++ b/bench/suite/portability.mjs
@@ -0,0 +1,62 @@
+/**
+ * Harness portability check: the SAME axuse MCP server, unmodified, driven by
+ * other agent harnesses. Uses the suite's server-side scoring.
+ * node bench/suite/portability.mjs [--harness claude,opencode] [--tasks t1,t5,t9]
+ */
+import { spawn } from "node:child_process";
+import { mkdirSync, writeFileSync, appendFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { homedir } from "node:os";
+import { fileURLToPath } from "node:url";
+import { startSuite, PROMPTS, SCORE } from "./server.mjs";
+
+const AXUSE_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
+const AXUSE_CLI = join(AXUSE_ROOT, "src", "cli.js");
+const WORK = join(homedir(), ".axbench-tmp", "port");
+const arg = (n, d) => { const i = process.argv.indexOf(n); return i >= 0 ? process.argv[i + 1] : d; };
+const HARNESSES = arg("--harness", "claude").split(",");
+const TASKS = arg("--tasks", "t1,t5,t9,t10").split(",");
+const OUT = join(AXUSE_ROOT, "bench", "suite", "results", `portability-${new Date().toISOString().replace(/[:.]/g, "-").slice(0, 16)}.jsonl`);
+mkdirSync(WORK, { recursive: true });
+const env = { ...process.env, AXUSE_HEADLESS: "1", AXUSE_PROFILE_DIR: join(homedir(), ".axbench-tmp", "axuse-profiles") };
+const RULES = "You are running unattended; every action is pre-approved. Use the axuse MCP tools (ax_*) for all browser interaction; do not use HTTP clients. Reply with ONLY the requested value.\n\n";
+
+function run(cmd, args, cwd) {
+ return new Promise((ok) => {
+ const t0 = Date.now();
+ const p = spawn(cmd, args, { cwd, env, stdio: ["ignore", "pipe", "pipe"], shell: process.platform === "win32" && !cmd.endsWith(".exe") });
+ let out = "", err = "";
+ p.stdout.on("data", (d) => (out += d)); p.stderr.on("data", (d) => (err += d));
+ const t = setTimeout(() => p.kill(), 300_000);
+ p.on("exit", (code) => { clearTimeout(t); ok({ code, out, err, ms: Date.now() - t0 }); });
+ });
+}
+
+const H = {
+ async claude(prompt, cwd) {
+ const cfg = join(cwd, "mcp.json");
+ writeFileSync(cfg, JSON.stringify({ mcpServers: { axuse: { command: "node", args: [AXUSE_CLI, "mcp"], env: { AXUSE_HEADLESS: "1" } } } }));
+ const r = await run("claude", ["-p", JSON.stringify(prompt), "--mcp-config", cfg, "--strict-mcp-config", "--allowedTools", "mcp__axuse", "--output-format", "json"], cwd);
+ let j = {}; try { j = JSON.parse(r.out.trim().split("\n").pop()); } catch {}
+ return { answer: j.result ?? r.out, ms: r.ms, turns: j.num_turns, usage: j.usage, err: r.code ? r.err.slice(0, 300) : undefined };
+ },
+ async opencode(prompt, cwd) {
+ writeFileSync(join(cwd, "opencode.json"), JSON.stringify({ $schema: "https://opencode.ai/config.json", mcp: { axuse: { type: "local", command: ["node", AXUSE_CLI, "mcp"], enabled: true, environment: { AXUSE_HEADLESS: "1" } } } }));
+ const r = await run("opencode", ["run", JSON.stringify(prompt)], cwd);
+ return { answer: r.out.trim().split("\n").filter(Boolean).pop() ?? "", ms: r.ms, err: r.code ? r.err.slice(0, 300) : undefined };
+ },
+};
+
+const s = await startSuite();
+for (const h of HARNESSES) {
+ for (const t of TASKS) {
+ const runId = `port-${h}-${t}-${Date.now().toString(36)}`;
+ const cwd = join(WORK, runId); mkdirSync(cwd, { recursive: true });
+ const r = await H[h](RULES + PROMPTS[t](`${s.base.parent}/${t}?run=${runId}`, s.truth(runId)), cwd);
+ const ok = SCORE[t](s.truth(runId), String(r.answer ?? ""));
+ appendFileSync(OUT, JSON.stringify({ harness: h, task: t, success: ok, ...r }) + "\n");
+ console.log(`${ok ? "PASS" : "FAIL"} ${h} ${t} ${Math.round(r.ms / 1000)}s answer=${String(r.answer).slice(0, 40)}${r.err ? " err=" + r.err : ""}`);
+ }
+}
+s.close();
+process.exit(0);
diff --git a/bench/suite/prof.mjs b/bench/suite/prof.mjs
new file mode 100644
index 0000000..1fe46b4
--- /dev/null
+++ b/bench/suite/prof.mjs
@@ -0,0 +1,30 @@
+// Ad-hoc latency profiler for individual axuse commands against suite pages.
+import { startSuite } from "./server.mjs";
+import { Controller } from "../../src/core/controller.js";
+const s = await startSuite();
+const c = new Controller();
+const T = async (label, p) => {
+ const t0 = Date.now();
+ try {
+ const r = await p;
+ console.log(label, Date.now() - t0, "ms", JSON.stringify(r).slice(0, 300));
+ return r;
+ } catch (e) {
+ console.log(label, "THREW", Date.now() - t0, "ms", e.code, e.message, String(e.stack).slice(0, 400));
+ return {};
+ }
+};
+let r = await T("open", c.execute("open", { url: `${s.base.parent}/t12?run=p1`, headless: true }));
+const txt = r.observation.text;
+const a = txt.match(/listitem "Fix login bug" \[ref=(e\d+)\]/)[1], b = txt.match(/region "Done column" \[ref=(e\d+)\]/)[1];
+await T("drag", c.execute("drag", { from: { ref: a }, to: { ref: b } }));
+await T("observe", c.execute("observe", {}));
+await T("observe-full", c.execute("observe", { mode: "full", max_nodes: 2000, max_chars: 200000 }));
+r = await T("nav t10", c.execute("navigate", { url: `${s.base.parent}/t10?run=p2` }));
+const l = r.observation?.text?.match(/link "help center"[^\n]*\[ref=(e\d+)\]/)?.[1];
+await T("click link", c.execute("click", { target: { ref: l } }));
+await new Promise((ok) => setTimeout(ok, 1500));
+await T("tabs", c.execute("tabs", {}));
+await c.execute("close", { browser: true });
+s.close();
+process.exit(0);
diff --git a/bench/suite/report.mjs b/bench/suite/report.mjs
new file mode 100644
index 0000000..93edb12
--- /dev/null
+++ b/bench/suite/report.mjs
@@ -0,0 +1,164 @@
+/**
+ * Build the HTML benchmark report from a summarize.mjs JSON.
+ * node bench/suite/report.mjs summary.json out.html
+ */
+import { readFileSync, writeFileSync } from "node:fs";
+
+const [src, out] = process.argv.slice(2);
+const d = JSON.parse(readFileSync(src, "utf8"));
+const ARMS = ["axuse", "codex-chrome", "browser-use"];
+const LABEL = { axuse: "axuse", "codex-chrome": "Codex + Chrome extension", "browser-use": "browser-use 0.13" };
+const TASK = {
+ t1: "Click to reveal", t2: "Form fill", t3: "150-row table lookup", t4: "4-step validated wizard",
+ t5: "Cross-origin iframe", t6: "Shadow DOM switches", t7: "Infinite scroll feed", t8: "Hover-only menu",
+ t9: "confirm → prompt dialogs", t10: "New-tab round trip", t11: "Async job, then download", t12: "Drag and drop",
+ t13: "Rich-text editor", t14: "Autocomplete + listbox", t15: "Search + pagination", t16: "Canvas (vision)",
+};
+const k = (n) => (n >= 1e6 ? (n / 1e6).toFixed(2) + "M" : n >= 1000 ? Math.round(n / 1000) + "k" : String(Math.round(n)));
+const s = (n) => `${Math.round(n)} s`;
+const p = d.perArm;
+const tasks = Object.keys(d.perTask);
+const wins = { wall: {}, tok: {} };
+for (const a of ARMS) { wins.wall[a] = 0; wins.tok[a] = 0; }
+for (const t of tasks) {
+ const x = d.perTask[t];
+ wins.wall[ARMS.reduce((b, a) => (x[a].wallS < x[b].wallS ? a : b))]++;
+ wins.tok[ARMS.reduce((b, a) => (x[a].tok < x[b].tok ? a : b))]++;
+}
+const runs = ARMS.reduce((n, a) => n + p[a].runs, 0);
+const maxWall = Math.max(...ARMS.map((a) => p[a].medianWallS));
+const maxTok = Math.max(...ARMS.map((a) => p[a].sumTotalTok));
+const bar = (a, v, max, fmt) => `<div class="bar-row"><span class="bar-label">${LABEL[a]}</span><span class="bar-track"><span class="bar arm-${a}" style="width:${(100 * v / max).toFixed(1)}%"></span></span><span class="bar-val">${fmt(v)}</span></div>`;
+const speedup = (a) => (p[a].medianWallS / p.axuse.medianWallS).toFixed(1);
+const tokRatio = (a) => (p[a].sumTotalTok / p.axuse.sumTotalTok).toFixed(1);
+
+const rowsTask = tasks.map((t) => {
+ const x = d.perTask[t];
+ const bw = ARMS.reduce((b, a) => (x[a].wallS < x[b].wallS ? a : b));
+ const bt = ARMS.reduce((b, a) => (x[a].tok < x[b].tok ? a : b));
+ const cell = (a) => `<td class="${a === bw ? "win" : ""}">${s(x[a].wallS)}</td><td class="${a === bt ? "win" : ""}">${k(x[a].tok)}</td><td class="ok">${x[a].ok}/${x[a].n}</td>`;
+ return `<tr><th scope="row"><span class="tid">${t}</span> ${TASK[t]}</th>${ARMS.map(cell).join("")}</tr>`;
+}).join("\n");
+
+const html = `<title>axuse Browser Benchmark</title>
+<meta name="claude:viewport-fit-sides" content="cover">
+<link rel="preconnect" href="https://fonts.googleapis.com">
+<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=IBM+Plex+Sans+Condensed:wght@500;600&family=IBM+Plex+Sans:wght@400;500;600&display=swap">
+<style>
+/* Layout: a lab report — verdict first, then the evidence table, then method. */
+:root {
+ --bg: #f6f7f9; --surface: #ffffff; --fg: #1b2230; --muted: #5d6676; --line: #dde1e8;
+ --axuse: #0b6e4f; --codex: #6a5acd; --bu: #b5651d; --win-bg: #e3f3ec; --win-fg: #0b5a41;
+ --display: "IBM Plex Sans Condensed", "Arial Narrow", system-ui, sans-serif;
+ --body: "IBM Plex Sans", system-ui, -apple-system, "Segoe UI", sans-serif;
+ --mono: "IBM Plex Mono", ui-monospace, Consolas, monospace;
+}
+@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) {
+ --bg: #11151c; --surface: #181d26; --fg: #e4e8ef; --muted: #98a2b3; --line: #2a313d;
+ --axuse: #3fbf8f; --codex: #9b8cf0; --bu: #e09a55; --win-bg: #173a2e; --win-fg: #7fe0b8; color-scheme: dark } }
+:root[data-theme="dark"] {
+ --bg: #11151c; --surface: #181d26; --fg: #e4e8ef; --muted: #98a2b3; --line: #2a313d;
+ --axuse: #3fbf8f; --codex: #9b8cf0; --bu: #e09a55; --win-bg: #173a2e; --win-fg: #7fe0b8; color-scheme: dark }
+body { background: var(--bg); color: var(--fg); font: 15px/1.55 var(--body); }
+.wrap { max-width: 1040px; margin: 0 auto; padding-block: 40px 64px; padding-left: max(16px, env(safe-area-inset-left, 0px)); padding-right: max(16px, env(safe-area-inset-right, 0px)); display: grid; gap: 36px; }
+h1, h2 { font-family: var(--display); text-wrap: balance; margin: 0; }
+h1 { font-size: clamp(28px, 4.2vw, 40px); line-height: 1.12; font-weight: 600; }
+h2 { font-size: 22px; font-weight: 600; margin-bottom: 12px; }
+p { margin: 0; max-width: 70ch; }
+.eyebrow { font: 500 12px/1 var(--mono); letter-spacing: .08em; text-transform: uppercase; color: var(--muted); margin-bottom: 10px; }
+.lede { color: var(--muted); font-size: 17px; margin-top: 12px; }
+.verdicts { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 14px; }
+.verdict { background: var(--surface); border: 1px solid var(--line); border-radius: 8px; padding: 16px 18px; display: grid; gap: 4px; }
+.verdict .big { font: 600 30px/1.1 var(--display); color: var(--axuse); font-variant-numeric: tabular-nums; }
+.verdict .what { font-weight: 600; }
+.verdict .vs { color: var(--muted); font-size: 13.5px; }
+.panel { background: var(--surface); border: 1px solid var(--line); border-radius: 8px; padding: 20px; min-width: 0; }
+.charts { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 14px; }
+.charts h3 { font: 600 14px/1.3 var(--body); margin: 0 0 12px; }
+.bar-row { display: grid; grid-template-columns: minmax(110px, 38%) 1fr 64px; align-items: center; gap: 10px; margin: 8px 0; font-size: 13.5px; }
+.bar-label { color: var(--fg); }
+.bar-track { height: 14px; background: var(--bg); border-radius: 3px; overflow: hidden; }
+.bar { display: block; height: 100%; border-radius: 3px; }
+.arm-axuse { background: var(--axuse); } .arm-codex-chrome { background: var(--codex); } .arm-browser-use { background: var(--bu); }
+.bar-val { font: 500 13px var(--mono); text-align: right; font-variant-numeric: tabular-nums; }
+.note { color: var(--muted); font-size: 13px; margin-top: 10px; }
+.scroll { overflow-x: auto; }
+table { border-collapse: collapse; width: 100%; font-size: 13.5px; font-variant-numeric: tabular-nums; }
+th, td { padding: 7px 10px; border-bottom: 1px solid var(--line); text-align: right; white-space: nowrap; }
+thead th { font: 600 12px var(--mono); color: var(--muted); text-transform: uppercase; letter-spacing: .04em; }
+thead tr:first-child th { text-align: center; font-family: var(--body); text-transform: none; letter-spacing: 0; font-size: 13.5px; color: var(--fg); }
+tbody th { text-align: left; font-weight: 500; }
+.tid { font: 500 12px var(--mono); color: var(--muted); margin-right: 6px; }
+td.win { background: var(--win-bg); color: var(--win-fg); font-weight: 600; }
+td.ok { color: var(--muted); }
+.grp { border-left: 1px solid var(--line); }
+.cols2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 14px; }
+ul { margin: 0; padding-left: 20px; display: grid; gap: 6px; }
+code { font: 13px var(--mono); background: var(--bg); padding: 1px 5px; border-radius: 4px; }
+.status { border-left: 3px solid var(--bu); padding-left: 14px; }
+</style>
+<div class="wrap">
+ <header>
+ <div class="eyebrow">Codex CLI · gpt-5.6-luna · reasoning medium · 16 tasks · ${runs} scored runs</div>
+ <h1>axuse finishes browser tasks ${speedup("codex-chrome")}× faster than Codex's Chrome extension, using half the tokens</h1>
+ <p class="lede">Same harness, same model, same tasks, same machine. The only thing that changes is the browser layer. Every task is scored by the test server, not by the agent's own report.</p>
+ </header>
+
+ <section class="verdicts" aria-label="Headline results">
+ <div class="verdict"><span class="big">${s(p.axuse.medianWallS)}</span><span class="what">median time per task</span><span class="vs">Codex + Chrome ${s(p["codex-chrome"].medianWallS)} · browser-use ${s(p["browser-use"].medianWallS)}</span></div>
+ <div class="verdict"><span class="big">${k(p.axuse.sumTotalTok)}</span><span class="what">tokens for all ${p.axuse.runs} runs</span><span class="vs">${tokRatio("codex-chrome")}× fewer than Codex + Chrome, ${tokRatio("browser-use")}× fewer than browser-use</span></div>
+ <div class="verdict"><span class="big">${p.axuse.success}/${p.axuse.runs}</span><span class="what">tasks passed</span><span class="vs">Codex + Chrome ${p["codex-chrome"].success}/${p["codex-chrome"].runs} · browser-use ${p["browser-use"].success}/${p["browser-use"].runs}. Accuracy is a tie on this suite.</span></div>
+ <div class="verdict"><span class="big">${wins.wall.axuse}/${tasks.length}</span><span class="what">tasks where axuse was fastest</span><span class="vs">fewest tokens on ${wins.tok.axuse}/${tasks.length}; Codex + Chrome took the rest, browser-use none</span></div>
+ </section>
+
+ <section class="charts">
+ <div class="panel"><h3>Median wall time per task (lower is better)</h3>${ARMS.map((a) => bar(a, p[a].medianWallS, maxWall, s)).join("")}</div>
+ <div class="panel"><h3>Total tokens across all runs (lower is better)</h3>${ARMS.map((a) => bar(a, p[a].sumTotalTok, maxTok, k)).join("")}<p class="note">Codex thread totals: cached prompt, fresh input and output. Median tool calls per task: axuse ${p.axuse.medianCalls}, Codex + Chrome ${p["codex-chrome"].medianCalls}, browser-use ${p["browser-use"].medianCalls}.</p></div>
+ </section>
+
+ <section class="panel">
+ <h2>Every task</h2>
+ <p class="note" style="margin:0 0 12px">Median over repetitions. The shaded cell is the best result for that task.</p>
+ <div class="scroll"><table>
+ <thead>
+ <tr><th></th>${ARMS.map((a) => `<th colspan="3" class="grp">${LABEL[a]}</th>`).join("")}</tr>
+ <tr><th scope="col" style="text-align:left">task</th>${ARMS.map(() => `<th class="grp">time</th><th>tokens</th><th>pass</th>`).join("")}</tr>
+ </thead>
+ <tbody>
+${rowsTask}
+ </tbody>
+ </table></div>
+ </section>
+
+ <section class="cols2">
+ <div class="panel">
+ <h2>Ease of use</h2>
+ <ul>
+ <li><b>axuse:</b> one MCP line (<code>codex mcp add axuse -- node src/cli.js mcp</code>). No dependencies beyond Node 22. The same server, unmodified, passed its tasks in Codex, Claude Code and OpenCode.</li>
+ <li><b>Codex + Chrome extension:</b> only works inside Codex with its desktop runtime and the extension installed. It refuses <code>localhost</code> and private IPs, so it cannot test the app you are developing locally. It also stopped to ask for confirmation on a pre-approved delete in an earlier pass.</li>
+ <li><b>browser-use:</b> needs Python, uv and a Chrome started with remote debugging, and the agent must write Python helper scripts through the shell. On Windows the agent first tried a bash heredoc in PowerShell.</li>
+ </ul>
+ </div>
+ <div class="panel">
+ <h2>How it was measured</h2>
+ <ul>
+ <li>16 deterministic, per-run seeded tasks: forms, tables, wizards, cross-origin iframes, shadow DOM, infinite scroll, hover menus, JS dialogs, new tabs, async waits, drag and drop, rich text, comboboxes, pagination, canvas.</li>
+ <li>Fixtures were served over public HTTPS tunnels so the Codex extension could load them; each arm loaded the same URLs.</li>
+ <li>A run passes only if the server saw the right actions and the agent reported the right value. Runs that used an HTTP client or another arm's browser tools are disqualified.</li>
+ <li>Each run used an empty working directory. axuse ran from a frozen copy. Arm order rotated per task.</li>
+ </ul>
+ </div>
+ </section>
+
+ <section class="panel status">
+ <h2>What this run does and does not show</h2>
+ <ul>
+ <li>${runs} runs are scored: one full pass of all 16 tasks per tool, plus a second pass of tasks 1–12. The Codex workspace ran out of credits during the second pass. The 5 runs that hit that outage are excluded for every tool.</li>
+ <li>All three tools solved every scored task, so this suite shows axuse is faster and cheaper, not more accurate.</li>
+ <li>Since this run, axuse gained two fixes found by reading the transcripts: <code>ax_fill</code> now reports per field what it did, and screenshot pixels are documented as click coordinates. The second pass and a third repetition still need to be re-run with Codex credits.</li>
+ </ul>
+ </section>
+</div>
+`;
+writeFileSync(out, html);
+console.log("wrote", out);
diff --git a/bench/suite/run.mjs b/bench/suite/run.mjs
new file mode 100644
index 0000000..73d6068
--- /dev/null
+++ b/bench/suite/run.mjs
@@ -0,0 +1,296 @@
+/**
+ * axuse benchmark suite v2 — head-to-head runner.
+ *
+ * Same harness (Codex CLI), same model, same reasoning effort, same tasks,
+ * same machine. The ONLY variable is the browser layer:
+ *
+ * codex-chrome Codex's own browser use: the Codex Chrome extension driving
+ * the user's real Chrome (Codex's built-in plugin + skill)
+ * axuse axuse MCP server (its own headless Chromium)
+ * browser-use browser-use 0.13 CLI + its official SKILL.md (dedicated
+ * headless Chromium via BU_CDP_URL)
+ *
+ * Fixtures are served over public HTTPS (Cloudflare quick tunnels) because the
+ * Codex extension refuses localhost / private IPs. Success is scored on
+ * SERVER-SIDE ground truth plus the final answer; runs that bypass the browser
+ * (HTTP clients against the task host) or use another arm's browser layer are
+ * disqualified. Each run gets an empty cwd outside the repo.
+ *
+ * node bench/suite/run.mjs [--arms codex-chrome,axuse,browser-use]
+ * [--tasks t1,...] [--reps 3] [--effort medium] [--parallel]
+ */
+import { spawn, execSync } from "node:child_process";
+import { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, appendFileSync, existsSync, rmSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { homedir } from "node:os";
+import { fileURLToPath } from "node:url";
+import { createServer } from "node:net";
+import { startSuite, TASK_IDS, PROMPTS, SCORE, LOCAL_TASKS } from "./server.mjs";
+import { locateBrowser } from "../../src/core/cdp.js";
+
+const AXUSE_DIR = process.env.AXBENCH_AXUSE_DIR ?? join(dirname(fileURLToPath(import.meta.url)), "..", "..");
+const WORK = process.env.AXBENCH_WORK ?? join(homedir(), ".axbench-tmp");
+const SESSIONS_ROOT = join(homedir(), ".codex", "sessions");
+const arg = (n, d) => { const i = process.argv.indexOf(n); return i >= 0 ? process.argv[i + 1] : d; };
+const MODEL = arg("--model", "gpt-5.6-luna");
+const EFFORT = arg("--effort", "medium");
+const ARMS = arg("--arms", "codex-chrome,axuse,browser-use").split(",");
+const TASKS = arg("--tasks", TASK_IDS.join(",")).split(",");
+const REPS = Number(arg("--reps", 1));
+const PARALLEL = process.argv.includes("--parallel");
+const RUN_TIMEOUT_MS = Number(arg("--timeout", 420_000));
+const TAG = arg("--tag", new Date().toISOString().replace(/[:.]/g, "-").slice(0, 16));
+const OUT = join(AXUSE_DIR, "bench", "suite", "results", `${TAG}.jsonl`);
+mkdirSync(join(AXUSE_DIR, "bench", "suite", "results"), { recursive: true });
+mkdirSync(WORK, { recursive: true });
+
+const BU_SKILL = (() => {
+ try {
+ return readFileSync(join(AXUSE_DIR, "bench", "suite", "browser-use-SKILL.md"), "utf8");
+ } catch { return null; }
+})();
+
+// ---------------------------------------------------------------- tunnels
+function startTunnel(port) {
+ return new Promise((resolve, reject) => {
+ const p = spawn(process.env.CLOUDFLARED ?? "cloudflared", ["tunnel", "--no-autoupdate", "--url", `http://127.0.0.1:${port}`], { stdio: ["ignore", "pipe", "pipe"] });
+ let buf = "";
+ const t = setTimeout(() => reject(new Error("tunnel timeout: " + buf.slice(-500))), 60_000);
+ const on = (d) => {
+ buf += d;
+ const m = buf.match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/);
+ if (m) { clearTimeout(t); resolve({ url: m[0], proc: p }); }
+ };
+ p.stdout.on("data", on); p.stderr.on("data", on);
+ p.on("exit", (c) => reject(new Error(`cloudflared exited ${c}: ${buf.slice(-500)}`)));
+ });
+}
+async function waitPublic(url) {
+ for (let i = 0; i < 60; i++) {
+ try { const r = await fetch(url + "/healthz", { signal: AbortSignal.timeout(5000) }); if (r.ok) return; } catch {}
+ await new Promise((ok) => setTimeout(ok, 2000));
+ }
+ throw new Error("public URL never became reachable: " + url);
+}
+
+// --------------------------------------------------- browser-use's Chrome
+const freePort = () => new Promise((ok) => { const s = createServer(); s.listen(0, "127.0.0.1", () => { const p = s.address().port; s.close(() => ok(p)); }); });
+async function launchChromeForBU(runId) {
+ const port = await freePort();
+ const dir = join(WORK, "bu-profiles", runId);
+ mkdirSync(dir, { recursive: true });
+ const exe = locateBrowser();
+ const proc = spawn(exe, [`--remote-debugging-port=${port}`, `--user-data-dir=${dir}`, "--headless", "--no-first-run", "--no-default-browser-check", "--remote-allow-origins=*", "about:blank"], { stdio: "ignore" });
+ for (let i = 0; i < 50; i++) {
+ try { const r = await fetch(`http://127.0.0.1:${port}/json/version`); if (r.ok) break; } catch {}
+ await new Promise((ok) => setTimeout(ok, 200));
+ }
+ return { port, proc, dir };
+}
+
+/** Kill only Chrome processes launched with this bench-owned profile dir. */
+function killByProfile(dir) {
+ const needle = dir.split(/[\\/]/).pop();
+ if (process.platform === "win32") {
+ spawn("powershell", ["-NoProfile", "-Command",
+ `Get-CimInstance Win32_Process -Filter "Name='chrome.exe'" | Where-Object { $_.CommandLine -match '${needle}' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`], { stdio: "ignore" });
+ return;
+ }
+ // POSIX: pgrep over full command lines, then TERM by pid. Never pkill by
+ // bare name — that would take down the user's daily browser.
+ try {
+ const out = execSync(`pgrep -f '${needle.replace(/'/g, "'\\''")}' || true`, { encoding: "utf8" });
+ for (const pid of out.split("\n").map((s) => Number(s.trim())).filter((p) => Number.isInteger(p) && p > 0 && p !== process.pid)) {
+ try { process.kill(pid, "SIGTERM"); } catch {}
+ }
+ } catch {}
+}
+
+// ---------------------------------------------------------- codex runs
+const DISABLE_NATIVE = [
+ "--disable", "browser_use", "--disable", "browser_use_external", "--disable", "computer_use",
+ "-c", 'plugins."chrome@openai-bundled".enabled=false', "-c", 'plugins."browser@openai-bundled".enabled=false',
+ "-c", 'plugins."unified-computer-use@openai-bundled".enabled=false', "-c", 'plugins."computer-use@openai-bundled".enabled=false',
+];
+const NO_AXUSE = ["-c", "mcp_servers.axuse.enabled=false"];
+// The axuse arm runs a FROZEN copy (--axuse-cli), so edits to the working
+// tree can never leak into a benchmark in flight.
+const AXUSE_CLI = arg("--axuse-cli", null);
+const AXUSE_FLAGS = AXUSE_CLI ? ["-c", `mcp_servers.axuse.command="node"`, "-c", `mcp_servers.axuse.args=["${AXUSE_CLI.replaceAll("\\", "/")}","mcp"]`] : [];
+
+const COMMON_RULES =
+ "You are running unattended: the user owns this test site and pre-approves every action the task asks for (including changing settings, deleting, submitting) — do not stop to ask for confirmation. " +
+ "Rules: do ALL page interaction in the browser. Do NOT use curl, wget, Invoke-WebRequest, Invoke-RestMethod, Python/Node HTTP clients, " +
+ "or any other non-browser HTTP request against the task site — those endpoints reject non-browser requests. " +
+ "Do not read local files to find answers. When done, reply with ONLY the requested value.\n\n";
+
+const ARM = {
+ "codex-chrome": {
+ flags: [...NO_AXUSE],
+ env: {},
+ directive: () => "Use your built-in browser tools (the Codex Chrome browser extension, which controls the user's Chrome) for this task.\n",
+ evidence: (calls) => calls.some((c) => (c.name === "js" || c.name === "exec") && /tab|browser|goto|playwright|cua\./i.test(c.args)),
+ foreign: (calls) => calls.some((c) => /^ax_|mcp__axuse/.test(c.name) || /mcp__axuse|browser-use/.test(c.args)),
+ },
+ axuse: {
+ flags: [...DISABLE_NATIVE, ...AXUSE_FLAGS],
+ env: { AXUSE_HEADLESS: "1", AXUSE_PROFILE_DIR: join(WORK, "axuse-profiles") },
+ directive: () => "Use the axuse MCP browser tools (ax_open, ax_click, ax_type, …) for this task. They launch their own browser.\n",
+ evidence: (calls) => calls.some((c) => /ax_/.test(c.name) || /mcp__axuse__ax_/.test(c.args)),
+ foreign: (calls) => calls.some((c) => (c.name === "js" && /cua\.|tabs\.new|playwright/.test(c.args)) || /browser-use/.test(c.args)),
+ },
+ "browser-use": {
+ flags: [...DISABLE_NATIVE, ...NO_AXUSE],
+ env: {},
+ directive: () =>
+ "Use the browser-use CLI (`browser-use`, already installed and on PATH) for this task. A dedicated Chrome is already running and configured via BU_CDP_URL. " +
+ "Its official skill documentation follows.\n\n<skill name=\"browser-use\">\n" + BU_SKILL + "\n</skill>\n\n",
+ evidence: (calls) => calls.some((c) => /browser-use/.test(c.args)),
+ foreign: (calls) => calls.some((c) => /^ax_|mcp__axuse/.test(c.name) || /mcp__axuse/.test(c.args) || (c.name === "js" && /cua\.|tabs\.new/.test(c.args))),
+ },
+};
+
+function runCodex(armName, prompt, cwd, extraEnv) {
+ const arm = ARM[armName];
+ const args = ["exec", "-s", "danger-full-access", "--skip-git-repo-check", "-m", MODEL, "-c", `model_reasoning_effort="${EFFORT}"`, ...arm.flags, prompt];
+ return new Promise((resolve) => {
+ const t0 = Date.now();
+ const child = spawn("codex", args, { cwd, env: { ...process.env, ...arm.env, ...extraEnv }, stdio: ["ignore", "pipe", "pipe"] });
+ let stdout = "", stderr = "";
+ child.stdout.on("data", (d) => (stdout += d));
+ child.stderr.on("data", (d) => (stderr += d));
+ const timer = setTimeout(() => { try { child.kill(); } catch {} ; spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" }); }, RUN_TIMEOUT_MS);
+ child.on("exit", (code) => { clearTimeout(timer); resolve({ code, wallMs: Date.now() - t0, stdout, stderr, timedOut: Date.now() - t0 >= RUN_TIMEOUT_MS - 1000 }); });
+ child.on("error", (e) => { clearTimeout(timer); resolve({ code: "spawn-error " + e.message, wallMs: Date.now() - t0, stdout, stderr, timedOut: false }); });
+ });
+}
+
+function findSession(sessionId) {
+ if (!sessionId) return null;
+ const hits = [];
+ const walk = (d) => { let es; try { es = readdirSync(d, { withFileTypes: true }); } catch { return; } for (const e of es) { const p = join(d, e.name); if (e.isDirectory()) walk(p); else if (e.name.includes(sessionId)) hits.push(p); } };
+ walk(SESSIONS_ROOT);
+ return hits[0] ?? null;
+}
+const outText = (p) => typeof p.output === "string" ? p.output : Array.isArray(p.output) ? p.output.map((x) => x.text ?? "").join("") : "";
+function parseSession(file) {
+ const calls = [], byId = new Map();
+ let tokens = null, turns = 0, finalMsg = "", images = 0;
+ for (const line of readFileSync(file, "utf8").split("\n")) {
+ if (!line.trim()) continue;
+ let o; try { o = JSON.parse(line); } catch { continue; }
+ const p = o.payload ?? {};
+ if (o.type === "response_item") {
+ if (p.type === "function_call" || p.type === "custom_tool_call") {
+ const rec = { name: p.name, args: String(p.arguments ?? p.input ?? ""), outChars: 0 };
+ byId.set(p.call_id, rec); calls.push(rec);
+ } else if (p.type === "function_call_output" || p.type === "custom_tool_call_output") {
+ const rec = byId.get(p.call_id);
+ if (rec) {
+ rec.outChars = outText(p).length;
+ if (Array.isArray(p.output)) images += p.output.filter((x) => x.type === "input_image").length;
+ }
+ }
+ } else if (o.type === "token_usage_record") {
+ turns++;
+ if (p.thread_token_usage) tokens = p.thread_token_usage;
+ } else if (o.type === "event_msg" && p.type === "token_count" && p.info?.total_token_usage) {
+ tokens ??= null; // older format fallback
+ if (!tokens) tokens = p.info.total_token_usage;
+ } else if (o.type === "event_msg" && p.type === "task_complete") {
+ finalMsg = p.last_agent_message ?? "";
+ }
+ }
+ return { calls, tokens, turns, finalMsg, images };
+}
+
+const HTTP_CLIENT = /\b(curl|wget|Invoke-WebRequest|Invoke-RestMethod|iwr|irm|requests\.(get|post)|urllib|http\.client|httpx|aiohttp|WebClient|net\/http)\b|(^|[^.\w])fetch\(/i;
+function violations(calls, hosts) {
+ const v = [];
+ for (const c of calls) {
+ const text = c.args;
+ if (!hosts.some((h) => text.includes(h))) continue;
+ // In-browser JS (page context) is browser behaviour; shell HTTP is not.
+ const isShell = c.name === "exec_command" || c.name === "shell" || (c.name === "exec" && /exec_command|shell/.test(text));
+ if (isShell && HTTP_CLIENT.test(text) && !/browser-use\s*<</.test(text)) v.push(text.slice(0, 200));
+ }
+ return v;
+}
+
+// ------------------------------------------------------------------ main
+async function main() {
+ if (ARMS.includes("browser-use") && !BU_SKILL) throw new Error("bench/suite/browser-use-SKILL.md missing (run: browser-use skill show > that file)");
+ const suite = await startSuite();
+ const [tp, tc] = await Promise.all([startTunnel(suite.parentPort), startTunnel(suite.childPort)]);
+ suite.setPublic({ parent: tp.url, child: tc.url });
+ await Promise.all([waitPublic(tp.url), waitPublic(tc.url)]);
+ const hosts = [new URL(tp.url).host, new URL(tc.url).host, `127.0.0.1:${suite.parentPort}`, `127.0.0.1:${suite.childPort}`];
+ console.log(`public: parent=${tp.url} child=${tc.url}`);
+ console.log(`model=${MODEL} effort=${EFFORT} arms=${ARMS} tasks=${TASKS.length} reps=${REPS} parallel=${PARALLEL} → ${OUT}`);
+
+ const one = async (task, armName, rep) => {
+ const run = `${task}-${armName}-${rep}-${Date.now().toString(36)}${Math.floor(Math.random() * 1e4).toString(36)}`;
+ // Local-dev tasks use the loopback address, exactly like testing your own dev server.
+ const url = LOCAL_TASKS.has(task) ? `http://127.0.0.1:${suite.parentPort}/${task}?run=${run}` : `${tp.url}/${task}?run=${run}`;
+ const cwd = join(WORK, "ws", run); mkdirSync(cwd, { recursive: true });
+ let uploadFile = null;
+ if (task === "t23") { // the file to upload lives in the run's working dir
+ const g = suite.truth(run);
+ uploadFile = join(cwd, g.t23.want).replaceAll("\\", "/");
+ writeFileSync(uploadFile, g.t23.content);
+ }
+ const prompt = ARM[armName].directive() + COMMON_RULES + PROMPTS[task](url, suite.truth(run), uploadFile);
+ let bu = null, extraEnv = {};
+ if (armName === "browser-use") {
+ bu = await launchChromeForBU(run);
+ extraEnv = { BU_CDP_URL: `http://127.0.0.1:${bu.port}`, BU_NAME: run.replace(/[^a-z0-9]/gi, "").slice(-12), BH_TAB_MARKER: "0", PYTHONUTF8: "1" };
+ }
+ const r = await runCodex(armName, prompt, cwd, extraEnv);
+ if (bu) {
+ spawn("browser-use", ["--reload"], { env: { ...process.env, ...extraEnv }, stdio: "ignore" });
+ try { bu.proc.kill(); } catch {}
+ killByProfile(bu.dir);
+ setTimeout(() => { try { rmSync(bu.dir, { recursive: true, force: true }); } catch {} }, 4000);
+ }
+ const truth = suite.truth(run);
+ const sid = (r.stderr.match(/session id:\s*([0-9a-f-]{36})/) ?? [])[1];
+ const file = findSession(sid);
+ const s = file ? parseSession(file) : { calls: [], tokens: null, turns: 0, finalMsg: "", images: 0 };
+ const answer = String(s.finalMsg || r.stdout || "").trim();
+ const viol = violations(s.calls, hosts);
+ const evidence = ARM[armName].evidence(s.calls);
+ const foreign = ARM[armName].foreign(s.calls);
+ const scored = SCORE[task](truth, answer);
+ const success = scored && !viol.length && evidence && !foreign;
+ const toolOut = s.calls.reduce((a, c) => a + c.outChars, 0);
+ const rec = {
+ run, task, arm: armName, rep, model: MODEL, effort: EFFORT,
+ success, scored, violations: viol, evidence, foreign,
+ wallMs: r.wallMs, timedOut: r.timedOut, exit: r.code,
+ turns: s.turns, toolCalls: s.calls.length, images: s.images, toolOutChars: toolOut,
+ tokens: s.tokens, answer: answer.slice(0, 120), sessionFile: file,
+ // Server-side truth for this task (audit trail; large static data omitted).
+ truth: (() => { const t = { ...truth[task] }; delete t.rows; delete t.feed; delete t.orders; delete t.circles; return t; })(),
+ tools: Object.entries(s.calls.reduce((m, c) => ((m[c.name] = (m[c.name] ?? 0) + 1), m), {})).map(([k, v]) => `${k}:${v}`).join(" "),
+ };
+ appendFileSync(OUT, JSON.stringify(rec) + "\n");
+ const tok = s.tokens ? `${s.tokens.total_tokens?.toLocaleString()} (in ${s.tokens.input_tokens?.toLocaleString()}, cached ${s.tokens.cached_input_tokens?.toLocaleString()}, out ${s.tokens.output_tokens?.toLocaleString()})` : "?";
+ console.log(`${success ? "PASS" : "FAIL"} ${task.padEnd(4)} ${armName.padEnd(12)} r${rep} ${String(Math.round(r.wallMs / 1000)).padStart(4)}s turns=${s.turns} calls=${s.calls.length} tok=${tok}${viol.length ? " VIOLATION" : ""}${!evidence ? " NO-EVIDENCE" : ""}${foreign ? " FOREIGN" : ""}${!scored ? ` [answer="${answer.slice(0, 40)}"]` : ""}`);
+ try { rmSync(cwd, { recursive: true, force: true }); } catch {}
+ return rec;
+ };
+
+ for (let rep = 1; rep <= REPS; rep++) {
+ for (const task of TASKS) {
+ // Arm order rotates per task+rep so no arm systematically goes first.
+ const k = (TASKS.indexOf(task) + rep) % ARMS.length;
+ const order = [...ARMS.slice(k), ...ARMS.slice(0, k)];
+ if (PARALLEL) await Promise.all(order.map((a) => one(task, a, rep)));
+ else for (const a of order) await one(task, a, rep);
+ }
+ }
+ tp.proc.kill(); tc.proc.kill(); suite.close();
+ console.log(`done → ${OUT}\nsummarize: node bench/suite/summarize.mjs ${OUT}`);
+ process.exit(0);
+}
+main().catch((e) => { console.error(e); process.exit(1); });
diff --git a/bench/suite/server.mjs b/bench/suite/server.mjs
new file mode 100644
index 0000000..34e5a4d
--- /dev/null
+++ b/bench/suite/server.mjs
@@ -0,0 +1,569 @@
+/**
+ * axuse benchmark suite v2 — fixture server.
+ *
+ * 16 deterministic, per-run-seeded web tasks that cover the things real
+ * browser agents trip over: forms, big tables, multi-step flows, cross-origin
+ * iframes, shadow DOM, infinite scroll, hover menus, JS dialogs, new tabs,
+ * async waits, pointer drag, contenteditable, custom comboboxes, pagination
+ * and canvas.
+ *
+ * Scoring is SERVER-SIDE: every state change POSTs here, and each task's
+ * pass condition is evaluated against what the server observed — never the
+ * agent's self-report alone. Ground truth is only readable with the bench key.
+ *
+ * Designed to be served over a public HTTPS tunnel (Codex's browser
+ * extension refuses localhost/private IPs), so every URL is relative except
+ * the cross-origin child, which is injected.
+ */
+import http from "node:http";
+import { once } from "node:events";
+import { randomBytes } from "node:crypto";
+
+export const BENCH_KEY = process.env.AXBENCH_KEY ?? randomBytes(12).toString("hex");
+
+// ---------------- seeded RNG ----------------
+function hash(s) {
+ let h = 2166136261;
+ for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }
+ return h >>> 0;
+}
+function mulberry32(a) {
+ return function () {
+ a |= 0; a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+const L = "ABCDEFGHJKLMNPQRSTUVWXYZ", D = "23456789";
+const pick = (r, a, n) => Array.from({ length: n }, () => a[Math.floor(r() * a.length)]).join("");
+const code6 = (r) => pick(r, L, 3) + pick(r, D, 3);
+const FIRST = ["Ada", "Alan", "Grace", "Linus", "Barbara", "Ken", "Edsger", "Donald", "Frances", "John", "Radia", "Tim", "Margaret", "Dennis", "Bjarne", "Guido", "Anita", "Niklaus", "Leslie", "Shafi"];
+const LAST = ["Lovelace", "Turing", "Hopper", "Torvalds", "Liskov", "Thompson", "Dijkstra", "Knuth", "Allen", "McCarthy", "Perlman", "Berners", "Hamilton", "Ritchie", "Stroustrup", "Rossum", "Borg", "Wirth", "Lamport", "Goldwasser"];
+const CITIES = ["Zurich", "Zurich Airport", "Zurichberg", "Zug", "Geneva", "Basel", "Bern", "Lausanne", "Lucerne", "Lugano", "Winterthur", "St. Gallen", "Biel", "Thun", "Vienna", "Munich", "Milan", "Lyon", "Paris", "Berlin", "Hamburg", "Prague", "Warsaw", "Madrid", "Lisbon", "Oslo", "Stockholm", "Helsinki", "Dublin", "Amsterdam", "Brussels", "Copenhagen", "Budapest", "Rome", "Turin", "Graz", "Salzburg", "Innsbruck", "Freiburg", "Stuttgart"];
+const COUNTRIES = ["Austria", "Belgium", "Denmark", "France", "Germany", "Italy", "Netherlands", "Norway", "Poland", "Portugal", "Spain", "Sweden", "Swaziland", "Switzerland", "Sweden (EU)"];
+
+const SHOP = [
+ ["Trail Runner", "Shoes", 129], ["Road Racer", "Shoes", 149], ["Trail Runner GTX", "Shoes", 169], ["City Walker", "Shoes", 99],
+ ["Rain Shell", "Jackets", 189], ["Rain Shell Lite", "Jackets", 149], ["Down Parka", "Jackets", 279], ["Wind Vest", "Jackets", 89],
+ ["Merino Tee", "Tops", 59], ["Running Tank", "Tops", 35], ["Thermal Crew", "Tops", 65], ["Trail Shorts", "Bottoms", 55],
+ ["Hiking Pants", "Bottoms", 95], ["Rain Pants", "Bottoms", 119], ["Trail Socks", "Accessories", 18], ["Running Cap", "Accessories", 25],
+].map(([name, cat, price], i) => ({ id: "p" + (i + 1), name, cat, price }));
+const COLORS = ["Black", "Blue", "Red"];
+export const LOCAL_TASKS = new Set(["t17"]);
+
+const runs = new Map();
+function ground(run) {
+ if (runs.has(run)) return runs.get(run);
+ const r = mulberry32(hash(run));
+ // t3 catalog
+ const t3rows = Array.from({ length: 150 }, (_, i) => ({ sku: `SKU-${1000 + i}`, product: `Widget ${pick(r, L, 2)}-${pick(r, D, 3)}`, price: (2 + r() * 480).toFixed(2), stock: Math.floor(r() * 90) + 1 }));
+ const t3t = t3rows[Math.floor(r() * 150)]; t3t.product = `Widget TARGET-${pick(r, L, 3)}`;
+ // t7 feed
+ const feed = Array.from({ length: 300 }, (_, i) => ({ id: `p${i}`, author: `@${FIRST[Math.floor(r() * 20)].toLowerCase()}_${pick(r, "abcdefghjkmnpqrstuvwxyz", 4)}`, text: `Post #${i + 1}: ${["shipping update", "weekly notes", "bug triage", "release plan", "design review"][Math.floor(r() * 5)]}` }));
+ const t7idx = 170 + Math.floor(r() * 110);
+ // t15 orders
+ const orders = [];
+ for (let i = 0; i < 240; i++) {
+ orders.push({ id: `ORD-${5000 + i}`, customer: `${FIRST[Math.floor(r() * 20)]} ${LAST[Math.floor(r() * 20)]}`, status: ["Paid", "Shipped", "Pending", "Paid", "Shipped"][Math.floor(r() * 5)], total: (10 + r() * 900).toFixed(2), code: code6(r) });
+ }
+ const tgtCustomer = `${FIRST[Math.floor(r() * 20)]} Q. ${LAST[Math.floor(r() * 20)]}`;
+ const slots = new Set(); while (slots.size < 4) slots.add(40 + Math.floor(r() * 190));
+ const [s0, ...rest] = [...slots];
+ orders[s0] = { ...orders[s0], customer: tgtCustomer, status: "Refunded" };
+ rest.forEach((s, k) => (orders[s] = { ...orders[s], customer: tgtCustomer, status: ["Paid", "Shipped", "Pending"][k] }));
+ // t16 canvas circles
+ const colors = ["red", "blue", "green", "orange", "purple"];
+ const circles = colors.map((c, i) => ({ color: c, x: 70 + i * 115 + Math.floor(r() * 20), y: 80 + Math.floor(r() * 140), rad: 26 }));
+ for (let i = circles.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [circles[i].x, circles[j].x] = [circles[j].x, circles[i].x]; }
+ const g = {
+ t1: { code: code6(r), claimed: false },
+ t2: { valid: false, confirmation: null, got: null },
+ t3: { rows: t3rows, target: t3t },
+ t4: { color: ["Red", "Green", "Blue"][Math.floor(r() * 3)], number: String(100 + Math.floor(r() * 900)), word: pick(r, L, 5), token: pick(r, L, 4) + pick(r, D, 4), step: 0, wrong: 0 },
+ t5: { code: code6(r), clicked: false },
+ t6: { ref: code6(r), saved: null },
+ t7: { feed, idx: t7idx, likes: [], code: code6(r) },
+ t8: { code: code6(r), exported: false, deleted: false },
+ t9: { files: ["report-q3.pdf", "old-backup.zip", "notes.txt", "photo.png", "archive-2024.tar"], target: "old-backup.zip", deletes: [], code: code6(r) },
+ t10: { code: code6(r), helpViewed: false, verified: false, attempts: 0, receipt: code6(r) },
+ t11: { started: null, downloaded: false, early: 0, code: code6(r) },
+ t12: { cols: { "To do": ["Write docs", "Fix login bug", "Update deps"], "In progress": ["Refactor API"], Done: ["Set up CI"] }, card: "Fix login bug", code: code6(r) },
+ t13: { want: "Release 4.2 fixes the export bug.", got: null, code: code6(r) },
+ t14: { got: null, code: code6(r) },
+ t15: { orders, customer: tgtCustomer, target: orders[s0].id, viewed: [] },
+ t16: { circles, hits: [], code: code6(r) },
+ t17: { todos: null, code: code6(r) },
+ t18: { cart: [], coupon: null, order: null, orderNo: "ORD-" + pick(r, D, 6) },
+ t19: { rows: Array.from({ length: 1200 }, (_, i) => ({ id: `INV-${10000 + i}`, vendor: `${LAST[Math.floor(r() * 20)]} GmbH`, amount: (50 + r() * 9000).toFixed(2) })), idx: 700 + Math.floor(r() * 450), approved: [], code: code6(r) },
+ t20: { saved: null, code: code6(r) },
+ t21: { attempts: [], created: null, code: code6(r) },
+ t22: { got: null, code: code6(r) },
+ t23: { upload: null, want: "axbench-avatar-" + pick(r, L, 4).toLowerCase() + ".txt", content: "avatar:" + pick(r, L, 8), code: code6(r) },
+ };
+ runs.set(run, g);
+ return g;
+}
+
+// ---------------- page shell ----------------
+const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
+const page = (title, body, script = "") => `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${title}</title>
+<meta name="viewport" content="width=device-width,initial-scale=1">
+<style>body{font-family:system-ui,sans-serif;max-width:900px;margin:24px auto;padding:0 16px;color:#222}
+table{border-collapse:collapse}td,th{border:1px solid #ccc;padding:4px 10px;font-size:14px}
+button{padding:6px 14px;margin:4px;cursor:pointer}input,select{margin:4px;padding:4px}.out{min-height:1.4em;font-size:18px;margin-top:8px}</style>
+</head><body>${body}<script>
+const RUN=new URLSearchParams(location.search).get('run');
+async function post(path,body){const r=await fetch(path+(path.includes('?')?'&':'?')+'run='+encodeURIComponent(RUN),{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body||{})});return r.json();}
+${script}</script></body></html>`;
+
+const json = (res, obj, status = 200) => { res.statusCode = status; res.setHeader("content-type", "application/json"); res.setHeader("cache-control", "no-store"); res.end(JSON.stringify(obj)); };
+const html = (res, s) => { res.setHeader("content-type", "text/html; charset=utf-8"); res.setHeader("cache-control", "no-store"); res.end(s); };
+
+/** Browser-only gate: fetch() from a page always carries Sec-Fetch-*; shells don't. */
+function browserOnly(req, res) {
+ const site = req.headers["sec-fetch-site"], mode = req.headers["sec-fetch-mode"];
+ if (!site || site === "none" || !mode || mode === "navigate") {
+ json(res, { error: "browser-only endpoint: complete this action in a real browser page" }, 403);
+ return false;
+ }
+ return true;
+}
+const readBody = (req) => new Promise((ok) => { let b = ""; req.on("data", (d) => (b += d)); req.on("end", () => { try { ok(JSON.parse(b || "{}")); } catch { ok({}); } }); });
+
+// ---------------- task pages ----------------
+const P = {};
+
+P.t1 = () => page("Claim", `<h1>Claim your code</h1><p>Press the button to reveal your personal code.</p>
+<button id="claim">Claim code</button><div class="out" id="out"></div>`,
+`claim.onclick=async()=>{const d=await post('/api/t1/claim');out.textContent='code: '+d.code;};`);
+
+P.t2 = () => page("Create account", `<h1>Create account</h1>
+<form id="f"><label for="f1">Full name</label><input id="f1"><br>
+<label for="f2">Email</label><input id="f2" type="email"><br>
+<label for="sel">Plan</label><select id="sel"><option value="">—</option><option>Alpha</option><option>Beta</option><option>Gamma</option></select><br>
+<input type="checkbox" id="cb"><label for="cb">I agree</label><br><button type="submit">Submit</button></form><div class="out" id="out"></div>`,
+`f.onsubmit=async(e)=>{e.preventDefault();const d=await post('/api/t2/submit',{name:f1.value,email:f2.value,plan:sel.value,agree:cb.checked});out.textContent=d.ok?('confirmation: '+d.confirmation):('error: '+d.error);};`);
+
+P.t3 = (g) => page("Catalog", `<h1>Catalog</h1><p>150 products.</p><table><thead><tr><th>SKU</th><th>Product</th><th>Price ($)</th><th>Stock</th></tr></thead><tbody>${g.t3.rows.map((x) => `<tr><td>${x.sku}</td><td>${x.product}</td><td>${x.price}</td><td>${x.stock}</td></tr>`).join("")}</tbody></table>`);
+
+P.t4 = () => page("Wizard", `<h1>Setup wizard</h1><div id="app">loading…</div>`, `
+async function step(msg){const r=await (await fetch('/api/t4/state?run='+RUN)).json();
+if(r.done){app.innerHTML='<p>final token: <b>'+r.token+'</b></p>';return;}
+let h=msg?'<p style="color:#b00">'+msg+'</p>':'';
+if(r.step===0)h+='<p>Step 1 of 4 — pick the color the server expects. (Hint: it is the color of the sky on a clear day, unless it is not.)</p>'+['Red','Green','Blue'].map(o=>'<button data-c="'+o+'">'+o+'</button>').join('');
+if(r.step===1)h+='<p>Step 2 of 4 — enter the displayed number:</p><p>number: <b>'+r.number+'</b></p><input id="num" aria-label="Number"><button id="v">Verify</button>';
+if(r.step===2)h+='<p>Step 3 of 4 — click the exact word <b>'+r.word+'</b>:</p>'+r.decoys.map(o=>'<button data-w="'+o+'">'+o+'</button>').join('');
+if(r.step===3)h+='<p>Step 4 of 4 — finish:</p><button id="fin">Finish</button>';
+app.innerHTML=h;
+app.querySelectorAll('[data-c]').forEach(b=>b.onclick=async()=>{const d=await post('/api/t4/pick',{c:b.dataset.c});step(d.ok?'':'wrong choice — try another color');});
+app.querySelectorAll('[data-w]').forEach(b=>b.onclick=async()=>{const d=await post('/api/t4/word',{w:b.dataset.w});step(d.ok?'':'wrong word');});
+const v=document.getElementById('v');if(v)v.onclick=async()=>{const d=await post('/api/t4/num',{n:document.getElementById('num').value});step(d.ok?'':'wrong number');};
+const f=document.getElementById('fin');if(f)f.onclick=async()=>{await post('/api/t4/finish');step();};}
+step();`);
+
+P.t5 = (g, base) => page("Host", `<h1>Host page</h1><p>The details live in the embedded secure panel below.</p>
+<iframe title="Secure panel" src="${base.child}/t5child?run=${encodeURIComponent(g.__run)}" style="width:440px;height:200px;border:1px solid #ccc"></iframe>`);
+
+P.t6 = () => page("Preferences", `<h1>Notification preferences</h1><notify-settings></notify-settings><div class="out" id="out"></div>`, `
+class ToggleSwitch extends HTMLElement{constructor(){super();const s=this.attachShadow({mode:'open'});s.innerHTML='<style>button{width:46px;height:24px;border-radius:12px;border:1px solid #888;background:#ddd}button[aria-checked=true]{background:#2a7}</style><button role="switch" aria-checked="false" aria-label="'+this.getAttribute('label')+'"></button>';this.btn=s.querySelector('button');this.btn.onclick=()=>{this.btn.setAttribute('aria-checked',String(this.btn.getAttribute('aria-checked')!=='true'));};}get on(){return this.btn.getAttribute('aria-checked')==='true';}}
+customElements.define('toggle-switch',ToggleSwitch);
+class NotifySettings extends HTMLElement{constructor(){super();const s=this.attachShadow({mode:'open'});
+s.innerHTML='<style>fieldset{margin:10px 0}</style><fieldset><legend>Channels</legend><label>Email alerts <toggle-switch label="Email alerts"></toggle-switch></label><br><label>SMS alerts <toggle-switch label="SMS alerts"></toggle-switch></label></fieldset><fieldset><legend>Digest frequency</legend><label><input type="radio" name="fq" value="Daily" checked> Daily</label><label><input type="radio" name="fq" value="Weekly"> Weekly</label><label><input type="radio" name="fq" value="Monthly"> Monthly</label></fieldset><button id="save">Save preferences</button>';
+s.getElementById('save').onclick=async()=>{const t=s.querySelectorAll('toggle-switch');const fq=s.querySelector('input[name=fq]:checked').value;const d=await post('/api/t6/save',{email:t[0].on,sms:t[1].on,frequency:fq});document.getElementById('out').textContent=d.ok?'Saved. Reference: '+d.ref:'Saved settings do not match what was requested.';};}}
+customElements.define('notify-settings',NotifySettings);`);
+
+P.t7 = () => page("Feed", `<h1>Team feed</h1><div id="feed"></div><div id="sentinel" style="height:40px">Loading more…</div><div class="out" id="out" style="position:fixed;top:0;right:12px;background:#ffd;padding:4px 8px"></div>`, `
+let next=0,busy=false;async function more(){if(busy)return;busy=true;const r=await (await fetch('/api/t7/page?run='+RUN+'&from='+next)).json();
+for(const p of r.items){const d=document.createElement('article');d.style.cssText='border:1px solid #ddd;margin:8px 0;padding:8px';d.innerHTML='<b>'+p.author+'</b><p>'+p.text+'</p><button>Like</button>';d.querySelector('button').onclick=async()=>{const x=await post('/api/t7/like',{id:p.id});document.getElementById('out').textContent=x.code?('Liked! code: '+x.code):'Liked.';};feed.appendChild(d);}
+next+=r.items.length;if(!r.more)sentinel.textContent='End of feed';busy=false;}
+new IntersectionObserver(e=>{if(e[0].isIntersecting)more();}).observe(sentinel);`);
+
+P.t8 = () => page("Dashboard", `<style>#menu{position:relative;display:inline-block}#sub{display:none;position:absolute;top:100%;left:0;background:#fff;border:1px solid #ccc;min-width:180px;z-index:2}#sub.open{display:block}#sub a{display:block;padding:6px 10px}</style>
+<nav><a href="#">Home</a> · <span id="menu"><a href="#" id="acct" aria-haspopup="true" onclick="return false">Account ▾</a><div id="sub" role="menu"><a role="menuitem" href="#" data-a="profile">Profile</a><a role="menuitem" href="#" data-a="export">Export data</a><a role="menuitem" href="#" data-a="delete">Delete account</a></div></span></nav>
+<h1>Dashboard</h1><p>Welcome back.</p><div class="out" id="out"></div>`, `
+let t;menu.onmouseenter=()=>{clearTimeout(t);sub.classList.add('open');};menu.onmouseleave=()=>{t=setTimeout(()=>sub.classList.remove('open'),250);};
+sub.querySelectorAll('a').forEach(a=>a.onclick=async(e)=>{e.preventDefault();const d=await post('/api/t8/'+a.dataset.a);out.textContent=d.msg;});`);
+
+P.t9 = (g) => page("Files", `<h1>Files</h1><table><thead><tr><th>Name</th><th></th></tr></thead><tbody>${g.t9.files.map((f) => `<tr><td>${f}</td><td><button data-f="${f}" aria-label="Delete ${f}">Delete</button></td></tr>`).join("")}</tbody></table><div class="out" id="out"></div>`, `
+document.querySelectorAll('[data-f]').forEach(b=>b.onclick=async()=>{const f=b.dataset.f;if(!confirm('Delete '+f+'? This cannot be undone.'))return;const why=prompt('Type the reason for deleting '+f+':');if(why===null)return;const d=await post('/api/t9/delete',{file:f,reason:why});if(d.ok){b.closest('tr').remove();}out.textContent=d.msg;});`);
+
+P.t10 = () => page("Verify", `<h1>Verify your account</h1><p>Your verification code is shown in the <a href="/t10help?run=__RUN__" target="_blank" rel="opener">help center</a> (opens in a new tab). Enter it below.</p>
+<input id="code" aria-label="Verification code"><button id="go">Verify</button><div class="out" id="out"></div>`, `
+document.querySelector('a').href='/t10help?run='+encodeURIComponent(RUN);go.onclick=async()=>{const d=await post('/api/t10/verify',{code:code.value});out.textContent=d.msg;};`);
+P.t10help = () => page("Help center", `<h1>Help center</h1><p>Your verification code is: <b id="c">…</b></p>`, `fetch('/api/t10/help?run='+RUN,{method:'POST'}).then(r=>r.json()).then(d=>c.textContent=d.code);`);
+
+P.t11 = () => page("Reports", `<h1>Reports</h1><button id="gen">Generate report</button><div id="status" class="out"></div><div id="dl"></div><div class="out" id="out"></div>`, `
+gen.onclick=async()=>{gen.disabled=true;await post('/api/t11/start');status.textContent='Generating… (this takes a few seconds)';
+const iv=setInterval(async()=>{const s=await (await fetch('/api/t11/status?run='+RUN)).json();if(s.ready){clearInterval(iv);status.textContent='Report ready.';dl.innerHTML='<button id="d">Download report</button>';document.getElementById('d').onclick=async()=>{const x=await post('/api/t11/download');out.textContent=x.msg;};}else status.textContent='Generating… '+s.pct+'%';},500);};`);
+
+P.t12 = (g) => page("Board", `<style>.cols{display:flex;gap:12px}.col{flex:1;border:1px solid #ccc;min-height:260px;padding:8px;background:#fafafa}.card{background:#fff;border:1px solid #999;padding:8px;margin:6px 0;cursor:grab;user-select:none;touch-action:none}.drag{opacity:.6}.over{background:#e6f4ff}</style>
+<h1>Sprint board</h1><p>Drag cards between columns.</p><div class="cols">${Object.entries(g.t12.cols).map(([c, cards]) => `<section class="col" data-col="${c}" aria-label="${c} column"><h2>${c}</h2>${cards.map((k) => `<div class="card" role="listitem">${k}</div>`).join("")}</section>`).join("")}</div><div class="out" id="out"></div>`, `
+let drag=null,ghost=null;
+document.addEventListener('pointerdown',e=>{const c=e.target.closest('.card');if(!c)return;drag=c;c.classList.add('drag');c.setPointerCapture?.(e.pointerId);});
+document.addEventListener('pointermove',e=>{if(!drag)return;document.querySelectorAll('.col').forEach(x=>x.classList.remove('over'));const el=document.elementsFromPoint(e.clientX,e.clientY).find(x=>x.classList&&x.classList.contains('col'));if(el)el.classList.add('over');});
+document.addEventListener('pointerup',async e=>{if(!drag)return;const c=drag;drag=null;c.classList.remove('drag');document.querySelectorAll('.col').forEach(x=>x.classList.remove('over'));
+const col=document.elementsFromPoint(e.clientX,e.clientY).find(x=>x.classList&&x.classList.contains('col'));if(!col||col.contains(c))return;col.appendChild(c);const d=await post('/api/t12/move',{card:c.textContent,to:col.dataset.col});out.textContent=d.msg;});`);
+
+P.t13 = () => page("Release notes", `<h1>New release note</h1><div id="ed" contenteditable="true" role="textbox" aria-multiline="true" aria-label="Release note editor" style="border:1px solid #888;min-height:100px;padding:8px"></div>
+<button id="pub">Publish</button><div class="out" id="out"></div>`, `pub.onclick=async()=>{const d=await post('/api/t13/publish',{text:ed.innerText});out.textContent=d.msg;};`);
+
+P.t14 = () => page("Shipping", `<style>.lb{border:1px solid #888;max-height:180px;overflow:auto;position:absolute;background:#fff;z-index:3;min-width:220px;margin:0;padding:0;list-style:none}.lb li{padding:4px 8px;cursor:pointer}.lb li:hover{background:#eef}.wrap{position:relative;margin:10px 0}</style>
+<h1>Shipping destination</h1>
+<div class="wrap"><label id="cl">City</label><br><input id="city" role="combobox" aria-labelledby="cl" aria-autocomplete="list" aria-expanded="false" aria-controls="cityl" autocomplete="off" placeholder="Start typing…"><ul id="cityl" class="lb" role="listbox" hidden></ul></div>
+<div class="wrap"><span id="ctl">Country</span><br><button id="country" aria-haspopup="listbox" aria-labelledby="ctl country" aria-expanded="false">Choose…</button><ul id="cl2" class="lb" role="listbox" hidden></ul></div>
+<button id="sub">Save destination</button><div class="out" id="out"></div>`, `
+const CITIES=${JSON.stringify(CITIES)},COUNTRIES=${JSON.stringify(COUNTRIES)};let cityVal='',countryVal='';
+city.oninput=()=>{const q=city.value.trim().toLowerCase();cityVal='';if(!q){cityl.hidden=true;return;}setTimeout(()=>{const m=CITIES.filter(c=>c.toLowerCase().startsWith(q));cityl.innerHTML=m.map(c=>'<li role="option">'+c+'</li>').join('');cityl.hidden=!m.length;city.setAttribute('aria-expanded',String(!!m.length));cityl.querySelectorAll('li').forEach(li=>li.onmousedown=(e)=>{e.preventDefault();cityVal=li.textContent;city.value=cityVal;cityl.hidden=true;city.setAttribute('aria-expanded','false');});},300);};
+country.onclick=()=>{cl2.innerHTML=COUNTRIES.map(c=>'<li role="option">'+c+'</li>').join('');cl2.hidden=!cl2.hidden;country.setAttribute('aria-expanded',String(!cl2.hidden));cl2.querySelectorAll('li').forEach(li=>li.onclick=()=>{countryVal=li.textContent;country.textContent=countryVal;cl2.hidden=true;country.setAttribute('aria-expanded','false');});};
+sub.onclick=async()=>{const d=await post('/api/t14/save',{city:cityVal,typed:city.value,country:countryVal});out.textContent=d.msg;};`);
+
+P.t15 = () => page("Orders", `<h1>Orders</h1><label for="q">Search customer</label><input id="q" type="search"><table><thead><tr><th>Order</th><th>Customer</th><th>Status</th><th>Total</th><th></th></tr></thead><tbody id="tb"></tbody></table>
+<div><button id="prev">Previous</button> <span id="pg"></span> <button id="nxt">Next</button></div><div class="out" id="out"></div>`, `
+let pageNo=0,q='',timer;async function load(){const r=await (await fetch('/api/t15/list?run='+RUN+'&page='+pageNo+'&q='+encodeURIComponent(q))).json();
+tb.innerHTML=r.rows.map(o=>'<tr><td>'+o.id+'</td><td>'+o.customer+'</td><td>'+o.status+'</td><td>'+o.total+'</td><td><button data-id="'+o.id+'">Details</button></td></tr>').join('');
+pg.textContent='Page '+(pageNo+1)+' of '+r.pages;prev.disabled=pageNo===0;nxt.disabled=pageNo>=r.pages-1;
+tb.querySelectorAll('button').forEach(b=>b.onclick=async()=>{const d=await post('/api/t15/details',{id:b.dataset.id});out.textContent=d.msg;});}
+q_=document.getElementById('q');q_.oninput=()=>{clearTimeout(timer);timer=setTimeout(()=>{q=q_.value;pageNo=0;load();},400);};prev.onclick=()=>{pageNo--;load();};nxt.onclick=()=>{pageNo++;load();};load();`);
+
+P.t16 = (g) => page("Canvas", `<h1>Target practice</h1><p>Click the requested shape on the canvas.</p><canvas id="cv" width="640" height="300" style="border:1px solid #888"></canvas><div class="out" id="out"></div>`, `
+const C=${JSON.stringify(g.t16.circles)};const x=cv.getContext('2d');C.forEach(c=>{x.beginPath();x.arc(c.x,c.y,c.rad,0,7);x.fillStyle=c.color;x.fill();});
+cv.onclick=async(e)=>{const r=cv.getBoundingClientRect();const d=await post('/api/t16/hit',{x:(e.clientX-r.left)*cv.width/r.width,y:(e.clientY-r.top)*cv.height/r.height});out.textContent=d.msg;};`);
+
+P.t17 = () => page("Todo (dev)", `<h1>Todo — local dev build</h1>
+<form id="f"><label for="new">New todo</label><input id="new" autocomplete="off"><button>Add</button></form>
+<ul id="list" style="list-style:none;padding:0"></ul><button id="sync">Sync to server</button><div class="out" id="out"></div>`, `
+let todos=[];function render(){list.innerHTML=todos.map((t,i)=>'<li><input type="checkbox" id="c'+i+'" '+(t.done?'checked':'')+'><label for="c'+i+'">'+t.text+'</label> <button data-del="'+i+'" aria-label="Delete '+t.text+'">✕</button></li>').join('');
+list.querySelectorAll('input').forEach((c,i)=>c.onchange=()=>{todos[i].done=c.checked;});list.querySelectorAll('[data-del]').forEach(b=>b.onclick=()=>{todos.splice(+b.dataset.del,1);render();});}
+f.onsubmit=(e)=>{e.preventDefault();const v=document.getElementById('new').value.trim();if(v){todos.push({text:v,done:false});document.getElementById('new').value='';render();}};
+sync.onclick=async()=>{const d=await post('/api/t17/sync',{todos});out.textContent=d.msg;};`);
+
+P.t18 = () => page("Shop", `<h1>Outdoor Shop</h1><label for="q">Search</label><input id="q" type="search"> <label for="cat">Category</label><select id="cat"><option value="">All</option>${[...new Set(SHOP.map((p) => p.cat))].map((c) => `<option>${c}</option>`).join("")}</select>
+<p><a id="cartlink" href="#">Cart</a></p><ul id="res"></ul>`, `
+const SHOP=${JSON.stringify(SHOP)};cartlink.href='/t18cart?run='+encodeURIComponent(RUN);
+function render(){const qv=q.value.toLowerCase().trim(),c=cat.value;res.innerHTML=SHOP.filter(p=>(!qv||p.name.toLowerCase().includes(qv))&&(!c||p.cat===c)).map(p=>'<li><a href="/t18p?id='+p.id+'&run='+encodeURIComponent(RUN)+'">'+p.name+'</a> — CHF '+p.price+'</li>').join('')||'<li>No products found.</li>';}
+q.oninput=render;cat.onchange=render;render();`);
+
+P.t18p = (g, base, u) => {
+ const p = SHOP.find((x) => x.id === u.searchParams.get("id")) ?? SHOP[0];
+ return page(p.name, `<p><a href="/t18?run=__R__" id="back">← Back to shop</a> · <a href="/t18cart?run=__R__" id="cl">Cart</a></p><h1>${p.name}</h1><p>CHF ${p.price} · ${p.cat}</p>
+<label for="size">Size</label><select id="size"><option value="">Choose size</option><option>S</option><option>M</option><option>L</option></select>
+<fieldset><legend>Color</legend>${COLORS.map((c) => `<label><input type="radio" name="color" value="${c}">${c}</label>`).join(" ")}</fieldset>
+<label for="qty">Quantity</label><input id="qty" type="number" min="1" value="1" style="width:60px"> <button id="add">Add to cart</button><div class="out" id="out"></div>`,
+ `document.querySelectorAll('a').forEach(a=>a.href=a.href.replace('__R__',encodeURIComponent(RUN)));
+add.onclick=async()=>{const col=document.querySelector('input[name=color]:checked');if(!size.value||!col){out.textContent='Please choose a size and a color.';return;}const d=await post('/api/t18/add',{id:${JSON.stringify(p.id)},size:size.value,color:col.value,qty:+qty.value});out.textContent=d.msg;};`);
+};
+
+P.t18cart = (g) => page("Cart", `<p><a href="/t18?run=__R__">← Continue shopping</a></p><h1>Your cart</h1><table><thead><tr><th>Item</th><th>Size</th><th>Color</th><th>Qty</th><th>Price</th><th></th></tr></thead><tbody id="tb"></tbody></table>
+<p id="tot"></p><label for="coupon">Coupon code</label><input id="coupon"><button id="apply">Apply</button><div class="out" id="cmsg"></div><p><a id="co" href="/t18checkout?run=__R__">Proceed to checkout</a></p>`, `
+document.querySelectorAll('a').forEach(a=>a.href=a.href.replace('__R__',encodeURIComponent(RUN)));
+async function load(){const c=await (await fetch('/api/t18/cart?run='+RUN)).json();tb.innerHTML=c.items.map((it,i)=>'<tr><td>'+it.name+'</td><td>'+it.size+'</td><td>'+it.color+'</td><td><input type="number" min="0" value="'+it.qty+'" aria-label="Quantity of '+it.name+' '+it.size+' '+it.color+'" data-i="'+i+'" style="width:56px"></td><td>CHF '+(it.price*it.qty)+'</td><td><button data-rm="'+i+'" aria-label="Remove '+it.name+' '+it.size+' '+it.color+'">Remove</button></td></tr>').join('');
+tot.textContent='Total: CHF '+c.total+(c.coupon?' (coupon '+c.coupon+' applied)':'');
+tb.querySelectorAll('input').forEach(x=>x.onchange=async()=>{await post('/api/t18/qty',{i:+x.dataset.i,qty:+x.value});load();});
+tb.querySelectorAll('[data-rm]').forEach(b=>b.onclick=async()=>{await post('/api/t18/qty',{i:+b.dataset.rm,qty:0});load();});}
+apply.onclick=async()=>{const d=await post('/api/t18/coupon',{code:coupon.value});cmsg.textContent=d.msg;load();};load();`);
+
+P.t18checkout = () => page("Checkout", `<h1>Checkout</h1><form id="f">
+<label for="nm">Full name</label><input id="nm" required><br><label for="st">Street</label><input id="st" required><br>
+<label for="zip">ZIP</label><input id="zip" required><span id="ziperr" style="color:#b00"></span><br><label for="ci">City</label><input id="ci" required><br>
+<label for="ct">Country</label><select id="ct"><option value="">Choose…</option><option>Austria</option><option>Germany</option><option>Switzerland</option></select><br>
+<fieldset><legend>Shipping</legend><label><input type="radio" name="ship" value="Standard" checked>Standard (free)</label><label><input type="radio" name="ship" value="Express">Express (CHF 15)</label></fieldset>
+<button>Place order</button></form><div class="out" id="out"></div>`, `
+f.onsubmit=async(e)=>{e.preventDefault();ziperr.textContent='';if(!/^\\d{4}$/.test(zip.value.trim())){ziperr.textContent=' ZIP must be 4 digits';return;}
+const d=await post('/api/t18/order',{name:nm.value,street:st.value,zip:zip.value.trim(),city:ci.value,country:ct.value,ship:document.querySelector('input[name=ship]:checked').value});out.textContent=d.msg;};`);
+
+P.t19 = () => page("Invoices", `<h1>Invoice approvals</h1><p>1,200 pending invoices.</p><div id="vp" role="grid" aria-label="Invoices" aria-rowcount="1200" style="height:420px;overflow:auto;border:1px solid #888;position:relative"><div id="spacer" style="position:relative"></div></div><div class="out" id="out"></div>`, `
+const H=34;let rows=[];fetch('/api/t19/rows?run='+RUN).then(r=>r.json()).then(d=>{rows=d.rows;spacer.style.height=(rows.length*H)+'px';draw();});
+function draw(){const top=vp.scrollTop,first=Math.max(0,Math.floor(top/H)-3),last=Math.min(rows.length,Math.ceil((top+vp.clientHeight)/H)+3);
+spacer.innerHTML=rows.slice(first,last).map((r,k)=>{const i=first+k;return '<div role="row" aria-rowindex="'+(i+1)+'" style="position:absolute;top:'+(i*H)+'px;left:0;right:0;height:'+H+'px;display:flex;gap:16px;align-items:center;padding:0 8px;border-bottom:1px solid #eee"><span role="gridcell" style="width:110px">'+r.id+'</span><span role="gridcell" style="width:180px">'+r.vendor+'</span><span role="gridcell" style="width:100px">'+r.amount+'</span><button data-id="'+r.id+'" aria-label="Approve '+r.id+'">Approve</button></div>';}).join('');
+spacer.querySelectorAll('button').forEach(b=>b.onclick=async()=>{const d=await post('/api/t19/approve',{id:b.dataset.id});out.textContent=d.msg;});}
+vp.addEventListener('scroll',draw);`);
+
+P.t20 = () => page("Trip dates", `<style>.cal{border:1px solid #888;padding:8px;display:inline-block;background:#fff}.cal table td{padding:0}.cal button{width:36px;margin:1px}</style>
+<h1>Plan your trip</h1><div><label for="dep">Departure</label> <input id="dep" readonly placeholder="Pick a date" aria-haspopup="dialog"></div>
+<div><label for="ret">Return</label> <input id="ret" readonly placeholder="Pick a date" aria-haspopup="dialog"></div><div id="calhost"></div><button id="save">Save dates</button><div class="out" id="out"></div>`, `
+const M=['January','February','March','April','May','June','July','August','September','October','November','December'];let target=null,y=2026,m=9;
+function open(inp){target=inp;y=2026;m=9;draw();}
+function draw(){const first=new Date(Date.UTC(y,m,1)).getUTCDay(),days=new Date(Date.UTC(y,m+1,0)).getUTCDate();let h='<div class="cal" role="dialog" aria-label="Choose date"><button id="pv" aria-label="Previous month">‹</button> <b id="ml">'+M[m]+' '+y+'</b> <button id="nx" aria-label="Next month">›</button><table><tr>'+['Su','Mo','Tu','We','Th','Fr','Sa'].map(d=>'<th>'+d+'</th>').join('')+'</tr><tr>';
+let c=0;for(let i=0;i<first;i++){h+='<td></td>';c++;}for(let d=1;d<=days;d++){h+='<td><button data-d="'+d+'" aria-label="'+M[m]+' '+d+', '+y+'">'+d+'</button></td>';c++;if(c%7===0)h+='</tr><tr>';}h+='</tr></table></div>';calhost.innerHTML=h;
+pv.onclick=()=>{m--;if(m<0){m=11;y--;}draw();};nx.onclick=()=>{m++;if(m>11){m=0;y++;}draw();};
+calhost.querySelectorAll('[data-d]').forEach(b=>b.onclick=()=>{target.value=y+'-'+String(m+1).padStart(2,'0')+'-'+String(b.dataset.d).padStart(2,'0');calhost.innerHTML='';});}
+dep.onclick=()=>open(dep);ret.onclick=()=>open(ret);save.onclick=async()=>{const d=await post('/api/t20/save',{dep:dep.value,ret:ret.value});out.textContent=d.msg;};`);
+
+P.t21 = () => page("Sign up", `<h1>Create your account</h1><form id="f" novalidate>
+<label for="u">Username</label><input id="u" autocomplete="off"><span class="err" id="eu" style="color:#b00"></span><br>
+<label for="pw">Password</label><input id="pw" type="password"><span class="err" id="ep" style="color:#b00"></span><br>
+<label for="pw2">Confirm password</label><input id="pw2" type="password"><span class="err" id="ep2" style="color:#b00"></span><br>
+<label for="bd">Date of birth (YYYY-MM-DD)</label><input id="bd"><span class="err" id="eb" style="color:#b00"></span><br>
+<input type="checkbox" id="tos"><label for="tos">I accept the terms</label><span class="err" id="et" style="color:#b00"></span><br>
+<button>Create account</button></form><div class="out" id="out"></div>`, `
+f.onsubmit=async(e)=>{e.preventDefault();document.querySelectorAll('.err').forEach(x=>x.textContent='');const d=await post('/api/t21/signup',{u:u.value,pw:pw.value,pw2:pw2.value,bd:bd.value,tos:tos.checked});
+if(d.ok){out.textContent='Welcome! Account code: '+d.code;return;}out.textContent='Please fix the errors above.';for(const [k,v] of Object.entries(d.errors||{}))document.getElementById(k).textContent=' '+v;};`);
+
+P.t22 = (g, base) => page("Portal", `<h1>Partner portal</h1><p>The partner widget is embedded below.</p>
+<iframe title="Partner widget" src="${base.child}/t22outer?run=${encodeURIComponent(g.__run)}" style="width:560px;height:330px;border:1px solid #ccc"></iframe>`);
+
+P.t23 = () => page("Profile", `<h1>Profile picture</h1><form id="f"><label for="av">Avatar file</label> <input type="file" id="av"> <button>Upload</button></form><div class="out" id="out"></div>`, `
+f.onsubmit=async(e)=>{e.preventDefault();const file=av.files[0];if(!file){out.textContent='Choose a file first.';return;}const text=await file.text();const d=await post('/api/t23/upload',{name:file.name,size:file.size,text:text.slice(0,200)});out.textContent=d.msg;};`);
+
+// ---------------- scoring (server truth) ----------------
+export const SCORE = {
+ t1: (g, a) => g.t1.claimed && a.includes(g.t1.code),
+ t2: (g, a) => g.t2.valid && a.includes(g.t2.confirmation),
+ t3: (g, a) => a.includes(g.t3.target.price) && a.includes(String(g.t3.target.stock)),
+ t4: (g, a) => g.t4.step >= 4 && a.includes(g.t4.token),
+ t5: (g, a) => g.t5.clicked && a.includes(g.t5.code),
+ t6: (g, a) => !!g.t6.saved && g.t6.saved.email === true && g.t6.saved.sms === false && g.t6.saved.frequency === "Weekly" && a.includes(g.t6.ref),
+ t7: (g, a) => g.t7.likes.length === 1 && g.t7.likes[0] === g.t7.feed[g.t7.idx].id && a.includes(g.t7.code),
+ t8: (g, a) => g.t8.exported && !g.t8.deleted && a.includes(g.t8.code),
+ t9: (g, a) => g.t9.deletes.length === 1 && g.t9.deletes[0].file === g.t9.target && g.t9.deletes[0].reason.trim().toLowerCase() === "cleanup" && a.includes(g.t9.code),
+ t10: (g, a) => g.t10.helpViewed && g.t10.verified && a.includes(g.t10.receipt),
+ t11: (g, a) => g.t11.downloaded && a.includes(g.t11.code),
+ t12: (g, a) => g.t12.cols.Done.includes(g.t12.card) && a.includes(g.t12.code),
+ t13: (g, a) => g.t13.got?.trim() === g.t13.want && a.includes(g.t13.code),
+ t14: (g, a) => g.t14.got?.city === "Zurich" && g.t14.got?.country === "Switzerland" && a.includes(g.t14.code),
+ t15: (g, a) => g.t15.viewed.includes(g.t15.target) && a.includes(g.t15.orders.find((o) => o.id === g.t15.target).code),
+ t16: (g, a) => g.t16.hits.length >= 1 && g.t16.hits.at(-1) === "red" && a.includes(g.t16.code),
+ t17: (g, a) => t17ok(g.t17.todos) && a.includes(g.t17.code),
+ t18: (g, a) => !!g.t18.order && t18ok(g.t18.order) && a.includes(g.t18.orderNo),
+ t19: (g, a) => g.t19.approved.length === 1 && g.t19.approved[0] === g.t19.rows[g.t19.idx].id && a.includes(g.t19.code),
+ t20: (g, a) => g.t20.saved?.dep === "2026-12-17" && g.t20.saved?.ret === "2027-01-03" && a.includes(g.t20.code),
+ t21: (g, a) => g.t21.created?.trim() === "ada_1815" && a.includes(g.t21.code),
+ t22: (g, a) => g.t22.got === "ZH-4471" && a.includes(g.t22.code),
+ t23: (g, a) => g.t23.upload?.name === g.t23.want && g.t23.upload?.text === g.t23.content && a.includes(g.t23.code),
+};
+
+const T17_WANT = [{ text: "Write release notes", done: false }, { text: "Fix flaky test", done: true }, { text: "Update changelog", done: false }];
+function t17ok(t) {
+ return Array.isArray(t) && t.length === 3 && T17_WANT.every((w, i) => String(t[i]?.text).trim() === w.text && !!t[i]?.done === w.done);
+}
+function t18ok(o) {
+ const items = o.items.filter((i) => i.qty > 0).map((i) => `${i.name}|${i.size}|${i.color}|${i.qty}`).sort();
+ const tr = items.filter((x) => x.startsWith("Trail Runner|"));
+ const rs = items.filter((x) => x.startsWith("Rain Shell|"));
+ return items.length === 2 && tr[0] === "Trail Runner|M|Blue|2" && rs.length === 1 && /^Rain Shell\|L\|\w+\|1$/.test(rs[0])
+ && o.coupon === "SAVE10" && o.ship === "Express" && o.name.trim() === "Ada Lovelace" && o.street.trim() === "Bahnhofstrasse 1"
+ && o.zip === "8001" && o.city.trim() === "Zurich" && o.country === "Switzerland";
+}
+
+// ---------------- prompts ----------------
+export const PROMPTS = {
+ t1: (u) => `Open ${u} . Click the button labeled "Claim code" and report the 6-character code that appears. Respond with ONLY the code.`,
+ t2: (u) => `Open ${u} . Fill the form: Full name = "Ada Lovelace", Email = "[email protected]", Plan = "Beta", check "I agree", then click Submit. Respond with ONLY the confirmation ID that appears.`,
+ t3: (u) => `Open ${u} . It is a catalog of 150 products. Find the product whose name starts with "Widget TARGET-" and report its price and stock as PRICE|STOCK (e.g. 123.45|67). Respond with ONLY that.`,
+ t4: (u) => `Open ${u} . It is a 4-step wizard validated server-side: a wrong choice shows an error and does not advance — find the correct choice and proceed. Complete every step until a final token appears. Respond with ONLY the final token.`,
+ t5: (u) => `Open ${u} . The page embeds a cross-origin iframe ("Secure panel"). Click "Reveal code" INSIDE the iframe and report the 6-character code. Respond with ONLY the code.`,
+ t6: (u) => `Open ${u} . Set the notification preferences so that Email alerts is ON, SMS alerts is OFF, and Digest frequency is Weekly, then click "Save preferences". Respond with ONLY the reference code shown after saving.`,
+ t7: (u, g) => `Open ${u} . It is an infinite-scroll feed (more posts load as you scroll). Find the post written by ${g.t7.feed[g.t7.idx].author} and click its "Like" button (do not like any other post). Respond with ONLY the code shown after liking.`,
+ t8: (u) => `Open ${u} . Use the "Account" menu in the top navigation (it opens on hover) and choose "Export data". Respond with ONLY the export code that appears.`,
+ t9: (u) => `Open ${u} . Delete the file "old-backup.zip" (and nothing else). The site asks for confirmation and then for a reason — the reason is: cleanup. Respond with ONLY the code shown after deletion.`,
+ t10: (u) => `Open ${u} . Get the verification code from the help center link (it opens in a new tab), enter it on the original page and click Verify. Respond with ONLY the receipt code shown after successful verification.`,
+ t11: (u) => `Open ${u} . Click "Generate report", wait until the report is ready, then click "Download report". Respond with ONLY the download code shown.`,
+ t12: (u) => `Open ${u} . On the sprint board, drag the card "Fix login bug" into the "Done" column. Respond with ONLY the code shown after the move.`,
+ t13: (u) => `Open ${u} . Type exactly this text into the release note editor: Release 4.2 fixes the export bug. — then click Publish. Respond with ONLY the code shown after publishing.`,
+ t14: (u) => `Open ${u} . Set the shipping destination: City = Zurich (pick it from the suggestions), Country = Switzerland (from the Country dropdown), then click "Save destination". Respond with ONLY the code shown after saving.`,
+ t15: (u, g) => `Open ${u} . Find the order of customer "${g.t15.customer}" whose status is "Refunded" and click its "Details" button. Respond with ONLY the order code shown in the details.`,
+ t16: (u) => `Open ${u} . Click the RED circle drawn on the canvas. Respond with ONLY the code shown after a correct hit.`,
+ t17: (u) => `Our todo app's local development build is running at ${u} — test it end to end: add three todos in this order: "Write release notes", "Fix flaky test", "Update changelog"; mark "Fix flaky test" as done; then click "Sync to server". Respond with ONLY the code shown after syncing.`,
+ t18: (u) => `Open the shop at ${u} and place this order: 2 × "Trail Runner" (exactly that product, not a variant) in size M, color Blue, and 1 × "Rain Shell" (not the Lite) in size L, any color. Apply the coupon code SAVE10 in the cart. Check out with Express shipping to: Ada Lovelace, Bahnhofstrasse 1, 8001 Zurich, Switzerland. Respond with ONLY the order number shown after placing the order.`,
+ t19: (u, g) => `Open ${u} . In the invoice list, approve invoice ${g.t19.rows[g.t19.idx].id} (and no other invoice). Respond with ONLY the code shown after approving.`,
+ t20: (u) => `Open ${u} . Using the date pickers, set Departure to 17 December 2026 and Return to 3 January 2027, then click "Save dates". Respond with ONLY the code shown after saving.`,
+ t21: (u) => `Open ${u} and create an account: username "ada" — if that username is taken, use "ada_1815" instead; password "Analytical#Engine1843" (confirm it too); date of birth 1990-12-10; accept the terms. Fix any errors the form reports until the account is created. Respond with ONLY the account code shown on success.`,
+ t22: (u) => `Open ${u} . Inside the embedded partner widget there is a "Branch lookup" form (it is nested one level deeper inside the widget). Enter the branch code ZH-4471 there and submit it. Respond with ONLY the confirmation code that appears.`,
+ t23: (u, g, file) => `Open ${u} . Upload the local file ${file} as the avatar and click Upload. Respond with ONLY the code shown after a successful upload.`,
+};
+export const TASK_IDS = Object.keys(PROMPTS);
+
+// ---------------- server ----------------
+function makeServer(role, base) {
+ return http.createServer(async (req, res) => {
+ const u = new URL(req.url, "http://x");
+ if (u.pathname === "/favicon.ico") { res.statusCode = 204; return res.end(); }
+ const run = u.searchParams.get("run") ?? "";
+ if (u.pathname === "/healthz") return json(res, { ok: true, role });
+ if (!run) return json(res, { error: "missing run" }, 400);
+ const g = ground(run); g.__run = run;
+ const p = u.pathname, POST = req.method === "POST";
+
+ if (role === "child") {
+ if (p === "/t5child") return html(res, page("Secure panel", `<h2>Secure panel</h2><button id="rev">Reveal code</button><div class="out" id="out"></div>`, `rev.onclick=async()=>{const d=await post('/api/t5/reveal');out.textContent='code: '+d.code;};`));
+ if (p === "/api/t5/reveal" && POST) { if (!browserOnly(req, res)) return; g.t5.clicked = true; return json(res, { code: g.t5.code }); }
+ if (p === "/t22outer") return html(res, page("Partner widget", `<h2>Partner widget</h2><p>Branch services:</p><iframe title="Branch lookup" src="/t22inner?run=${encodeURIComponent(run)}" style="width:480px;height:200px;border:1px dashed #999"></iframe>`));
+ if (p === "/t22inner") return html(res, page("Branch lookup", `<h3>Branch lookup</h3><form id="f"><label for="bc">Branch code</label><input id="bc"><button>Look up</button></form><div class="out" id="out"></div>`, `f.onsubmit=async(e)=>{e.preventDefault();const d=await post('/api/t22/lookup',{code:bc.value});out.textContent=d.msg;};`));
+ if (p === "/api/t22/lookup" && req.method === "POST") {
+ if (!browserOnly(req, res)) return;
+ const b = await readBody(req);
+ g.t22.got = String(b.code ?? "").trim().toUpperCase();
+ return json(res, { msg: g.t22.got === "ZH-4471" ? "Branch Zurich HB found. Confirmation: " + g.t22.code : "Unknown branch code." });
+ }
+ return json(res, { error: "not found" }, 404);
+ }
+
+ if (p === "/api/state") {
+ if (u.searchParams.get("key") !== BENCH_KEY) return json(res, { error: "forbidden" }, 403);
+ return json(res, g);
+ }
+ const tid = p.slice(1);
+ if (P[tid] && !POST) return html(res, P[tid](g, base, u));
+
+ if (!p.startsWith("/api/")) return json(res, { error: "not found" }, 404);
+ // read-only APIs (GET, used by page scripts)
+ if (p === "/api/t4/state") return json(res, { step: g.t4.step, done: g.t4.step >= 4, token: g.t4.step >= 4 ? g.t4.token : null, number: g.t4.step === 1 ? g.t4.number : null, word: g.t4.step === 2 ? g.t4.word : null, decoys: g.t4.step === 2 ? [g.t4.word + "S", g.t4.word.toLowerCase(), g.t4.word, g.t4.word.slice(0, 4)].sort() : [] });
+ if (p === "/api/t7/page") { const from = Number(u.searchParams.get("from") ?? 0); await new Promise((r) => setTimeout(r, 250)); return json(res, { items: g.t7.feed.slice(from, from + 20).map(({ id, author, text }) => ({ id, author, text })), more: from + 20 < g.t7.feed.length }); }
+ if (p === "/api/t11/status") { const el = g.t11.started ? Date.now() - g.t11.started : 0; return json(res, { ready: !!g.t11.started && el >= 5000, pct: Math.min(99, Math.floor(el / 50)) }); }
+ if (p === "/api/t15/list") {
+ const q = (u.searchParams.get("q") ?? "").toLowerCase().trim(); const pg = Number(u.searchParams.get("page") ?? 0);
+ const rows = g.t15.orders.filter((o) => !q || o.customer.toLowerCase().includes(q));
+ return json(res, { rows: rows.slice(pg * 20, pg * 20 + 20).map(({ id, customer, status, total }) => ({ id, customer, status, total })), pages: Math.max(1, Math.ceil(rows.length / 20)) });
+ }
+ if (p === "/api/t18/cart") {
+ const items = g.t18.cart.filter((i) => i.qty > 0);
+ const sub = items.reduce((a, i) => a + i.price * i.qty, 0);
+ return json(res, { items: g.t18.cart, coupon: g.t18.coupon, total: g.t18.coupon ? Math.round(sub * 0.9) : sub });
+ }
+ if (p === "/api/t19/rows") return json(res, { rows: g.t19.rows });
+ if (!POST) return json(res, { error: "method" }, 405);
+ if (!browserOnly(req, res)) return;
+ const b = await readBody(req);
+ switch (p) {
+ case "/api/t1/claim": g.t1.claimed = true; return json(res, { code: g.t1.code });
+ case "/api/t2/submit": {
+ g.t2.got = b;
+ const ok = b.name === "Ada Lovelace" && b.email === "[email protected]" && b.plan === "Beta" && b.agree === true;
+ if (ok) { g.t2.valid = true; g.t2.confirmation = "CNF-" + hash(run + "t2").toString(36).toUpperCase().slice(0, 6); }
+ return json(res, ok ? { ok: true, confirmation: g.t2.confirmation } : { ok: false, error: "fields do not match the required values" });
+ }
+ case "/api/t4/pick": { const ok = b.c === g.t4.color; if (ok && g.t4.step === 0) g.t4.step = 1; else if (!ok) g.t4.wrong++; return json(res, { ok }); }
+ case "/api/t4/num": { const ok = String(b.n).trim() === g.t4.number; if (ok && g.t4.step === 1) g.t4.step = 2; else if (!ok) g.t4.wrong++; return json(res, { ok }); }
+ case "/api/t4/word": { const ok = b.w === g.t4.word; if (ok && g.t4.step === 2) g.t4.step = 3; else if (!ok) g.t4.wrong++; return json(res, { ok }); }
+ case "/api/t4/finish": if (g.t4.step === 3) g.t4.step = 4; return json(res, { ok: true });
+ case "/api/t6/save": {
+ g.t6.saved = { email: b.email, sms: b.sms, frequency: b.frequency };
+ const ok = b.email === true && b.sms === false && b.frequency === "Weekly";
+ return json(res, ok ? { ok: true, ref: g.t6.ref } : { ok: false });
+ }
+ case "/api/t7/like": { g.t7.likes.push(b.id); const ok = b.id === g.t7.feed[g.t7.idx].id && g.t7.likes.length === 1; return json(res, ok ? { code: g.t7.code } : {}); }
+ case "/api/t8/export": g.t8.exported = true; return json(res, { msg: "Export started. Export code: " + g.t8.code });
+ case "/api/t8/delete": g.t8.deleted = true; return json(res, { msg: "Account scheduled for deletion." });
+ case "/api/t8/profile": return json(res, { msg: "Profile: (nothing to see here)" });
+ case "/api/t9/delete": {
+ g.t9.deletes.push({ file: b.file, reason: String(b.reason ?? "") });
+ const ok = b.file === g.t9.target && String(b.reason ?? "").trim().toLowerCase() === "cleanup" && g.t9.deletes.length === 1;
+ return json(res, { ok: true, msg: ok ? "Deleted. Code: " + g.t9.code : "Deleted " + b.file + "." });
+ }
+ case "/api/t10/help": g.t10.helpViewed = true; return json(res, { code: g.t10.code });
+ case "/api/t10/verify": {
+ g.t10.attempts++;
+ const ok = String(b.code ?? "").trim().toUpperCase() === g.t10.code && g.t10.helpViewed;
+ if (ok) g.t10.verified = true;
+ return json(res, { msg: ok ? "Verified! Receipt: " + g.t10.receipt : "Invalid code." });
+ }
+ case "/api/t11/start": if (!g.t11.started) g.t11.started = Date.now(); return json(res, { ok: true });
+ case "/api/t11/download": {
+ const ready = g.t11.started && Date.now() - g.t11.started >= 5000;
+ if (!ready) { g.t11.early++; return json(res, { msg: "Report not ready." }); }
+ g.t11.downloaded = true; return json(res, { msg: "Downloaded. Code: " + g.t11.code });
+ }
+ case "/api/t12/move": {
+ for (const c of Object.values(g.t12.cols)) { const i = c.indexOf(b.card); if (i >= 0) c.splice(i, 1); }
+ (g.t12.cols[b.to] ??= []).push(b.card);
+ const ok = g.t12.cols.Done.includes(g.t12.card);
+ return json(res, { msg: ok ? "Moved. Code: " + g.t12.code : `Moved "${b.card}" to ${b.to}.` });
+ }
+ case "/api/t13/publish": {
+ g.t13.got = String(b.text ?? "");
+ const ok = g.t13.got.trim() === g.t13.want;
+ return json(res, { msg: ok ? "Published. Code: " + g.t13.code : "Published (text does not match the requested note)." });
+ }
+ case "/api/t14/save": {
+ g.t14.got = { city: b.city, country: b.country, typed: b.typed };
+ const ok = b.city === "Zurich" && b.country === "Switzerland";
+ return json(res, { msg: ok ? "Saved. Code: " + g.t14.code : !b.city ? "Please pick a city from the suggestions." : "Saved destination " + b.city + ", " + (b.country || "?") + "." });
+ }
+ case "/api/t15/details": {
+ g.t15.viewed.push(b.id);
+ const o = g.t15.orders.find((x) => x.id === b.id);
+ return json(res, { msg: o ? `${o.id} — ${o.customer} — ${o.status} — order code: ${o.code}` : "unknown order" });
+ }
+ case "/api/t17/sync": {
+ g.t17.todos = Array.isArray(b.todos) ? b.todos.map((t) => ({ text: String(t.text ?? ""), done: !!t.done })) : null;
+ return json(res, { msg: t17ok(g.t17.todos) ? "Synced. Code: " + g.t17.code : `Synced ${g.t17.todos?.length ?? 0} todos.` });
+ }
+ case "/api/t18/add": {
+ const prod = SHOP.find((x) => x.id === b.id);
+ if (!prod || !["S", "M", "L"].includes(b.size) || !COLORS.includes(b.color) || !(b.qty >= 1)) return json(res, { msg: "Could not add to cart." });
+ const ex = g.t18.cart.find((i) => i.name === prod.name && i.size === b.size && i.color === b.color);
+ if (ex) ex.qty += Math.floor(b.qty); else g.t18.cart.push({ name: prod.name, price: prod.price, size: b.size, color: b.color, qty: Math.floor(b.qty) });
+ return json(res, { msg: `Added ${Math.floor(b.qty)} × ${prod.name} (${b.size}, ${b.color}) to the cart.` });
+ }
+ case "/api/t18/qty": { const it = g.t18.cart[b.i]; if (it) it.qty = Math.max(0, Math.floor(b.qty)); return json(res, { ok: true }); }
+ case "/api/t18/coupon": {
+ const ok = String(b.code ?? "").trim().toUpperCase() === "SAVE10";
+ if (ok) g.t18.coupon = "SAVE10";
+ return json(res, { msg: ok ? "Coupon SAVE10 applied: 10% off." : "Invalid coupon." });
+ }
+ case "/api/t18/order": {
+ if (!g.t18.cart.some((i) => i.qty > 0)) return json(res, { msg: "Your cart is empty." });
+ g.t18.order = { items: g.t18.cart.map((i) => ({ ...i })), coupon: g.t18.coupon, ship: b.ship, name: String(b.name ?? ""), street: String(b.street ?? ""), zip: String(b.zip ?? ""), city: String(b.city ?? ""), country: String(b.country ?? "") };
+ return json(res, { msg: "Thank you! Order number: " + g.t18.orderNo });
+ }
+ case "/api/t19/approve": {
+ g.t19.approved.push(b.id);
+ const ok = b.id === g.t19.rows[g.t19.idx].id && g.t19.approved.length === 1;
+ return json(res, { msg: ok ? "Approved. Code: " + g.t19.code : `Approved ${b.id}.` });
+ }
+ case "/api/t20/save": {
+ g.t20.saved = { dep: b.dep, ret: b.ret };
+ const ok = b.dep === "2026-12-17" && b.ret === "2027-01-03";
+ return json(res, { msg: ok ? "Saved. Code: " + g.t20.code : `Saved ${b.dep || "?"} → ${b.ret || "?"}.` });
+ }
+ case "/api/t21/signup": {
+ g.t21.attempts.push(b.u);
+ const errors = {};
+ if (!b.u) errors.eu = "Username is required.";
+ else if (["ada", "admin", "root"].includes(String(b.u).toLowerCase())) errors.eu = `"${b.u}" is already taken.`;
+ const pw = String(b.pw ?? "");
+ if (pw.length < 12 || !/\d/.test(pw) || !/[^A-Za-z0-9]/.test(pw)) errors.ep = "At least 12 characters, with a digit and a symbol.";
+ if (pw !== b.pw2) errors.ep2 = "Passwords do not match.";
+ const bd = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(b.bd ?? ""));
+ if (!bd) errors.eb = "Use the format YYYY-MM-DD.";
+ else if (2026 - Number(bd[1]) < 18) errors.eb = "You must be at least 18.";
+ if (!b.tos) errors.et = "You must accept the terms.";
+ if (Object.keys(errors).length) return json(res, { ok: false, errors });
+ g.t21.created = String(b.u);
+ return json(res, { ok: true, code: g.t21.code });
+ }
+ case "/api/t23/upload": {
+ g.t23.upload = { name: String(b.name ?? ""), size: b.size, text: String(b.text ?? "") };
+ const ok = g.t23.upload.name === g.t23.want && g.t23.upload.text === g.t23.content;
+ return json(res, { msg: ok ? "Avatar updated. Code: " + g.t23.code : `Uploaded ${g.t23.upload.name} — that is not the requested file.` });
+ }
+ case "/api/t16/hit": {
+ const c = g.t16.circles.find((c) => (b.x - c.x) ** 2 + (b.y - c.y) ** 2 <= (c.rad + 2) ** 2);
+ g.t16.hits.push(c ? c.color : "miss");
+ return json(res, { msg: c?.color === "red" ? "Hit! Code: " + g.t16.code : c ? "That was " + c.color + "." : "Missed." });
+ }
+ }
+ return json(res, { error: "not found" }, 404);
+ });
+}
+
+/**
+ * Start parent + child servers. `publicBase` lets a tunnel front them:
+ * pass { parent: "https://a.trycloudflare.com", child: "https://b..." }.
+ */
+export async function startSuite({ parentPort = 0, childPort = 0, publicBase } = {}) {
+ const base = { parent: "", child: "" };
+ const child = makeServer("child", base); child.listen(childPort, "127.0.0.1"); await once(child, "listening");
+ const parent = makeServer("parent", base); parent.listen(parentPort, "127.0.0.1"); await once(parent, "listening");
+ base.parent = publicBase?.parent ?? `http://127.0.0.1:${parent.address().port}`;
+ base.child = publicBase?.child ?? `http://localhost:${child.address().port}`;
+ return {
+ base, parentPort: parent.address().port, childPort: child.address().port,
+ setPublic(pb) { Object.assign(base, pb); },
+ truth: (run) => ground(run),
+ close: () => { child.close(); parent.close(); },
+ };
+}
+
+export { ground };
diff --git a/bench/suite/summarize.mjs b/bench/suite/summarize.mjs
new file mode 100644
index 0000000..ef91181
--- /dev/null
+++ b/bench/suite/summarize.mjs
@@ -0,0 +1,82 @@
+/**
+ * Summarize suite results (one or more JSONL files) per arm and per task.
+ * node bench/suite/summarize.mjs results/a.jsonl [results/b.jsonl ...] [--json out.json]
+ *
+ * Token accounting (from Codex thread totals):
+ * total = every input + output token the harness billed for the task
+ * fresh = uncached input + output — what actually grows with tool output
+ * and with the number of steps (cached prefix excluded)
+ */
+import { readFileSync, writeFileSync } from "node:fs";
+
+const files = process.argv.slice(2).filter((a, i, all) => !a.startsWith("--") && all[i - 1] !== "--json");
+const jsonOut = process.argv.includes("--json") ? process.argv[process.argv.indexOf("--json") + 1] : null;
+const rows = files.flatMap((f) => readFileSync(f, "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)));
+
+const med = (xs) => { const s = xs.filter((x) => x != null).sort((a, b) => a - b); if (!s.length) return null; const m = Math.floor(s.length / 2); return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2; };
+const mean = (xs) => { const s = xs.filter((x) => x != null); return s.length ? s.reduce((a, b) => a + b, 0) / s.length : null; };
+const sum = (xs) => xs.filter((x) => x != null).reduce((a, b) => a + b, 0);
+const total = (r) => r.tokens?.total_tokens ?? null;
+// Runs where the agent stopped to ask the (absent) user for confirmation
+// instead of acting — a safety-policy outcome, not a capability failure.
+const asked = (r) => !r.success && /\b(confirm|confirmation|should I|shall I|do you want|proceed\?|approve)\b/i.test(r.answer ?? "");
+const fresh = (r) => r.tokens ? (r.tokens.input_tokens - (r.tokens.cached_input_tokens ?? 0)) + r.tokens.output_tokens : null;
+
+const arms = [...new Set(rows.map((r) => r.arm))];
+const tasks = [...new Set(rows.map((r) => r.task))].sort((a, b) => Number(a.slice(1)) - Number(b.slice(1)));
+
+const perArm = {};
+for (const a of arms) {
+ const rs = rows.filter((r) => r.arm === a);
+ const ok = rs.filter((r) => r.success);
+ perArm[a] = {
+ runs: rs.length,
+ success: ok.length,
+ successRate: ok.length / rs.length,
+ askedConfirmation: rs.filter(asked).length,
+ capabilityRate: ok.length / Math.max(1, rs.length - rs.filter(asked).length),
+ tasksSolvedAll: tasks.filter((t) => { const x = rs.filter((r) => r.task === t); return x.length && x.every((r) => r.success); }).length,
+ medianWallS: med(rs.map((r) => r.wallMs / 1000)),
+ meanWallS: mean(rs.map((r) => r.wallMs / 1000)),
+ medianTotalTok: med(rs.map(total)),
+ meanTotalTok: mean(rs.map(total)),
+ sumTotalTok: sum(rs.map(total)),
+ medianFreshTok: med(rs.map(fresh)),
+ meanFreshTok: mean(rs.map(fresh)),
+ medianOutTok: med(rs.map((r) => r.tokens?.output_tokens)),
+ medianCalls: med(rs.map((r) => r.toolCalls)),
+ medianTurns: med(rs.map((r) => r.turns)),
+ timeouts: rs.filter((r) => r.timedOut).length,
+ violations: rs.filter((r) => r.violations?.length).length,
+ // Efficiency on SUCCESSFUL runs only (cost of getting it right).
+ succMedianWallS: med(ok.map((r) => r.wallMs / 1000)),
+ succMedianTotalTok: med(ok.map(total)),
+ };
+}
+
+const perTask = {};
+for (const t of tasks) {
+ perTask[t] = {};
+ for (const a of arms) {
+ const rs = rows.filter((r) => r.task === t && r.arm === a);
+ if (!rs.length) continue;
+ perTask[t][a] = {
+ ok: rs.filter((r) => r.success).length, n: rs.length,
+ wallS: med(rs.map((r) => r.wallMs / 1000)), tok: med(rs.map(total)), fresh: med(rs.map(fresh)), calls: med(rs.map((r) => r.toolCalls)),
+ fails: rs.filter((r) => !r.success).map((r) => (r.timedOut ? "timeout" : r.violations?.length ? "violation" : !r.evidence ? "no-evidence" : r.foreign ? "foreign" : asked(r) ? "asked-confirmation" : `answer:${r.answer?.slice(0, 30)}`)),
+ };
+ }
+}
+
+const k = (n) => (n == null ? "—" : n >= 1000 ? (n / 1000).toFixed(1) + "k" : Math.round(n).toString());
+console.log(`\n${rows.length} runs · arms: ${arms.join(", ")} · tasks: ${tasks.length}\n`);
+console.log("arm".padEnd(14) + "success".padEnd(12) + "capab.".padEnd(8) + "wall med".padEnd(10) + "tok med".padEnd(10) + "tok mean".padEnd(10) + "fresh med".padEnd(11) + "calls".padEnd(7) + "timeouts");
+for (const a of arms) {
+ const p = perArm[a];
+ console.log(a.padEnd(14) + `${p.success}/${p.runs} ${(100 * p.successRate).toFixed(0)}%`.padEnd(12) + `${(100 * p.capabilityRate).toFixed(0)}%`.padEnd(8) + `${p.medianWallS?.toFixed(0)}s`.padEnd(10) + k(p.medianTotalTok).padEnd(10) + k(p.meanTotalTok).padEnd(10) + k(p.medianFreshTok).padEnd(11) + String(p.medianCalls).padEnd(7) + p.timeouts);
+}
+console.log("\nper task (ok/n · median wall · median total tokens):");
+for (const t of tasks) {
+ console.log(t.padEnd(5) + arms.map((a) => { const x = perTask[t][a]; return x ? `${a}: ${x.ok}/${x.n} ${x.wallS?.toFixed(0)}s ${k(x.tok)}${x.fails.length ? " ✗" + x.fails.join(",") : ""}` : ""; }).join(" | "));
+}
+if (jsonOut) writeFileSync(jsonOut, JSON.stringify({ generated: new Date().toISOString(), files, perArm, perTask, rows: rows.map(({ sessionFile, ...r }) => r) }, null, 1));
diff --git a/bridge/extension/background.js b/bridge/extension/background.js
new file mode 100644
index 0000000..7c7299f
--- /dev/null
+++ b/bridge/extension/background.js
@@ -0,0 +1,172 @@
+/**
+ * axuse bridge — extension service worker.
+ *
+ * Lineage: the Codex ChatGPT extension's background bridge — the extension
+ * holds chrome.debugger (real CDP over the user's real browser and sessions)
+ * and relays commands from the harness over native messaging. That is the
+ * pattern that makes harness browser use "run in the user's session": no
+ * second browser, no credential copies, and the debugger infobar keeps the
+ * human honestly informed.
+ *
+ * Protocol (one JSON object per native-messaging message):
+ * from hub: {t:"req", id, method, params} | {t:"ping"}
+ * to hub: {t:"hello", ext, ua} | {t:"res", id, ok, result?|error?}
+ * | {t:"evt", tabId, method, params} | {t:"pong"}
+ * methods: open_tab {url} | cdp {tabId, method, params}
+ * close_tab {tabId} | list_tabs {}
+ */
+
+const HOST_NAME = "com.axuse.bridge";
+let port = null;
+let reconnectTimer = null;
+
+// Field diagnostics: readable from an attached DevTools session
+// (`self.__axuseDiag` in the service worker). Answers "did connect() run,
+// did the port disconnect, and why" without guessing.
+self.__axuseDiag = { connects: 0, disconnects: 0, lastError: null, startedAt: null, reqs: {}, replies: {}, msgs: [] };
+
+function send(msg) {
+ if (!port) return;
+ try {
+ port.postMessage(msg);
+ } catch (e) {
+ port = null;
+ }
+}
+
+function connect() {
+ // Idempotent: at SW start, top-level code AND wake listeners (onInstalled
+ // etc.) may all fire — a second connect() must never open a second native
+ // host. Two hosts cascade: the hub keeps only the latest, killing the old
+ // host's socket, whose onDisconnect would otherwise clobber the live port.
+ if (port) return;
+ clearTimeout(reconnectTimer);
+ self.__axuseDiag.connects++;
+ self.__axuseDiag.startedAt = new Date().toISOString();
+ let p;
+ try {
+ p = chrome.runtime.connectNative(HOST_NAME);
+ } catch (e) {
+ self.__axuseDiag.lastError = "connectNative threw: " + String(e && e.message ? e.message : e);
+ reconnectTimer = setTimeout(connect, 1000);
+ return;
+ }
+ port = p;
+ p.onMessage.addListener(onMessage);
+ p.onDisconnect.addListener(() => {
+ // Guard: only the CURRENT port's disconnect is actionable. A stale
+ // port's disconnect (replaced by a newer connect) must be ignored.
+ if (port !== p) return;
+ self.__axuseDiag.disconnects++;
+ self.__axuseDiag.lastError = chrome.runtime.lastError
+ ? "onDisconnect lastError: " + chrome.runtime.lastError.message
+ : "onDisconnect (host exited or SW was killed)";
+ port = null;
+ reconnectTimer = setTimeout(connect, 1000);
+ });
+ send({ t: "hello", ext: chrome.runtime.getManifest().version, ua: navigator.userAgent });
+}
+
+function onMessage(msg) {
+ // Receiving a message resets the MV3 idle timer (the hub pings every 20s).
+ try {
+ if (!msg || typeof msg !== "object") return;
+ if (msg.t === "req") {
+ self.__axuseDiag.reqs[msg.method] = (self.__axuseDiag.reqs[msg.method] || 0) + 1;
+ self.__axuseDiag.msgs.push("req " + msg.method + " id=" + msg.id);
+ void handleReq(msg);
+ } else if (msg.t === "ping") {
+ self.__axuseDiag.msgs.push("ping");
+ send({ t: "pong" });
+ }
+ } catch (e) {
+ if (msg && msg.id !== undefined) send({ t: "res", id: msg.id, ok: false, error: String(e) });
+ }
+}
+
+function reply(id, ok, result, error) {
+ self.__axuseDiag.replies[ok ? "ok" : "err"] = (self.__axuseDiag.replies[ok ? "ok" : "err"] || 0) + 1;
+ self.__axuseDiag.msgs.push("reply id=" + id + " ok=" + ok);
+ send(ok
+ ? { t: "res", id, ok: true, result }
+ : { t: "res", id, ok: false, error: String(error ?? "unknown error") });
+}
+
+async function handleReq(msg) {
+ const p = msg.params || {};
+ switch (msg.method) {
+ case "ping":
+ return reply(msg.id, true, { ok: true });
+ case "open_tab": {
+ try {
+ const tab = await chrome.tabs.create({ url: p.url || "about:blank", active: true });
+ await ensureAttached(tab.id);
+ return reply(msg.id, true, { tabId: tab.id });
+ } catch (e) {
+ return reply(msg.id, false, null, e);
+ }
+ }
+ case "cdp": {
+ try {
+ const result = await chrome.debugger.sendCommand({ tabId: p.tabId }, p.method, p.params || {});
+ return reply(msg.id, true, result === undefined ? {} : result);
+ } catch (e) {
+ // Tab reload/navigation can detach the debugger: one re-attach retry.
+ const s = String(e && e.message ? e.message : e);
+ if (/attach/i.test(s)) {
+ try {
+ await ensureAttached(p.tabId);
+ const result = await chrome.debugger.sendCommand({ tabId: p.tabId }, p.method, p.params || {});
+ return reply(msg.id, true, result === undefined ? {} : result);
+ } catch (e2) {
+ return reply(msg.id, false, null, e2);
+ }
+ }
+ return reply(msg.id, false, null, e);
+ }
+ }
+ case "close_tab": {
+ try { await chrome.debugger.detach({ tabId: p.tabId }); } catch {}
+ try { await chrome.tabs.remove(p.tabId); } catch {}
+ return reply(msg.id, true, { closed: true });
+ }
+ case "list_tabs": {
+ try {
+ const tabs = await chrome.tabs.query({});
+ return reply(msg.id, true, {
+ tabs: tabs.map((t) => ({ tabId: t.id, url: t.url, title: t.title, active: t.active })),
+ });
+ } catch (e) {
+ return reply(msg.id, false, null, e);
+ }
+ }
+ default:
+ return reply(msg.id, false, null, `unknown method ${msg.method}`);
+ }
+}
+
+async function ensureAttached(tabId) {
+ try {
+ await chrome.debugger.attach({ tabId }, "1.3");
+ } catch (e) {
+ if (!/already attached/i.test(String(e && e.message ? e.message : e))) throw e;
+ }
+}
+
+chrome.debugger.onEvent.addListener((source, method, params) => {
+ if (source && source.tabId != null) send({ t: "evt", tabId: source.tabId, method, params: params ?? {} });
+});
+chrome.debugger.onDetach.addListener((source) => {
+ if (source && source.tabId != null) {
+ send({ t: "evt", tabId: source.tabId, method: "debugger.detached", params: {} });
+ }
+});
+
+// Wake triggers: any of these starting the SW runs the top-level connect().
+// Without them an MV3 SW can stay dormant at browser start and never dial
+// the hub.
+chrome.runtime.onStartup.addListener(() => connect());
+chrome.runtime.onInstalled.addListener(() => connect());
+chrome.tabs.onCreated.addListener(() => connect());
+
+connect();
diff --git a/bridge/extension/manifest.json b/bridge/extension/manifest.json
new file mode 100644
index 0000000..95c3144
--- /dev/null
+++ b/bridge/extension/manifest.json
@@ -0,0 +1,12 @@
+{
+ "manifest_version": 3,
+ "name": "axuse bridge",
+ "version": "1.0.0",
+ "description": "Bridge your real Chrome to the axuse agent MCP server. Lets an agent harness control this browser through trusted CDP (chrome.debugger) while you watch.",
+ "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAytFe+1ptPXR/EbCQTzxq01OsH1QShTl0eWmSf2Esjp6eIYKdsL8s6wMBjn21GLA9cC/R9tgyvebqp84DMV+QIFs+RWBwnrbaJzSNBZuB+x00gZxj5Du+TUsllPI9J3NV28MlY6vUS9TVcqlS0KbFVYSC1nZQpuzphlL1cgLs+K0nkfGSIjrhmrTRbXtP1cygbHoZRAO1S6CZX9ZK/Ru7z6084IDA2HYgIwzE9zlf21D4VxXSb1zGsUIxONJ2SB8ToyZxjVxZKtasZRoD1MX8NXIm7l+7FIlREhXdwL0IRfcwCOGAIV7vZAvpzMQLSas0yOCoZtXKwWEp+H4C+CIyvwIDAQAB",
+ "minimum_chrome_version": "116",
+ "background": {
+ "service_worker": "background.js"
+ },
+ "permissions": ["nativeMessaging", "tabs", "debugger"]
+}
diff --git a/docs/macos-support.md b/docs/macos-support.md
new file mode 100644
index 0000000..ac75e9d
--- /dev/null
+++ b/docs/macos-support.md
@@ -0,0 +1,367 @@
+# macOS Support — Production Guide
+
+axuse treats macOS as a first-class platform, not a port. This document is
+the complete reference: what is supported, how permissions work, how failures
+are classified, how to run the matrix, and what remains out of scope with
+evidence.
+
+- [Support matrix](#support-matrix)
+- [TCC permissions model](#tcc-permissions-model)
+- [Failure taxonomy](#failure-taxonomy)
+- [First-run, stale grants, and recovery](#first-run-stale-grants-and-recovery)
+- [Headless and CI environments](#headless-and-ci-environments)
+- [Platform conventions axuse applies](#platform-conventions-axuse-applies)
+- [Testing lanes](#testing-lanes)
+- [Performance characteristics](#performance-characteristics)
+- [Known limitations (documented blockers)](#known-limitations)
+- [Release checklist](#release-checklist)
+- [Migration notes](#migration-notes)
+
+## Support matrix
+
+| Capability | macOS 14 (Sonoma) | macOS 15 (Sequoia) | macOS 26 (Tahoe) | Notes |
+|---|---|---|---|---|
+| Browser tools (`ax_*`, CDP backend) | ✅ | ✅ | ✅ (this doc's evidence) | Intel + Apple Silicon |
+| OOPIF frames, dialogs, popups, downloads events | ✅ | ✅ | ✅ | Same CDP surface as Windows/Linux |
+| Trusted input in pages (`Input.dispatch*`) | ✅ | ✅ | ✅ | macOS native key codes + `commands` editing mapping |
+| Browser screenshots (`Page.captureScreenshot`) | ✅ | ✅ | ✅ | CSS-px scale-1 contract |
+| Extension bridge (native messaging + `chrome.debugger`) | ✅ | ✅ | ✅ | See browser matrix below |
+| Desktop driver (`ax_desktop_*`) | opt-in | opt-in | opt-in | `AXUSE_ENABLE_MACOS_CUA=1` + TCC grants |
+| **Desktop AX structure layer** (`ax_desktop_ax_*`: snapshot/refs/click/set/read) | ✅ with Accessibility | ✅ with Accessibility | ✅ (protocol-verified; granted paths in the manual lane) | System Events AX tree — structure-first desktop, browser-observe style |
+| Desktop screenshots (`screencapture`+`sips`) | ✅ with grant | ✅ with grant | ✅ with grant (live-verified) | Display-point contract, Retina-normalized |
+| Native input (CGEvent via JXA) | ✅ with grant | ✅ with grant | ✅ with grant | Never runs silently; opt-in only |
+
+Verified Node: 22 LTS and 24 LTS. Architecture evidence: arm64 (M1, macOS
+26.6) locally; Intel via the `macos-15-intel` CI lane.
+
+### Browser matrix (macOS, verified 2026-10-19)
+
+| Browser | CDP backend | Extension bridge | Notes |
+|---|---|---|---|
+| Google Chrome (branded, stable 155) | ✅ | n/a¹ | ¹macOS branded Chrome silently ignores `--load-extension`; load the bridge unpacked in your daily profile, or use another browser for automated extension lanes. |
+| Google Chrome Beta / Canary | ✅ | n/a¹ | **Live-verified this audit**: the `--load-extension` policy covers ALL branded Chrome channels — Beta and Canary both refuse automated extension loading (extension never dials in). The extension-capable lane excludes every branded Chrome channel; the manual unpacked path still works. |
+| Chrome for Testing (155) | ✅ | ✅ | Primary CI browser; native messaging verified. |
+| Chromium trunk (r1721585 / v158) | ✅ | ⚠️² | ²Trunk stall on headless `Page.navigate` — axuse auto-falls back to `location.href` (one RPC timeout on the first stall); CDP backend unaffected. |
+| Microsoft Edge (stable 155) | ✅ | ✅ | Full chain verified: NM → hub → debugger → click. |
+| Microsoft Edge Beta | ✅ | ✅ | **Live-verified this audit**: NM (profile-local manifest under the Edge Beta dir) → hub → debugger → click, full chain. |
+
+## TCC permissions model
+
+The macOS desktop driver is **opt-in twice**: the environment must set
+`AXUSE_ENABLE_MACOS_CUA=1`, and macOS must have granted the host binary both
+privileges. axuse never requests grants silently:
+
+- **Probes are non-interactive.** `permissions()` uses `AXIsProcessTrusted()`
+ and `CGPreflightScreenCaptureAccess()` — neither can open a TCC prompt.
+ The test suite enforces this (`desktop.test.js`: "probe scripts never
+ request a TCC prompt").
+- **Operations fail closed and typed.** Without the grants, every desktop
+ op raises `DESKTOP_PERMISSION_REQUIRED` with the exact System Settings path
+ and no side effects. Input is never posted; nothing is captured.
+- **The grant belongs to the exact binary** that runs axuse (your Terminal,
+ IDE, or node). A grant to a different app does not transfer.
+
+Grant procedure (human step, by design):
+
+1. System Settings → Privacy & Security → **Accessibility** → add the host.
+2. System Settings → Privacy & Security → **Screen Recording** → add the host.
+3. **Restart the host** if it was running when Screen Recording was granted
+ (macOS applies capture grants to new processes only).
+4. Verify: `AXUSE_ENABLE_MACOS_CUA=1 axuse doctor` — it prints the detected
+ permission state, probes native event construction (posting nothing), and
+ attempts a 1×1 px capture when allowed.
+
+## Failure taxonomy
+
+Every macOS desktop failure is a typed `AxError`, never a bare string:
+
+| Code | Meaning | Agent action |
+|---|---|---|
+| `DESKTOP_DRIVER_UNAVAILABLE` | macOS driver not enabled (`AXUSE_ENABLE_MACOS_CUA` unset) or platform has no driver | Enable or use `ax_*` browser tools |
+| `DESKTOP_PERMISSION_REQUIRED` | TCC grant missing, or an op failed with a permission-classified error | Grant per hint, retry; stale-grant hint includes `tccutil reset` guidance |
+| `DESKTOP_OP_FAILED` | Native op failed (bad output, headless session, unsupported gesture) | Read hint; headless hint points to `ax_*` |
+| `BAD_COORDS` | Rect outside the active display layout or non-finite values | Call `ax_desktop_screen_info`, keep the crop in bounds |
+| `COMMAND_REJECTED` | Invalid params (button, steps, quality) | Fix inputs |
+| `SCREENSHOT_BUDGET_EXCEEDED` | Even lowest-quality encode exceeds budget | Smaller crop or higher budget |
+| `TIMEOUT` | Native command exceeded 15 s | Retry |
+
+Denied-state matrix (all verified live on macOS 26 with both grants denied):
+
+| State | Probe result | Operation result |
+|---|---|---|
+| Accessibility denied | `permissions().accessibility === false` | `move`/`click`/`type`/`press` → `DESKTOP_PERMISSION_REQUIRED` |
+| Screen Recording denied | `permissions().screen_recording === false` | `screenshot` → `DESKTOP_PERMISSION_REQUIRED` before any capture attempt |
+| Probe unavailable (old OS/headless) | `screen_recording === null` | Op proceeds; the failing native call is classified from its stderr |
+
+## First-run, stale grants, and recovery
+
+- **First run**: nothing prompts. Probes report `false`; ops fail typed.
+- **Stale grant** (host binary moved/updated, TCC still trusts the old path):
+ preflight may pass while the op fails. axuse classifies the failure
+ (`could not create image from display` / `operation not permitted`) as
+ `DESKTOP_PERMISSION_REQUIRED` with the stale-grant hint: restart the host,
+ then `tccutil reset ScreenCapture` / `tccutil reset Accessibility` if it
+ persists.
+- **Recovery**: probe results are cached for 5 s and **invalidated on every
+ permission-classified failure** — a grant made after a denial is visible on
+ the next operation without restarting axuse. (macOS itself may still
+ require a host restart for Screen Recording; that is OS behavior and the
+ error hint says so.)
+- **Display changes**: cached layout is re-probed once when a caller's rect
+ falls outside it (monitor plugged/unplugged, resolution change) before the
+ coordinates are rejected.
+
+## Headless and CI environments
+
+GitHub-hosted macOS runners have a WindowServer session but **no TCC grants**:
+the suite exercises discovery/probe/typed-denial paths there, and the granted
+paths run in the manual lane. In truly headless sessions (SSH, CI services
+without a GUI), display probes report the condition with a typed hint to use
+the `ax_*` browser tools — never a hang or a generic failure.
+
+## Platform conventions axuse applies
+
+- **The desktop is structure-first too (AX layer)**: `ax_desktop_ax_snapshot`
+ reads the target app's accessibility tree through System Events (same
+ Accessibility grant as input) — roles, titles, values, bounds, and
+ budgeted, live-re-resolved refs (`ax1.2.1` style paths). Act with trusted
+ AXPress (`ax_desktop_ax_click`, with an automatic CGEvent coordinate
+ fallback when an app refuses programmatic press), set writable text
+ fields with read-back verification (`ax_desktop_ax_set`), and re-read
+ elements (`ax_desktop_ax_read`). Stale refs fail typed `REF_NOT_FOUND`
+ with a reobserve hint — the browser vocabulary, applied to native apps.
+ One Apple Event per node (`properties`), 250-node/depth-10 budgets with
+ honest truncation facts.
+- **Coordinates**: macOS global display points everywhere (`CGDisplayBounds`
+ / CGEvent space); screenshots are sips-resized to point dimensions so a
+ pixel in the image maps 1:1 onto a click coordinate on Retina.
+- **Window rows carry geometry**: `ax_desktop_windows` returns per-window
+ `bounds {x,y,w,h}` in the same display-point space (titles+bounds need the
+ Accessibility grant; without it you get honest process-level rows and the
+ `window_access` field says so). The **frontmost app's rows come first**
+ and carry `frontmost: true` (plus a top-level `frontmost_pid`) — the row
+ an agent usually wants. One Apple-Event walk costs ~0.7–1 s on a busy
+ Mac — an anchor call, not a poll. Typing `""` is a guaranteed no-op (no
+ spawn, no permission path).
+- **Gestures never interleave**: every input op (move/click/drag/wheel/type/
+ press/activate) is serialized on one chain, and a failed drag releases its
+ held button inside the same chain slot — concurrent calls can never
+ interleave down/up pairs.
+- **Scroll direction is preference-aware**: `ax_desktop_scroll`/`wheel` uses
+ the browser-tool contract (dy>0 = content down) regardless of the user's
+ Natural Scrolling setting; the CG delta is flipped per
+ `com.apple.swipescrolldirection` (read once, cached).
+- **Activate is pid-addressed**: `ax_desktop_activate` accepts a `pid` (most
+ robust), exact `title`, or `window_id` from the windows call.
+- **Key codes**: two vocabularies, both frozen and tested — CDP input uses
+ macOS `nativeVirtualKeyCode` (F1–F20, keypad, punctuation row, editing
+ modifiers; `commands: ["selectAll"|"copy"|…]` for ⌘-editing combos); the
+ desktop driver uses AppleScript key codes including F13–F20.
+- **Shortcuts**: `ax_press {platform:true}` translates Windows-convention app
+ shortcuts to the OS convention (macOS: `ctrl+alt+1` → `cmd+alt+1`,
+ `ctrl+end` → `cmd+end`). Literal Control combos remain available for
+ terminals/devtools. Select-all is `meta+a` on macOS automatically.
+- **Double-click**: one CGEvent batch whose second press/up pair carries
+ `kCGMouseEventClickState = 2` — what Cocoa requires to register a real
+ double-click (timing alone does not).
+- **Secrets can live in the Keychain — for every plugin secret, not just
+ passphrases**: licenses (`license-<pkg>`), vision keys
+ (`captcha-pro-vision`, `challenge-vision`, `editor-vision`,
+ `remote-vision`), the Places API key (`places-api`), and the
+ session-vault/auth-bridge passphrases — all resolve env-var first, then
+ the login Keychain under service `axuse` (`security add-generic-password
+ -s axuse -a <account> -w '<secret>'`). Lookups are once-per-process,
+ cached, and typed failures name the exact command. `AXUSE_KEYCHAIN=0`
+ severs the fallback (deterministic CI/test isolation; the plugin test
+ harness sets it automatically).
+- **Native messaging**: manifests land in each browser's
+ `NativeMessagingHosts` dir (`~/Library/Application Support/…`); isolated
+ launches resolve manifests **relative to `--user-data-dir`**, which the
+ E2E test uses and the probe script re-verifies per browser. The generated
+ launcher guards the installing node binary with an existence check and
+ falls back to PATH `node`, so node upgrades cannot orphan the host.
+- **Bridge security**: the hub binds 127.0.0.1 only, token-auths every
+ connection role, and writes its info file owner-only (dir 0700, file 0600
+ — enforced and CI-asserted; Windows relies on `%LOCALAPPDATA%` ACLs).
+- **Extension-backend resilience**: when a `Page.navigate` RPC through
+ `chrome.debugger` stalls (observed on Chromium trunk r1721585 headless),
+ the backend routes the navigation through `Runtime.evaluate`
+ (`location.href = …`) once, reports `via` in the result, and keeps the
+ session alive.
+- **No shell**: every native call is `execFile` (argv, no shell string).
+ The one shell launcher (`/bin/sh` shebang for the NM host) is a fixed,
+ generated script with a quoted `exec node`.
+- **Process hygiene**: browser teardown waits for exit, then deletes the
+ ephemeral profile with backoff; stale profiles (>1 h) are swept at launch.
+
+## Testing lanes
+
+| Lane | Where | What it proves |
+|---|---|---|
+| `macos-26`, `macos-15`, `macos-15-intel` | CI (`ci.yml`) | Full suite × 3 runners (2 versions × arm64 + Intel), CfT installed, gates on, skip audit, doctor, bridge-security assertion |
+| `windows-latest`, `ubuntu-latest` | CI (`ci.yml`) | Cross-platform guard (Windows desktop driver live; Linux browser tools with CfT) |
+| Plugin E2E | CI-private runner or dev machine | `AXUSE_TEST_LIVE_*=1 node --test test/plugins.test.js` — every plugin's unit + live suite on macOS |
+| `tcc-manual` | `tcc-manual.yml`, self-hosted | Granted-state proofs: real (corner) capture, inert zero-delta CGEvent, recovery re-probe. Fails closed with typed instructions if the runner's grants are missing. Zero skips allowed. |
+
+The **skip audit** (`tools/skip-audit.mjs` + `test/skip-allowlist.json`) makes
+every `# SKIP` explicit, typed, and CI-visible: an undocumented skip fails
+the lane, so gated coverage can never silently vanish.
+
+## Performance characteristics
+
+Measured on Apple M1, macOS 26.6, Node 26 (`bench/macos-hotpaths.mjs`):
+
+| Hot path | Cost | Notes |
+|---|---|---|
+| `osascript` spawn flavors (JXA noop / JXA+CoreGraphics / AppleScript) | 11–13 ms idle M1; 35–47 ms loaded | The floor every desktop gesture pays once; JXA+CG is the per-gesture flavor |
+| `osascript` spawn (per native gesture batch) | ~36 ms | The floor every desktop op pays once |
+| `screen_info` / `permissions` cold probe | 125 / 72 ms | Once per 5 s window |
+| Same, cached | ~0 ms | Introduced by this hardening: warm screenshots save ~2 spawns (~200 ms) |
+| Drag (3 batches: hover+down, moves, up) | 3 spawns | Was 4 — hover and press merged |
+| Double-click | 1 spawn | Was 2 + a 40 ms sleep — and now a real double-click (clickState 2) |
+| CDP observe (diff) | ~1 ms | Warm path |
+| CDP click + diff | ~230 ms | Settle-dominated |
+| `windows()` System Events walk | ~700–1100 ms | One Apple Event per attribute; anchor call, not a poll |
+| Browser launch → CDP ready | ~440 ms | 30 s cold-start allowance (`AXUSE_LAUNCH_TIMEOUT_MS`) |
+| Bridge hub start/stop | ~5 ms / ~0 ms | Includes 0600 token file |
+| 24-way concurrent CDP evaluate | ~4 ms total | Single WebSocket, flat sessions |
+
+## Known limitations
+
+1. **Trunk-Chromium headless + extension bridge** — `chrome.debugger`
+ navigation RPCs can stall on Chromium r1721585 (v158) in headless mode
+ (headed works; the CDP backend is unaffected). axuse now detects the
+ stall and falls back to `location.href` navigation through
+ `Runtime.evaluate`, so the session continues; the first stalled
+ navigation still pays one RPC timeout (~30 s). Upstream regression;
+ re-verified each release.
+2. **macOS desktop `down()`/`up()` (held button)** — intentionally not
+ implemented; typed error directs to `ax_desktop_drag`.
+3. **Screen Recording grants require host restart** — macOS behavior; axuse
+ detects and reports it, cannot bypass it.
+4. **`windows()` cannot use CGWindowList from JXA** — on current macOS the
+ ObjC bridge boxes the CFArrayRef as an opaque Ref (no `deepUnwrap`, and
+ manual CF bridging segfaults — verified empirically), so window
+ discovery stays on the System Events walk, which needs Accessibility for
+ per-window rows and costs one Apple Event per attribute (~0.7–1 s).
+5. **Per-gesture `osascript` floor (measured per flavor in
+ `bench/macos-hotpaths.mjs`)** — ~11–13 ms/spawn idle on M1 (JXA+CoreGraphics
+ is the floor; JXA also beats plain AppleScript, so the flavor choice is
+ already optimal), 35–47 ms under load. A resident helper was evaluated
+ and rejected: JXA cannot receive push callbacks (no blocks/selectors),
+ so a resident process must POLL a command file — at a 10 ms tick it
+ saves ≤13 ms per gesture while permanently burning wakeups and adding
+ crash/cleanup failure modes. At agent action scales (≥200 ms per
+ operation) the spawn is not the bottleneck; revisit only if Apple ships
+ a scriptable event channel.
+6. **Natural-scroll mapping: derived + unit-pinned, live pin in the manual
+ lane** — the wheel sign per preference follows AppKit scroll conventions;
+ the manual lane includes an automated live pin (`tcc lane: LIVE
+ scroll-direction pin`) that scrolls axuse's OWN fixture window and
+ asserts the direction via `scrollY` read-back, so the first manual-lane
+ run closes this with measured truth.
+7. **Vision-gated plugin live demos** (challenge-handler B–E) — require
+ `CHALLENGE_VISION_KEY` / `CHALLENGE_CF_DEMO_URL`; they self-skip typed and
+ are listed in the allowlist. Not macOS-specific.
+8. **Linux desktop driver** — does not exist (by design; browser tools only).
+
+## Release checklist
+
+### Evidence: 2026-10-19 audit (Apple M1, macOS 26.6.2, Node 26.10)
+
+Core suite (private, macOS, gates on): **78 tests, 64 pass, 0 fail, 14
+skipped — every skip typed and allowlisted** (audit PASS). Public open-core
+suite: **78 tests, 62 pass, 0 fail** (audit PASS). TCC state during the run:
+Accessibility denied, Screen Recording preflight true with a stale grant —
+the denied and stale paths were exercised LIVE, not only via mocks.
+
+Per-plugin macOS E2E (unit + live with `AXUSE_TEST_LIVE_*=1`, fixture server
++ public demos where designed):
+
+| Plugin | tests | pass | typed skips | Live evidence on macOS |
+|---|---|---|---|---|
+| ats-apply | 10 | 10 | 0 | fixture ATS dry-walk + full apply + duplicate refusal; public Greenhouse board observe-only |
+| auth-bridge | 13 | 13 | 0 | fixture IdP (password+TOTP+consent+webhook OTP), virtual passkey authenticator, webauthn.io |
+| challenge-handler | 14 | 10 | 4 | fixture slider + interstitial; vision-gated public demos (datadome/geetest/aws-waf) and CF-URL gate self-skip typed |
+| commerce-operator | 6 | 6 | 0 | fixture admin tasks, validation loop, commits |
+| downloads-pdf | 10 | 10 | 0 | verified download sha256, multi-page PDF, disguised-download → `*.suspect`, large-file deadline cancel |
+| enterprise-app-driver | 5 | 5 | 0 | spine state machine + drift demo (design-partner gate) |
+| net-governor | 8 | 8 | 0 | block ≥2× fewer requests, tap round-trip |
+| places-extractor | 7 | 7 | 0 | fixture feed dedupe; API mode typed `PLACES_NO_KEY` without a key |
+| portal-extractor | 8 | 8 | 0 | 12 docs/3 pages, cross-check, dedupe across runs |
+| remote-app-driver | 7 | 7 | 0 | canvas replay 10/10 bars 8, drift never confirms |
+| rich-editor-driver | 7 | 7 | 0 | DOM insert verified; canvas chunking via injected OCR; public ProseMirror demo |
+| session-vault | 16 | 16 | 0 | live cookie save → cold-tab restore, zero re-auth events, sealed at rest |
+| transaction-guard | 12 | 12 | 0 | full cycle, wrong-total refusal, replay duplicate, export verifies |
+| virtual-grid-driver | 7 | 7 | 0 | official AG Grid infinite demo, 1000 rows by identity, zero duplicates |
+| captcha-pro | 4 | 4 | 0 (unit) | live gate rides `test/plugin.test.js` (`AXUSE_TEST_LIVE_CAPTCHA=1` + public demo + vision key) — typed skip here |
+
+Skip inventory (16 total across public/private runs): 8 macOS TCC/manual
+lanes, 2 external live gates (captcha demo), 6 paid-tree lanes (public
+checkout). No other skips exist; the audit enforces this on every CI lane.
+
+Live stale-grant validation (this machine, during the audit): preflight
+reported `screen_recording: true` while `screencapture` failed with `could
+not create image from rect` → axuse returned
+`DESKTOP_PERMISSION_REQUIRED` with the stale-grant hint (restart host;
+`tccutil reset ScreenCapture`; re-grant) and invalidated its probe caches —
+recovery on next call without an axuse restart.
+
+### Checklist
+
+1. `npm test` green on macOS (all gates off) and with
+ `AXUSE_ENABLE_MACOS_CUA=1 AXUSE_TEST_MACOS_DESKTOP=1`.
+2. Plugin E2E: `AXUSE_TEST_LIVE_*=1 node --test test/plugins.test.js` green;
+ every skip matches `test/skip-allowlist.json`.
+3. `node bench/macos-hotpaths.mjs --json` recorded; no regression > 20% on
+ the table above without a documented reason.
+4. Browser matrix: branded Chrome + CfT (+ Edge, Chromium) —
+ `node tools/macos-nm-probe.mjs` green, or blockers re-verified.
+5. CI green on all three macOS runners, Windows, and Linux.
+6. Manual TCC lane green on the self-hosted runner this cycle.
+7. Public open-core ported and green (same CI).
+8. This document's matrices updated with the new evidence and date.
+
+## Migration notes
+
+- **From the pre-hardening driver (≤ df34aa3)**: desktop ops now cache probes
+ for 5 s. If you rely on `permissions()` reflecting an instantaneous grant
+ within the same second, call `permissions({refresh:true})` (or wait for the
+ automatic invalidation after any permission failure).
+- **Wheel/scroll semantics (2026-10 second pass)**: `wheel(dx, dy)` now uses
+ the content-direction contract (dy>0 scrolls content down, matching the
+ browser tool) and flips the CG delta per the Natural Scrolling preference.
+ If you compensated for inverted scrolling before, remove that
+ compensation.
+- **`windows()` now returns per-window rows with bounds** when Accessibility
+ is granted (was title-only); process-fallback rows remain for un-granted
+ hosts. `activate` accepts `{pid}` — the most robust selector — in addition
+ to exact titles.
+- **`press` gained `platform:true`** — plugins and harness prompts that send
+ Windows-convention app shortcuts should pass it on macOS. The old behavior
+ (literal `ctrl` → Control modifier) is unchanged when the flag is absent.
+- **`ax_capture {kind:"reveal"}`** (downloads-pdf): shows a verified capture
+ in Finder (`open -R`) / Explorer (`/select,`) / the folder on Linux —
+ typed `CAPTURE_REVEAL_MISSING`/`CAPTURE_REVEAL_FAILED` errors never blame
+ the capture itself.
+- **Passphrase resolution order for session-vault/auth-bridge** — env var
+ first, then the macOS Keychain (`-s axuse -a <plugin>`). Existing
+ env-var setups are unaffected; the Keychain is strictly additive. In this
+ pass the same order now applies to license tokens, vision keys, and
+ `PLACES_API_KEY`; `AXUSE_KEYCHAIN=0` severs all Keychain lookups (used by
+ the test harness for determinism).
+- **Preview browser channels** — `chrome-beta`, `chrome-canary`, `edge-beta`
+ are first-class in discovery, native-messaging registration, and
+ `axuse setup --browser`; preview builds rank after the stable automation
+ builds in unpinned discovery. Live-verified: Edge Beta runs the full
+ extension chain; Chrome Beta/Canary refuse `--load-extension` like branded
+ stable (so the extension lane excludes every branded Chrome channel, and
+ `AXUSE_BROWSER` overrides pointing at them cannot defeat that).
+- **`AXUSE_LAUNCH_TIMEOUT_MS`** now exists (default 30 s, was a hardcoded
+ 15 s). Cold macOS first launches that used to fail typed `LAUNCH_FAILED`
+ now succeed.
+- **Bridge info files are now written 0600** in a 0700 directory. Existing
+ wider modes are tightened opportunistically when a hub starts. The NM
+ launcher falls back to PATH `node` when the installing binary is gone.
+- **CI**: `macos-13`/`macos-14` labels are retired/deprecated upstream;
+ lanes moved to `macos-26` / `macos-15` / `macos-15-intel`.
diff --git a/docs/non-developer-onboarding.md b/docs/non-developer-onboarding.md
new file mode 100644
index 0000000..92932ac
--- /dev/null
+++ b/docs/non-developer-onboarding.md
@@ -0,0 +1,172 @@
+# Axuse for journalists
+
+## What this is
+
+Axuse lets Codex or ChatGPT Work use a browser for research: opening pages,
+searching, reading results, collecting links, and producing an evidence-backed
+brief.
+
+You do not need Git, Node.js, a terminal, or the Axuse source code.
+
+There is one important requirement: Axuse must first be provided as an official
+connector or signed desktop/browser installer by your organization. The source
+repository currently contains the developer setup, not a finished consumer
+installer. Do not download an unofficial browser extension.
+
+## One-time setup
+
+1. Install or enable the official Axuse connector supplied by your
+ organization. In ChatGPT Work this will normally be listed as an app or
+ connector. In Codex it may be supplied as a connector or desktop helper.
+2. Open Chrome and approve the Axuse browser permission when Chrome asks.
+ This is the one step that cannot safely be approved silently by an agent.
+3. Start a new Codex or ChatGPT Work conversation and paste the following
+ message.
+
+```text
+Set up Axuse for my browser research work.
+
+Use only the official Axuse connector or installer that is already provided.
+Do not ask me to clone a repository, install Node.js, edit configuration files,
+or load an unpacked extension.
+
+Please:
+
+1. Connect Axuse to my default Chrome browser.
+2. Start or configure any required Axuse bridge components.
+3. If Chrome or the operating system needs my approval, pause and tell me
+ exactly what to click.
+4. Verify the connection by opening https://example.com and reading its page
+ title and main content.
+5. Confirm which browser is connected and that Axuse can open pages and read
+ their content.
+6. From now on, automatically use Axuse whenever I ask you to search the web,
+ open a website, collect information, compare sources, or monitor news. I
+ should not need to mention Axuse again.
+7. Keep browser actions read-only unless I explicitly approve logging in,
+ submitting a form, downloading a file, publishing, or contacting someone.
+
+Do not report success until the example.com test has passed.
+If Axuse is not installed or cannot be reached, explain that plainly and tell
+me what the administrator needs to install. Do not invent a successful setup.
+```
+
+The setup is complete when the assistant reports a successful `example.com`
+test. If it asks you to approve a browser permission, approve only the official
+Axuse extension or connector.
+
+## First test
+
+Try a small browser request first:
+
+```text
+Open google.com and search for the latest news in the United States.
+```
+
+You should see Axuse open or use the browser. If the assistant answers from
+memory without opening Google, say:
+
+```text
+Use the connected Axuse browser for this task. Show me the pages you opened
+and their URLs before summarizing the results.
+```
+
+## Useful research prompts
+
+### A news brief
+
+```text
+Search the latest US news from the last 24 hours. Use Axuse to open the
+relevant results, deduplicate repeated wire stories, and prioritize primary
+sources.
+
+Create a concise Markdown brief with:
+- headline
+- outlet and publication time
+- URL
+- two-sentence summary
+- the main claim supported by the source
+- whether the source is primary or secondary
+- uncertainty, missing information, and conflicting reports
+
+Do not publish anything or contact anyone. Tell me which pages were blocked,
+paywalled, or unavailable instead of guessing.
+```
+
+### Collect structured information
+
+```text
+Find the official press releases published by [ORGANIZATION] about [TOPIC]
+between [START DATE] and [END DATE]. Open each source with Axuse and return a
+table containing date, title, URL, named people or organizations, locations,
+and the exact facts supported by each page. Mark anything you could not verify.
+```
+
+### Compare claims
+
+```text
+Investigate the claim that [CLAIM]. Use Axuse to open at least five distinct
+sources, including the most relevant primary source. Separate verified facts,
+source interpretations, and unresolved claims. Include URLs and publication
+dates for every item.
+```
+
+### Save a report
+
+```text
+Repeat the research above and save the final result as a Markdown report and
+a CSV source list. Include the collection time, every URL opened, and a note
+for each source that was blocked, paywalled, or unavailable.
+```
+
+## How to ask for better results
+
+Include four things when they matter:
+
+- **Topic:** what you are investigating.
+- **Time window:** for example, “since yesterday” or exact dates.
+- **Source rules:** official sources, local outlets, public records, or a
+ specific list of publications.
+- **Output:** a brief, timeline, table, source list, or Markdown/CSV files.
+
+You do not need to describe browser clicks. Say what you want researched and
+the assistant should choose the Axuse browser actions.
+
+## Safety rules
+
+Axuse should be used as a research assistant, not as an invisible publishing
+agent. Ask for confirmation before it:
+
+- logs into an account or handles private messages;
+- submits a form or sends an email;
+- downloads files;
+- publishes, edits, or deletes content;
+- contacts a source or another person.
+
+It should record URLs and collection times, distinguish primary from secondary
+sources, and say when a page could not be read. Never treat a search-result
+snippet as proof when the underlying page is unavailable.
+
+## If something goes wrong
+
+**“Axuse is not available.”** The official connector or desktop helper has not
+been installed, or the conversation was opened before it was installed. Ask
+the administrator to install Axuse, then start a new conversation.
+
+**The browser is not connected.** Open Chrome, make sure the official Axuse
+extension is enabled, and repeat the setup prompt. Do not install a second
+extension with a similar name.
+
+**A page is blocked or requires a login.** Ask Axuse to record the URL and
+continue with accessible sources. Do not ask it to bypass a paywall, CAPTCHA,
+or access control.
+
+**The answer has no URLs.** Ask: “Redo this using Axuse, show every source URL
+and publication date, and separate verified facts from your interpretation.”
+
+## For the person installing Axuse
+
+The non-developer experience is only complete when Axuse is distributed as an
+official connector or signed installer. A repository checkout, a local
+`src/cli.js` path, manual MCP configuration, and Chrome’s **Load unpacked**
+workflow are developer setup steps and should not be given to journalists.
diff --git a/docs/plugins.md b/docs/plugins.md
new file mode 100644
index 0000000..44e2f8f
--- /dev/null
+++ b/docs/plugins.md
@@ -0,0 +1,180 @@
+# axuse solver plugins — the ABI and the business model
+
+axuse's core is (and stays) free for noncommercial use (PolyForm Noncommercial
+1.0.0, copyright CTOL Digital Solutions) and **CAPTCHA-agnostic**.
+Solvers — Turnstile, hCaptcha, reCAPTCHA, or anything else — are **separate
+packages**, separately licensed (paid), that plug into axuse through a thin,
+frozen seam. Nothing about the seam knows what a CAPTCHA is; nothing a solver
+does leaks into the core.
+
+```
+ axuse core (PolyForm Noncommercial 1.0.0)
+ ┌────────────────────────────────────────────────┐
+ │ src/plugins/index.js ← the ONLY seam │
+ │ discovery → validation → registry │
+ │ buildSolveContext() → the narrow ctx │
+ └──────────────┬─────────────────────────────────┘
+ │ in-process, trusted code (not sandboxed)
+ ┌──────────────▼─────────────────────────────────┐
+ │ plugins/<your-solver>/ (paid, gitignored) │
+ │ index.js exporting `solver` │
+ └──────────────────────────────────────────────┘
+```
+
+## The frozen ABI
+
+A solver plugin is one ESM module (a directory with `index.js`, or a
+`package.json` with a `main`) exporting:
+
+```js
+export const solver = {
+ id: "captcha-pro", // unique slug
+ version: "1.0.0",
+ label: "human-readable name (optional)",
+ providers: ["turnstile", "recaptcha-v2", "hcaptcha"], // what it solves
+ async solve(provider, ctx, opts = {}) {
+ // → { solved, provider, token, elapsedMs, notes, ...facts }
+ },
+};
+export default solver; // optional but recommended
+```
+
+Validation is fail-closed and typed (`PLUGIN_LOAD_FAILED`): a broken paid
+package is reported by `axuse plugins` and never takes the MCP server down.
+
+## The narrow `ctx`
+
+The solver never touches the Controller. It gets four primitives — the same
+lesson set the core commands encode, distilled for solvers:
+
+```js
+ctx.evaluate(jsExpression) // → parsed JSON value (NOT the raw
+ // ax_evaluate string — single-encoded
+ // for you; a real double-encoding trap)
+ctx.click({ x, y } | { ref }, { settleMs }) // trusted CDP input
+ctx.screenshot({ crop, quality, budgetBytes })
+ // → { base64, mime, bytes, quality, crop }
+ // crop-first: never vision-tax a whole page
+ctx.waitFor({ selector|expression|text, timeoutMs }) // bounded in-page wait
+ctx.wait(ms) // bounded sleep
+ctx.meta // { startedAt }
+```
+
+Rules of the road:
+
+- **Facts, never fabrication.** `token: null` when unsolved; never a made-up
+ token. Notes are one honest sentence.
+- **Own your config.** Read your own env vars (`CAPTCHA_PRO_*` style); the core
+ never sees your keys, endpoints or models.
+- **Deadline math beats retries.** Challenge windows are ~110 s; don't start a
+ round that cannot finish (`deadline.has(ROUND_TRIP_MS)` pattern).
+- **Account your cost.** Return `visionCalls`, token counts, rounds — the
+ caller should be able to see "efficient", not take it on faith.
+
+## Where plugins load from
+
+1. Every directory in `AXUSE_PLUGINS` (`;`-separated on Windows, `:` elsewhere)
+2. axuse's `plugins/` directory (the install target; gitignored except its
+ README, so paid packages never enter the open repo)
+
+Loading happens once, at `axuse mcp` / `axuse plugins` / `axuse solve` start.
+One import per plugin directory; no patching, no fork, no rebuild.
+
+## Surfaces a loaded solver appears on
+
+| Surface | Tool / command |
+|---|---|
+| MCP | `ax_solve_captcha { provider, url?, headless?, max_attempts?, deadline_ms? }` |
+| MCP | `ax_plugins` (loaded + failed + search paths + contributed tool names) |
+| MCP | **any tool the plugin contributes through its `tools()` export** (below) |
+| CLI | `axuse plugins` |
+| CLI | `axuse solve <provider> [--url URL] [--headless] [--max-attempts N] [--deadline-ms N]` |
+
+`ax_solve_captcha` optionally opens `url` first (headed by default — the most
+human-looking launch, per the anti-bot reality notes), then dispatches to the
+loaded solver for that provider through the ctx.
+
+## Contributing extra MCP tools (`tools()`)
+
+A plugin that owns a capability rather than a solve (a session vault, a
+network governor, a guard cycle) exports a `tools()` function **in addition
+to the solver ABI**. Tools are validated at load time — names must match
+`ax_<slug>`, must never shadow core tools, every schema property needs a
+type — and a broken `tools()` fails that plugin typed (`PLUGIN_LOAD_FAILED`),
+never the server:
+
+```js
+export function tools() {
+ return [{
+ name: "ax_vault", // ax_<slug>, never a core tool name
+ description: "session-vault: save/restore aged sessions …",
+ inputSchema: { // same generator shape as core tools
+ type: "object",
+ properties: { op: { type: "string", enum: ["save", "restore", "list"] } },
+ required: ["op"], additionalProperties: false,
+ },
+ handle: async (args, ctx) => { … }, // the SAME trusted ctx solve() gets
+ }];
+}
+export const solver = { id, version, providers: ["session"], solve }; // still required
+```
+
+The handle receives the same context as `solve` (below) — including the
+extended primitives. Return a JSON facts object; throw typed errors
+(`{ code, message, hint, retry }` via a `toJSON()`-carrying Error) and they
+surface to the model as structured tool results, not opaque internals.
+
+## The ctx — narrow core + Wave-1 extensions
+
+The four frozen primitives every solver gets:
+
+```js
+ctx.evaluate(expr) // parsed JSON value (single-encoded for you)
+ctx.click({x,y}|{ref}, { settleMs })
+ctx.screenshot({ crop, quality, budgetBytes }) // crop-first, never a page
+ctx.waitFor({ selector|expression|text, timeoutMs })
+ctx.wait(ms)
+ctx.meta // { startedAt }
+```
+
+Plugins that need more than the frozen four (the premium catalog) receive
+the sanctioned Wave-1 extensions — still narrow, still typed, still never
+the raw Controller:
+
+```js
+ctx.cdp(method, params, sessionId?) // typed CDP passthrough (Storage cookies,
+ // Browser download behavior, WebAuthn
+ // virtual authenticators, Fetch/Network,
+ // raw Input.* for human-curve drags)
+ctx.cdpBroadcast(method, params) // send to the tab + EVERY OOPIF frame
+ // session, replay on future attaches
+ctx.cdpOn(method, handler) → off() // raw CDP event subscription, frame-aware
+ctx.press / ctx.type / ctx.drag / ctx.scroll / ctx.upload // trusted input
+ // ctx.press(combo, { platform: true })
+ // translates Windows-convention app
+ // shortcuts to the host OS (macOS:
+ // ctrl+alt+1 → cmd+alt+1)
+ctx.observe({ mode, find }) // AX snapshots (the same trees the harness sees)
+ctx.open(url, { profileDir }) // profileDir: a persistent (never deleted) profile
+ctx.navigate / ctx.tabs / ctx.events // navigation, tab list (+ frame sessions,
+ // downloads), the event ring tail
+```
+
+Rules unchanged: **facts, never fabrication**; own your env config;
+deadline math beats retries; account your cost.
+
+## A working reference
+
+[`examples/plugin-turnstile-demo/`](../examples/plugin-turnstile-demo/) is a
+complete, free (PolyForm Noncommercial 1.0.0), working Turnstile solver for demo pages — copy it as a
+skeleton. The commercial `captcha-pro` package (Turnstile + hCaptcha +
+reCAPTCHA v2 with vision loops) is a drop-in with the same shape.
+
+## Why in-process and trusted (not sandboxed)
+
+The seam exists for **packaging and licensing separation** (open core ↔ paid
+solvers), not for isolation: a solver drives your real browser with your real
+clicks. That is exactly as much trust as the browser tools themselves already
+carry — sandboxing here would be security theater on top of a CDP session that
+already has full page access. Buy solvers from vendors you'd trust with the
+pages they drive.
diff --git a/examples/plugin-turnstile-demo/README.md b/examples/plugin-turnstile-demo/README.md
new file mode 100644
index 0000000..f274a94
--- /dev/null
+++ b/examples/plugin-turnstile-demo/README.md
@@ -0,0 +1,32 @@
+# Example solver plugin — `turnstile-demo` (free for noncommercial use, PolyForm Noncommercial 1.0.0)
+
+A complete, minimal, working solver for **Cloudflare Turnstile on demo/test
+pages**. Shipped with axuse under the PolyForm Noncommercial 1.0.0 license to
+prove the plugin seam end-to-end —
+production CAPTCHA solving (all providers, image challenges, vision loops) is
+the domain of separate commercial packages such as `captcha-pro`.
+
+## What it demonstrates
+
+- The full plugin ABI: `{ id, version, providers, solve(provider, ctx, opts) }`
+- The narrow `ctx` in action: `evaluate`, `click`, `waitFor`/`wait`, deadline math
+- Facts-only results: `{ solved, token, elapsedMs, notes }` — never a fabricated token
+- Zero-dependency, single-file, no configuration
+
+## Run it
+
+```bash
+# Load it without copying: point the search path at this directory
+set AXUSE_PLUGINS=E:\path\to\axuse\examples\plugin-turnstile-demo
+node src/cli.js plugins
+
+# Solve (Cloudflare's official demo, test sitekey)
+node src/cli.js solve turnstile --url https://demo.turnstile.workers.dev/
+```
+
+Or copy this folder into axuse's `plugins/` directory — same effect.
+
+## Authoring your own solver
+
+Read [`docs/plugins.md`](../../docs/plugins.md) for the contract, the `ctx`
+reference, and packaging/licensing guidance.
diff --git a/examples/plugin-turnstile-demo/index.js b/examples/plugin-turnstile-demo/index.js
new file mode 100644
index 0000000..6d160f0
--- /dev/null
+++ b/examples/plugin-turnstile-demo/index.js
@@ -0,0 +1,72 @@
+/**
+ * axuse example solver plugin — "turnstile-demo" (free for noncommercial use,
+ * PolyForm Noncommercial 1.0.0, ships with the
+ * repo). A complete, working solver for Cloudflare Turnstile on demo/test
+ * pages. It exists to prove the plugin seam end-to-end and to serve as the
+ * reference for authoring solver plugins (commercial solvers are drop-in
+ * replacements with the same shape).
+ *
+ * Run it:
+ * node src/cli.js plugins # verify it loads
+ * node src/cli.js solve turnstile --url https://demo.turnstile.workers.dev/
+ *
+ * (Point AXUSE_PLUGINS at this directory to load it without copying:
+ * set AXUSE_PLUGINS=E:\...\axuse\examples\plugin-turnstile-demo )
+ */
+
+const TOKEN_EXPR = `(() => {
+ const el = document.querySelector('[name="cf-turnstile-response"]');
+ return { token: el && el.value ? el.value : "", len: el && el.value ? el.value.length : 0 };
+})()`;
+
+const WIDGET_EXPR = `(() => {
+ const w = document.querySelector('.cf-turnstile') || document.querySelector('[class*="cf-turnstile"]');
+ if (!w) return null;
+ const r = w.getBoundingClientRect();
+ return r.width > 0 ? { x: Math.round(r.x), y: Math.round(r.y), w: Math.round(r.width), h: Math.round(r.height) } : null;
+})()`;
+
+const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
+
+async function poll(ctx, ms) {
+ const end = Date.now() + ms;
+ while (Date.now() < end) {
+ const t = await ctx.evaluate(TOKEN_EXPR);
+ if (t && t.len > 0) return t.token;
+ await sleep(400);
+ }
+ return null;
+}
+
+export const solver = {
+ id: "turnstile-demo",
+ version: "1.0.0",
+ label: "example (free): Turnstile demo-page solver",
+ providers: ["turnstile"],
+ async solve(provider, ctx, opts = {}) {
+ const deadlineMs = opts.deadlineMs ?? 45_000;
+ const t0 = Date.now();
+ // 1. Fast path: most demo widgets self-solve and fill the token input.
+ let token = await poll(ctx, 8000);
+ let notes = "non-interactive pass (token appeared without a click)";
+ // 2. Interactive: one trusted click on the checkbox anchor.
+ if (!token) {
+ const w = await ctx.evaluate(WIDGET_EXPR);
+ if (!w) {
+ return { solved: false, provider, token: null, elapsedMs: Date.now() - t0, notes: "no .cf-turnstile widget on the page" };
+ }
+ await ctx.click({ x: w.x + 30, y: w.y + 32 }, { settleMs: 800 });
+ token = await poll(ctx, Math.max(1000, deadlineMs - (Date.now() - t0) - 1000));
+ notes = `interactive widget clicked at (${w.x + 30},${w.y + 32})`;
+ }
+ return {
+ solved: !!token,
+ provider,
+ token: token ?? null,
+ elapsedMs: Date.now() - t0,
+ notes: token ? notes : `${notes}, but no token appeared within ${deadlineMs}ms`,
+ };
+ },
+};
+
+export default solver;
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..f40d15c
--- /dev/null
+++ b/package.json
@@ -0,0 +1,28 @@
+{
+ "name": "axuse",
+ "version": "0.1.0",
+ "description": "Accessibility-first browser & computer use for agent harnesses (Codex, Claude Code, OpenCode, Antigravity, ...). Instrument, don't photograph. MCP-native, zero dependencies.",
+ "type": "module",
+ "bin": {
+ "axuse": "./src/cli.js"
+ },
+ "main": "./src/core/controller.js",
+ "engines": {
+ "node": ">=22"
+ },
+ "scripts": {
+ "test": "node --test test/*.test.js",
+ "doctor": "node src/cli.js doctor"
+ },
+ "keywords": [
+ "mcp",
+ "browser-use",
+ "computer-use",
+ "cua",
+ "cdp",
+ "accessibility",
+ "agent",
+ "automation"
+ ],
+ "license": "PolyForm-Noncommercial-1.0.0"
+}
diff --git a/plugins/README.md b/plugins/README.md
new file mode 100644
index 0000000..99bfcc0
--- /dev/null
+++ b/plugins/README.md
@@ -0,0 +1,43 @@
+# Solver plugins — the paid install target
+
+axuse's open core ships **no solvers**. CAPTCHA solvers (Cloudflare Turnstile,
+hCaptcha, reCAPTCHA) are **separate, commercially licensed packages** that plug
+into axuse through the thin plugin seam in `src/plugins/`.
+
+This directory is the default install target. It is git-ignored except for this
+README: whatever you drop here stays on your machine and out of the open repo.
+
+## Install
+
+1. Obtain a solver package (e.g. `captcha-pro`), either as a directory or a
+ `.tgz`.
+2. Place it here: `plugins/captcha-pro/` (must contain `index.js` or a
+ `package.json` with a `main`).
+3. Configure the package (its own env vars — see its README).
+4. Verify:
+
+ ```bash
+ node src/cli.js plugins # → ✓ [email protected] — providers: ...
+ node src/cli.js solve turnstile --url https://demo.turnstile.workers.dev/
+ ```
+
+Or point axuse elsewhere (before the MCP server starts):
+
+```bash
+set AXUSE_PLUGINS=D:\paid-solvers;E:\more-solvers
+```
+
+## Where solvers appear
+
+- CLI: `axuse plugins`, `axuse solve <provider> [--url …]`
+- MCP tools: `ax_solve_captcha { provider, url? }` and `ax_plugins`
+ (both present in every harness once a plugin is loaded)
+- Plugins may also contribute their **own MCP tools** (a validated `tools()`
+ export — e.g. `ax_vault`, `ax_net`, `ax_guard`); see
+ [`docs/plugins.md`](../docs/plugins.md) for the exact contract.
+
+## Authoring your own
+
+See [`docs/plugins.md`](../docs/plugins.md) for the frozen plugin ABI and
+[`examples/plugin-turnstile-demo/`](../examples/plugin-turnstile-demo/) for a
+complete, free, working reference solver.
diff --git a/src/bridge/backend.js b/src/bridge/backend.js
new file mode 100644
index 0000000..b4c37a5
--- /dev/null
+++ b/src/bridge/backend.js
@@ -0,0 +1,155 @@
+/**
+ * axuse bridge — backend.
+ *
+ * Lineage: Codex's tab_cdp_call over chrome.debugger — the extension holds
+ * real CDP over the user's real browser (cookies, logged-in sessions, 2FA
+ * devices all present), and the harness drives it through a thin transport.
+ * ExtensionBrowser duck-types the surface the Controller already uses for
+ * CDP-launched browsers (conn/createTab/closeTabTarget/dispose), so the
+ * entire frozen command contract — snapshots, diffs, trusted input, budgets
+ * — runs unchanged against the user's daily Chrome.
+ *
+ * Known backend gap (documented honestly): chrome.debugger exposes no
+ * Target domain, so OOPIF frames are listed but not entered here (the CDP
+ * backend enters them).
+ */
+import { AxError, Codes } from "../core/errors.js";
+import { getBridge } from "./hub.js";
+
+/** conn-like surface over the bridge (duck-types CdpConnection where the
+ * controller cares: send / onEvent / close / closed). */
+class ExtConn {
+ constructor(bridge) {
+ this.bridge = bridge;
+ this.handlers = new Set();
+ this.offRoute = bridge.onEvent((e) => {
+ for (const h of this.handlers) { try { h(e); } catch {} }
+ });
+ this.closedFlag = false;
+ }
+
+ get closed() {
+ return this.closedFlag;
+ }
+
+ async send(method, params, sessionId) {
+ if (sessionId === undefined) {
+ throw new AxError(Codes.COMMAND_REJECTED,
+ `Command "${method}" needs a browser-level CDP domain the extension backend does not expose (chrome.debugger has no Target domain).`,
+ { hint: "Use backend cdp (default) for that command.", retry: "never" });
+ }
+ let res;
+ try {
+ res = await this.bridge.rpc("cdp", { tabId: Number(sessionId), method, params: params ?? {} });
+ } catch (e) {
+ if (e instanceof AxError && e.code === Codes.TIMEOUT) {
+ // Trunk-Chromium stall fallback (verified on r1721585 headless): a
+ // Page.navigate RPC can hang while the SAME build answers
+ // Runtime.evaluate fine. Route the navigation through the page once,
+ // verify the URL actually changed, and answer with a navigate result.
+ if (method === "Page.navigate" && typeof params?.url === "string") {
+ return this.navigateViaEvaluate(params.url, sessionId);
+ }
+ // Side-effect accounting, same as the CDP backend: a timeout after
+ // dispatch means the input may have landed.
+ throw new AxError(Codes.TIMEOUT, e.message, { ...e, sideEffect: "uncertain" });
+ }
+ throw e;
+ }
+ if (!res.ok) {
+ const s = String(res.error ?? "unknown error");
+ if (/no attached target|tab.*(closed|not found)|detach/i.test(s)) {
+ throw new AxError(Codes.ATTACH_FAILED, `CDP ${method} failed: ${s}`,
+ { hint: "The tab was closed or the debugger detached (navigation can detach it; axuse re-attaches on the next command).", retry: "retry" });
+ }
+ throw new AxError(Codes.INTERNAL, `CDP ${method} failed: ${s}`);
+ }
+ return res.result ?? {};
+ }
+
+ /** Navigate by assignment when the debugger RPC stalls: the page executes
+ * location.href = url; we confirm with a same-turn read-back and return
+ * the Page.navigate result shape the controller expects. */
+ async navigateViaEvaluate(url, sessionId) {
+ const expr = `(function(){ location.href = ${JSON.stringify(url)}; return location.href; })()`;
+ const res = await this.bridge.rpc("cdp", {
+ tabId: Number(sessionId),
+ method: "Runtime.evaluate",
+ params: { expression: expr, returnByValue: true },
+ });
+ if (res.ok && res.result?.result?.value !== undefined) {
+ return { frameId: null, loaderId: undefined, via: "location.href (Page.navigate RPC stalled — trunk-Chromium fallback)" };
+ }
+ throw new AxError(Codes.TIMEOUT,
+ `Page.navigate stalled and the location.href fallback did not confirm (browser may be mid-detach).`,
+ { hint: "Retry: the debugger re-attach on the next command usually restores the direct path.", retry: "retry", sideEffect: "uncertain" });
+ }
+
+ onEvent(handler) {
+ this.handlers.add(handler);
+ return () => this.handlers.delete(handler);
+ }
+
+ close() {
+ this.closedFlag = true;
+ try { this.offRoute && this.offRoute(); } catch {}
+ }
+}
+
+/** BrowserHandle-compatible surface backed by the user's real Chrome. */
+export class ExtensionBrowser {
+ constructor(bridge) {
+ this.bridge = bridge;
+ this.conn = new ExtConn(bridge);
+ this.tabs = new Set();
+ this.launched = false; // we never launched it — it's the user's browser
+ this.proc = null;
+ this.userDataDir = null;
+ this.createdTargets = new Set();
+ }
+
+ async waitOnline(timeoutMs = 20_000) {
+ await this.bridge.waitExt(timeoutMs);
+ }
+
+ async createTab(url = "about:blank") {
+ const res = await this.bridge.rpc("open_tab", { url });
+ if (!res.ok) {
+ throw new AxError(Codes.ATTACH_FAILED, `open_tab failed: ${res.error}`,
+ { hint: "Is Chrome running with the axuse bridge extension loaded? (axuse bridge install; load bridge/extension unpacked)", retry: "retry" });
+ }
+ const tabId = String(res.result.tabId);
+ for (const m of ["Page.enable", "Runtime.enable", "Log.enable"]) {
+ await this.conn.send(m, {}, tabId);
+ }
+ // NOTE: no Target.setAutoAttach — chrome.debugger has no Target domain,
+ // so OOPIF frames stay listed-but-not-entered on this backend.
+ this.createdTargets.add(tabId);
+ return { targetId: tabId, sessionId: tabId };
+ }
+
+ async closeTabTarget(targetId) {
+ const id = String(targetId);
+ this.createdTargets.delete(id);
+ try { await this.bridge.rpc("close_tab", { tabId: Number(id) }); } catch {}
+ }
+
+ dispose() {
+ // Codex semantics: disposing this backend closes the tabs WE created —
+ // never the user's browser.
+ const targets = [...this.createdTargets];
+ this.createdTargets.clear();
+ for (const t of targets) {
+ void this.bridge.rpc("close_tab", { tabId: Number(t) }).catch(() => {});
+ }
+ this.conn.close();
+ }
+}
+
+/** Build (and wait for) the extension-backed browser handle. */
+export async function createExtensionHandle() {
+ const bridge = await getBridge();
+ const b = new ExtensionBrowser(bridge);
+ await b.waitOnline(20_000);
+ return b;
+}
diff --git a/src/bridge/hub.js b/src/bridge/hub.js
new file mode 100644
index 0000000..06517e5
--- /dev/null
+++ b/src/bridge/hub.js
@@ -0,0 +1,421 @@
+/**
+ * axuse bridge hub.
+ *
+ * Lineage: Codex's side-panel ↔ app-server transport (localhost socket +
+ * version handshake + the native-messaging port as the extension link).
+ * The hub is the rendezvous point: Chrome spawns the native-messaging host
+ * (nm-host.js) when the extension connects; the host dials the hub; the
+ * axuse backend (in this or another process) drives the extension over the
+ * same socket. NDJSON lines; token auth; ext-online/offline status events.
+ *
+ * Two deployment shapes, one API (`rpc`, `onEvent`, `extOnline`, `waitExt`):
+ * - BridgeHub (server): started in-process by the controller, or
+ * standalone via `axuse bridge` (survives MCP restarts).
+ * - BridgeClient: used when an external hub is already running.
+ */
+import net from "node:net";
+import { randomBytes, createHash } from "node:crypto";
+import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { join, resolve } from "node:path";
+import { AxError, Codes } from "../core/errors.js";
+
+const PING_MS = 20_000; // keeps the MV3 service worker alive
+const RPC_TIMEOUT_MS = 30_000;
+
+export function bridgeDir() {
+ const override = process.env.AXUSE_BRIDGE_DIR?.trim();
+ if (override) return resolve(override);
+ if (process.platform === "win32") {
+ return join(process.env.LOCALAPPDATA ?? homedir(), "axuse");
+ }
+ if (process.platform === "darwin") {
+ return join(homedir(), "Library", "Application Support", "axuse");
+ }
+ return join(process.env.XDG_RUNTIME_DIR ?? join(homedir(), ".cache"), "axuse");
+}
+
+/** The bridge info file carries the hub auth token: the owner-only mode is
+ * enforced on POSIX (mkdir 0700 for the dir, chmod 0600 for the file), and
+ * pre-existing wider modes are tightened. Windows ACLs already scope
+ * %LOCALAPPDATA% to the user. */
+function secureBridgePaths(dir, file) {
+ if (process.platform === "win32") return;
+ try {
+ const st = statSync(dir);
+ if (st.isDirectory() && (st.mode & 0o077) !== 0) chmodSync(dir, 0o700);
+ } catch {}
+ try {
+ const st = statSync(file);
+ if (st.isFile() && (st.mode & 0o077) !== 0) chmodSync(file, 0o600);
+ } catch {}
+}
+
+export function infoPath() {
+ return join(bridgeDir(), "bridge.json");
+}
+
+export function readInfo() {
+ try {
+ return JSON.parse(readFileSync(infoPath(), "utf8"));
+ } catch {
+ return null;
+ }
+}
+
+function pidAlive(pid) {
+ try { process.kill(pid, 0); return true; } catch { return false; }
+}
+
+function offlineError() {
+ return new AxError(Codes.ATTACH_FAILED,
+ "The axuse extension is not connected (no browser running, extension not loaded, or hub unreachable).",
+ {
+ hint: "Run `axuse bridge install`, then launch Chrome normally with the axuse bridge extension loaded (unpacked). The service worker connects automatically.",
+ retry: "retry",
+ });
+}
+
+/** Server-side hub. */
+export class BridgeHub {
+ constructor() {
+ this.server = null;
+ this.port = null;
+ this.token = null;
+ this.extConn = null;
+ this.clients = new Set();
+ this.reqSeq = 0;
+ this.pending = new Map(); // id → {resolve(msg), timer}
+ this.eventHandlers = new Set();
+ this.pingTimer = null;
+ }
+
+ async start() {
+ mkdirSync(bridgeDir(), { recursive: true, mode: 0o700 });
+ this.token = randomBytes(16).toString("hex");
+ this.server = net.createServer((sock) => this.onConnection(sock));
+ await new Promise((resolve, reject) => {
+ this.server.once("error", reject);
+ this.server.listen(0, "127.0.0.1", resolve);
+ });
+ this.port = this.server.address().port;
+ // The info file is how the native-messaging host (spawned by Chrome)
+ // finds the hub: {port, token, pid}.
+ writeFileSync(infoPath(), JSON.stringify({ port: this.port, token: this.token, pid: process.pid, ts: Date.now() }, null, 2));
+ secureBridgePaths(bridgeDir(), infoPath());
+ this.pingTimer = setInterval(() => {
+ if (this.extConn) this.writeTo(this.extConn.sock, { t: "ping" });
+ }, PING_MS);
+ if (this.pingTimer.unref) this.pingTimer.unref();
+ return this;
+ }
+
+ stop() {
+ if (this.pingTimer) clearInterval(this.pingTimer);
+ for (const [, p] of this.pending) { clearTimeout(p.timer); }
+ this.pending.clear();
+ for (const c of this.clients) { try { c.sock.destroy(); } catch {} }
+ this.clients.clear();
+ if (this.extConn) { try { this.extConn.sock.destroy(); } catch {} this.extConn = null; }
+ try { this.server.close(); } catch {}
+ try { writeFileSync(infoPath(), ""); } catch {}
+ }
+
+ writeTo(sock, obj) {
+ try { sock.write(JSON.stringify(obj) + "\n"); } catch {}
+ }
+
+ onConnection(sock) {
+ let authed = false;
+ let role = null;
+ let buffer = "";
+ const conn = { sock, role, write: (o) => this.writeTo(sock, o) };
+ sock.setNoDelay(true);
+ sock.on("data", (d) => {
+ buffer += String(d);
+ let i;
+ while ((i = buffer.indexOf("\n")) >= 0) {
+ const line = buffer.slice(0, i).trim();
+ buffer = buffer.slice(i + 1);
+ if (!line) continue;
+ let msg;
+ try { msg = JSON.parse(line); } catch { sock.destroy(); return; }
+ if (!authed) {
+ if (msg && msg.t === "hello" && msg.token === this.token &&
+ (msg.role === "extension-host" || msg.role === "client")) {
+ authed = true;
+ conn.role = msg.role;
+ if (msg.role === "extension-host") {
+ if (this.extConn && this.extConn.sock !== sock) {
+ // Superseded connection: fail in-flight requests immediately
+ // instead of letting them hang to a timeout.
+ for (const [, p] of this.pending) {
+ clearTimeout(p.timer);
+ p.reject(new AxError(Codes.ATTACH_FAILED,
+ "Extension connection was replaced mid-request (SW restart). Retry the command.",
+ { retry: "retry" }));
+ }
+ this.pending.clear();
+ try { this.extConn.sock.destroy(); } catch {}
+ }
+ this.extConn = conn;
+ this.writeTo(sock, { t: "hello-ack", ok: true });
+ this.broadcastStatus();
+ for (const h of this.eventHandlers) { try { h({ kind: "ext-online" }); } catch {} }
+ } else {
+ this.clients.add(conn);
+ this.writeTo(sock, { t: "hello-ack", ok: true, ext: !!this.extConn });
+ }
+ } else {
+ this.writeTo(sock, { t: "hello-ack", ok: false, error: "bad token or role" });
+ sock.destroy();
+ return;
+ }
+ continue;
+ }
+ if (conn.role === "extension-host") this.onFromExt(msg);
+ else this.onFromClient(conn, msg);
+ }
+ });
+ sock.on("close", () => {
+ if (conn.role === "client") this.clients.delete(conn);
+ if (this.extConn === conn) {
+ this.extConn = null;
+ this.broadcastStatus();
+ for (const h of this.eventHandlers) { try { h({ kind: "ext-offline" }); } catch {} }
+ for (const [, p] of this.pending) {
+ clearTimeout(p.timer);
+ p.reject(offlineError());
+ }
+ this.pending.clear();
+ }
+ });
+ sock.on("error", () => {});
+ }
+
+ broadcastStatus() {
+ for (const c of this.clients) c.write({ t: "status", ext: !!this.extConn });
+ }
+
+ onFromExt(msg) {
+ if (!msg || typeof msg !== "object") return;
+ if (process.env.AXUSE_BRIDGE_DEBUG) {
+ process.stderr.write(`[axuse:hub] ext→ ${JSON.stringify(msg).slice(0, 300)}\n`);
+ }
+ if (msg.t === "res") {
+ const p = this.pending.get(msg.id);
+ if (p) {
+ this.pending.delete(msg.id);
+ clearTimeout(p.timer);
+ p.resolve({ ok: !!msg.ok, result: msg.result, error: msg.error });
+ } else if (process.env.AXUSE_BRIDGE_DEBUG) {
+ process.stderr.write(`[axuse:hub] res for unknown id ${msg.id} (stale?)\n`);
+ }
+ } else if (msg.t === "evt") {
+ const event = { sessionId: String(msg.tabId), method: msg.method, params: msg.params ?? {} };
+ for (const h of this.eventHandlers) { try { h(event); } catch {} }
+ for (const c of this.clients) c.write({ t: "evt", ...msg });
+ } else if (msg.t === "ext-hello") {
+ for (const c of this.clients) c.write({ t: "ext-hello", ...msg });
+ }
+ // "pong" ignored (keepalive reply)
+ }
+
+ async onFromClient(conn, msg) {
+ if (!msg || msg.t !== "req") return;
+ try {
+ const res = await this.rpc(msg.method, msg.params);
+ conn.write({ t: "res", id: msg.id, ok: res.ok, result: res.result, error: res.error });
+ } catch (e) {
+ conn.write({ t: "res", id: msg.id, ok: false, error: e instanceof AxError ? e.toJSON() : { code: Codes.INTERNAL, message: String(e.message ?? e) } });
+ }
+ }
+
+ /** In-process request to the extension (client requests route through it). */
+ rpc(method, params, timeoutMs = RPC_TIMEOUT_MS) {
+ if (!this.extConn) return Promise.reject(offlineError());
+ const id = "h" + ++this.reqSeq;
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pending.delete(id);
+ reject(new AxError(Codes.TIMEOUT, `bridge rpc "${method}" timed out`, { retry: "retry" }));
+ }, timeoutMs);
+ this.pending.set(id, {
+ resolve: (res) => resolve(res),
+ reject,
+ timer,
+ });
+ this.writeTo(this.extConn.sock, { t: "req", id, method, params });
+ });
+ }
+
+ onEvent(handler) {
+ this.eventHandlers.add(handler);
+ return () => this.eventHandlers.delete(handler);
+ }
+
+ extOnline() {
+ return !!this.extConn;
+ }
+
+ async waitExt(timeoutMs = 20_000) {
+ const t0 = Date.now();
+ while (!this.extConn) {
+ if (Date.now() - t0 > timeoutMs) throw offlineError();
+ await new Promise((r) => setTimeout(r, 250));
+ }
+ return true;
+ }
+}
+
+/** Client to an already-running standalone hub. Same surface as BridgeHub. */
+export class BridgeClient {
+ constructor() {
+ this.sock = null;
+ this.seq = 0;
+ this.pending = new Map();
+ this.eventHandlers = new Set();
+ this.online = false;
+ }
+
+ async connect(info, timeoutMs = 5000) {
+ const sock = net.connect(info.port, "127.0.0.1");
+ this.sock = sock;
+ sock.setNoDelay(true);
+ let buffer = "";
+ let authed = false;
+ await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => { sock.destroy(); reject(new AxError(Codes.ATTACH_FAILED, "hub connect/handshake timed out")); }, timeoutMs);
+ sock.once("connect", () => {
+ sock.write(JSON.stringify({ t: "hello", role: "client", token: info.token }) + "\n");
+ });
+ sock.once("error", (e) => {
+ clearTimeout(timer);
+ reject(new AxError(Codes.ATTACH_FAILED, `hub connect failed: ${e.message}`));
+ });
+ sock.on("data", (d) => {
+ buffer += String(d);
+ let i;
+ while ((i = buffer.indexOf("\n")) >= 0) {
+ const line = buffer.slice(0, i).trim();
+ buffer = buffer.slice(i + 1);
+ if (!line) continue;
+ let msg;
+ try { msg = JSON.parse(line); } catch { continue; }
+ if (!authed) {
+ if (msg.t === "hello-ack" && msg.ok) {
+ authed = true;
+ this.online = !!msg.ext;
+ clearTimeout(timer);
+ resolve();
+ } else if (msg.t === "hello-ack") {
+ clearTimeout(timer);
+ sock.destroy();
+ reject(new AxError(Codes.ATTACH_FAILED, `hub auth failed: ${msg.error}`));
+ }
+ continue;
+ }
+ this.onMessage(msg);
+ }
+ });
+ });
+ return this;
+ }
+
+ onMessage(msg) {
+ if (msg.t === "res") {
+ const p = this.pending.get(msg.id);
+ if (p) {
+ this.pending.delete(msg.id);
+ clearTimeout(p.timer);
+ p.resolve({ ok: !!msg.ok, result: msg.result, error: msg.error });
+ }
+ } else if (msg.t === "evt") {
+ const event = { sessionId: String(msg.tabId), method: msg.method, params: msg.params ?? {} };
+ for (const h of this.eventHandlers) { try { h(event); } catch {} }
+ } else if (msg.t === "status") {
+ this.online = !!msg.ext;
+ for (const h of this.eventHandlers) { try { h({ kind: msg.ext ? "ext-online" : "ext-offline" }); } catch {} }
+ }
+ }
+
+ rpc(method, params, timeoutMs = RPC_TIMEOUT_MS) {
+ const id = "c" + ++this.seq;
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pending.delete(id);
+ reject(new AxError(Codes.TIMEOUT, `bridge rpc "${method}" timed out`, { retry: "retry" }));
+ }, timeoutMs);
+ this.pending.set(id, { resolve: (res) => resolve(res), reject, timer });
+ this.sock.write(JSON.stringify({ t: "req", id, method, params }) + "\n");
+ });
+ }
+
+ onEvent(handler) {
+ this.eventHandlers.add(handler);
+ return () => this.eventHandlers.delete(handler);
+ }
+
+ extOnline() {
+ return this.online;
+ }
+
+ close() {
+ for (const [, p] of this.pending) clearTimeout(p.timer);
+ this.pending.clear();
+ try { this.sock?.destroy(); } catch {}
+ this.sock = null;
+ this.online = false;
+ }
+
+ async waitExt(timeoutMs = 20_000) {
+ const t0 = Date.now();
+ while (!this.online) {
+ if (Date.now() - t0 > timeoutMs) throw offlineError();
+ await new Promise((r) => setTimeout(r, 250));
+ }
+ return true;
+ }
+}
+
+let cachedBridge = null;
+
+/** Get the bridge: an external hub if one is alive, else start one here. */
+export async function getBridge() {
+ if (cachedBridge) return cachedBridge;
+ const info = readInfo();
+ if (info && info.port && info.token && info.pid && pidAlive(info.pid) && info.pid !== process.pid) {
+ // Opportunistically tighten a pre-existing info file (token hygiene).
+ secureBridgePaths(bridgeDir(), infoPath());
+ try {
+ const client = await new BridgeClient().connect(info, 3000);
+ cachedBridge = client;
+ return cachedBridge;
+ } catch { /* fall through: start our own */ }
+ }
+ const hub = await new BridgeHub().start();
+ cachedBridge = hub;
+ return hub;
+}
+
+/** Test/tool hook: forget the cached bridge so the next getBridge() starts
+ * fresh (stops nothing — the caller owns the previous instance's lifecycle). */
+export function __resetBridgeForTests() {
+ cachedBridge = null;
+}
+
+/** For the CLI's standalone mode. */
+export async function runStandaloneHub() { const info = readInfo();
+ if (info && info.pid && pidAlive(info.pid) && info.pid !== process.pid) {
+ console.log(`axuse bridge: another hub is already running (pid ${info.pid}, port ${info.port}) — this process will exit.`);
+ return;
+ }
+ const hub = await new BridgeHub().start();
+ console.log(`axuse bridge: hub listening on 127.0.0.1:${hub.port} (info: ${infoPath()})`);
+ console.log("Waiting for the axuse extension to connect (load it in Chrome and it dials in automatically).");
+ hub.onEvent((e) => {
+ if (e.kind === "ext-online") console.log("axuse bridge: extension connected.");
+ if (e.kind === "ext-offline") console.log("axuse bridge: extension disconnected.");
+ });
+ await new Promise(() => {}); // run until killed
+}
diff --git a/src/bridge/install.js b/src/bridge/install.js
new file mode 100644
index 0000000..172f90f
--- /dev/null
+++ b/src/bridge/install.js
@@ -0,0 +1,189 @@
+/**
+ * axuse bridge — installer.
+ *
+ * Registers the native messaging host for Chrome so the extension's
+ * connectNative() can reach the hub:
+ * - Windows: writes a batch launcher (cmd.exe relays the native-messaging
+ * stdio pipes faithfully; native messaging manifests need a full
+ * executable — no args allowed — and .bat qualifies) plus the host
+ * manifest to %LOCALAPPDATA%\axuse, registered under HKCU (no admin).
+ * - macOS/Linux: writes a shebang launcher (chmod +x) and the manifest into
+ * the selected Chromium-family browser's NativeMessagingHosts directory.
+ *
+ * The extension ID is derived from the "key" in the extension manifest
+ * (SHA-256 of the DER SPKI, first 32 hex nibbles, 0-f → a-p), so
+ * allowed_extensions can never drift from the shipped key.
+ */
+import { spawnSync } from "node:child_process";
+import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { createHash } from "node:crypto";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { bridgeDir } from "./hub.js";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+export const EXTENSION_DIR = join(HERE, "..", "..", "bridge", "extension");
+export const HOST_NAME = "com.axuse.bridge";
+
+export function extensionId() {
+ const manifest = JSON.parse(readFileSync(join(EXTENSION_DIR, "manifest.json"), "utf8"));
+ const der = Buffer.from(manifest.key, "base64");
+ const hex = createHash("sha256").update(der).digest("hex").slice(0, 32);
+ return [...hex].map((h) => "abcdefghijklmnop"[parseInt(h, 16)]).join("");
+}
+
+const POSIX_BROWSERS = new Set(["chrome", "edge", "edge-beta", "chromium", "chrome-for-testing", "chrome-beta", "chrome-canary"]);
+
+function normalizeBrowser(browser) {
+ const value = String(browser ?? "chrome").trim().toLowerCase();
+ if (!POSIX_BROWSERS.has(value)) {
+ throw new Error(`Unsupported browser "${browser}". Use chrome, edge, chromium, chrome-for-testing, chrome-beta, chrome-canary, or edge-beta.`);
+ }
+ if (process.platform === "win32" && !["chrome", "edge", "edge-beta"].includes(value)) {
+ throw new Error(`Browser "${value}" is not supported by the Windows native-host installer.`);
+ }
+ return value;
+}
+
+function winRegistryKey(browser) {
+ const vendors = {
+ chrome: "Google\\Chrome",
+ edge: "Microsoft\\Edge",
+ "edge-beta": "Microsoft\\Edge Beta",
+ };
+ return `HKCU\\Software\\${vendors[browser] ?? vendors.chrome}\\NativeMessagingHosts\\${HOST_NAME}`;
+}
+
+function otherPosixRegistrationExists(excludedPath) {
+ const excluded = resolve(excludedPath);
+ for (const browser of POSIX_BROWSERS) {
+ const candidate = join(nativeMessagingDir(browser), `${HOST_NAME}.json`);
+ if (resolve(candidate) !== excluded && existsSync(candidate)) return true;
+ }
+ return false;
+}
+
+function otherWindowsRegistrationExists(browser) {
+ const other = browser === "chrome" ? "edge" : "chrome";
+ const result = spawnSync("reg", ["query", winRegistryKey(other)], { encoding: "utf8" });
+ return result.status === 0;
+}
+
+export function nativeMessagingDir(browser = "chrome") {
+ const value = normalizeBrowser(browser);
+ if (process.platform === "darwin") {
+ const roots = {
+ chrome: join(homedir(), "Library", "Application Support", "Google", "Chrome", "NativeMessagingHosts"),
+ "chrome-beta": join(homedir(), "Library", "Application Support", "Google", "Chrome Beta", "NativeMessagingHosts"),
+ "chrome-canary": join(homedir(), "Library", "Application Support", "Google", "Chrome Canary", "NativeMessagingHosts"),
+ edge: join(homedir(), "Library", "Application Support", "Microsoft Edge", "NativeMessagingHosts"),
+ "edge-beta": join(homedir(), "Library", "Application Support", "Microsoft Edge Beta", "NativeMessagingHosts"),
+ chromium: join(homedir(), "Library", "Application Support", "Chromium", "NativeMessagingHosts"),
+ "chrome-for-testing": join(homedir(), "Library", "Application Support", "Google", "ChromeForTesting", "NativeMessagingHosts"),
+ };
+ return roots[value];
+ }
+ const roots = {
+ chrome: join(homedir(), ".config", "google-chrome", "NativeMessagingHosts"),
+ "chrome-beta": join(homedir(), ".config", "google-chrome-beta", "NativeMessagingHosts"),
+ "chrome-canary": join(homedir(), ".config", "google-chrome-canary", "NativeMessagingHosts"),
+ edge: join(homedir(), ".config", "microsoft-edge", "NativeMessagingHosts"),
+ "edge-beta": join(homedir(), ".config", "microsoft-edge-beta", "NativeMessagingHosts"),
+ chromium: join(homedir(), ".config", "chromium", "NativeMessagingHosts"),
+ "chrome-for-testing": join(homedir(), ".config", "google-chrome-for-testing", "NativeMessagingHosts"),
+ };
+ return roots[value];
+}
+
+/**
+ * @param {{browser?: "chrome"|"edge"|"chromium"|"chrome-for-testing", stateDir?: string, manifestDir?: string}} [opts]
+ * @returns {{hostPath: string, extensionDir: string, extensionId: string, registry?: string}}
+ */
+export async function installBridge({ browser = "chrome", stateDir, manifestDir } = {}) {
+ browser = normalizeBrowser(browser);
+ const dir = stateDir ?? bridgeDir();
+ mkdirSync(dir, { recursive: true });
+ const extId = extensionId();
+ const script = join(HERE, "nm-host.js");
+
+ let hostPath;
+ let via;
+ if (process.platform === "win32") {
+ // Batch launcher (empirically proven on Chromium 155/Edge: cmd.exe relays
+ // the native-messaging stdio pipes faithfully; a compiled C# shim using
+ // Console.OpenStandardInput failed to see Chrome's stdin writes). The
+ // manifest "path" must be a full executable — .bat qualifies here.
+ // Fallback chain: the installing node first, then PATH node — the
+ // launcher keeps working across node upgrades that move the binary.
+ const bat = join(dir, "axuse-nm.bat");
+ writeFileSync(bat, `@echo off\r\nif exist "${process.execPath}" ("${process.execPath}" "${script}") else (node "${script}")\r\n`);
+ hostPath = bat;
+ via = "batch launcher";
+ } else {
+ // Same resilience on POSIX: exec the installing node when it still
+ // exists, else whatever node resolves on PATH. `exec` replaces the
+ // shell, so a node that starts and exits non-zero never double-runs.
+ const launcher = join(dir, "axuse-nm");
+ writeFileSync(launcher, `#!/bin/sh\nif [ -x "${process.execPath}" ]; then exec "${process.execPath}" "${script}" "$@"; fi\nexec node "${script}" "$@"\n`);
+ chmodSync(launcher, 0o755);
+ hostPath = launcher;
+ via = "shebang launcher";
+ }
+
+ const manifest = {
+ name: HOST_NAME,
+ description: "axuse bridge — lets an agent harness control this browser via trusted CDP (chrome.debugger), Codex-style.",
+ path: hostPath,
+ type: "stdio",
+ // Both authorization fields: Chrome accepts allowed_extensions (IDs);
+ // Edge documents allowed_origins (chrome-extension://ID/ URLs). Carrying
+ // both satisfies every Chromium build without drift.
+ allowed_extensions: [extId],
+ allowed_origins: [`chrome-extension://${extId}/`],
+ };
+
+ let registry = null;
+ if (process.platform === "win32") {
+ const manifestPath = join(dir, `${HOST_NAME}.json`);
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
+ const key = winRegistryKey(browser);
+ const r = spawnSync("reg", ["add", key, "/ve", "/t", "REG_SZ", "/d", manifestPath, "/f"], { encoding: "utf8" });
+ if (r.status !== 0) {
+ throw new Error(`reg add failed (${r.status}): ${r.stderr ?? r.stdout}`);
+ }
+ registry = key;
+ } else {
+ const targetDir = manifestDir ?? nativeMessagingDir(browser);
+ mkdirSync(targetDir, { recursive: true });
+ writeFileSync(join(targetDir, `${HOST_NAME}.json`), JSON.stringify(manifest, null, 2));
+ registry = join(targetDir, `${HOST_NAME}.json`);
+ }
+
+ return { hostPath, via, extensionDir: EXTENSION_DIR, extensionId: extId, registry, browser };
+}
+
+/** Remove the native-host registration (leaves the hub/info file alone). */
+export async function uninstallBridge({ browser = "chrome", stateDir, manifestDir } = {}) {
+ browser = normalizeBrowser(browser);
+ const removed = [];
+ const dir = stateDir ?? bridgeDir();
+ if (process.platform === "win32") {
+ const key = winRegistryKey(browser);
+ const r = spawnSync("reg", ["delete", key, "/f"], { encoding: "utf8" });
+ if (r.status === 0) removed.push(key);
+ if (!otherWindowsRegistrationExists(browser)) {
+ for (const f of ["axuse-nm.bat", "axuse-nm.exe", "axuse-nm-shim.cs", `${HOST_NAME}.json`]) {
+ const p = join(dir, f);
+ try { unlinkSync(p); removed.push(p); } catch {}
+ }
+ }
+ } else {
+ const p = join(manifestDir ?? nativeMessagingDir(browser), `${HOST_NAME}.json`);
+ try { unlinkSync(p); removed.push(p); } catch {}
+ if (!otherPosixRegistrationExists(p)) {
+ try { unlinkSync(join(dir, "axuse-nm")); removed.push(join(dir, "axuse-nm")); } catch {}
+ }
+ }
+ return { removed };
+}
diff --git a/src/bridge/nm-host.js b/src/bridge/nm-host.js
new file mode 100644
index 0000000..15045da
--- /dev/null
+++ b/src/bridge/nm-host.js
@@ -0,0 +1,106 @@
+#!/usr/bin/env node
+/**
+ * axuse bridge — native messaging host.
+ *
+ * Chrome spawns this process when the extension calls connectNative()
+ * (the manifest the installer wrote points here). Native messaging framing
+ * on stdio is [4-byte LE length][UTF-8 JSON]; the hub speaks NDJSON lines.
+ * This process is a dumb, robust relay between the two, plus the
+ * authenticated hello to the hub (the extension never sees the token).
+ *
+ * Spawned via:
+ * - Windows: the batch launcher (axuse-nm.bat) → node nm-host.js
+ * - macOS/Linux: a shebang launcher script (exec node nm-host.js)
+ */
+import net from "node:net";
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { join, dirname } from "node:path";
+import { bridgeDir } from "./hub.js";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+
+function die(msg) {
+ process.stderr.write(`[axuse:nm-host] ${msg}\n`);
+ process.exit(1);
+}
+
+let info;
+try {
+ info = JSON.parse(readFileSync(join(bridgeDir(), "bridge.json"), "utf8"));
+} catch (e) {
+ die(`no bridge info at ${join(bridgeDir(), "bridge.json")} — is the hub running? (axuse mcp starts it automatically; or run: axuse bridge)`);
+}
+if (!info || !info.port || !info.token) die("bridge info is malformed — restart the hub (axuse bridge).");
+
+const sock = net.connect(info.port, "127.0.0.1");
+sock.setNoDelay(true);
+let hubBuf = "";
+
+sock.on("connect", () => {
+ // Authenticated hello first; then pure relay.
+ sock.write(JSON.stringify({ t: "hello", role: "extension-host", token: info.token }) + "\n");
+});
+
+sock.on("data", (d) => {
+ hubBuf += String(d);
+ let i;
+ while ((i = hubBuf.indexOf("\n")) >= 0) {
+ const line = hubBuf.slice(0, i).trim();
+ hubBuf = hubBuf.slice(i + 1);
+ if (!line) continue;
+ if (process.env.AXUSE_BRIDGE_DEBUG) {
+ process.stderr.write(`[axuse:nm-host] hub→ ${line.slice(0, 300)}\n`);
+ }
+ writeNative(line); // hub → extension, framed
+ }
+});
+
+sock.on("close", () => process.exit(0));
+sock.on("error", () => process.exit(0));
+
+// ---- native messaging framing on stdio ----
+
+function writeNative(text) {
+ const payload = Buffer.from(text, "utf8");
+ const head = Buffer.alloc(4);
+ head.writeUInt32LE(payload.length, 0);
+ process.stdout.write(Buffer.concat([head, payload]));
+}
+
+let stdinBuf = Buffer.alloc(0);
+
+process.stdin.on("data", (d) => {
+ stdinBuf = Buffer.concat([stdinBuf, d]);
+ while (stdinBuf.length >= 4) {
+ const len = stdinBuf.readUInt32LE(0);
+ if (stdinBuf.length < 4 + len) break;
+ const payload = stdinBuf.subarray(4, 4 + len).toString("utf8");
+ stdinBuf = stdinBuf.subarray(4 + len);
+ let msg;
+ try {
+ msg = JSON.parse(payload);
+ } catch {
+ if (process.env.AXUSE_BRIDGE_DEBUG) {
+ process.stderr.write(`[axuse:nm-host] stdin JSON parse failed: ${payload.slice(0, 200)}\n`);
+ }
+ continue;
+ }
+ if (process.env.AXUSE_BRIDGE_DEBUG) {
+ process.stderr.write(`[axuse:nm-host] ext→ ${payload.slice(0, 300)}\n`);
+ }
+ // The extension's own hello becomes ext-hello for the hub/backend.
+ if (msg && msg.t === "hello") {
+ msg = { t: "ext-hello", ext: msg.ext, ua: msg.ua };
+ }
+ sock.write(JSON.stringify(msg) + "\n");
+ }
+});
+
+process.stdin.on("end", () => process.exit(0)); // Chrome closed the port (SW died)
+process.stdin.on("error", () => process.exit(0));
+
+// Never let a stray exception kill the relay silently.
+process.on("uncaughtException", (e) => {
+ process.stderr.write(`[axuse:nm-host] ${e && e.stack ? e.stack : e}\n`);
+});
diff --git a/src/cli.js b/src/cli.js
new file mode 100644
index 0000000..4003407
--- /dev/null
+++ b/src/cli.js
@@ -0,0 +1,457 @@
+#!/usr/bin/env node
+/**
+ * axuse — CLI.
+ *
+ * axuse mcp run the MCP server on stdio (default)
+ * axuse print-config emit harness config for: codex | claude-code | opencode | agy | generic
+ * axuse doctor environment + smoke-test check
+ * axuse setup guided native-host + extension setup
+ * axuse open-urls bounded URL inspection report
+ * axuse help
+ */
+import { fileURLToPath } from "node:url";
+import { spawn } from "node:child_process";
+import { writeFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { locateBrowser } from "./core/cdp.js";
+import { Controller } from "./core/controller.js";
+import { runStdio } from "./mcp/server.js";
+import { resolveDesktopDriver } from "./desktop/index.js";
+import { extractUrls, readUrlSource, renderUrlReport } from "./workflows/url-batch.js";
+
+const HERE = fileURLToPath(import.meta.url);
+
+function usage() {
+ console.log(`axuse — accessibility-first browser & computer use for agent harnesses.
+
+Usage:
+ axuse mcp run the MCP server over stdio
+ axuse print-config [--harness NAME] emit config for a harness
+ axuse doctor check the environment + smoke test
+ [--request-tcc] macOS: explicitly open the TCC
+ prompts (Accessibility + Screen
+ Recording) for this binary
+ axuse setup [--browser chrome|edge|chromium|chrome-for-testing]
+ register bridge + open extension setup
+ axuse open-urls <file|url|-> inspect a URL list and write Markdown
+ axuse plugins list loaded solver plugins
+ axuse solve <provider> [--url URL] run a loaded solver (e.g. turnstile)
+ [--headless] [--max-attempts N] [--deadline-ms N]
+ axuse bridge run the bridge hub standalone
+ axuse bridge install [--browser chrome|edge|chromium|chrome-for-testing]
+ register the native host for the extension
+ axuse bridge verify verify the extension is connected
+ axuse bridge uninstall [--browser chrome|edge|chromium|chrome-for-testing]
+ axuse bridge status
+
+Harnesses: codex, claude-code, opencode, agy, generic`);
+}
+
+function commandVector() {
+ return ["node", HERE.replaceAll("\\", "/"), "mcp"];
+}
+
+function printConfig(harness) {
+ const [cmd, ...args] = commandVector();
+ const vec = [...args];
+ const vectJson = JSON.stringify([cmd, ...vec]);
+ switch (harness) {
+ case "codex":
+ console.log(`# Codex — append to ~/.codex/config.toml
+[mcp_servers.axuse]
+command = "${cmd}"
+args = ${JSON.stringify(vec)}`);
+ break;
+ case "claude-code":
+ console.log(`# Claude Code — run once (user scope):
+claude mcp add --scope user axuse -- ${cmd} ${vec.join(" ")}
+
+# or add to a project's .mcp.json:
+${JSON.stringify({ mcpServers: { axuse: { type: "stdio", command: cmd, args: vec } } }, null, 2)}`);
+ break;
+ case "opencode":
+ console.log(`# OpenCode — merge into opencode.json
+${JSON.stringify({ mcp: { axuse: { type: "local", command: [cmd, ...vec] } } }, null, 2)}`);
+ break;
+ case "agy":
+ console.log(`# Antigravity — register this as an MCP server in the agent's MCP settings
+# (standard mcpServers block; the CLI also accepts it for any MCP-capable host):
+${JSON.stringify({ mcpServers: { axuse: { type: "stdio", command: cmd, args: vec } } }, null, 2)}`);
+ break;
+ default:
+ console.log(`# Generic mcpServers block (any MCP host):
+${JSON.stringify({ mcpServers: { axuse: { type: "stdio", command: cmd, args: vec } } }, null, 2)}`);
+ }
+ console.log(`\nCommand vector: ${vectJson}`);
+}
+
+function hasFlag(name) {
+ return rest.includes(name);
+}
+
+function numberArg(name) {
+ const value = arg(name);
+ if (value === undefined) return undefined;
+ const n = Number(value);
+ if (!Number.isFinite(n)) throw new Error(`${name} must be a number`);
+ return n;
+}
+
+function positionalArgs() {
+ const valueFlags = new Set(["--browser", "--harness", "--backend", "--output", "--settle-ms", "--excerpt-chars", "--timeout-ms"]);
+ const out = [];
+ for (let i = 0; i < rest.length; i++) {
+ const token = rest[i];
+ if (valueFlags.has(token)) { i++; continue; }
+ if (token !== "-" && token.startsWith("-")) continue;
+ out.push(token);
+ }
+ return out;
+}
+
+/** macOS product version via sw_vers (evidence line for doctor); "unknown"
+ * when sw_vers is unavailable (rare embedded setups). */
+async function macOsVersion() {
+ const { execFile } = await import("node:child_process");
+ return new Promise((resolve) => {
+ execFile("sw_vers", ["-productVersion"], { timeout: 5000 }, (err, stdout) => {
+ resolve(err ? "unknown" : String(stdout).trim());
+ });
+ });
+}
+
+/** `security` presence (the Keychain CLI plugins use for secret fallback). */
+async function keychainAvailable() {
+ const { execFile } = await import("node:child_process");
+ return new Promise((resolve) => {
+ execFile("security", ["help"], { timeout: 5000 }, (err) => resolve(!err));
+ });
+}
+
+function openExtensionsPage(browser, browserPath) { const url = "chrome://extensions";
+ const launch = (command, args, label) => {
+ const child = spawn(command, args, { detached: true, stdio: "ignore" });
+ child.once("error", (e) => process.stderr.write(`[axuse] could not open ${label}: ${e.message}\n`));
+ child.unref();
+ return label;
+ };
+ if (process.platform === "darwin") {
+ if (browserPath) return launch(browserPath, [url], browserPath);
+ const apps = {
+ edge: "Microsoft Edge",
+ "edge-beta": "Microsoft Edge Beta",
+ chromium: "Chromium",
+ "chrome-for-testing": "Google Chrome for Testing",
+ "chrome-beta": "Google Chrome Beta",
+ "chrome-canary": "Google Chrome Canary",
+ };
+ const app = apps[browser] ?? "Google Chrome";
+ return launch("open", ["-a", app, url], app);
+ }
+ const command = browserPath ?? (process.platform === "win32" ? "chrome.exe" : "google-chrome");
+ return launch(command, [url], browserPath ?? "browser");
+}
+
+async function setupCmd() {
+ const browser = arg("--browser") ?? "chrome";
+ if (!["chrome", "edge", "edge-beta", "chromium", "chrome-for-testing", "chrome-beta", "chrome-canary"].includes(browser)) {
+ throw new Error("--browser must be chrome, edge, edge-beta, chromium, chrome-for-testing, chrome-beta, or chrome-canary");
+ }
+ const { installBridge } = await import("./bridge/install.js");
+ const browserPath = locateBrowser({ browser, exact: true });
+ const inst = await installBridge({ browser });
+
+ console.log(`✓ axuse bridge registered for ${browser}`);
+ console.log(` native host: ${inst.hostPath}`);
+ console.log(` extension id: ${inst.extensionId}`);
+ console.log("\nFinish setup in Chrome:");
+ console.log(" 1. Turn on Developer mode.");
+ console.log(" 2. Click Load unpacked.");
+ console.log(` 3. Select: ${inst.extensionDir}`);
+ console.log("\nThen verify the connection:");
+ console.log(" axuse bridge verify");
+
+ if (!hasFlag("--no-open")) {
+ try {
+ const opened = openExtensionsPage(browser, browserPath);
+ console.log(`\nOpened ${opened} at chrome://extensions. Use --no-open to skip this next time.`);
+ } catch (e) {
+ console.log(`\nCould not open the extensions page automatically: ${e.message}`);
+ }
+ }
+
+ const harness = arg("--harness");
+ if (harness) {
+ console.log(`\nMCP configuration for ${harness}:`);
+ printConfig(harness);
+ }
+}
+
+async function openUrlsCmd() {
+ const source = positionalArgs()[0];
+ if (!source) throw new Error("open-urls requires a URL, a text/Markdown file, or - for stdin");
+ const urls = extractUrls(readUrlSource(source));
+ if (!urls.length) throw new Error(`No http(s) URLs found in ${source}`);
+ if (urls.length > 100) throw new Error(`At most 100 URLs can be opened per batch (found ${urls.length})`);
+ const backend = arg("--backend") ?? "cdp";
+ if (!["cdp", "extension"].includes(backend)) throw new Error("--backend must be cdp or extension");
+ const output = arg("--output") ?? "axuse-url-report.md";
+ const controller = new Controller();
+ let batch;
+ try {
+ batch = await controller.execute("open_many", {
+ urls,
+ backend,
+ headless: hasFlag("--headless") ? true : undefined,
+ settle_ms: numberArg("--settle-ms"),
+ excerpt_chars: numberArg("--excerpt-chars"),
+ close_after: true,
+ });
+ } finally {
+ await controller.dispose();
+ }
+ writeFileSync(output, renderUrlReport({ results: batch.results, backend, source }) + "\n");
+ console.log(`Wrote ${batch.opened}/${batch.count} opened URL results to ${resolve(output)}`);
+ if (batch.failed) console.log(`${batch.failed} URL${batch.failed === 1 ? "" : "s"} failed; see the report for details.`);
+}
+
+async function pluginsCmd() {
+ const { loadSolvers, pluginDirs } = await import("./plugins/index.js");
+ const { solvers, errors } = await loadSolvers();
+ const dirs = pluginDirs();
+ console.log(`search: ${dirs.join(" ; ")}`);
+ if (!solvers.length && !errors.length) {
+ console.log("solvers: none loaded (open core ships none — plugins are separate packages)");
+ console.log(" install: drop a solver package into plugins/ or list dirs in AXUSE_PLUGINS");
+ return;
+ }
+ for (const s of solvers) {
+ console.log(`✓ ${s.id}@${s.version} — providers: ${s.providers.join(", ")}${s.tools?.length ? ` · tools: ${s.tools.map((t) => t.name).join(", ")}` : ""} (${s.dir})`);
+ }
+ for (const e of errors) {
+ console.error(`✗ ${e.plugin}: [${e.code}] ${e.message}`);
+ }
+ if (errors.length) process.exitCode = 1;
+}
+
+async function solveCmd() {
+ const provider = positionalArgs()[0];
+ if (!provider) throw new Error("solve requires a provider, e.g. axuse solve turnstile --url <page>");
+ const { loadSolvers, buildSolveContext, solveWith } = await import("./plugins/index.js");
+ const { solvers } = await loadSolvers();
+ const controller = new Controller();
+ let result;
+ try {
+ if (arg("--url")) {
+ await controller.execute("open", {
+ url: arg("--url"),
+ ...(hasFlag("--headless") ? { headless: true } : {}),
+ settle_ms: 4000,
+ });
+ }
+ const opts = {};
+ if (numberArg("--max-attempts")) opts.maxAttempts = numberArg("--max-attempts");
+ if (numberArg("--deadline-ms")) opts.deadlineMs = numberArg("--deadline-ms");
+ const ctx = buildSolveContext(controller);
+ result = await solveWith(solvers, provider, ctx, opts);
+ } finally {
+ await Promise.race([controller.dispose(), new Promise((ok) => setTimeout(ok, 5000))]);
+ }
+ console.log(JSON.stringify(result, null, 2));
+ if (!result?.solved) process.exitCode = 2;
+}
+
+async function verifyBridge() {
+ const { getBridge } = await import("./bridge/hub.js");
+ let bridge;
+ try {
+ bridge = await getBridge();
+ await bridge.waitExt(numberArg("--timeout-ms") ?? 5000);
+ const tabs = await bridge.rpc("list_tabs", {});
+ if (!tabs.ok) throw new Error(String(tabs.error ?? "the extension rejected list_tabs"));
+ console.log(`✓ axuse bridge connected (${tabs.result?.tabs?.length ?? 0} browser tabs visible).`);
+ } catch (e) {
+ console.error("✗ axuse bridge is not connected.");
+ console.error(` ${e.message}`);
+ console.error(" Run `axuse setup`, load the unpacked extension, then try again.");
+ process.exitCode = 1;
+ } finally {
+ if (bridge?.stop) bridge.stop();
+ else if (bridge?.close) bridge.close();
+ }
+}
+
+async function doctor() {
+ const out = (s) => console.log(s);
+ const requestTcc = process.argv.includes("--request-tcc");
+ out(`node: ${process.version} ${process.platform}`);
+ if (process.platform === "darwin") {
+ out(`macos: ${await macOsVersion()} (${process.arch})`);
+ out(`keychain: ${await keychainAvailable() ? "available (plugins can read secrets via service 'axuse')" : "unavailable (passphrases/keys must come from env vars)"}`);
+ }
+ const hasWs = typeof WebSocket !== "undefined";
+ out(`native WebSocket: ${hasWs ? "yes" : "NO — need Node >= 22"}`);
+ const browser = locateBrowser();
+ out(`browser: ${browser ?? "not found (set AXUSE_BROWSER)"}`);
+ if (process.platform === "win32" || process.platform === "darwin") {
+ if (process.platform === "darwin" && !/^(1|true)$/i.test(process.env.AXUSE_ENABLE_MACOS_CUA ?? "")) {
+ out("desktop driver: disabled (set AXUSE_ENABLE_MACOS_CUA=1; Accessibility + Screen Recording grants are required for OS control)");
+ } else {
+ try {
+ const d = await resolveDesktopDriver();
+ if (requestTcc && process.platform === "darwin" && typeof d.requestPermissions === "function") {
+ // The ONLY path that may open a TCC prompt — explicit user request.
+ const r = await d.requestPermissions();
+ out(`desktop tcc request: prompts opened (accessibility now: ${r.accessibility ? "granted" : "not granted yet"}; screen-recording prompt: ${r.screen_recording_prompt_opened ? "shown" : "not shown"})`);
+ out(` ${r.note}`);
+ }
+ const info = await d.screenInfo();
+ const units = process.platform === "darwin" ? "macOS display points" : "physical px";
+ out(`desktop driver: ok — active screen layout ${info.w}x${info.h} at (${info.x},${info.y}) (${units})`);
+ if (process.platform === "darwin" && typeof d.permissions === "function") {
+ const p = await d.permissions();
+ out(`desktop permissions: Accessibility ${p.accessibility ? "granted" : "not detected"}; Screen Recording ${p.screen_recording === null ? "check on first screenshot" : p.screen_recording ? "granted" : "not detected"}`);
+ try {
+ await d.probe();
+ out("desktop native events: CoreGraphics construction ok (no events posted)");
+ } catch (e) {
+ out(`desktop native events: unavailable — ${e.message}`);
+ }
+ if (p.screen_recording === false) {
+ out("desktop screenshot: skipped — Screen Recording permission not detected");
+ } else {
+ try {
+ await d.screenshot({ x: info.x, y: info.y, w: 1, h: 1, budgetBytes: 20_000 });
+ out("desktop screenshot: ok");
+ } catch (e) {
+ out(`desktop screenshot: unavailable — ${e.message}`);
+ }
+ }
+ }
+ d.dispose();
+ } catch (e) {
+ out(`desktop driver: FAILED — ${e.message}`);
+ }
+ }
+ } else {
+ out("desktop driver: not implemented on this platform (browser tools still work)");
+ }
+ try {
+ const { readInfo } = await import("./bridge/hub.js");
+ const info = readInfo();
+ if (info && info.port) {
+ out(`bridge hub: info present → 127.0.0.1:${info.port} (pid ${info.pid}${(() => { try { process.kill(info.pid, 0); return ", alive"; } catch { return ", stale"; } })()})`);
+ } else {
+ out("bridge hub: not started (run `axuse setup` for daily Chrome, or use ax_open {backend:\"extension\"} after loading the bridge)");
+ }
+ } catch (e) {
+ out(`bridge hub: ${e.message}`);
+ }
+ if (browser && hasWs) {
+ out("smoke test: launching headless browser, opening a page, observing…");
+ try {
+ const { Controller } = await import("./core/controller.js");
+ const c = new Controller();
+ const html = `data:text/html,<button id="b" onclick="this.textContent='clicked'">go</button><input id="i" value="">`;
+ const r = await c.execute("open", { url: html, headless: true, settle_ms: 100 });
+ const obs = r.observation;
+ const click = await c.execute("click", { target: { ref: "e1" }, settle_ms: 100 });
+ const ok = /clicked|changed/.test(click.observation?.text ?? "");
+ out(`smoke test: ${ok ? "OK — observed tree, clicked ref e1, saw the diff" : "partial — observe worked, verify diff below"}`);
+ out((click.observation?.text ?? obs.text).split("\n").slice(0, 8).map((l) => ` | ${l}`).join("\n"));
+ await c.execute("close", { browser: true });
+ } catch (e) {
+ out(`smoke test: FAILED — ${e.message}`);
+ }
+ }
+}
+
+const [command = "mcp", ...rest] = process.argv.slice(2);
+const arg = (name) => {
+ const i = rest.indexOf(name);
+ return i >= 0 ? rest[i + 1] : undefined;
+};
+
+async function bridgeCmd(sub) {
+ const { readInfo } = await import("./bridge/hub.js");
+ if (!sub) {
+ const { runStandaloneHub } = await import("./bridge/hub.js");
+ await runStandaloneHub();
+ return;
+ }
+ if (sub === "install") {
+ const { installBridge } = await import("./bridge/install.js");
+ const browser = arg("--browser") ?? "chrome";
+ const r = await installBridge({ browser });
+ console.log(`native host: ${r.hostPath} (${r.via})`);
+ console.log(`registered: ${r.registry}`);
+ console.log(`extension id: ${r.extensionId} (allowed_extensions is pinned to it)`);
+ console.log(`\nLoad the extension UNPACKED in ${browser} → chrome://extensions → Developer mode → Load unpacked:`);
+ console.log(` ${r.extensionDir}`);
+ console.log(`\nThe service worker connects automatically whenever Chrome runs. Start the hub with:`);
+ console.log(` axuse bridge (or just use ax_open {backend:"extension"} — the hub starts on demand)`);
+ return;
+ }
+ if (sub === "uninstall") {
+ const { uninstallBridge } = await import("./bridge/install.js");
+ const browser = arg("--browser") ?? "chrome";
+ const r = await uninstallBridge({ browser });
+ console.log(r.removed.length ? `removed:\n ${r.removed.join("\n ")}` : "nothing to remove");
+ return;
+ }
+ if (sub === "status") {
+ const info = readInfo();
+ if (!info || !info.port) {
+ console.log("hub: not running (it starts on demand with the MCP server, or: axuse bridge)");
+ } else {
+ let alive = false;
+ try { process.kill(info.pid, 0); alive = true; } catch {}
+ console.log(`hub: ${alive ? `running (pid ${info.pid})` : `stale info (pid ${info.pid})`} → 127.0.0.1:${info.port}`);
+ }
+ return;
+ }
+ if (sub === "verify") {
+ await verifyBridge();
+ return;
+ }
+ console.log("usage: axuse bridge [install|uninstall|status|verify] [--browser chrome|edge|chromium|chrome-for-testing]");
+}
+
+try {
+ switch (command) {
+ case "mcp":
+ await runStdio();
+ break;
+ case "setup":
+ await setupCmd();
+ break;
+ case "open-urls":
+ await openUrlsCmd();
+ break;
+ case "bridge":
+ await bridgeCmd(rest[0]);
+ break;
+ case "plugins":
+ await pluginsCmd();
+ break;
+ case "solve":
+ await solveCmd();
+ break;
+ case "print-config": {
+ const harness = arg("--harness") ?? arg("-h");
+ printConfig(harness ?? "generic");
+ break;
+ }
+ case "doctor":
+ await doctor();
+ break;
+ case "help":
+ case "--help":
+ case "-h":
+ default:
+ usage();
+ }
+} catch (e) {
+ console.error(`axuse: ${e.message ?? e}`);
+ process.exitCode = 1;
+}
diff --git a/src/core/actuate.js b/src/core/actuate.js
new file mode 100644
index 0000000..ff2215e
--- /dev/null
+++ b/src/core/actuate.js
@@ -0,0 +1,388 @@
+/**
+ * axuse — actuator: trusted input synthesis + live ref resolution over CDP.
+ *
+ * Lineage: Codex acts through chrome.debugger → Input.dispatch* (isTrusted
+ * events — many sites reject synthetic DOM events) and resolves element
+ * targets live at action time instead of trusting remembered coordinates.
+ * ZCode contributes the error vocabulary (ELEMENT_HIDDEN, STALE_STATE,
+ * actionSent) and the rule "coordinates are the last resort".
+ */
+
+import { AxError, Codes } from "./errors.js";
+
+/** CDP modifier bitmasks. */
+export const MOD = { alt: 1, ctrl: 2, control: 2, meta: 4, cmd: 4, command: 4, shift: 8 };
+
+/** macOS virtual key codes used by Chromium's native event builder. */
+const MAC_NATIVE_KEY_CODES = Object.freeze({
+ Enter: 36, Tab: 48, Escape: 53, Backspace: 51, Delete: 117, Space: 49,
+ ArrowUp: 126, ArrowDown: 125, ArrowLeft: 123, ArrowRight: 124,
+ Home: 115, End: 119, PageUp: 116, PageDown: 121, Insert: 114, Help: 114,
+ F1: 122, F2: 120, F3: 99, F4: 118, F5: 96, F6: 97,
+ F7: 98, F8: 100, F9: 101, F10: 109, F11: 103, F12: 111,
+ // Function row beyond F12 (HIToolbox Events.h).
+ F13: 105, F14: 107, F15: 113, F16: 106, F17: 64, F18: 79, F19: 80, F20: 90,
+ ControlLeft: 59, ShiftLeft: 56, AltLeft: 58, MetaLeft: 55,
+ CapsLock: 57, ContextMenu: 110, Fn: 63,
+ KeyA: 0, KeyB: 11, KeyC: 8, KeyD: 2, KeyE: 14, KeyF: 3, KeyG: 5,
+ KeyH: 4, KeyI: 34, KeyJ: 38, KeyK: 40, KeyL: 37, KeyM: 46, KeyN: 45,
+ KeyO: 31, KeyP: 35, KeyQ: 12, KeyR: 15, KeyS: 1, KeyT: 17, KeyU: 32,
+ KeyV: 9, KeyW: 13, KeyX: 7, KeyY: 16, KeyZ: 6,
+ Digit0: 29, Digit1: 18, Digit2: 19, Digit3: 20, Digit4: 21,
+ Digit5: 23, Digit6: 22, Digit7: 26, Digit8: 28, Digit9: 25,
+ // Punctuation row (US layout physical codes — layout-independent).
+ Backquote: 50, Minus: 27, Equal: 24, BracketLeft: 33, BracketRight: 30,
+ Backslash: 42, Semicolon: 41, Quote: 39, Comma: 43, Period: 47, Slash: 44,
+ // Numeric keypad.
+ Numpad0: 82, Numpad1: 83, Numpad2: 84, Numpad3: 85, Numpad4: 86,
+ Numpad5: 87, Numpad6: 88, Numpad7: 89, Numpad8: 91, Numpad9: 92,
+ NumpadEnter: 76, NumpadAdd: 69, NumpadSubtract: 78, NumpadMultiply: 67,
+ NumpadDivide: 75, NumpadDecimal: 65, NumpadEqual: 81, NumLock: 71,
+});
+
+/** Keyboard descriptors: name → {vk, key, code, text}. */
+export const KEYS = {
+ enter: { vk: 13, key: "Enter", code: "Enter", text: "\r" },
+ tab: { vk: 9, key: "Tab", code: "Tab" },
+ escape: { vk: 27, key: "Escape", code: "Escape" },
+ esc: { vk: 27, key: "Escape", code: "Escape" },
+ backspace: { vk: 8, key: "Backspace", code: "Backspace" },
+ delete: { vk: 46, key: "Delete", code: "Delete" },
+ del: { vk: 46, key: "Delete", code: "Delete" },
+ up: { vk: 38, key: "ArrowUp", code: "ArrowUp" },
+ down: { vk: 40, key: "ArrowDown", code: "ArrowDown" },
+ left: { vk: 37, key: "ArrowLeft", code: "ArrowLeft" },
+ right: { vk: 39, key: "ArrowRight", code: "ArrowRight" },
+ home: { vk: 36, key: "Home", code: "Home" },
+ end: { vk: 35, key: "End", code: "End" },
+ pageup: { vk: 33, key: "PageUp", code: "PageUp" },
+ pagedown: { vk: 34, key: "PageDown", code: "PageDown" },
+ space: { vk: 32, key: " ", code: "Space", text: " " },
+ ctrl: { vk: 0x11, key: "Control", code: "ControlLeft" },
+ control: { vk: 0x11, key: "Control", code: "ControlLeft" },
+ shift: { vk: 0x10, key: "Shift", code: "ShiftLeft" },
+ alt: { vk: 0x12, key: "Alt", code: "AltLeft" },
+ meta: { vk: 0x5b, key: "Meta", code: "MetaLeft" },
+ cmd: { vk: 0x5b, key: "Meta", code: "MetaLeft" },
+ command: { vk: 0x5b, key: "Meta", code: "MetaLeft" },
+};
+for (let i = 1; i <= 12; i++) {
+ KEYS["f" + i] = { vk: 0x70 + (i - 1), key: "F" + i, code: "F" + i };
+}
+for (let i = 0; i < 26; i++) {
+ const ch = String.fromCharCode(97 + i);
+ KEYS[ch] = {
+ vk: 65 + i,
+ key: ch.toUpperCase(),
+ code: "Key" + ch.toUpperCase(),
+ text: ch,
+ };
+}
+for (let i = 0; i < 10; i++) {
+ KEYS[String(i)] = { vk: 48 + i, key: String(i), code: "Digit" + i, text: String(i) };
+}
+
+/** Parse a combo like "ctrl+shift+p" → {mods: ["ctrl","shift"], main: {…}} */
+export function parseCombo(combo) {
+ const parts = String(combo).toLowerCase().split("+").map((s) => s.trim()).filter(Boolean);
+ const mods = [];
+ let main = null;
+ for (const p of parts) {
+ if (MOD[p]) mods.push(p);
+ else if (main) throw new AxError(Codes.COMMAND_REJECTED, `Combo has two non-modifier keys: "${combo}"`);
+ else main = KEYS[p];
+ }
+ if (!main) throw new AxError(Codes.COMMAND_REJECTED, `Unknown key in combo "${combo}"`);
+ return { mods, main };
+}
+
+/** @param {{conn: import("./cdp.js").CdpConnection, sessionId: string}} ctx */
+function keyEvent(ctx, type, k, modifiers, withText, command) {
+ const params = {
+ type,
+ key: k.key,
+ code: k.code,
+ windowsVirtualKeyCode: k.vk,
+ // Chromium's Mac input path expects a native macOS key code when it is
+ // provided; Windows VK values are not Mac key codes.
+ nativeVirtualKeyCode: process.platform === "darwin" ? (MAC_NATIVE_KEY_CODES[k.code] ?? 0) : k.vk,
+ modifiers,
+ };
+ if (withText && k.text) params.text = k.text;
+ if (command) params.commands = [command];
+ return ctx.conn.send("Input.dispatchKeyEvent", params, ctx.sessionId);
+}
+
+function macEditingCommand(main, mask) {
+ if (process.platform !== "darwin" || !(mask & MOD.meta)) return null;
+ if (main.code === "KeyA") return "selectAll";
+ if (main.code === "KeyC") return "copy";
+ if (main.code === "KeyX") return "cut";
+ if (main.code === "KeyV") return "paste";
+ if (main.code === "KeyZ") return mask & MOD.shift ? "redo" : "undo";
+ return null;
+}
+
+/** Press a key combo. Text is sent for single printable keys only. */
+export async function pressCombo(ctx, combo) {
+ const { mods, main } = parseCombo(combo);
+ const mask = mods.reduce((m, x) => m | MOD[x], 0);
+ for (const m of mods) await keyEvent(ctx, "keyDown", KEYS[m], mask, false);
+ const command = macEditingCommand(main, mask);
+ await keyEvent(ctx, "keyDown", main, mask, mods.length === 0, command);
+ await keyEvent(ctx, "keyUp", main, mask, false);
+ for (let i = mods.length - 1; i >= 0; i--) await keyEvent(ctx, "keyUp", KEYS[mods[i]], mask, false);
+}
+
+const BUTTON_MAP = { left: "left", middle: "middle", right: "right", 1: "left", 2: "middle", 3: "right" };
+
+/** Dispatch a trusted click (hover-move → press → release). */
+export async function click(ctx, { x, y, button = "left", count = 1, modifiers = 0 }) {
+ const b = BUTTON_MAP[button];
+ if (!b) throw new AxError(Codes.COMMAND_REJECTED, `button must be left|middle|right, got "${button}"`);
+ await ctx.conn.send("Input.dispatchMouseEvent", { type: "mouseMoved", x, y, button: "none", modifiers }, ctx.sessionId);
+ const base = { x, y, button: b, clickCount: count, modifiers };
+ await ctx.conn.send("Input.dispatchMouseEvent", { type: "mousePressed", ...base }, ctx.sessionId);
+ await ctx.conn.send("Input.dispatchMouseEvent", { type: "mouseReleased", ...base }, ctx.sessionId);
+}
+
+export async function hover(ctx, { x, y }) {
+ await ctx.conn.send("Input.dispatchMouseEvent", { type: "mouseMoved", x, y, button: "none", modifiers: 0 }, ctx.sessionId);
+}
+
+export async function drag(ctx, from, to, steps = 12) {
+ await hover(ctx, from);
+ await ctx.conn.send("Input.dispatchMouseEvent", { type: "mousePressed", ...from, button: "left", clickCount: 1, modifiers: 0 }, ctx.sessionId);
+ for (let i = 1; i <= steps; i++) {
+ const x = from.x + ((to.x - from.x) * i) / steps;
+ const y = from.y + ((to.y - from.y) * i) / steps;
+ await ctx.conn.send("Input.dispatchMouseEvent", { type: "mouseMoved", x, y, button: "left", modifiers: 0 }, ctx.sessionId);
+ }
+ await ctx.conn.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: to.x, y: to.y, button: "left", clickCount: 1, modifiers: 0 }, ctx.sessionId);
+}
+
+export async function wheel(ctx, { x, y, dx = 0, dy = 0 }) {
+ await ctx.conn.send("Input.dispatchMouseEvent", { type: "mouseWheel", x, y, button: "none", deltaX: dx, deltaY: dy, modifiers: 0 }, ctx.sessionId);
+}
+
+/** Trusted bulk text entry (one CDP call, produces native input events). */
+export async function insertText(ctx, text) {
+ await ctx.conn.send("Input.insertText", { text: String(text) }, ctx.sessionId);
+}
+
+/** Select-all combo is platform-dependent (macOS uses Meta+A). */
+export function selectAllCombo() {
+ return process.platform === "darwin" ? "meta+a" : "ctrl+a";
+}
+
+/**
+ * Translate a Windows-convention application shortcut to this platform's
+ * convention. On macOS, application shortcuts (bold, heading, caret-to-end…)
+ * are Cmd-based: a literal Control+Alt+1 dispatch never reaches the app's
+ * accelerator table. Web apps that hard-code ctrlKey handlers still work —
+ * callers only opt into translation for platform-convention shortcuts.
+ */
+export function platformShortcut(combo) {
+ if (process.platform !== "darwin") return String(combo);
+ return String(combo)
+ .split("+")
+ .map((part) => (part.trim().toLowerCase() === "ctrl" || part.trim().toLowerCase() === "control" ? "meta" : part))
+ .join("+");
+}
+
+/**
+ * Expression that resolves a ref to fresh coordinates at action time.
+ * This is the Codex move: the layout may have moved since the observation;
+ * scrolling happens here; covered/overlay state is reported, not guessed.
+ *
+ * Elements inside same-origin iframes live in the parent ref map (the walk
+ * crosses contentDocument), but their rects are relative to the child
+ * frame's viewport — coordinates are translated up through each hosting
+ * iframe (+ borders) until they are main-viewport coordinates.
+ */
+export function refResolveExpression(ref) {
+ return `(async function(){
+ try {
+ var el = (window.__axuseRefs || {})${indexExpr(ref)};
+ if (!el) return { error: "no_ref" };
+ if (!el.isConnected) return { error: "no_ref" };
+ if (el.scrollIntoViewIfNeeded) el.scrollIntoViewIfNeeded(true);
+ else el.scrollIntoView({ block: "center" });
+ // Wait until the box is stable across animation frames: smooth/wheel
+ // scroll animations and late layout shifts otherwise move the target
+ // between measuring and clicking (the click lands on a neighbour).
+ var raf = function(){ return new Promise(function(ok){ var t = setTimeout(ok, 50); requestAnimationFrame(function(){ clearTimeout(t); ok(); }); }); };
+ var prev = el.getBoundingClientRect();
+ for (var k = 0; k < 20; k++) {
+ await raf();
+ var cur = el.getBoundingClientRect();
+ if (Math.abs(cur.top - prev.top) < 0.5 && Math.abs(cur.left - prev.left) < 0.5) break;
+ prev = cur;
+ }
+ var r = el.getBoundingClientRect();
+ if (r.width < 1 || r.height < 1) return { error: "hidden" };
+ var cx = r.left + r.width / 2, cy = r.top + r.height / 2;
+ // Translate out of same-origin frame nesting: each host iframe's box
+ // offsets the child viewport inside the parent viewport.
+ var w = el.ownerDocument.defaultView;
+ var hops = 0;
+ while (w !== window && hops < 10) {
+ hops++;
+ var hosts = w.parent.document.querySelectorAll("iframe");
+ var host = null;
+ for (var i = 0; i < hosts.length; i++) {
+ if (hosts[i].contentWindow === w) { host = hosts[i]; break; }
+ }
+ if (!host) return { error: "frame_host_not_found" };
+ var hr = host.getBoundingClientRect();
+ var hcs = window.getComputedStyle(host);
+ cx += hr.left + (parseFloat(hcs.borderLeftWidth) || 0);
+ cy += hr.top + (parseFloat(hcs.borderTopWidth) || 0);
+ w = w.parent;
+ }
+ var hit = document.elementFromPoint(cx, cy);
+ var covered = !(hit === el || (hit && el.contains(hit)));
+ return { ok: true, x: cx, y: cy, w: r.width, h: r.height, covered: covered,
+ hitTag: hit ? hit.tagName.toLowerCase() : null };
+ } catch (e) { return { error: String(e) }; }
+ })()`;
+}
+
+/** Set a <select> value + dispatch input/change (synthetic, React-safe). */
+export function selectOptionExpression(ref, value) {
+ return `(function(){
+ try {
+ var el = (window.__axuseRefs || {})${indexExpr(ref)};
+ if (!el || el.tagName !== "SELECT") return { error: "no_ref" };
+ var want = ${JSON.stringify(String(value))};
+ var found = null;
+ for (var i = 0; i < el.options.length; i++) {
+ var o = el.options[i];
+ if (o.value === want || o.text === want) { found = o; break; }
+ }
+ if (!found) return { error: "no_option", options: Array.prototype.map.call(el.options, function(o){ return o.value || o.text; }) };
+ el.value = found.value;
+ el.dispatchEvent(new Event("input", { bubbles: true }));
+ el.dispatchEvent(new Event("change", { bubbles: true }));
+ return { ok: true, value: el.value };
+ } catch (e) { return { error: String(e) }; }
+ })()`;
+}
+
+/** Describe a ref'd element for form filling: control kind + boolean state. */
+export function fieldKindExpression(ref) {
+ return `(function(){
+ try {
+ var el = (window.__axuseRefs || {})${indexExpr(ref)};
+ if (!el || !el.isConnected) return { error: "no_ref" };
+ var tag = el.tagName, type = (el.getAttribute("type") || "").toLowerCase(), role = el.getAttribute("role") || "";
+ if (tag === "SELECT") return { kind: "select" };
+ if (tag === "INPUT" && (type === "checkbox" || type === "radio")) return { kind: "bool", on: !!el.checked };
+ if (role === "switch" || role === "checkbox" || role === "radio" || role === "menuitemcheckbox") return { kind: "bool", on: el.getAttribute("aria-checked") === "true" };
+ if ((role === "combobox" && (tag === "INPUT" || tag === "TEXTAREA")) || el.getAttribute("aria-autocomplete") === "list" || (tag === "INPUT" && el.getAttribute("list"))) return { kind: "combo" };
+ if (role === "combobox" || el.getAttribute("aria-haspopup") === "listbox") return { kind: "popup" };
+ if (role === "slider" || (tag === "INPUT" && type === "range")) {
+ var num = function (v, dflt) { var n = parseFloat(v); return isFinite(n) ? n : dflt; };
+ var native = tag === "INPUT" && type === "range";
+ return {
+ kind: "slider",
+ min: native ? num(el.min, 0) : num(el.getAttribute("aria-valuemin"), 0),
+ max: native ? num(el.max, 100) : num(el.getAttribute("aria-valuemax"), 100),
+ now: native ? num(el.value, null) : num(el.getAttribute("aria-valuenow"), null),
+ step: native ? (num(el.step, 1) || 1) : null,
+ };
+ }
+ if (tag === "INPUT" || tag === "TEXTAREA" || el.isContentEditable) return { kind: "text" };
+ return { kind: "other", tag: tag, role: role || null };
+ } catch (e) { return { error: String(e) }; }
+ })()`;
+}
+
+/** Read the live value of a ref'd slider — aria-valuenow for ARIA widgets
+ * (noUiSlider, ionRangeSlider, MUI…), .value for native range inputs. */
+export function sliderValueExpression(ref) {
+ return `(function(){
+ try {
+ var el = (window.__axuseRefs || {})${indexExpr(ref)};
+ if (!el || !el.isConnected) return { error: "no_ref" };
+ var tag = el.tagName, type = (el.getAttribute("type") || "").toLowerCase();
+ var v = tag === "INPUT" && type === "range" ? el.value : el.getAttribute("aria-valuenow");
+ var n = parseFloat(v);
+ return isFinite(n) ? { now: n } : { error: "no_value" };
+ } catch (e) { return { error: String(e) }; }
+ })()`;
+}
+
+/** Find a visible option whose text matches (exact, then case-insensitive),
+ * bind it to a ref, return the ref. Searches shadow roots too. */
+export function findOptionExpression(value) {
+ return `(function(){
+ var want = ${JSON.stringify(String(value))}.trim(), lw = want.toLowerCase();
+ var all = [];
+ (function walk(root){
+ var els = root.querySelectorAll('[role=option],[role=menuitem],[role=menuitemradio],[role=treeitem],li');
+ for (var i = 0; i < els.length; i++) all.push(els[i]);
+ var hosts = root.querySelectorAll('*');
+ for (var j = 0; j < hosts.length; j++) if (hosts[j].shadowRoot) walk(hosts[j].shadowRoot);
+ })(document);
+ var vis = all.filter(function(e){ var r = e.getBoundingClientRect(); return r.width > 0 && r.height > 0; });
+ var t = function(e){ return (e.innerText || e.textContent || "").replace(/\\s+/g, " ").trim(); };
+ var hit = vis.find(function(e){ return t(e) === want; }) || vis.find(function(e){ return t(e).toLowerCase() === lw; });
+ if (!hit) return { error: "no_option", visible: vis.slice(0, 15).map(t) };
+ var refs = window.__axuseRefs || (window.__axuseRefs = {});
+ var reg = window.__axuseRefRegistry;
+ var ref = reg && reg.get(hit);
+ if (!ref) { window.__axuseRefSeq = (window.__axuseRefSeq || 0) + 1; ref = "e" + window.__axuseRefSeq; if (reg) reg.set(hit, ref); }
+ refs[ref] = hit;
+ return { ok: true, ref: ref, text: t(hit) };
+ })()`;
+}
+
+/** Hit-test an (x,y) and walk up to the nearest ref'd element (vision↔structure bridge). */
+export function elementInfoExpression(x, y) {
+ return `(function(){
+ try {
+ var el = document.elementFromPoint(${x}, ${y});
+ if (!el) return { ok: false, reason: "nothing at point" };
+ var ref = null;
+ var m = window.__axuseRefs || {};
+ for (var k in m) { var n = m[k]; if (n === el || n.contains(el)) { ref = k; el = n; break; } }
+ var r = el.getBoundingClientRect();
+ return { ok: true, ref: ref, tag: el.tagName.toLowerCase(),
+ role: el.getAttribute("role") || "",
+ name: (el.getAttribute("aria-label") || el.innerText || el.value || "").trim().slice(0, 120),
+ rect: { x: r.left, y: r.top, w: r.width, h: r.height },
+ actionable: !!ref };
+ } catch (e) { return { error: String(e) }; }
+ })()`;
+}
+
+/** Wait for the document to settle — a bounded in-page wait, not host polling. */
+export function settleExpression(budgetMs, debounceMs) {
+ return `(async () => {
+ const t0 = Date.now();
+ while (document.readyState !== "complete" && Date.now() - t0 < ${budgetMs}) {
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ await new Promise((r) => setTimeout(r, ${debounceMs}));
+ return document.readyState;
+ })()`;
+}
+
+/** Bounded in-page wait-for: expression or selector, single round trip. */
+export function waitForExpression(expression, timeoutMs) {
+ return `(async () => {
+ const t0 = Date.now();
+ for (;;) {
+ let v;
+ try { v = await (${expression}); } catch (e) { return { ok: false, error: String(e) }; }
+ if (v) return { ok: true, elapsed: Date.now() - t0 };
+ if (Date.now() - t0 > ${timeoutMs}) return { ok: false, timeout: true, elapsed: Date.now() - t0 };
+ await new Promise((r) => setTimeout(r, 80));
+ }
+ })()`;
+}
+
+function indexExpr(ref) {
+ return `[${JSON.stringify(String(ref))}]`;
+}
diff --git a/src/core/cdp.js b/src/core/cdp.js
new file mode 100644
index 0000000..6e03119
--- /dev/null
+++ b/src/core/cdp.js
@@ -0,0 +1,408 @@
+/**
+ * axuse — CDP transport and browser lifecycle.
+ *
+ * Lineage: Codex's chrome.debugger bridge (browser-level CDP with flat
+ * sessions, event routing, send timeouts) and ZCode's guest debugger
+ * discipline (attach → enable → use → detach, pending-command accounting).
+ *
+ * Node >= 22 gives us a native WebSocket client, which keeps axuse
+ * dependency-free — important for a library that harnesses vendor via MCP.
+ */
+import { spawn } from "node:child_process";
+import { accessSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync } from "node:fs";
+import { homedir, tmpdir } from "node:os";
+import { delimiter, join } from "node:path";
+import { AxError, Codes } from "./errors.js";
+
+const SEND_TIMEOUT_MS = 30_000;
+
+function isMacBrandedChrome(executable) {
+ // ALL branded Chrome channels (stable/Beta/Dev/Canary) ignore
+ // --load-extension on current macOS builds — live-verified for stable and
+ // Beta/Canary (Edge Beta honors it; CfT/Chromium do too).
+ return process.platform === "darwin"
+ && /(?:^|\/)Google Chrome(?: Beta| Dev| Canary)?\.app\/Contents\/MacOS\/Google Chrome(?: Beta| Dev| Canary)?$/.test(executable);
+}
+
+/** Candidate Chromium-family executables, best first. */
+export function browserCandidates({ extensionCapable = false, browser, ignoreEnv = false, exact = false } = {}) {
+ const out = [];
+ if (!ignoreEnv && process.env.AXUSE_BROWSER && process.env.AXUSE_BROWSER.trim()) {
+ const configured = process.env.AXUSE_BROWSER.trim();
+ // Current macOS branded Chrome builds silently ignore --load-extension.
+ // Do not let a general AXUSE_BROWSER override defeat the explicit
+ // extension-capable selection used by the bridge test/setup lane.
+ if (!(extensionCapable && isMacBrandedChrome(configured))) {
+ out.push(configured);
+ return out;
+ }
+ }
+ if (process.platform === "win32") {
+ const chrome = [];
+ const edge = [];
+ for (const envVar of ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"]) {
+ const base = process.env[envVar];
+ if (!base) continue;
+ chrome.push(join(base, "Google", "Chrome", "Application", "chrome.exe"));
+ }
+ for (const envVar of ["ProgramFiles", "ProgramFiles(x86)"]) {
+ const base = process.env[envVar];
+ if (!base) continue;
+ edge.push(join(base, "Microsoft", "Edge", "Application", "msedge.exe"));
+ }
+ out.push(...(browser === "edge" ? edge : browser === "chrome" ? chrome : [...chrome, ...edge]));
+ } else if (process.platform === "darwin") {
+ const app = (name, executable) => [
+ `/Applications/${name}.app/Contents/MacOS/${executable}`,
+ join(homedir(), "Applications", `${name}.app`, "Contents", "MacOS", executable),
+ ];
+ const chrome = app("Google Chrome", "Google Chrome");
+ const cft = app("Google Chrome for Testing", "Google Chrome for Testing");
+ const chromium = app("Chromium", "Chromium");
+ const edge = app("Microsoft Edge", "Microsoft Edge");
+ // Preview/beta channels — test-matrix coverage, best-effort ordering.
+ // NOTE: branded Chrome Beta/Canary ignore --load-extension like stable
+ // branded Chrome (live-verified); Edge Beta honors it. Only Edge Beta
+ // joins the extension-capable lane.
+ const chromeBeta = app("Google Chrome Beta", "Google Chrome Beta");
+ const chromeCanary = app("Google Chrome Canary", "Google Chrome Canary");
+ const edgeBeta = app("Microsoft Edge Beta", "Microsoft Edge Beta");
+ const preview = [...chromeBeta, ...chromeCanary, ...edgeBeta];
+ // Branded Chrome (any channel) intentionally stays out of the automated
+ // extension lane: current macOS builds silently ignore --load-extension.
+ // Users can still load the unpacked bridge manually in branded Chrome.
+ if (extensionCapable) {
+ const preferred = browser === "edge" ? edge
+ : browser === "edge-beta" ? edgeBeta
+ : browser === "chromium" ? chromium
+ : browser === "chrome-for-testing" ? cft
+ : [...edge, ...edgeBeta, ...chromium, ...cft];
+ out.push(...preferred);
+ for (const dir of (process.env.PATH ?? "").split(delimiter).filter(Boolean)) {
+ if (!browser || browser === "chromium") out.push(join(dir, "chromium"));
+ if (!browser || browser === "chrome-for-testing") out.push(join(dir, "google-chrome-for-testing"));
+ }
+ } else if (browser === "edge") {
+ out.push(...edge);
+ } else if (browser === "edge-beta") {
+ out.push(...edgeBeta);
+ } else if (browser === "chromium") {
+ out.push(...chromium);
+ } else if (browser === "chrome-for-testing") {
+ out.push(...cft);
+ } else if (browser === "chrome-beta") {
+ out.push(...chromeBeta);
+ } else if (browser === "chrome-canary") {
+ out.push(...chromeCanary);
+ } else if (browser === "chrome") {
+ out.push(...(exact ? chrome : [...chrome, ...cft, ...preview, ...chromium, ...edge]));
+ } else {
+ out.push(...chrome, ...cft, ...preview, ...chromium, ...edge);
+ }
+ } else {
+ const chrome = [
+ "/usr/bin/google-chrome",
+ "/usr/bin/google-chrome-stable",
+ ];
+ const chromium = ["/usr/bin/chromium", "/usr/bin/chromium-browser"];
+ const cft = ["/usr/bin/google-chrome-for-testing", "/usr/bin/chrome-for-testing"];
+ const edge = ["/usr/bin/microsoft-edge"];
+ const chromeBeta = ["/usr/bin/google-chrome-beta"];
+ out.push(...(browser === "edge" ? edge
+ : browser === "chromium" ? chromium
+ : browser === "chrome-for-testing" ? cft
+ : browser === "chrome-beta" ? chromeBeta
+ : browser === "chrome" ? (exact ? chrome : [...chrome, ...cft, ...chromeBeta, ...chromium, ...edge])
+ : [...chrome, ...cft, ...chromeBeta, ...chromium, ...edge]));
+ }
+ return [...new Set(out)];
+}
+
+/** Probe candidates, return the first that exists, or null. */
+export function locateBrowser(options = {}) {
+ for (const c of browserCandidates(options)) {
+ try {
+ accessSync(c);
+ return c;
+ } catch {}
+ }
+ return null;
+}
+
+/** A single browser-level WebSocket connection with flat session routing. */
+export class CdpConnection {
+ /** @param {string} wsUrl */
+ constructor(wsUrl) {
+ this.wsUrl = wsUrl;
+ this.ws = null;
+ this.seq = 0;
+ this.pending = new Map(); // id → {resolve, reject, timer}
+ this.eventHandlers = new Set(); // (msg) => void
+ this.closed = false;
+ }
+
+ async connect() {
+ const ws = new WebSocket(this.wsUrl);
+ this.ws = ws;
+ await new Promise((resolve, reject) => {
+ const t = setTimeout(
+ () => reject(new AxError(Codes.ATTACH_FAILED, `CDP WebSocket handshake timed out: ${this.wsUrl}`)),
+ 10_000,
+ );
+ ws.addEventListener("open", () => { clearTimeout(t); resolve(); }, { once: true });
+ ws.addEventListener("error", () => {
+ clearTimeout(t);
+ reject(new AxError(Codes.ATTACH_FAILED,
+ `CDP WebSocket handshake failed: ${this.wsUrl}. If attaching to a Chrome you started yourself, relaunch it with --remote-allow-origins=* and --remote-debugging-port=<port>.`,
+ { retry: "never" }));
+ }, { once: true });
+ });
+ ws.addEventListener("message", (ev) => {
+ let msg;
+ try { msg = JSON.parse(String(ev.data)); } catch { return; }
+ if (msg.id !== undefined && this.pending.has(msg.id)) {
+ const p = this.pending.get(msg.id);
+ this.pending.delete(msg.id);
+ clearTimeout(p.timer);
+ if (msg.error) p.reject(new AxError(Codes.INTERNAL, `CDP ${msg.error.code ?? ""} ${msg.error.message}`));
+ else p.resolve(msg.result);
+ } else if (msg.method) {
+ for (const h of this.eventHandlers) {
+ try { h(msg); } catch {}
+ }
+ }
+ });
+ ws.addEventListener("close", () => {
+ this.closed = true;
+ for (const [, p] of this.pending) {
+ clearTimeout(p.timer);
+ p.reject(new AxError(Codes.ATTACH_FAILED, "CDP connection closed"));
+ }
+ this.pending.clear();
+ });
+ }
+
+ onEvent(handler) {
+ this.eventHandlers.add(handler);
+ return () => this.eventHandlers.delete(handler);
+ }
+
+ /**
+ * Send a CDP command. `sessionId` routes to a flattened target session.
+ * Mirrors Codex's `tab_cdp_call` semantics (generic passthrough + timeout).
+ */
+ send(method, params = {}, sessionId) {
+ if (this.closed || this.ws.readyState !== WebSocket.OPEN) {
+ return Promise.reject(new AxError(Codes.ATTACH_FAILED, "CDP connection is not open"));
+ }
+ const id = ++this.seq;
+ const msg = { id, method, params };
+ if (sessionId) msg.sessionId = sessionId;
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pending.delete(id);
+ reject(new AxError(Codes.TIMEOUT, `CDP ${method} timed out after ${SEND_TIMEOUT_MS}ms`, { retry: "retry" }));
+ }, SEND_TIMEOUT_MS);
+ this.pending.set(id, { resolve, reject, timer });
+ this.ws.send(JSON.stringify(msg));
+ });
+ }
+
+ close() {
+ this.closed = true;
+ try { this.ws.close(); } catch {}
+ }
+}
+
+/** One controlled browser (launched by us, or attached to an existing one). */
+export class BrowserHandle {
+ constructor() {
+ this.conn = null;
+ this.proc = null; // child process when we launched it
+ this.userDataDir = null;
+ this.ephemeral = true; // false: a persistent A2 profile — never deleted
+ this.launched = false;
+ this.tabs = new Map(); // tab_id → session bookkeeping (owned by controller)
+ }
+
+ /** Launch a fresh Chromium with an ephemeral profile. Headed by default so
+ * a human can watch the agent work (the Codex/ZCode "visible browser"
+ * philosophy); headless is opt-in for servers and tests.
+ * `userDataDir` (plugin prerequisite A2, session-vault): reuse a PERSISTENT
+ * profile — not deleted on dispose, only swept by nobody but the owner. */
+ static async launch({ executablePath, headless = false, extraArgs = [], userDataDir, profileRoot: profileRootOverride } = {}) {
+ const exe = executablePath || locateBrowser();
+ if (!exe) {
+ throw new AxError(Codes.LAUNCH_FAILED,
+ "No Chromium-family browser found. axuse needs Google Chrome or Microsoft Edge: tell the user to install Chrome from https://www.google.com/chrome/ and try again. (Developers: set AXUSE_BROWSER=/path/to/chrome or pass executable_path.)",
+ { retry: "never" });
+ }
+ // Cold starts vary by OS and host: a fresh macOS .app can spend >15 s in
+ // first-run work (signature verification, updates) before DevTools comes
+ // up. The default accommodates that; AXUSE_LAUNCH_TIMEOUT_MS overrides.
+ const launchTimeoutMs = Number(process.env.AXUSE_LAUNCH_TIMEOUT_MS ?? 30_000);
+ const persistent = typeof userDataDir === "string" && userDataDir.trim().length > 0;
+ const profileRoot = profileRootOverride || process.env.AXUSE_PROFILE_DIR || tmpdir();
+ try { mkdirSync(profileRoot, { recursive: true }); } catch {}
+ sweepStaleProfiles(profileRoot);
+ const dir = persistent ? userDataDir : mkdtempSync(join(profileRoot, "axuse-profile-"));
+ const args = [
+ `--user-data-dir=${dir}`,
+ "--remote-debugging-port=0", // ephemeral port, parsed from stderr
+ "--no-first-run",
+ "--no-default-browser-check",
+ "--disable-background-timer-throttling",
+ "--disable-backgrounding-occluded-windows",
+ "--disable-smooth-scrolling", // wheel input lands instantly: no in-flight scroll when clicking
+ "--remote-allow-origins=*", // modern Chrome rejects unknown ws Origins
+ ];
+ if (headless) args.push("--headless");
+ args.push(...extraArgs);
+ const proc = spawn(exe, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: false });
+ let wsUrl;
+ try {
+ wsUrl = await new Promise((resolve, reject) => {
+ let buf = "";
+ let settled = false;
+ const timer = setTimeout(() => {
+ try { proc.kill(); } catch {}
+ if (!settled) {
+ settled = true;
+ reject(new AxError(Codes.LAUNCH_FAILED,
+ `Timed out after ${launchTimeoutMs}ms waiting for the DevTools WebSocket URL (first launch of a browser can be slow; raise AXUSE_LAUNCH_TIMEOUT_MS if this recurs)`,
+ { retry: "retry" }));
+ }
+ }, launchTimeoutMs);
+ const onData = (d) => {
+ buf += String(d);
+ const m = buf.match(/DevTools listening on (ws:\/\/\S+)/);
+ if (m) {
+ settled = true;
+ clearTimeout(timer);
+ resolve(m[1]);
+ }
+ };
+ proc.stderr.on("data", onData);
+ proc.stdout.on("data", onData);
+ proc.on("error", (e) => {
+ clearTimeout(timer);
+ if (settled) return;
+ settled = true;
+ reject(new AxError(Codes.LAUNCH_FAILED, `Could not start browser: ${e.message}`, { retry: "never" }));
+ });
+ proc.on("exit", (code) => {
+ clearTimeout(timer);
+ if (settled) return;
+ settled = true;
+ reject(new AxError(Codes.LAUNCH_FAILED, `Browser exited during startup (code ${code})`, { retry: "retry" }));
+ });
+ });
+ } catch (e) {
+ try { proc.kill(); } catch {}
+ if (!persistent) await removeDirWithRetry(dir);
+ throw e;
+ }
+ const h = new BrowserHandle();
+ h.proc = proc;
+ h.userDataDir = dir;
+ h.ephemeral = !persistent; // persistent (A2) profiles are never deleted on dispose
+ h.launched = true;
+ h.conn = new CdpConnection(wsUrl);
+ try {
+ await h.conn.connect();
+ } catch (e) {
+ await h.dispose();
+ throw e;
+ }
+ return h;
+ }
+
+ /** Attach to an already-running browser (user's real Chrome with its real
+ * logged-in sessions — the Codex "runs in the user's session" pattern). */
+ static async attach(cdpUrl) {
+ let wsUrl = cdpUrl;
+ if (!wsUrl.startsWith("ws://")) {
+ // Assume an http endpoint like http://127.0.0.1:9222
+ const base = cdpUrl.replace(/\/$/, "");
+ const res = await fetch(`${base}/json/version`);
+ if (!res.ok) throw new AxError(Codes.ATTACH_FAILED, `Cannot reach ${base}/json/version`);
+ const info = await res.json();
+ wsUrl = info.webSocketDebuggerUrl;
+ if (!wsUrl) throw new AxError(Codes.ATTACH_FAILED, "Target exposes no webSocketDebuggerUrl");
+ }
+ const h = new BrowserHandle();
+ h.conn = new CdpConnection(wsUrl);
+ await h.conn.connect();
+ return h;
+ }
+
+ async createTab(url = "about:blank", { autoAttach = true } = {}) {
+ const { targetId } = await this.conn.send("Target.createTarget", { url });
+ return this.attachTab(targetId, { autoAttach });
+ }
+
+ /** Attach to an existing page target (e.g. a popup / target=_blank tab). */
+ async attachTab(targetId, { autoAttach = true } = {}) {
+ const { sessionId } = await this.conn.send("Target.attachToTarget", { targetId, flatten: true });
+ // Enable the domains our event ring buffer records.
+ await this.conn.send("Page.enable", {}, sessionId);
+ await this.conn.send("Runtime.enable", {}, sessionId);
+ await this.conn.send("Log.enable", {}, sessionId);
+ // File inputs: intercept the native chooser (it would block forever) and
+ // let ax_upload answer it with DOM.setFileInputFiles.
+ try { await this.conn.send("Page.setInterceptFileChooserDialog", { enabled: true }, sessionId); } catch {}
+ // OOPIF support (Codex/ZCode merge frames into the snapshot): child
+ // iframe targets auto-attach as flat sessions; Target.attachedToTarget
+ // events arrive tagged with this tab's sessionId. Not available through
+ // the chrome.debugger extension bridge (no Target domain there) — that
+ // backend degrades to listed-but-not-entered frames.
+ if (autoAttach) {
+ await this.conn.send("Target.setAutoAttach",
+ { autoAttach: true, waitForDebuggerOnStart: false, flatten: true }, sessionId);
+ }
+ return { targetId, sessionId };
+ }
+
+ async closeTabTarget(targetId) {
+ try { await this.conn.send("Target.closeTarget", { targetId }); } catch {}
+ }
+
+ /** Close the connection, stop a launched browser, and delete its
+ * ephemeral profile once Chrome has released the files. Persistent
+ * profiles (A2: session-vault, aged profiles) are left on disk — the
+ * owner (the vault) manages their lifecycle. */
+ async dispose() {
+ try { this.conn.close(); } catch {}
+ const proc = this.proc;
+ if (proc && proc.exitCode === null) {
+ const exited = new Promise((ok) => proc.once("exit", ok));
+ try { proc.kill(); } catch {}
+ await Promise.race([exited, new Promise((ok) => setTimeout(ok, 3000))]);
+ }
+ if (this.userDataDir && this.ephemeral) await removeDirWithRetry(this.userDataDir);
+ }
+}
+
+/** Chrome's helper processes can hold profile files briefly after exit. */
+async function removeDirWithRetry(dir, attempts = 10) {
+ for (let i = 0; i < attempts; i++) {
+ try { rmSync(dir, { recursive: true, force: true }); return true; } catch {}
+ await new Promise((ok) => setTimeout(ok, 200 * (i + 1)));
+ }
+ return false;
+}
+
+/** Best-effort GC of profiles leaked by crashed/killed runs (older than 1h;
+ * a profile still in use is locked by Chrome and simply fails to delete). */
+function sweepStaleProfiles(root, maxAgeMs = 3_600_000) {
+ let names;
+ try { names = readdirSync(root); } catch { return; }
+ const now = Date.now();
+ for (const name of names) {
+ if (!name.startsWith("axuse-profile-")) continue;
+ const dir = join(root, name);
+ try {
+ if (now - statSync(dir).mtimeMs > maxAgeMs) rmSync(dir, { recursive: true, force: true });
+ } catch {}
+ }
+}
diff --git a/src/core/commands.js b/src/core/commands.js
new file mode 100644
index 0000000..65180ba
--- /dev/null
+++ b/src/core/commands.js
@@ -0,0 +1,355 @@
+/**
+ * axuse — the frozen command contract.
+ *
+ * Lineage: ZCode's `packages/shared/src/browser-use/commands.ts` — a single
+ * discriminated union every backend accepts, so the model-facing surface,
+ * validation and docs can never drift apart. Here the same contract object
+ * also *generates* the MCP tool schemas, so the tool list the model sees is
+ * literally derived from what the controller executes.
+ *
+ * "observed" values:
+ * "full" — command returns a FULL observation (navigations, open)
+ * "diff" — command returns a DIFF against the last observation (actions)
+ * "none" — command returns its own payload (screenshots, evaluate, ...)
+ */
+
+// Shared param specs: identical wording everywhere, and short — the tool
+// list rides along in the model's context on EVERY turn.
+const TAB = { t: "string", desc: "Tab id (default: active tab)." };
+const STATE = { t: "number", desc: "state_id the ref came from (rejects stale refs)." };
+const SETTLE = { t: "number", desc: "Settle ms before the diff (default 150)." };
+const TARGET = { t: "target", req: true, desc: '{ref:"e7"} from the latest observation, or {x,y} viewport CSS px = ax_screenshot pixels (last resort).' };
+
+export const Contract = Object.freeze({
+ open: {
+ group: "browser",
+ title: "Open a controlled browser tab",
+ desc: "Open a URL in a new tab (launches a browser on first use). Returns the FULL accessibility snapshot: one line per element, actionable ones with [ref=eN]. cdp_url attaches to a running Chrome; backend=extension drives the user's own Chrome via the axuse extension.",
+ params: {
+ url: { t: "string", req: true, desc: "http(s), file, about, data or blob URL." },
+ headless: { t: "boolean", desc: "No window (cdp backend)." },
+ cdp_url: { t: "string", desc: 'Attach instead of launching, e.g. "http://127.0.0.1:9222".' },
+ backend: { t: "enum", values: ["cdp", "extension"], desc: "cdp (default) or extension." },
+ executable_path: { t: "string", desc: "Browser binary (default: auto-detect)." },
+ profile_dir: { t: "string", desc: "Persistent user-data-dir to reuse an aged profile (e.g. a session-vault profile). A persistent profile is never deleted on close." },
+ settle_ms: { t: "number", desc: "Settle ms before observing (default 300)." },
+ },
+ observed: "full",
+ },
+
+ open_many: {
+ group: "browser",
+ title: "Open multiple URLs",
+ desc: "Open a bounded list of URLs sequentially and return compact page results. Tabs are closed after each URL by default, so this is safe for source lists and batch inspection. Use ax_open for interactive work on one page.",
+ params: {
+ urls: { t: "urls", req: true, desc: "Non-empty list of http(s), file, about, data or blob URLs (maximum 100)." },
+ headless: { t: "boolean", desc: "No window (cdp backend)." },
+ cdp_url: { t: "string", desc: 'Attach instead of launching, e.g. "http://127.0.0.1:9222".' },
+ backend: { t: "enum", values: ["cdp", "extension"], desc: "cdp (default) or extension." },
+ executable_path: { t: "string", desc: "Browser binary (default: auto-detect)." },
+ settle_ms: { t: "number", desc: "Settle ms per URL (default 300)." },
+ close_after: { t: "boolean", desc: "Close each axuse-created tab after observing it (default true)." },
+ excerpt_chars: { t: "number", desc: "Maximum accessibility-text excerpt per URL (default 1600, max 20000)." },
+ },
+ observed: "none",
+ },
+
+ navigate: {
+ group: "browser",
+ title: "Navigate the current tab to a URL",
+ desc: "Load a URL in the tab; returns a FULL snapshot (old refs die).",
+ params: { url: { t: "string", req: true, desc: "Target URL." }, tab_id: TAB, settle_ms: { t: "number", desc: "Default 300." } },
+ observed: "full",
+ },
+
+ go: {
+ group: "browser",
+ title: "Go back / forward in history",
+ desc: "History back (delta −1, default) or forward (+1); returns a FULL snapshot.",
+ params: { delta: { t: "number", desc: "Steps (default −1)." }, tab_id: TAB },
+ observed: "full",
+ },
+
+ tabs: {
+ group: "browser",
+ title: "List controlled tabs",
+ desc: "Controlled tabs: tab_id, url, title, state_id, open dialog. Popups opened by the page are adopted automatically.",
+ params: {},
+ observed: "none",
+ },
+
+ observe: {
+ group: "browser",
+ title: "Observe a tab (accessibility snapshot; diff by default)",
+ desc: "Accessibility snapshot. mode=diff (default): only what changed since the last observation (unchanged refs stay valid); mode=full: whole page. find=\"text\": only matching lines (+context, refs) from the whole page — cheapest way to locate a row/item on big pages. Actions already return a diff, so you rarely need this.",
+ params: {
+ tab_id: TAB,
+ mode: { t: "enum", values: ["diff", "full"], desc: "diff (default) or full." },
+ find: { t: "string", desc: "Return only lines containing this text (case-insensitive)." },
+ max_nodes: { t: "number", desc: "Element budget (default 300, max 2000)." },
+ max_chars: { t: "number", desc: "Char budget (default 24000, max 200000)." },
+ },
+ observed: "none",
+ },
+
+ click: {
+ group: "browser",
+ title: "Click (trusted input)",
+ desc: "Trusted click on a ref (or {x,y}). Returns the diff; a JS dialog or a new tab it opens is reported in the result.",
+ params: {
+ target: TARGET,
+ button: { t: "enum", values: ["left", "middle", "right"], desc: "Default left." },
+ count: { t: "number", desc: "2 = double click." },
+ modifiers: { t: "enum", values: ["alt", "ctrl", "meta", "shift"], multi: true, desc: "Held modifiers." },
+ state_id: STATE, tab_id: TAB, settle_ms: SETTLE,
+ },
+ observed: "diff",
+ },
+
+ fill: {
+ group: "browser",
+ title: "Fill a form in one call",
+ desc: "Set many fields in ONE call, optionally clicking submit after; returns one diff. value: string for text inputs/textareas/editors, <select>s, dropdown buttons and autocomplete comboboxes (types, then picks the exact suggestion); true/false for checkboxes, radios, switches; number for ARIA/native sliders (trusted Arrow key presses, converges and reports the step). Stops at the first failing field and says which.",
+ params: {
+ fields: { t: "fields", req: true, desc: '[{"ref":"e3","value":"Ada"},{"ref":"e6","value":true}]' },
+ submit: { t: "string", desc: "Ref to click after filling." },
+ state_id: STATE, tab_id: TAB, settle_ms: { t: "number", desc: "Default 200." },
+ },
+ observed: "diff",
+ },
+
+ upload: {
+ group: "browser",
+ title: "Upload local files",
+ desc: "Set local file(s) on a file input (ref of the <input type=file>, or omit ref right after a click opened a file chooser). Absolute paths. Returns the diff.",
+ params: {
+ ref: { t: "string", desc: "Ref of the file input (optional if a file chooser is pending)." },
+ paths: { t: "paths", req: true, desc: 'Absolute local paths, e.g. ["C:/Users/me/a.png"].' },
+ tab_id: TAB, settle_ms: SETTLE,
+ },
+ observed: "diff",
+ },
+
+ hover: {
+ group: "browser",
+ title: "Hover (trusted input)",
+ desc: "Move the mouse over a ref (opens hover menus/tooltips). Returns the diff.",
+ params: { target: TARGET, state_id: STATE, tab_id: TAB, settle_ms: SETTLE },
+ observed: "diff",
+ },
+
+ type: {
+ group: "browser",
+ title: "Type text (trusted input)",
+ desc: "Click the target, then type (trusted). Replaces existing content by default; submit=true presses Enter. Works on inputs and contenteditable editors. Returns the diff.",
+ params: {
+ target: { t: "target", desc: "{ref} of the field (omit: focused element)." },
+ text: { t: "string", req: true, desc: "Text to type." },
+ replace: { t: "boolean", desc: "Replace content (default true)." },
+ submit: { t: "boolean", desc: "Press Enter after." },
+ state_id: STATE, tab_id: TAB, settle_ms: SETTLE,
+ },
+ observed: "diff",
+ },
+
+ press: {
+ group: "browser",
+ title: "Press a key or combo (trusted input)",
+ desc: 'Key combo, e.g. "enter", "escape", "ctrl+a", "shift+tab". platform:true translates a Windows-convention application shortcut to this OS\'s convention (macOS: ctrl→cmd, e.g. ctrl+alt+1→cmd+alt+1 for headings, ctrl+end→cmd+end). Use it for app shortcuts (bold, headings, caret-to-end); leave it off for combos that must be literal Control (terminals, browser devtools). Returns the diff.',
+ params: {
+ combo: { t: "string", req: true, desc: "Key combo." },
+ platform: { t: "boolean", desc: "Translate ctrl-based app shortcuts to the platform convention (macOS: cmd)." },
+ tab_id: TAB, settle_ms: SETTLE,
+ },
+ observed: "diff",
+ },
+
+ scroll: {
+ group: "browser",
+ title: "Scroll (trusted input)",
+ desc: "Wheel scroll by direction+amount (pages) or dx/dy, anchored at target. until=\"text\": keeps scrolling in ONE call until that text is on the page (infinite feeds, lazy lists) or the page ends, and returns only the matching lines with refs.",
+ params: {
+ direction: { t: "enum", values: ["up", "down", "left", "right"], desc: "Direction." },
+ amount: { t: "number", desc: "Pages (default 1)." },
+ dx: { t: "number", desc: "Raw px." },
+ dy: { t: "number", desc: "Raw px." },
+ until: { t: "string", desc: "Scroll until this text appears (case-insensitive)." },
+ target: { t: "target", desc: "Anchor {ref} or {x,y}." },
+ tab_id: TAB, settle_ms: SETTLE,
+ },
+ observed: "diff",
+ },
+
+ select: {
+ group: "browser",
+ title: "Select an option (combobox)",
+ desc: "Set a native <select> by option value or text. (Custom dropdowns: use ax_fill.) Returns the diff.",
+ params: {
+ ref: { t: "string", req: true, desc: "Ref of the <select>." },
+ value: { t: "string", req: true, desc: "Option value or text." },
+ state_id: STATE, tab_id: TAB, settle_ms: SETTLE,
+ },
+ observed: "diff",
+ },
+
+ drag: {
+ group: "browser",
+ title: "Drag (trusted input)",
+ desc: "Drag from one ref/point to another (trusted pointer moves). Returns the diff.",
+ params: {
+ from: { t: "target", req: true, desc: "{ref} or {x,y}." },
+ to: { t: "target", req: true, desc: "{ref} or {x,y}." },
+ steps: { t: "number", desc: "Move steps (default 12)." },
+ tab_id: TAB, settle_ms: SETTLE,
+ },
+ observed: "diff",
+ },
+
+ screenshot: {
+ group: "browser",
+ title: "Screenshot (budgeted, one raster)",
+ desc: "JPEG of the viewport (or crop {x,y,w,h}), byte-budgeted. 1 image px = 1 viewport CSS px = the {x,y} ax_click takes. Only when pixels matter (canvas, visual checks).",
+ params: {
+ tab_id: TAB,
+ crop: { t: "rect", desc: "{x,y,w,h} viewport region." },
+ budget_bytes: { t: "number", desc: "Default 200000." },
+ quality: { t: "number", desc: "JPEG 1-100 (default 80)." },
+ },
+ observed: "none",
+ },
+
+ element_info: {
+ group: "browser",
+ title: "Element info at a point (vision↔structure bridge)",
+ desc: "What is at viewport point (x,y) (screenshot pixels): tag, role, name, rect and its ref.",
+ params: { x: { t: "number", req: true, desc: "Viewport X." }, y: { t: "number", req: true, desc: "Viewport Y." }, tab_id: TAB },
+ observed: "none",
+ },
+
+ evaluate: {
+ group: "browser",
+ title: "Evaluate JavaScript in the page",
+ desc: "Escape hatch: run a JS expression in the page (await ok); JSON result, 64KB cap.",
+ params: { expression: { t: "string", req: true, desc: "JS expression or (async) IIFE." }, tab_id: TAB },
+ observed: "none",
+ },
+
+ wait_for: {
+ group: "browser",
+ title: "Wait for a condition (bounded, in-page)",
+ desc: "One bounded in-page wait for a CSS selector or a truthy JS expression (default 3s, max 25s). Use for slow async UI instead of polling.",
+ params: {
+ selector: { t: "string", desc: "CSS selector (visible)." },
+ expression: { t: "string", desc: "JS expression." },
+ text: { t: "string", desc: "Wait until this text is on the page." },
+ timeout_ms: { t: "number", desc: "Default 3000, max 25000." },
+ tab_id: TAB,
+ },
+ observed: "none",
+ },
+
+ events: {
+ group: "browser",
+ title: "CDP/page events since a cursor",
+ desc: "Sequenced event log (navigations, dialogs, console errors, tabs opened). Poll with after_sequence.",
+ params: {
+ after_sequence: { t: "number", desc: "Only events after this (default 0)." },
+ limit: { t: "number", desc: "Max events (default 50)." },
+ tab_id: TAB,
+ },
+ observed: "none",
+ },
+
+ dialog: {
+ group: "browser",
+ title: "Read or answer a JS dialog",
+ desc: "Answer an open alert/confirm/prompt (accept|dismiss, prompt_text for prompts), or read it (no answer). Pages are frozen while one is open.",
+ params: {
+ answer: { t: "enum", values: ["accept", "dismiss"], desc: "Omit to just read." },
+ prompt_text: { t: "string", desc: "Text for a prompt()." },
+ tab_id: TAB,
+ },
+ observed: "diff",
+ },
+
+ close: {
+ group: "browser",
+ title: "Close tabs / browsers",
+ desc: "Close a tab (default active), or browser:true to close every controlled browser.",
+ params: { tab_id: TAB, browser: { t: "boolean", desc: "Close all browsers." } },
+ observed: "none",
+ },
+});
+
+import { AxError, Codes } from "./errors.js";
+
+const TYPE_NAMES = new Set(["string", "boolean", "number", "enum", "target", "rect", "fields", "paths", "urls", "any"]);
+
+/**
+ * Validate args against a contract entry. Returns a shallow-coerced copy.
+ * Throws AxError(COMMAND_REJECTED) — always recoverable by fixing the call.
+ */
+export function validate(name, args) {
+ const entry = Contract[name];
+ if (!entry) throw new AxError(Codes.COMMAND_REJECTED, `Unknown command "${name}"`, { retry: "never" });
+ const out = {};
+ const src = args ?? {};
+ const problems = [];
+ for (const [key, spec] of Object.entries(entry.params)) {
+ if (!TYPE_NAMES.has(spec.t)) problems.push(`internal: bad param type for ${key}`);
+ const v = src[key];
+ const present = v !== undefined && v !== null;
+ if (!present) {
+ if (spec.req) problems.push(`${key} is required`);
+ continue;
+ }
+ switch (spec.t) {
+ case "string":
+ if (typeof v !== "string") { problems.push(`${key} must be a string`); continue; }
+ break;
+ case "boolean":
+ if (typeof v !== "boolean") { problems.push(`${key} must be a boolean`); continue; }
+ break;
+ case "number":
+ if (typeof v !== "number" || !Number.isFinite(v)) { problems.push(`${key} must be a number`); continue; }
+ break;
+ case "enum":
+ if (spec.multi) {
+ if (!Array.isArray(v) || v.some((x) => !spec.values.includes(x))) { problems.push(`${key} must be an array of: ${spec.values.join("|")}`); continue; }
+ } else if (!spec.values.includes(v)) { problems.push(`${key} must be one of: ${spec.values.join("|")}`); continue; }
+ break;
+ case "target":
+ if (typeof v !== "object") { problems.push(`${key} must be {ref} or {x,y}`); continue; }
+ if (v.ref !== undefined) {
+ if (typeof v.ref !== "string") { problems.push(`${key}.ref must be a string`); continue; }
+ } else if (Number.isFinite(v.x) && Number.isFinite(v.y)) {
+ out[key] = { x: v.x, y: v.y };
+ continue;
+ } else { problems.push(`${key} must be {ref:"eN"} or {x,y}`); continue; }
+ break;
+ case "rect":
+ if (typeof v !== "object" || !["x", "y", "w", "h"].every((k) => Number.isFinite(v[k]))) { problems.push(`${key} must be {x,y,w,h} numbers`); continue; }
+ break;
+ case "fields":
+ if (!Array.isArray(v) || !v.length || v.some((f) => !f || typeof f.ref !== "string" || !["string", "boolean", "number"].includes(typeof f.value))) {
+ problems.push(`${key} must be a non-empty array of {ref:string, value:string|boolean}`); continue;
+ }
+ break;
+ case "paths":
+ if (!Array.isArray(v) || !v.length || v.some((x) => typeof x !== "string" || !x)) { problems.push(`${key} must be a non-empty array of paths`); continue; }
+ break;
+ case "urls":
+ if (!Array.isArray(v) || !v.length || v.some((x) => typeof x !== "string" || !x)) {
+ problems.push(`${key} must be a non-empty array of URLs`); continue;
+ }
+ break;
+ case "any":
+ break;
+ }
+ out[key] = v;
+ }
+ if (problems.length) {
+ throw new AxError(Codes.COMMAND_REJECTED, `${name}: ${problems.join("; ")}`, { retry: "never" });
+ }
+ return out;
+}
diff --git a/src/core/controller.js b/src/core/controller.js
new file mode 100644
index 0000000..4f8dc75
--- /dev/null
+++ b/src/core/controller.js
@@ -0,0 +1,1245 @@
+/**
+ * axuse — controller: the state owner and command executor.
+ *
+ * Lineage: Codex's native-messaging host owns browser/tab state (tab leases,
+ * state ids, event routing, watchdogs) behind a thin transport adapter; ZCode
+ * keeps browser/AX state in the host while the model-facing tool calls are
+ * stateless one-shots. Same shape here: MCP tool calls are thin and
+ * stateless; every durable fact (tabs, refs' state_id, dialogs, event
+ * cursors, snapshots for diffing) lives in this process.
+ */
+
+import { BrowserHandle } from "./cdp.js";
+import { Contract, validate } from "./commands.js";
+import { AxError, Codes } from "./errors.js";
+import { serializeExpression } from "./serialize.js";
+import { diffSnapshots, noChangeText } from "./diff.js";
+import { captureScreenshot, DEFAULT_BUDGET_BYTES } from "./screenshot.js";
+import {
+ click as doClick, hover as doHover, drag as doDrag, wheel as doWheel,
+ insertText, pressCombo, platformShortcut, selectAllCombo,
+ refResolveExpression, selectOptionExpression, elementInfoExpression, fieldKindExpression, findOptionExpression,
+ sliderValueExpression, settleExpression, waitForExpression, MOD,
+} from "./actuate.js";
+
+const URL_SCHEMES = /^(https?|file|about|data|blob):/i;
+const EVENT_RING_MAX = 1000; // Codex tab_cdp_events: limit ≤ 1000
+const MAX_EVAL_CHARS = 64_000; // Codex DOM text cap: 64k default
+const EVENT_TEXT_CAP = 2000;
+const MAX_OPEN_MANY_URLS = 100;
+const MOD_MASK = { alt: 1, ctrl: 2, control: 2, meta: 4, cmd: 4, command: 4, shift: 8 };
+
+/** Event methods worth a round trip — the signal, not the noise. */
+const RECORDED_EVENTS = new Set([
+ "Page.fileChooserOpened",
+ "Page.javascriptDialogOpening",
+ "Page.javascriptDialogClosed",
+ "Page.frameNavigated",
+ "Page.navigatedWithinDocument",
+ "Page.loadEventFired",
+ "Page.windowOpen",
+ "Page.crashed",
+ "Page.downloadWillBegin", // plugin prerequisite R1: downloads-pdf
+ "Page.downloadProgress",
+ "Runtime.consoleAPICalled", // error/warning only, filtered below
+ "Log.entryAdded", // error level only, filtered below
+]);
+
+export class Controller {
+ constructor() {
+ this.browsers = new Map(); // browser_id → {handle, tabs:Set, key}
+ this.browserIndex = new Map(); // reuse key ("launch:headless" / "attach:url") → browser_id
+ this.tabs = new Map(); // tab_id → tab record
+ this.tabSeq = 0;
+ this.browserSeq = 0;
+ this.activeTabId = null;
+ }
+
+ /* ------------------------------------------------------------------ util */
+
+ tabOrActive(tabId) {
+ const id = tabId ?? this.activeTabId;
+ if (!id || !this.tabs.has(id)) {
+ throw new AxError(Codes.NO_TAB, "No controlled tab. Open one with ax_open first.", { retry: "never" });
+ }
+ return this.tabs.get(id);
+ }
+
+ /** Guard: acting on refs from an older observation than the current page state. */
+ checkStale(tab, args) {
+ if (args.state_id !== undefined && args.state_id !== tab.stateId) {
+ throw new AxError(Codes.STALE_STATE,
+ `state_id ${args.state_id} predates current state ${tab.stateId} (url: ${tab.url}).`,
+ { hint: "Call ax_observe, then act on fresh refs.", retry: "reobserve" });
+ }
+ }
+
+ /** Guard: JS dialogs block everything until answered. */
+ checkDialog(tab) {
+ if (tab.dialog) {
+ throw new AxError(Codes.DIALOG_OPEN,
+ `A ${tab.dialog.type} dialog is open: "${tab.dialog.message}".`,
+ { hint: "Answer it with ax_dialog (answer: accept|dismiss).", retry: "retry" });
+ }
+ }
+
+ /** Parse an `f<slot>:eN` ref → the owning session, or the tab's own. */
+ sessionForRef(tab, ref) {
+ const m = /^f(\d+):(.+)$/.exec(String(ref));
+ if (!m) return { session: tab.sessionId, ref: String(ref), frame: null };
+ for (const [, f] of tab.frames) {
+ if (f.slot === Number(m[1])) return { session: f.sessionId, ref: m[2], frame: `f${f.slot}` };
+ }
+ throw new AxError(Codes.REF_NOT_FOUND,
+ `frame slot f${m[1]} is gone (frame navigated away or detached).`,
+ { hint: "Call ax_observe — the frame tree is re-merged each observation.", retry: "reobserve" });
+ }
+
+ /** Run the injected serializer and build a snapshot record.
+ * OOPIF frames are serialized in their own sessions and merged with
+ * `f<slot>:` ref namespacing (identity-stable slots + per-document
+ * registries, so unchanged frame refs stay valid across observations). */
+ async serialize(tab, { maxNodes = 300, maxChars = 24000 } = {}) {
+ const expression = serializeExpression({ maxNodes, maxChars });
+ const res = await this.evalInTab(tab, expression, { awaitPromise: false });
+ if (!res || res.ok === false) {
+ throw new AxError(Codes.EVALUATE_FAILED, `Serializer failed: ${res && res.error}`);
+ }
+ const entries = [...res.entries];
+ const textLines = [...res.textLines];
+ let text = res.text;
+ let truncated = res.truncated;
+ const frameNotes = [];
+ // Frames in slot order; each frame's own serializer runs in its session.
+ const frames = [...tab.frames.values()].sort((a, b) => a.slot - b.slot);
+ for (const f of frames) {
+ if (text.length >= maxChars) { truncated = true; break; }
+ let fres;
+ try {
+ fres = await this.evalInTab(tab, serializeExpression({ maxNodes: Math.min(maxNodes, 100), maxChars: Math.max(2000, Math.floor(maxChars / 4)) }), { awaitPromise: false }, f.sessionId);
+ } catch {
+ frameNotes.push(`--- frame f${f.slot} (${f.url}) not ready ---`);
+ continue;
+ }
+ if (!fres || fres.ok === false || !Array.isArray(fres.entries)) {
+ frameNotes.push(`--- frame f${f.slot} (${f.url}) not ready ---`);
+ continue;
+ }
+ const prefix = `f${f.slot}:`;
+ const section = [`--- frame f${f.slot} (${fres.url ?? f.url}) ---`];
+ for (const e of fres.entries) {
+ const line = e.line.replace(/\[ref=(e\d+)\]/, (m, r) => `[ref=${prefix}${r}]`);
+ entries.push({ ref: `${prefix}${e.ref}`, line });
+ section.push(" " + line);
+ }
+ for (const tl of fres.textLines) {
+ textLines.push(tl);
+ section.push(" " + tl);
+ }
+ if (fres.truncated) truncated = true;
+ text += "\n" + section.join("\n");
+ }
+ for (const n of frameNotes) text += "\n" + n;
+ if (text.length > maxChars) {
+ text = text.slice(0, maxChars) + "\n…[truncated — pass max_chars or observe in pieces]";
+ truncated = true;
+ }
+ tab.stateId += 1;
+ return {
+ stateId: tab.stateId,
+ entries,
+ textLines,
+ url: res.url,
+ title: res.title,
+ truncated,
+ refCount: entries.length,
+ frameCount: frames.length,
+ text,
+ };
+ }
+
+ /** Runtime.evaluate with typed error mapping and size clipping. `session`
+ * routes the evaluation into a frame session (OOPIF refs). */
+ async evalInTab(tab, expression, { awaitPromise = false } = {}, session) {
+ const sessionId = session ?? tab.sessionId;
+ let res;
+ try {
+ res = await tab.browser.handle.conn.send("Runtime.evaluate", {
+ expression,
+ returnByValue: true,
+ awaitPromise,
+ }, sessionId);
+ } catch (e) {
+ if (e instanceof AxError && e.code === Codes.TIMEOUT) {
+ throw new AxError(Codes.NAVIGATION_IN_PROGRESS,
+ "The tab is navigating (execution context replaced mid-call).",
+ { hint: "Call ax_observe once navigation settles.", retry: "reobserve", sideEffect: "uncertain" });
+ }
+ throw e;
+ }
+ if (res.exceptionDetails) {
+ const d = res.exceptionDetails;
+ const msg = (d.exception && (d.exception.description || d.exception.value)) || d.text || "unknown error";
+ throw new AxError(Codes.EVALUATE_FAILED, String(msg).slice(0, 400), { retry: "never" });
+ }
+ return res.result?.value;
+ }
+
+ /** Bounded settle wait, in-page (ZCode rule: wait for UI settle, no host polling). */
+ async settle(tab, budgetMs = 4000, debounceMs = 150) {
+ await this.evalInTab(tab, settleExpression(budgetMs, debounceMs), { awaitPromise: true }).catch(() => null);
+ }
+
+ /**
+ * Produce an observation: full snapshot text or diff vs the last one.
+ * This is the Codex/ZCode observation engine — the model normally reads
+ * diffs, full trees only on navigation or explicit request.
+ */
+ async observation(tab, { mode = "diff", maxNodes, maxChars, settleMs } = {}) {
+ if (settleMs !== undefined) await this.settle(tab, 4000, settleMs);
+ const snap = await this.serialize(tab, { maxNodes, maxChars });
+ if (snap.url) tab.url = snap.url;
+ if (snap.title !== undefined) tab.title = snap.title;
+ const header = `url: ${snap.url}\ntitle: ${snap.title}\nentries: ${snap.entries.length} refs, state ${snap.stateId}${snap.truncated ? "\nnote: truncated by budget — pass max_nodes/max_chars or observe in pieces" : ""}`;
+ const fullText = `${header}\n${snap.text}`;
+ if (mode === "full" || !tab.lastSnapshot) {
+ tab.lastSnapshot = snap;
+ return { state_id: snap.stateId, mode: "full", url: snap.url, title: snap.title, truncated: snap.truncated, ref_count: snap.refCount, text: fullText };
+ }
+ const prev = tab.lastSnapshot;
+ const d = diffSnapshots(prev, snap);
+ tab.lastSnapshot = snap;
+ if (d.mode === "full") {
+ return { state_id: snap.stateId, mode: "full", url: snap.url, title: snap.title, truncated: snap.truncated, ref_count: snap.refCount, text: fullText, diff_suppressed: true };
+ }
+ const churn = d.removed.length + d.added.length + d.changed.length
+ + (d.textAdded?.length ?? 0) + (d.textRemoved?.length ?? 0);
+ if (churn === 0) {
+ return { state_id: snap.stateId, mode: "diff", url: snap.url, title: snap.title, truncated: snap.truncated, ref_count: snap.refCount, text: noChangeText(prev, snap) };
+ }
+ return { state_id: snap.stateId, mode: "diff", url: snap.url, title: snap.title, truncated: snap.truncated, ref_count: snap.refCount, text: d.text };
+ }
+
+ /** Post-action auto-observation. Never masks a successful action. */
+ async autoObserve(tab, settleMs) {
+ try {
+ if (tab.dialog) return this.dialogNote(tab);
+ if (settleMs !== undefined && settleMs > 0) await this.raceDialog(tab, this.settle(tab, 4000, settleMs));
+ if (tab.dialog) return this.dialogNote(tab);
+ const obs = await this.raceDialog(tab, this.observation(tab, { mode: "diff" }));
+ if (tab.dialog) return this.dialogNote(tab);
+ return obs;
+ } catch (e) {
+ return { skipped: e.code ?? "ERROR", hint: "Call ax_observe." };
+ }
+ }
+
+ /** Resolve target {ref} | {x,y} to live coordinates. `f<slot>:eN` refs
+ * resolve inside the frame's session (frame-local coordinates, matching
+ * frame-local CDP input dispatch). */
+ async resolveTarget(tab, target) {
+ if (target.x !== undefined) {
+ if (!Number.isFinite(target.x) || !Number.isFinite(target.y)) {
+ throw new AxError(Codes.BAD_COORDS, "x/y must be finite numbers", { retry: "never" });
+ }
+ return { x: target.x, y: target.y, from: "coords" };
+ }
+ const { session, ref, frame } = this.sessionForRef(tab, target.ref);
+ const res = await this.evalInTab(tab, refResolveExpression(ref), { awaitPromise: true }, session);
+ if (!res) throw new AxError(Codes.REF_NOT_FOUND, `ref "${target.ref}" does not exist in the page.`,
+ { hint: "Refs are per-observation. Call ax_observe (mode full if needed), then act on fresh refs.", retry: "reobserve" });
+ if (res.error === "no_ref" || res.error === "detached") {
+ throw new AxError(Codes.REF_NOT_FOUND, `ref "${target.ref}" is gone (navigation or re-render).`,
+ { hint: "Call ax_observe, then act on fresh refs.", retry: "reobserve" });
+ }
+ if (res.error === "hidden") {
+ throw new AxError(Codes.ELEMENT_HIDDEN, `ref "${target.ref}" has no visible box.`,
+ { hint: "Scroll it into view or re-observe.", retry: "reobserve" });
+ }
+ return { x: res.x, y: res.y, covered: res.covered, hitTag: res.hitTag, from: "ref", session, frame };
+ }
+
+ modifierMask(modifiers) {
+ return (modifiers ?? []).reduce((m, x) => m | (MOD_MASK[x] ?? 0), 0);
+ }
+
+ /* ------------------------------------------------------------- commands */
+
+ /** Single entry point — the frozen contract executes here and only here. */
+ async execute(name, rawArgs = {}) {
+ const args = validate(name, rawArgs);
+ const entry = Contract[name];
+ if (entry.group !== "browser") throw new AxError(Codes.INTERNAL, `unroutable group ${entry.group}`);
+ const fn = this[`$${name}`];
+ if (!fn) throw new AxError(Codes.INTERNAL, `command "${name}" has no executor`);
+ const started = Date.now();
+ const result = await fn.call(this, args);
+ const meta = { elapsed_ms: Date.now() - started };
+ if (result && typeof result === "object") {
+ if (entry.observed === "full") meta.observed = "full";
+ return { ...result, meta };
+ }
+ return { result, meta };
+ }
+
+ async $open(a) {
+ const url = String(a.url);
+ if (!URL_SCHEMES.test(url)) {
+ throw new AxError(Codes.COMMAND_REJECTED, `url must start with http(s)://, file://, about:, data: or blob:`, { retry: "never" });
+ }
+ const headless = a.headless ?? /^(1|true)$/i.test(process.env.AXUSE_HEADLESS ?? "");
+ const browser = await this.ensureBrowser({ headless, cdpUrl: a.cdp_url, executablePath: a.executable_path, backend: a.backend, profileDir: a.profile_dir });
+ const { targetId, sessionId } = await browser.handle.createTab("about:blank");
+ const tab = this.registerTab(browser, targetId, sessionId, "about:blank");
+ const tabId = tab.tabId;
+ await this.navigateInTab(tab, url, a.settle_ms ?? 300);
+ const observation = await this.observation(tab, { mode: "full" });
+ return { browser_id: browser.browserId, tab_id: tabId, observation, dialog: tab.dialog ?? null };
+ }
+
+ /** Open a bounded source list without forcing the caller to write an MCP
+ * client. Results are deliberately compact; callers can use ax_open for a
+ * single page when they need the full interactive snapshot and live refs. */
+ async $open_many(a) {
+ if (a.urls.length > MAX_OPEN_MANY_URLS) {
+ throw new AxError(Codes.COMMAND_REJECTED,
+ `open_many accepts at most ${MAX_OPEN_MANY_URLS} URLs (received ${a.urls.length})`,
+ { retry: "never" });
+ }
+ const closeAfter = a.close_after ?? true;
+ const excerptChars = Math.min(Math.max(Math.floor(a.excerpt_chars ?? 1600), 0), 20_000);
+ const results = [];
+
+ for (const url of a.urls) {
+ const before = new Set(this.tabs.keys());
+ let opened = null;
+ try {
+ opened = await this.$open({
+ url,
+ headless: a.headless,
+ cdp_url: a.cdp_url,
+ backend: a.backend,
+ executable_path: a.executable_path,
+ settle_ms: a.settle_ms,
+ });
+ const obs = opened.observation ?? {};
+ const body = String(obs.text ?? "").split("\n").slice(3).join("\n").trim();
+ const excerpt = excerptChars ? body.slice(0, excerptChars) : "";
+ results.push({
+ url,
+ final_url: obs.url ?? url,
+ title: obs.title ?? "",
+ status: "opened",
+ ref_count: obs.ref_count ?? 0,
+ truncated: !!obs.truncated,
+ ...(excerpt ? { excerpt } : {}),
+ ...(!closeAfter ? { tab_id: opened.tab_id } : {}),
+ });
+ } catch (e) {
+ const created = [...this.tabs.keys()].filter((id) => !before.has(id));
+ const error = typeof e?.toJSON === "function"
+ ? e.toJSON()
+ : { code: e?.code ?? Codes.INTERNAL, message: String(e?.message ?? e), retry: "never" };
+ results.push({
+ url,
+ status: "error",
+ ...(created.at(-1) && !closeAfter ? { tab_id: created.at(-1) } : {}),
+ error,
+ });
+ } finally {
+ if (closeAfter) {
+ const created = [...this.tabs.keys()].filter((id) => !before.has(id));
+ for (const tabId of created) {
+ try { await this.$close({ tab_id: tabId }); } catch {}
+ }
+ }
+ }
+ }
+
+ return {
+ results,
+ count: results.length,
+ opened: results.filter((r) => r.status === "opened").length,
+ failed: results.filter((r) => r.status === "error").length,
+ closed_after: closeAfter,
+ };
+ }
+
+ registerTab(browser, targetId, sessionId, url, openerTabId) {
+ const tabId = `t${++this.tabSeq}`;
+ const tab = {
+ tabId, browserId: browser.browserId, targetId, sessionId,
+ url, title: "", stateId: 0, lastSnapshot: null,
+ events: [], eventSeq: 0, dialog: null, closed: false,
+ frames: new Map(), // OOPIF child sessionId → {slot, sessionId, targetId, url}
+ frameSeq: 0,
+ downloads: new Map(), // guid → {suggestedFilename, url, state, receivedBytes, totalBytes} (R1)
+ cdpBroadcasts: [], // [method, params] replays on every future frame attach (R2)
+ browser,
+ ...(openerTabId ? { opener: openerTabId } : {}),
+ };
+ this.tabs.set(tabId, tab);
+ browser.tabs.add(tabId);
+ this.activeTabId = tabId;
+ this.attachEventRouting(tab);
+ return tab;
+ }
+
+ /**
+ * Popups / target=_blank / window.open: a page target whose opener is a
+ * controlled tab is adopted as a new controlled tab and becomes active —
+ * otherwise the agent clicks a link and the result silently vanishes.
+ * Targets we didn't open (the user's own tabs on an attached browser)
+ * are never touched.
+ */
+ async watchPopups(rec) {
+ const conn = rec.handle.conn;
+ if (!conn?.onEvent) return;
+ rec.adopted = [];
+ conn.onEvent((msg) => {
+ if (msg.sessionId) return;
+ if (msg.method === "Target.targetCreated") {
+ const ti = msg.params.targetInfo;
+ if (ti?.type !== "page" || !ti.openerId) return;
+ const opener = [...this.tabs.values()].find((t) => t.targetId === ti.openerId && t.browserId === rec.browserId);
+ if (!opener || [...this.tabs.values()].some((t) => t.targetId === ti.targetId)) return;
+ const p = rec.handle.attachTab(ti.targetId).then(({ sessionId }) => {
+ const tab = this.registerTab(rec, ti.targetId, sessionId, ti.url || "about:blank", opener.tabId);
+ this.recordEvent(opener, "tab.opened", { tab_id: tab.tabId, url: ti.url });
+ rec.adopted.push(tab.tabId);
+ return tab;
+ }).catch(() => null);
+ rec.pendingAdopt = (rec.pendingAdopt ?? Promise.resolve()).then(() => p);
+ } else if (msg.method === "Target.targetDestroyed") {
+ const tab = [...this.tabs.values()].find((t) => t.targetId === msg.params.targetId && t.browserId === rec.browserId);
+ if (tab && tab.opener) this.deregisterTab(tab);
+ }
+ });
+ try { await conn.send("Target.setDiscoverTargets", { discover: true }); } catch {}
+ }
+
+ /** After an action: if it opened popup tabs, report them (with a full
+ * observation of the newest, which is now the active tab). */
+ async popupReport(tab) {
+ const rec = tab.browser;
+ if (!rec.adopted) return null;
+ await new Promise((ok) => setTimeout(ok, 150));
+ await rec.pendingAdopt;
+ if (!rec.adopted.length) return null;
+ const ids = rec.adopted.splice(0);
+ const newest = this.tabs.get(ids.at(-1));
+ if (!newest) return null;
+ try { await this.settleLoad(newest); } catch {}
+ const observation = await this.observation(newest, { mode: "full" }).catch(() => null);
+ return {
+ opened_tabs: ids,
+ tab_note: `The action opened a new tab ${newest.tabId} (now the active tab). Its observation is below; the original tab ${tab.tabId} is unchanged — pass tab_id:"${tab.tabId}" to act there again.`,
+ new_tab: { tab_id: newest.tabId, observation },
+ };
+ }
+
+ async settleLoad(tab) {
+ // Wait (bounded) for the popup document to finish loading.
+ for (let i = 0; i < 30; i++) {
+ const st = await this.evalInTab(tab, "document.readyState", { awaitPromise: false }).catch(() => null);
+ if (st === "complete" || st === "interactive") { await this.settle(tab, 2000, 150); return; }
+ await new Promise((ok) => setTimeout(ok, 100));
+ }
+ }
+
+ async ensureBrowser({ headless, cdpUrl, executablePath, backend, profileDir }) {
+ // Extension backend: the user's real Chrome through the axuse bridge
+ // (Codex pattern: one browser, the user's own, tabs visible to them).
+ if (backend === "extension") {
+ const key = "extension";
+ const existing = this.browserIndex.get(key);
+ if (existing) {
+ const b = this.browsers.get(existing);
+ if (b && !b.handle.conn.closed) return b;
+ this.browsers.delete(existing);
+ this.browserIndex.delete(key);
+ }
+ const { createExtensionHandle } = await import("../bridge/backend.js");
+ const handle = await createExtensionHandle();
+ const browserId = `b${++this.browserSeq}`;
+ const rec = { browserId, handle, tabs: new Set(), key };
+ this.browsers.set(browserId, rec);
+ this.browserIndex.set(key, browserId);
+ return rec;
+ }
+ const key = cdpUrl ? `attach:${cdpUrl}` : `launch:${headless ? "headless" : "headed"}:${profileDir ?? "ephemeral"}`;
+ const existing = this.browserIndex.get(key);
+ if (existing) {
+ const b = this.browsers.get(existing);
+ if (b && !b.handle.conn.closed) return b;
+ this.browsers.delete(existing);
+ this.browserIndex.delete(key);
+ }
+ const handle = cdpUrl
+ ? await BrowserHandle.attach(cdpUrl)
+ : await BrowserHandle.launch({ headless, executablePath, userDataDir: profileDir });
+ const browserId = `b${++this.browserSeq}`;
+ const rec = { browserId, handle, tabs: new Set(), key };
+ this.browsers.set(browserId, rec);
+ this.browserIndex.set(key, browserId);
+ await this.watchPopups(rec);
+ return rec;
+ }
+
+ attachEventRouting(tab) {
+ const off = tab.browser.handle.conn.onEvent((msg) => {
+ // Frame lifecycle (auto-attach): Target.attachedToTarget events arrive
+ // tagged with the PARENT tab session; type "iframe" children register
+ // as frames (type "page" children are ignored — a duplicate attach).
+ if (msg.sessionId === tab.sessionId && msg.method === "Target.attachedToTarget") {
+ const ti = msg.params.targetInfo;
+ if (ti && ti.type === "iframe") {
+ this.registerFrame(tab, msg.params).catch(() => {});
+ }
+ return;
+ }
+ if (msg.sessionId === tab.sessionId && msg.method === "Target.detachedFromTarget") {
+ const frame = tab.frames.get(msg.params.sessionId);
+ if (frame) {
+ tab.frames.delete(msg.params.sessionId);
+ this.recordEvent(tab, "frame.detached", { frame: `f${frame.slot}`, url: frame.url });
+ }
+ return;
+ }
+ // Events from frame sessions are tagged with their frame slot.
+ if (tab.frames.has(msg.sessionId)) {
+ if (RECORDED_EVENTS.has(msg.method)) {
+ this.recordEvent(tab, msg.method, msg.params, `f${tab.frames.get(msg.sessionId).slot}`);
+ }
+ return;
+ }
+ if (msg.sessionId !== tab.sessionId || !RECORDED_EVENTS.has(msg.method)) return;
+ this.recordEvent(tab, msg.method, msg.params);
+ });
+ tab.offEventRouting = off;
+ }
+
+ async registerFrame(tab, { sessionId, targetInfo }) {
+ if (tab.frames.has(sessionId)) return;
+ const conn = tab.browser.handle.conn;
+ // Frame slots are identity-stable (monotonic per tab): refs f2:e7 keep
+ // pointing at the same frame across observations, mirroring the element
+ // registry design.
+ const slot = ++tab.frameSeq;
+ const frame = { slot, sessionId, targetId: targetInfo.targetId, url: targetInfo.url ?? "" };
+ tab.frames.set(sessionId, frame);
+ try {
+ await conn.send("Page.enable", {}, sessionId);
+ await conn.send("Runtime.enable", {}, sessionId);
+ await conn.send("Log.enable", {}, sessionId);
+ // Nested cross-origin frames auto-attach within the frame session too.
+ await conn.send("Target.setAutoAttach",
+ { autoAttach: true, waitForDebuggerOnStart: false, flatten: true }, sessionId);
+ } catch {}
+ // Plugin prerequisite R2: domain enables broadcast by plugins (Fetch/
+ // Network, WebAuthn) must survive cross-origin frame churn — replay the
+ // registered broadcasts on every newly attached frame session.
+ for (const [method, params] of tab.cdpBroadcasts) {
+ try { await conn.send(method, params, sessionId); } catch {}
+ }
+ this.recordEvent(tab, "frame.attached", { frame: `f${slot}`, url: frame.url });
+ }
+
+ /** Plugin plumbing (R1-R4): typed CDP passthrough on a controlled tab's
+ * connection — the narrow lever for Storage (cookies, R4), Browser
+ * (download behavior, R1), WebAuthn (virtual authenticators, R3), Fetch /
+ * Network (governor, R2) and raw Input.* dispatch (human-curve drags).
+ * Dialog-aware like every input send; the plugin never touches the
+ * Controller itself. */
+ async cdpSend(tabId, method, params = {}, sessionId) {
+ const tab = this.tabOrActive(tabId);
+ return this.raceDialog(tab, tab.browser.handle.conn.send(method, params, sessionId ?? tab.sessionId));
+ }
+
+ /** Plugin prerequisite R2 (event delivery): subscribe to raw CDP events on
+ * the tab's connection. The handler receives the full message
+ * ({ method, params, sessionId? }); events from the tab's own session and
+ * its OOPIF frame sessions are delivered (scope by msg.sessionId against
+ * tabs().frame_sessions). Returns an unsubscribe function. */
+ cdpOn(tabId, method, handler) {
+ const tab = this.tabOrActive(tabId);
+ const frameSessions = () => new Set([...tab.frames.values()].map((f) => f.sessionId));
+ const off = tab.browser.handle.conn.onEvent((msg) => {
+ if (msg.method !== method) return;
+ if (msg.sessionId && msg.sessionId !== tab.sessionId && !frameSessions().has(msg.sessionId)) return;
+ handler(msg);
+ });
+ return () => { try { off(); } catch {} };
+ }
+
+ /** Plugin prerequisite R2: send to the tab session AND every attached
+ * OOPIF frame session, and replay on every future frame attach (Fetch/
+ * Network enables must survive cross-origin frame churn). Broadcasts are
+ * deduped by method+params; per-frame send failures never fail the call. */
+ async cdpBroadcast(tabId, method, params = {}) {
+ const tab = this.tabOrActive(tabId);
+ const key = JSON.stringify([method, params]);
+ if (!tab.cdpBroadcasts.some((pair) => JSON.stringify(pair) === key)) {
+ tab.cdpBroadcasts.push([method, params]);
+ }
+ await this.raceDialog(tab, tab.browser.handle.conn.send(method, params, tab.sessionId));
+ let frames = 0;
+ for (const [, f] of tab.frames) {
+ try {
+ await this.raceDialog(tab, tab.browser.handle.conn.send(method, params, f.sessionId));
+ frames++;
+ } catch {}
+ }
+ return { sent: 1 + frames, sessions: 1 + tab.frames.size, replayedOnAttach: true };
+ }
+
+ recordEvent(tab, method, params, frame) {
+ let data = params ?? {};
+ if (method === "Page.javascriptDialogOpening") {
+ tab.dialog = { type: params.type, message: String(params.message ?? "").slice(0, 300), default_prompt: params.defaultPrompt ?? "" };
+ data = { type: params.type, message: tab.dialog.message };
+ } else if (method === "Page.fileChooserOpened") {
+ tab.fileChooser = { backendNodeId: params.backendNodeId, mode: params.mode };
+ data = { mode: params.mode };
+ } else if (method === "Page.javascriptDialogClosed") {
+ tab.dialog = null;
+ data = {};
+ } else if (method === "Page.frameNavigated") {
+ if (!params.frame.parentId) { // main frame only for the tab-level fact
+ tab.dialog = null;
+ data = { url: params.frame.url, frameId: params.frame.id };
+ tab.url = params.frame.url;
+ } else return; // child frames → noise
+ } else if (method === "Page.navigatedWithinDocument") {
+ tab.url = params.url;
+ data = { url: params.url };
+ } else if (method === "Runtime.consoleAPICalled") {
+ if (params.type !== "error" && params.type !== "warning") return;
+ const text = (params.args ?? []).map((x) => x.value ?? x.description ?? "").join(" ").slice(0, 300);
+ data = { type: params.type, text };
+ } else if (method === "Log.entryAdded") {
+ if (params.entry?.level !== "error") return;
+ data = { source: params.entry.source, text: String(params.entry.text ?? "").slice(0, 300) };
+ } else if (method === "Page.loadEventFired" || method === "Page.windowOpen" || method === "Page.crashed") {
+ data = {};
+ } else if (method === "Page.downloadWillBegin") {
+ // Plugin prerequisite R1: download lifecycle through the event ring —
+ // a click that produces a file must never hang an agent silently.
+ const dl = {
+ guid: params.guid ?? null,
+ suggestedFilename: params.suggestedFilename ?? null,
+ url: params.url ?? null,
+ state: "inProgress", receivedBytes: 0, totalBytes: null,
+ };
+ if (params.guid) tab.downloads.set(params.guid, dl);
+ data = { ...dl };
+ } else if (method === "Page.downloadProgress") {
+ const dl = params.guid ? (tab.downloads.get(params.guid) ?? { guid: params.guid, suggestedFilename: null, url: null }) : null;
+ if (dl) {
+ if (typeof params.state === "string") dl.state = params.state;
+ if (Number.isFinite(params.receivedBytes)) dl.receivedBytes = params.receivedBytes;
+ if (Number.isFinite(params.totalBytes)) dl.totalBytes = params.totalBytes;
+ tab.downloads.set(params.guid, dl);
+ }
+ data = { guid: params.guid ?? null, state: dl?.state ?? params.state ?? null, receivedBytes: dl?.receivedBytes ?? null, totalBytes: dl?.totalBytes ?? null };
+ }
+ tab.eventSeq += 1;
+ tab.events.push({ sequence: tab.eventSeq, method, ...(frame ? { frame } : {}), data });
+ if (tab.events.length > EVENT_RING_MAX) tab.events.splice(0, tab.events.length - EVENT_RING_MAX);
+ }
+
+ async navigateInTab(tab, url, settleMs = 300) {
+ let res;
+ try {
+ res = await tab.browser.handle.conn.send("Page.navigate", { url }, tab.sessionId);
+ } catch (e) {
+ throw new AxError(Codes.NAVIGATION_IN_PROGRESS, `Navigation to ${url} failed: ${e.message}`,
+ { hint: "Check the URL; ax_observe to see current state.", retry: "never" });
+ }
+ if (res && res.errorText) {
+ throw new AxError(Codes.NAVIGATION_IN_PROGRESS, `Navigation error: ${res.errorText} (${url})`,
+ { hint: "The tab may be blocked by the network or bot detection. Observe to inspect.", retry: "never" });
+ }
+ tab.url = url;
+ tab.lastSnapshot = null; // refs died with the old document
+ await this.settle(tab, 4000, settleMs);
+ }
+
+ async $navigate(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ this.checkDialog(tab);
+ await this.navigateInTab(tab, String(a.url), a.settle_ms ?? 300);
+ const observation = await this.observation(tab, { mode: "full" });
+ return { tab_id: tab.tabId, observation };
+ }
+
+ async $go(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ this.checkDialog(tab);
+ const delta = a.delta ?? -1;
+ const hist = await tab.browser.handle.conn.send("Page.getNavigationHistory", {}, tab.sessionId);
+ const idx = Math.min(Math.max(hist.currentIndex + delta, 0), hist.entries.length - 1);
+ await tab.browser.handle.conn.send("Page.navigateToHistoryEntry", { entryId: hist.entries[idx].id }, tab.sessionId);
+ tab.lastSnapshot = null;
+ await this.settle(tab, 4000, 300);
+ const observation = await this.observation(tab, { mode: "full" });
+ return { tab_id: tab.tabId, observation };
+ }
+
+ async $tabs() {
+ const out = [];
+ for (const [tabId, tab] of this.tabs) {
+ out.push({
+ tab_id: tabId,
+ browser_id: tab.browserId,
+ url: tab.url,
+ title: tab.lastSnapshot?.title ?? tab.title,
+ state_id: tab.stateId,
+ frames: tab.frames.size, // OOPIF frames merged under f-slot refs
+ // Frame sessions (for plugin cdp(sessionId) routing — R2 plumbing):
+ frame_sessions: [...tab.frames.values()].map((f) => ({ frame: `f${f.slot}`, url: f.url, session_id: f.sessionId })),
+ // Live downloads (R1): guid-keyed, for downloads-pdf adoption.
+ downloads: [...tab.downloads.values()].map(({ guid, suggestedFilename, url, state, receivedBytes, totalBytes }) => ({ guid, suggested_filename: suggestedFilename, url, state, received_bytes: receivedBytes, total_bytes: totalBytes })),
+ ...(tab.dialog ? { dialog: tab.dialog } : {}),
+ });
+ }
+ return { tabs: out, active_tab_id: this.activeTabId };
+ }
+
+ async $observe(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ if (tab.dialog) {
+ throw new AxError(Codes.DIALOG_OPEN, `A ${tab.dialog.type} dialog is open: "${tab.dialog.message}" — the page is frozen.`,
+ { hint: "Answer it with ax_dialog first.", retry: "retry" });
+ }
+ const mode = a.mode ?? "diff";
+ const maxNodes = Math.min(a.max_nodes ?? 300, 2000);
+ const maxChars = Math.min(a.max_chars ?? 24000, 200000);
+ if (a.find) return { tab_id: tab.tabId, observation: await this.findObservation(tab, a.find) };
+ const observation = await this.observation(tab, { mode, maxNodes, maxChars });
+ return { tab_id: tab.tabId, observation };
+ }
+
+ /**
+ * Grep the (large-budget) snapshot for `needle`: matching lines plus a
+ * little context, refs intact. The snapshot becomes the diff baseline, so
+ * later actions still return proper diffs.
+ */
+ async findObservation(tab, needle, { before = 2, after = 3, maxHits = 12 } = {}) {
+ const obs = await this.observation(tab, { mode: "full", maxNodes: 2000, maxChars: 200000 });
+ const lines = obs.text.split("\n");
+ const head = lines.slice(0, 3);
+ const body = lines.slice(3);
+ const n = String(needle).toLowerCase();
+ const keep = new Set();
+ let hits = 0;
+ body.forEach((l, i) => {
+ if (hits >= maxHits || !l.toLowerCase().includes(n)) return;
+ hits++;
+ for (let k = Math.max(0, i - before); k <= Math.min(body.length - 1, i + after); k++) keep.add(k);
+ });
+ const out = [];
+ let last = -2;
+ for (const i of [...keep].sort((x, y) => x - y)) {
+ if (i !== last + 1 && out.length) out.push(" …");
+ out.push(body[i]);
+ last = i;
+ }
+ const text = [...head, `find "${needle}": ${hits ? `${hits} match${hits > 1 ? "es" : ""}` : "no matches"} (of ${body.length} lines)`, ...out].join("\n");
+ return { ...obs, mode: "find", text };
+ }
+
+ async $click(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ this.checkDialog(tab);
+ this.checkStale(tab, a);
+ const pos = await this.resolveTarget(tab, a.target);
+ await this.doSent(tab, () => doClick(this.ctx(tab, pos.session), {
+ x: pos.x, y: pos.y,
+ button: a.button ?? "left",
+ count: a.count ?? 1,
+ modifiers: this.modifierMask(a.modifiers),
+ }));
+ const observation = await this.autoObserve(tab, a.settle_ms ?? 150);
+ const popup = await this.popupReport(tab);
+ const noChange = typeof observation?.text === "string" && observation.text.startsWith("no changes detected");
+ return {
+ action_sent: "sent",
+ ...(tab.fileChooser ? { tab_note: "The click opened a file chooser — answer it with ax_upload {paths:[...]} (no ref needed)." } : {}),
+ ...(pos.frame ? { frame: pos.frame } : {}),
+ ...(pos.covered ? { note: `Target center is covered by a ${pos.hitTag ?? "element"} — the click landed on the overlay. Verify with the observation diff and re-plan if wrong.` } : {}),
+ ...(noChange && !tab.fileChooser && !popup ? {
+ note: "No observable change. If the page was still settling (SPA/framework wiring listeners after load), one retry click is reasonable; otherwise the element may be a no-op in this state (e.g. an already-selected tab).",
+ } : {}),
+ observation,
+ ...(popup ?? {}),
+ };
+ }
+
+ async $fill(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ this.checkDialog(tab);
+ this.checkStale(tab, a);
+ const done = [];
+ const fail = (i, f, msg, extraHint) => {
+ throw new AxError(Codes.COMMAND_REJECTED, `fill: field ${i + 1} (${f.ref}) ${msg}. Filled before it: ${done.join(", ") || "none"}.`,
+ { hint: [extraHint, "Fix that field (re-observe if the ref is gone) and call ax_fill again with the remaining fields."].filter(Boolean).join(" "), retry: "reobserve" });
+ };
+ const clickRef = async (r) => {
+ const pos = await this.resolveTarget(tab, { ref: r });
+ await this.doSent(tab, () => doClick(this.ctx(tab, pos.session), { x: pos.x, y: pos.y, button: "left", count: 1, modifiers: 0 }));
+ };
+ for (const [i, f] of a.fields.entries()) {
+ if (tab.dialog) fail(i, f, `was not filled: a ${tab.dialog.type} dialog opened`);
+ const { session, ref } = this.sessionForRef(tab, f.ref);
+ const info = await this.evalInTab(tab, fieldKindExpression(ref), { awaitPromise: false }, session);
+ if (!info || info.error) {
+ const foreign = info?.error === "no_ref" ? await this.foreignFieldHint(tab, f.ref) : null;
+ fail(i, f, info?.error === "no_ref" ? "is gone (stale ref)" : `could not be inspected (${info?.error})`, foreign);
+ }
+ let what = "";
+ if (info.kind === "bool") {
+ const want = f.value === true || ["true", "on", "checked", "yes"].includes(String(f.value).toLowerCase());
+ if (info.on !== want) await clickRef(f.ref);
+ what = info.on !== want ? (want ? "checked" : "unchecked") : `already ${want ? "checked" : "unchecked"}`;
+ } else if (info.kind === "select") {
+ const res = await this.evalInTab(tab, selectOptionExpression(ref, String(f.value)), { awaitPromise: false }, session);
+ if (!res || res.error) fail(i, f, `has no option "${f.value}" (options: ${(res?.options ?? []).join(", ")})`);
+ what = `selected "${f.value}"`;
+ } else if (info.kind === "popup") {
+ await clickRef(f.ref);
+ let opt = null;
+ for (let k = 0; k < 10 && !opt?.ok; k++) {
+ await new Promise((ok) => setTimeout(ok, 100));
+ opt = await this.evalInTab(tab, findOptionExpression(f.value), { awaitPromise: false }, session);
+ }
+ if (!opt?.ok) fail(i, f, `opened but has no option "${f.value}" (visible: ${(opt?.visible ?? []).join(", ")})`);
+ await clickRef(opt.ref);
+ what = `opened, picked option "${opt.text}"`;
+ } else if (info.kind === "slider") {
+ what = await this.fillSlider(tab, f, { session, ref, clickRef, fail: (msg, hint) => fail(i, f, msg, hint) });
+ } else if (info.kind === "text" || info.kind === "combo") {
+ await clickRef(f.ref);
+ const ctx = this.ctx(tab, session);
+ await this.doSent(tab, () => pressCombo(ctx, selectAllCombo()));
+ await this.doSent(tab, () => insertText(ctx, String(f.value)));
+ if (info.kind === "combo") {
+ // Autocomplete: wait for suggestions, pick the exact match.
+ let opt = null;
+ for (let k = 0; k < 12 && !opt?.ok; k++) {
+ await new Promise((ok) => setTimeout(ok, 150));
+ opt = await this.evalInTab(tab, findOptionExpression(f.value), { awaitPromise: false }, session);
+ }
+ if (opt?.ok) await clickRef(opt.ref);
+ what = opt?.ok ? `typed "${f.value}", picked suggestion "${opt.text}"` : `typed "${f.value}" (no matching suggestion appeared)`;
+ } else what = `typed "${f.value}"`;
+ } else {
+ const foreign = await this.foreignFieldHint(tab, f.ref);
+ const desc = info.kind === "other" ? `${info.tag ?? "element"}${info.role ? `[role=${info.role}]` : ""}` : "element";
+ fail(i, f, `is not a form field on tab ${tab.tabId} — it is a ${desc} here (use ax_click / ax_type)`, foreign);
+ }
+ done.push(`${f.ref} ${what}`);
+ }
+ let submitted = false;
+ if (a.submit && !tab.dialog) {
+ await clickRef(a.submit);
+ submitted = true;
+ }
+ const observation = await this.autoObserve(tab, a.settle_ms ?? 200);
+ return { action_sent: "sent", filled: done, ...(submitted ? { submitted: a.submit } : {}), observation, ...((await this.popupReport(tab)) ?? {}) };
+ }
+
+ /** Set an ARIA/native slider to a numeric value with trusted keyboard
+ * input only (ArrowUp/ArrowDown; no synthetic value writes). Step is
+ * discovered empirically with one key press; convergence is capped and
+ * verified after every press, so a clamped handle (the other end of a
+ * range pair) stops the loop honestly instead of spinning. */
+ async fillSlider(tab, f, { session, ref, clickRef, fail }) {
+ const target = Number(f.value);
+ if (!Number.isFinite(target)) fail(`wants a number for a slider (got ${JSON.stringify(String(f.value))})`);
+ await clickRef(f.ref); // focus the handle / native track
+ const readNow = async () => {
+ const r = await this.evalInTab(tab, sliderValueExpression(ref), { awaitPromise: false }, session);
+ return r && !r.error ? r.now : null;
+ };
+ let now = await readNow();
+ if (now === null) fail("has no readable slider value (aria-valuenow / value missing)");
+ if (Math.abs(now - target) < 1e-9) return `already at ${now}`;
+ const ctx = this.ctx(tab, session);
+ const key = target > now ? "up" : "down";
+ const prev = now;
+ await this.doSent(tab, () => pressCombo(ctx, key));
+ now = (await readNow()) ?? prev;
+ if (Math.abs(now - prev) < 1e-9) {
+ fail(`did not respond to trusted keyboard ${key} — this widget needs pointer dragging; set it with ax_evaluate`,
+ "The click focused it, but the value did not move one step.");
+ }
+ const step = Math.abs(now - prev);
+ let presses = 1;
+ while (Math.abs(target - now) >= step - 1e-9 && presses++ < 500) {
+ await this.doSent(tab, () => pressCombo(ctx, key));
+ const next = (await readNow()) ?? now;
+ if (Math.abs(next - now) < 1e-9) break; // clamped (e.g. by the other handle of a range pair)
+ now = next;
+ }
+ if (Math.abs(target - now) > step / 2 + 1e-9) {
+ fail(`stopped at ${now} (target ${target}, step ${step}) — clamped or uneven stepping`,
+ "The nearest reachable value was kept; finish exactly with ax_evaluate if the widget supports scripting.");
+ }
+ return `set to ${now} (from ${prev}, step ${step}, ${presses} trusted key presses)`;
+ }
+
+ /** Refs are per-tab (every page numbers its own e1, e2, …). When a fill
+ * misses right after a tab switch, the caller almost certainly observed
+ * one tab and is acting on another — check the other controlled tabs and
+ * name the one where this ref IS a fillable field. */
+ async foreignFieldHint(activeTab, ref) {
+ const FILLABLE = new Set(["bool", "select", "popup", "combo", "text", "slider"]);
+ const hits = [];
+ for (const [id, t] of this.tabs) {
+ if (id === activeTab.tabId || !t.sessionId) continue;
+ try {
+ const info = await this.evalInTab(t, fieldKindExpression(ref), { awaitPromise: false });
+ if (info && !info.error && FILLABLE.has(info.kind)) {
+ hits.push(`${id} (${info.kind}, ${String(t.url).slice(0, 60)})`);
+ }
+ } catch { /* tab navigating or closed — not a candidate */ }
+ }
+ if (!hits.length) return null;
+ return `Ref "${ref}" is a fillable field on ${hits.join(", ")} — pass that tab_id if that is the field you meant.`;
+ }
+
+ async $upload(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ this.checkDialog(tab);
+ const { existsSync } = await import("node:fs");
+ const { resolve } = await import("node:path");
+ const files = a.paths.map((p) => resolve(p));
+ const missing = files.filter((f) => !existsSync(f));
+ if (missing.length) throw new AxError(Codes.COMMAND_REJECTED, `upload: file not found: ${missing.join(", ")}`, { retry: "never" });
+ const conn = tab.browser.handle.conn;
+ if (a.ref) {
+ const { session, ref } = this.sessionForRef(tab, a.ref);
+ const ev = await conn.send("Runtime.evaluate", { expression: `(window.__axuseRefs||{})[${JSON.stringify(ref)}]`, returnByValue: false }, session);
+ const objectId = ev?.result?.objectId;
+ if (!objectId) throw new AxError(Codes.REF_NOT_FOUND, `ref "${a.ref}" is gone.`, { hint: "Call ax_observe, then retry.", retry: "reobserve" });
+ await conn.send("DOM.setFileInputFiles", { files, objectId }, session);
+ } else if (tab.fileChooser) {
+ await conn.send("DOM.setFileInputFiles", { files, backendNodeId: tab.fileChooser.backendNodeId }, tab.sessionId);
+ } else {
+ throw new AxError(Codes.COMMAND_REJECTED, "upload: pass the ref of the file input (or click it first to open a file chooser).", { retry: "never" });
+ }
+ tab.fileChooser = null;
+ return { action_sent: "sent", uploaded: files.map((f) => f.split(/[\\/]/).pop()), observation: await this.autoObserve(tab, a.settle_ms ?? 150) };
+ }
+
+ async $hover(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ this.checkDialog(tab);
+ this.checkStale(tab, a);
+ const pos = await this.resolveTarget(tab, a.target);
+ await this.doSent(tab, () => doHover(this.ctx(tab, pos.session), pos));
+ return { action_sent: "sent", ...(pos.frame ? { frame: pos.frame } : {}), observation: await this.autoObserve(tab, a.settle_ms ?? 150) };
+ }
+
+ async $type(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ this.checkDialog(tab);
+ this.checkStale(tab, a);
+ const pos = a.target ? await this.resolveTarget(tab, a.target) : null;
+ const session = pos?.session;
+ if (pos) {
+ await this.doSent(tab, () => doClick(this.ctx(tab, session), { x: pos.x, y: pos.y, button: "left", count: 1, modifiers: 0 }));
+ }
+ if (a.replace !== false) {
+ await this.doSent(tab, () => pressCombo(this.ctx(tab, session), selectAllCombo()));
+ }
+ await this.doSent(tab, () => insertText(this.ctx(tab, session), String(a.text)));
+ if (a.submit) {
+ await this.doSent(tab, () => pressCombo(this.ctx(tab, session), "enter"));
+ }
+ return { action_sent: "sent", ...(pos?.frame ? { frame: pos.frame } : {}), observation: await this.autoObserve(tab, a.settle_ms ?? 150) };
+ }
+
+ async $press(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ this.checkDialog(tab);
+ const combo = a.platform ? platformShortcut(a.combo) : a.combo;
+ await this.doSent(tab, () => pressCombo(this.ctx(tab), combo));
+ const observation = await this.autoObserve(tab, a.settle_ms ?? 150);
+ return { action_sent: "sent", ...(combo !== a.combo ? { combo_sent: combo } : {}), observation, ...((await this.popupReport(tab)) ?? {}) };
+ }
+
+ async $scroll(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ this.checkDialog(tab);
+ const amount = a.amount ?? 1;
+ let dx = a.dx ?? 0;
+ let dy = a.dy ?? 0;
+ if (a.direction) {
+ const px = amount * 400;
+ if (a.direction === "up") dy = -px;
+ else if (a.direction === "down") dy = px;
+ else if (a.direction === "left") dx = -px;
+ else if (a.direction === "right") dx = px;
+ }
+ if (a.until) return this.scrollUntil(tab, a);
+ if (!dx && !dy) throw new AxError(Codes.COMMAND_REJECTED, "scroll: pass direction/amount or dx/dy", { retry: "never" });
+ let x, y, session;
+ if (a.target) {
+ const pos = await this.resolveTarget(tab, a.target);
+ x = pos.x; y = pos.y; session = pos.session;
+ } else {
+ const vp = await this.evalInTab(tab, `({ w: innerWidth, h: innerHeight })`);
+ x = vp.w / 2; y = vp.h / 2;
+ }
+ await this.doSent(tab, () => doWheel(this.ctx(tab, session), { x, y, dx, dy }));
+ return { action_sent: "sent", observation: await this.autoObserve(tab, a.settle_ms ?? 150) };
+ }
+
+ /** Scroll (trusted wheel input) until `until` text exists in the page or
+ * the page stops growing; bounded. Infinite feeds load as we go. */
+ /**
+ * Scroll until `until` text is in the DOM, in ONE page-side loop. Works on
+ * the window AND on inner scroll containers (virtualized grids, chat panes,
+ * feeds in a div): scrollers are tried largest-first (or the target's own
+ * scroller). Lazy lists get time to load at the end; bounded at 35 s.
+ */
+ async scrollUntil(tab, a) {
+ const needle = String(a.until);
+ let session;
+ let targetExpr = "null";
+ if (a.target?.ref) {
+ const r = this.sessionForRef(tab, a.target.ref);
+ session = r.session;
+ targetExpr = `(window.__axuseRefs||{})[${JSON.stringify(r.ref)}]`;
+ }
+ const expr = `(async function(){
+ var n = ${JSON.stringify(needle.toLowerCase())}, up = ${a.direction === "up"};
+ function has(r){ if ((r.innerText || r.textContent || "").toLowerCase().indexOf(n) >= 0) return true;
+ var all = r.querySelectorAll("*"); for (var i = 0; i < all.length; i++) if (all[i].shadowRoot && has(all[i].shadowRoot)) return true; return false; }
+ function scrollable(el){ var cs = getComputedStyle(el); return /(auto|scroll|overlay)/.test(cs.overflowY) && el.scrollHeight > el.clientHeight + 20 && el.clientHeight > 40; }
+ var scrollers = [];
+ var t = ${targetExpr};
+ for (var e = t; e && e !== document.body; e = e.parentElement) if (scrollable(e)) { scrollers.push(e); break; }
+ var se = document.scrollingElement || document.documentElement;
+ if (se.scrollHeight > innerHeight + 20) scrollers.push(se);
+ var cands = Array.prototype.filter.call(document.querySelectorAll("*"), function(el){ return el !== se && scrollable(el) && el.getBoundingClientRect().width > 0; });
+ cands.sort(function(x, y){ return y.clientWidth * y.clientHeight - x.clientWidth * x.clientHeight; });
+ scrollers = scrollers.concat(cands.slice(0, 4));
+ var sleep = function(ms){ return new Promise(function(ok){ setTimeout(ok, ms); }); };
+ var steps = 0, t0 = Date.now();
+ if (has(document.body)) return { found: true, steps: 0, where: "already on the page" };
+ for (var s = 0; s < scrollers.length; s++) {
+ var el = scrollers[s], stuck = 0;
+ while (Date.now() - t0 < 35000 && steps < 400) {
+ var before = el.scrollTop, h = el.scrollHeight;
+ var page = (el === se ? innerHeight : el.clientHeight) * 0.85;
+ el.scrollTop = before + (up ? -page : page);
+ steps++;
+ await sleep(stuck ? 400 : 90);
+ if (has(document.body)) return { found: true, steps: steps, where: el === se ? "page" : (el.getAttribute("aria-label") || el.id || el.tagName.toLowerCase()) };
+ if (el.scrollTop === before && el.scrollHeight === h) { if (++stuck >= 5) break; } else stuck = 0;
+ }
+ }
+ return { found: false, steps: steps, scrollers: scrollers.length, timedOut: Date.now() - t0 >= 35000 };
+ })()`;
+ const st = await this.raceDialog(tab, this.evalInTab(tab, expr, { awaitPromise: true }, session)) ?? {};
+ if (st.found) {
+ // Center the first match in its own scroller.
+ await this.evalInTab(tab, `(function(){var n=${JSON.stringify(needle.toLowerCase())};var w=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);var t;while((t=w.nextNode()))if(t.nodeValue.toLowerCase().indexOf(n)>=0){t.parentElement.scrollIntoView({block:"center"});return true}return false})()`, {}, session).catch(() => null);
+ await new Promise((ok) => setTimeout(ok, 150));
+ }
+ const observation = await this.findObservation(tab, needle);
+ const how = st.found ? `found after ${st.steps} scroll step${st.steps === 1 ? "" : "s"} (${st.where})` : st.timedOut ? "NOT found — gave up after 35 s" : `NOT found — scrolled ${st.steps} steps to the end of ${st.scrollers ?? 0} scrollable area(s)`;
+ observation.text = `${how}\n` + observation.text;
+ return { action_sent: "sent", observation };
+ }
+
+ async $select(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ this.checkDialog(tab);
+ this.checkStale(tab, a);
+ const { session, ref } = this.sessionForRef(tab, a.ref);
+ const res = await this.evalInTab(tab, selectOptionExpression(ref, a.value), { awaitPromise: false }, session);
+ if (!res || res.error) {
+ if (res?.error === "no_ref") {
+ throw new AxError(Codes.REF_NOT_FOUND, `ref "${a.ref}" is gone.`, { hint: "Call ax_observe, then re-select.", retry: "reobserve" });
+ }
+ throw new AxError(Codes.COMMAND_REJECTED, `Option "${a.value}" not found. Available: ${(res?.options ?? []).join(", ")}`, { retry: "never" });
+ }
+ return { action_sent: "sent", value: res.value, observation: await this.autoObserve(tab, a.settle_ms ?? 150) };
+ }
+
+ async $drag(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ this.checkDialog(tab);
+ this.checkStale(tab, a);
+ const from = await this.resolveTarget(tab, a.from);
+ const to = await this.resolveTarget(tab, a.to);
+ await this.doSent(tab, () => doDrag(this.ctx(tab, from.session), { x: from.x, y: from.y }, { x: to.x, y: to.y }, a.steps ?? 12));
+ return { action_sent: "sent", observation: await this.autoObserve(tab, a.settle_ms ?? 150) };
+ }
+
+ async $screenshot(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ this.checkDialog(tab);
+ const shot = await captureScreenshot(tab.browser.handle.conn, tab.sessionId, {
+ crop: a.crop,
+ budgetBytes: a.budget_bytes ?? DEFAULT_BUDGET_BYTES,
+ quality: a.quality ?? 80,
+ });
+ return { image: { base64: shot.base64, mime: shot.mime, bytes: shot.bytes, budget_bytes: shot.budget_bytes, quality: shot.quality }, note: shot.geometry };
+ }
+
+ async $element_info(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ const res = await this.evalInTab(tab, elementInfoExpression(a.x, a.y), { awaitPromise: false });
+ if (!res || res.ok === false) {
+ return { hit: null, hint: "Nothing actionable at that point — check coordinates against the latest screenshot." };
+ }
+ return { hit: { ref: res.ref, tag: res.tag, role: res.role, name: res.name, rect: res.rect, actionable: res.actionable } };
+ }
+
+ async $evaluate(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ this.checkDialog(tab);
+ const value = await this.evalInTab(tab, a.expression, { awaitPromise: true });
+ let json;
+ try {
+ json = JSON.stringify(value ?? null);
+ } catch {
+ json = String(value);
+ }
+ if (json === undefined) json = "undefined";
+ const truncated = json.length > MAX_EVAL_CHARS;
+ return { value: truncated ? json.slice(0, MAX_EVAL_CHARS) + "…[truncated]" : json, truncated };
+ }
+
+ async $wait_for(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ this.checkDialog(tab);
+ const timeoutMs = Math.min(a.timeout_ms ?? 3000, 25000);
+ let expr = a.expression;
+ if (a.selector) {
+ const sel = JSON.stringify(a.selector);
+ expr = `(function(){var e=document.querySelector(${sel});return !!e && e.getBoundingClientRect().height>0;})()`;
+ }
+ if (a.text) {
+ const t = JSON.stringify(String(a.text).toLowerCase());
+ expr = `(document.body.innerText||"").toLowerCase().indexOf(${t})>=0`;
+ }
+ if (!expr) throw new AxError(Codes.COMMAND_REJECTED, "wait_for: pass selector, text or expression", { retry: "never" });
+ const res = await this.raceDialog(tab, this.evalInTab(tab, waitForExpression(expr, timeoutMs), { awaitPromise: true }));
+ const ok = !!res?.ok;
+ // On success hand back what changed — saves the usual follow-up observe.
+ return { ok, timeout: !!res?.timeout, elapsed_ms: res?.elapsed ?? null, ...(ok ? { observation: await this.autoObserve(tab, 100) } : {}) };
+ }
+
+ async $events(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ const after = a.after_sequence ?? 0;
+ const limit = Math.min(a.limit ?? 50, 1000);
+ const events = tab.events.filter((e) => e.sequence > after).slice(0, limit);
+ return {
+ events,
+ cursor: tab.eventSeq,
+ has_more: tab.events.filter((e) => e.sequence > after).length > events.length,
+ note: "Sequenced ring buffer (max 1000). Poll with after_sequence=cursor.",
+ };
+ }
+
+ async $dialog(a) {
+ const tab = this.tabOrActive(a.tab_id);
+ if (!a.answer) {
+ return { dialog: tab.dialog ?? null };
+ }
+ if (!tab.dialog) throw new AxError(Codes.COMMAND_REJECTED, "No dialog is open.", { retry: "never" });
+ const answered = tab.dialog;
+ await tab.browser.handle.conn.send("Page.handleJavaScriptDialog",
+ { accept: a.answer === "accept", ...(a.prompt_text !== undefined ? { promptText: String(a.prompt_text) } : {}) }, tab.sessionId);
+ // A follow-up dialog (confirm → prompt) may already be open: keep it.
+ if (tab.dialog === answered) tab.dialog = null;
+ return { answered: a.answer, observation: await this.autoObserve(tab, 150) };
+ }
+
+ async $close(a) {
+ if (a.browser) {
+ const count = this.browsers.size;
+ await this.dispose();
+ return { closed: { browsers: count } };
+ }
+ const tab = this.tabOrActive(a.tab_id);
+ this.deregisterTab(tab);
+ await tab.browser.handle.closeTabTarget(tab.targetId);
+ return { closed: { tab_id: tab.tabId } };
+ }
+
+ deregisterTab(tab) {
+ tab.closed = true;
+ if (tab.offEventRouting) { try { tab.offEventRouting(); } catch {} }
+ this.tabs.delete(tab.tabId);
+ tab.browser.tabs.delete(tab.tabId);
+ if (this.activeTabId === tab.tabId) {
+ // Newest remaining tab becomes active (ZCode: scope-selected tab).
+ this.activeTabId = this.tabs.size ? [...this.tabs.keys()].pop() : null;
+ }
+ }
+
+ /**
+ * Input context whose sends are dialog-aware: a click that opens
+ * alert/confirm/prompt makes CDP's Input.dispatch* block until the dialog
+ * is answered. Race every send against the dialog event, and never queue
+ * further input behind an open dialog (it would land after the answer).
+ */
+ ctx(tab, session) {
+ const conn = tab.browser.handle.conn;
+ return {
+ sessionId: session ?? tab.sessionId,
+ conn: { send: (method, params, sid) => (tab.dialog ? Promise.resolve({ skipped: "dialog_open" }) : this.raceDialog(tab, conn.send(method, params, sid))) },
+ };
+ }
+
+ raceDialog(tab, promise) {
+ return new Promise((resolve, reject) => {
+ let done = false;
+ const finish = (fn, v) => { if (done) return; done = true; clearInterval(iv); fn(v); };
+ const iv = setInterval(() => { if (tab.dialog) { promise.catch(() => {}); finish(resolve, { dialog_opened: true }); } }, 20);
+ promise.then((v) => finish(resolve, v), (e) => finish(reject, e));
+ });
+ }
+
+ dialogNote(tab) {
+ return {
+ dialog: tab.dialog,
+ hint: `The action opened a JS ${tab.dialog.type} dialog — the page is frozen until you answer it with ax_dialog (answer: accept|dismiss${tab.dialog.type === "prompt" ? ", prompt_text" : ""}).`,
+ };
+ }
+
+ /**
+ * Side-effect accounting (ZCode's actionSent): a CDP timeout after dispatch
+ * means the input MAY have landed — report `possibly_sent`, not a clean no.
+ */
+ async doSent(tab, fn) {
+ try {
+ return await fn();
+ } catch (e) {
+ if (e instanceof AxError && (e.code === Codes.TIMEOUT || e.code === Codes.ATTACH_FAILED)) {
+ throw new AxError(e.code, e.message, { ...e, sideEffect: "uncertain" });
+ }
+ throw e;
+ }
+ }
+
+ async dispose() {
+ const all = [...this.browsers.values()];
+ this.browsers.clear();
+ this.browserIndex?.clear();
+ this.tabs.clear();
+ this.activeTabId = null;
+ await Promise.all(all.map((b) => Promise.resolve(b.handle.dispose()).catch(() => {})));
+ }
+}
+
+// Re-export for the MCP layer.
+export { MOD };
diff --git a/src/core/diff.js b/src/core/diff.js
new file mode 100644
index 0000000..7d87c38
--- /dev/null
+++ b/src/core/diff.js
@@ -0,0 +1,122 @@
+/**
+ * axuse — snapshot differ.
+ *
+ * Lineage: Codex's page-state diffing (`disable_diffing` flag → default is
+ * diff-on; the model learns "what changed", not the whole page again) and
+ * ZCode's diffed AX trees ("the tree comes back as a diff only against a
+ * tree this cell already showed you… unchanged rows are omitted and their
+ * indices stay valid").
+ *
+ * The diff is computed over per-ref entries, so unchanged refs keep their
+ * identity across observations — an agent can plan "click e7" after a diff
+ * without re-reading the whole tree.
+ */
+
+/**
+ * @typedef {{ref: string, line: string}} Entry
+ * @typedef {{stateId: number, entries: Entry[], textLines?: string[], url: string, title: string, truncated: boolean, text?: string}} Snapshot
+ */
+
+const TEXT_DIFF_CAP = 40; // per direction — beyond this a full snapshot is clearer than a partial diff
+
+function multisetDiff(prevLines = [], nextLines = []) {
+ const prev = new Map();
+ for (const l of prevLines) prev.set(l, (prev.get(l) ?? 0) + 1);
+ const next = new Map();
+ for (const l of nextLines) next.set(l, (next.get(l) ?? 0) + 1);
+ const added = [];
+ let capped = false;
+ for (const [l, c] of next) {
+ const d = c - (prev.get(l) ?? 0);
+ for (let i = 0; i < d; i++) {
+ if (added.length >= TEXT_DIFF_CAP) { capped = true; break; }
+ added.push(l);
+ }
+ }
+ const removed = [];
+ for (const [l, c] of prev) {
+ const d = c - (next.get(l) ?? 0);
+ for (let i = 0; i < d; i++) {
+ if (removed.length >= TEXT_DIFF_CAP) { capped = true; break; }
+ removed.push(l);
+ }
+ }
+ return { added, removed, capped };
+}
+
+/**
+ * @param {Snapshot} prev previous stored snapshot
+ * @param {Snapshot} next the fresh one
+ * @returns {{mode: "diff"|"full", text: string, removed: Entry[], added: Entry[], changed: {ref: string, was: string, now: string}[], nextEntries: Entry[]}}
+ */
+export function diffSnapshots(prev, next) {
+ const empty = (s) => !s || ((!s.entries || !s.entries.length) && !(s.textLines || []).length);
+ if (empty(prev) || empty(next)) {
+ return { mode: "full", text: null, removed: [], added: [], changed: [], textAdded: [], textRemoved: [], nextEntries: next?.entries ?? [] };
+ }
+ const prevBy = new Map(prev.entries.map((e) => [e.ref, e]));
+ const nextBy = new Map(next.entries.map((e) => [e.ref, e]));
+ const removed = [];
+ const added = [];
+ const changed = [];
+ for (const [ref, e] of prevBy) {
+ const nx = nextBy.get(ref);
+ if (!nx) removed.push(e);
+ else if (nx.line !== e.line) changed.push({ ref, was: e.line, now: nx.line });
+ }
+ for (const [ref, e] of nextBy) {
+ if (!prevBy.has(ref)) added.push(e);
+ }
+ const out = [];
+ out.push(`url: ${prev.url === next.url ? next.url : prev.url + " → " + next.url}`);
+ out.push(`title: ${prev.title === next.title ? next.title : '"' + prev.title + '" → "' + next.title + '"'}`);
+ out.push(`entries: ${prev.entries.length} → ${next.entries.length} (removed ${removed.length}, added ${added.length}, changed ${changed.length})`);
+ if (next.truncated) out.push("note: snapshot truncated by budget — pass max_nodes/max_chars or observe sections");
+ if (removed.length) {
+ out.push("removed:");
+ for (const e of removed) out.push(` - ${e.line}`);
+ }
+ if (added.length) {
+ out.push("added:");
+ for (const e of added) out.push(` + ${e.line}`);
+ }
+ if (changed.length) {
+ out.push("changed:");
+ // Only the new state: the old line rarely matters and doubles the cost.
+ for (const c of changed) out.push(` ~ ${c.now.trimStart()}`);
+ }
+ // Text lines (anonymous, no ref) diff by multiset — text changes are
+ // observable even when no ref'd element changed.
+ const textDiff = multisetDiff(prev.textLines, next.textLines);
+ if (textDiff.removed.length) {
+ out.push("text removed:");
+ for (const l of textDiff.removed) out.push(` - ${l}`);
+ }
+ if (textDiff.added.length) {
+ out.push("text added:");
+ for (const l of textDiff.added) out.push(` + ${l}`);
+ }
+ // Full-fallback is a COST decision, not a count decision: on big trees,
+ // when rendering the diff costs nearly as much as the full snapshot
+ // (navigation / full re-render), return the full tree instead. On small
+ // trees the diff is always cheaper AND preserves per-ref addressing.
+ // A capped text diff would silently drop content (pagination, feed
+ // reloads): the full snapshot is the honest answer.
+ if (textDiff.capped) {
+ return { mode: "full", text: null, removed, added, changed, textAdded: textDiff.added, textRemoved: textDiff.removed, nextEntries: next.entries };
+ }
+ if (next.entries.length >= 20) {
+ const diffLen = out.join("\n").length;
+ const fullLen = Math.max(1, (next.text ?? "").length);
+ if (diffLen >= 0.8 * fullLen) {
+ return { mode: "full", text: null, removed, added, changed, textAdded: textDiff.added, textRemoved: textDiff.removed, nextEntries: next.entries };
+ }
+ }
+ const text = out.join("\n");
+ return { mode: "diff", text, removed, added, changed, textAdded: textDiff.added, textRemoved: textDiff.removed, nextEntries: next.entries };
+}
+
+/** Render "no changes" — the agent should NOT re-observe in a loop. */
+export function noChangeText(prev, next) {
+ return `no changes detected (state ${prev.stateId} → ${next.stateId}, ${next.entries.length} entries stable)`;
+}
diff --git a/src/core/errors.js b/src/core/errors.js
new file mode 100644
index 0000000..c5ba265
--- /dev/null
+++ b/src/core/errors.js
@@ -0,0 +1,79 @@
+/**
+ * axuse — typed error model.
+ *
+ * Lineage: ZCode's typed CUA errors (STALE_STATE / ELEMENT_UNAVAILABLE /
+ * sideEffect:"none"|"uncertain" / actionSent / retry hints). A blind
+ * `throw new Error(...)` loses exactly the information an agent loop needs
+ * to decide "retry, re-observe, or give up" — so every failure here is a
+ * structured fact, not a string.
+ */
+
+/** Error codes are a frozen vocabulary shared by core, MCP layer and docs. */
+export const Codes = Object.freeze({
+ COMMAND_REJECTED: "COMMAND_REJECTED", // bad params — fix the call, do not retry as-is
+ LAUNCH_FAILED: "LAUNCH_FAILED",
+ ATTACH_FAILED: "ATTACH_FAILED",
+ NO_BROWSER: "NO_BROWSER", // nothing open yet → ax_open first
+ NO_TAB: "NO_TAB",
+ REF_NOT_FOUND: "REF_NOT_FOUND", // ref is from a stale observation → re-observe
+ STALE_STATE: "STALE_STATE", // caller state_id predates current page state → re-observe
+ ELEMENT_HIDDEN: "ELEMENT_HIDDEN",
+ BAD_COORDS: "BAD_COORDS",
+ DIALOG_OPEN: "DIALOG_OPEN", // a JS dialog is blocking → ax_dialog
+ SCREENSHOT_BUDGET_EXCEEDED: "SCREENSHOT_BUDGET_EXCEEDED",
+ EVALUATE_FAILED: "EVALUATE_FAILED",
+ TIMEOUT: "TIMEOUT",
+ NAVIGATION_IN_PROGRESS: "NAVIGATION_IN_PROGRESS",
+ DESKTOP_DRIVER_UNAVAILABLE: "DESKTOP_DRIVER_UNAVAILABLE",
+ DESKTOP_OP_FAILED: "DESKTOP_OP_FAILED",
+ DESKTOP_PERMISSION_REQUIRED: "DESKTOP_PERMISSION_REQUIRED",
+ PLUGIN_LOAD_FAILED: "PLUGIN_LOAD_FAILED", // a plugin dir failed to load — fix the plugin, not the call
+ NO_SOLVER: "NO_SOLVER", // no loaded plugin solves this provider → install one
+ SOLVER_FAILED: "SOLVER_FAILED", // a solver ran and gave up — see its result facts
+ INTERNAL: "INTERNAL",
+});
+
+/** What the agent should do after a failure. */
+export const Retry = Object.freeze({
+ REOBSERVE: "reobserve", // state changed under you — call ax_observe, then re-plan
+ RETRY: "retry", // same call will likely succeed now
+ NEVER: "never", // fix inputs or give up
+});
+
+/** Whether a side-effecting action definitely reached the page. */
+export const ActionSent = Object.freeze({
+ SENT: "sent",
+ POSSIBLY_SENT: "possibly_sent", // dispatch timed out after send — state unknown
+ NOT_SENT: "not_sent",
+});
+
+export class AxError extends Error {
+ /**
+ * @param {keyof typeof Codes} code
+ * @param {string} message
+ * @param {{hint?: string, retry?: keyof typeof Retry, sideEffect?: "none"|"uncertain"}} [extra]
+ */
+ constructor(code, message, extra = {}) {
+ super(message);
+ this.name = "AxError";
+ this.code = code;
+ this.hint = extra.hint;
+ this.retry = extra.retry;
+ this.sideEffect = extra.sideEffect ?? "none";
+ }
+
+ toJSON() {
+ return {
+ code: this.code,
+ message: this.message,
+ ...(this.hint ? { hint: this.hint } : {}),
+ ...(this.retry ? { retry: this.retry } : {}),
+ side_effect: this.sideEffect,
+ };
+ }
+}
+
+/** Convenience: throw a typed error. */
+export function fail(code, message, extra) {
+ throw new AxError(code, message, extra);
+}
diff --git a/src/core/screenshot.js b/src/core/screenshot.js
new file mode 100644
index 0000000..caa16e2
--- /dev/null
+++ b/src/core/screenshot.js
@@ -0,0 +1,68 @@
+/**
+ * axuse — screenshot capture with hard budgets.
+ *
+ * Lineage: ZCode enforces image budgets at the *protocol* boundary
+ * (max 2 images × 200KB, "one raster per result", downscale guards) instead
+ * of trusting the model to be frugal. Codex treats screenshots as optional,
+ * croppable, explicitly-not-always-available ("screenshot_unavailable").
+ *
+ * Here: one raster per call (by construction), byte budget with automatic
+ * quality fallback, then a typed error with a crop hint. Vision is an
+ * on-demand escape hatch — never the default observation.
+ */
+import { AxError, Codes } from "./errors.js";
+
+export const DEFAULT_BUDGET_BYTES = 200_000; // ~200KB, matches ZCode's cap
+const RETRY_QUALITY = 45;
+
+/** Exact payload size of a base64 string (padding-aware). */
+function approxBytes(b64) {
+ return Buffer.byteLength(Buffer.from(b64, "base64"));
+}
+
+/**
+ * @param {import("./cdp.js").CdpConnection} conn
+ * @param {string} sessionId
+ */
+export async function captureScreenshot(conn, sessionId, { crop, budgetBytes = DEFAULT_BUDGET_BYTES, quality = 80 } = {}) {
+ const base = { format: "jpeg", quality, captureBeyondViewport: false };
+ // Viewport geometry in CSS px. Clips are in document coordinates, so the
+ // scroll offset is added; scale 1 renders at CSS resolution regardless of
+ // devicePixelRatio, keeping image pixels == click coordinates.
+ let vp = { x: 0, y: 0, w: 0, h: 0 };
+ try {
+ const m = await conn.send("Page.getLayoutMetrics", {}, sessionId);
+ const v = m.cssVisualViewport ?? m.visualViewport;
+ vp = { x: v.pageX ?? 0, y: v.pageY ?? 0, w: Math.round(v.clientWidth), h: Math.round(v.clientHeight) };
+ } catch {}
+ let region = { x: 0, y: 0, w: vp.w, h: vp.h };
+ if (crop) {
+ const { x, y, w, h } = crop;
+ for (const [k, v] of Object.entries({ x, y, w, h })) {
+ if (!Number.isFinite(v)) throw new AxError(Codes.BAD_COORDS, `crop.${k} must be a finite number`);
+ }
+ if (w < 1 || h < 1) throw new AxError(Codes.BAD_COORDS, "crop.w and crop.h must be ≥ 1");
+ region = { x, y, w, h };
+ }
+ if (region.w > 0 && region.h > 0) {
+ base.clip = { x: vp.x + region.x, y: vp.y + region.y, width: region.w, height: region.h, scale: 1 };
+ }
+ let res = await conn.send("Page.captureScreenshot", base, sessionId);
+ let bytes = approxBytes(res.data);
+ let usedQuality = quality;
+ if (bytes > budgetBytes) {
+ // One automatic fallback pass, then fail honestly.
+ res = await conn.send("Page.captureScreenshot", { ...base, quality: RETRY_QUALITY }, sessionId);
+ usedQuality = RETRY_QUALITY;
+ bytes = approxBytes(res.data);
+ }
+ if (bytes > budgetBytes) {
+ throw new AxError(Codes.SCREENSHOT_BUDGET_EXCEEDED,
+ `Screenshot is ${bytes} bytes, over the ${budgetBytes} byte budget even at quality ${RETRY_QUALITY}.`,
+ { hint: "Pass crop:{x,y,w,h} to capture just the region you need — or prefer ax_observe (text snapshot) when pixels are not required.", retry: "never" });
+ }
+ const geometry = region.w
+ ? `image ${region.w}x${region.h} = viewport CSS px${crop ? ` (crop at ${region.x},${region.y})` : ""}; pass ax_click {x,y} in these same pixels${crop ? ` + (${region.x},${region.y})` : ""}`
+ : "viewport size unknown";
+ return { base64: res.data, bytes, quality: usedQuality, budget_bytes: budgetBytes, mime: "image/jpeg", geometry };
+}
diff --git a/src/core/serialize.js b/src/core/serialize.js
new file mode 100644
index 0000000..4c46e78
--- /dev/null
+++ b/src/core/serialize.js
@@ -0,0 +1,394 @@
+/**
+ * axuse — page serializer (injected into the page via Runtime.evaluate).
+ *
+ * Lineage: Codex's injected DOM sanitizer (shadow roots, script/style skip,
+ * absolute hrefs, character budgets) + ZCode's ref-addressed snapshot
+ * ("elements[] with ref e1,e2… stored in the page", anonymous containers
+ * flattened, nameless images dropped).
+ *
+ * The snapshot is a compact YAML-ish accessibility tree. Every actionable
+ * element gets a stable ref for this observation cycle. Refs live in the
+ * page (window.__axuseRefs) and are resolved LIVE at action time — if the
+ * layout moved between observe and act, the click still lands on the
+ * element, not on remembered pixels.
+ *
+ * Design rules:
+ * - refs are per-observation: a fresh snapshot replaces the map. Acting on a
+ * ref from an older observation fails with REF_NOT_FOUND → re-observe.
+ * - budgets are enforced here (max_nodes, max_chars), with a truncated flag.
+ * - pixels are never taken here. This is the cheap observation.
+ * - names follow the accessible-name rules that matter in practice
+ * (aria-labelledby → aria-label → <label> → content → placeholder/title),
+ * and STATES are printed (checked/expanded/selected/pressed/disabled/…):
+ * a switch without its on/off state is a coin flip for the model.
+ * - tables print one line per row; paragraphs keep inline link text in the
+ * sentence. Both are cheaper AND easier to read than per-cell lines.
+ */
+
+/**
+ * Runs inside the page. Returns an observation object.
+ * Keep it self-contained and ES2017-ish; it is stringified and evaluated.
+ *
+ * @param {{maxNodes?: number, maxChars?: number, maxText?: number}} [opts]
+ */
+export function pageSerializer(opts) {
+ opts = opts || {};
+ var MAX_NODES = opts.maxNodes || 300;
+ var MAX_CHARS = opts.maxChars || 24000;
+ var MAX_TEXT = opts.maxText || 160;
+ var ROW_TEXT = 400;
+
+ var refs = {}; // ref → live element (CURRENT observation only)
+ window.__axuseRefs = refs; // fresh map per observation (stale refs must die)
+ // Identity registry: a ref is bound to the ELEMENT, not to its ordinal —
+ // so unchanged elements keep their refs across observations and diffs can
+ // safely omit unchanged rows. Insertions mid-tree never re-number.
+ var REG = window.__axuseRefRegistry;
+ if (!REG || !(REG instanceof Map)) { REG = new Map(); window.__axuseRefRegistry = REG; }
+ var regSeq = window.__axuseRefSeq || 0;
+ var lines = [];
+ var entries = []; // {ref, line} — the diffable representation
+ var textLines = []; // raw text/row lines — text participates in diffs
+ var n = 0;
+ var chars = 0;
+ var truncated = false;
+
+ var SKIP = { SCRIPT: 1, STYLE: 1, LINK: 1, META: 1, NOSCRIPT: 1, TEMPLATE: 1, HEAD: 1, TITLE: 1, SVG: 1 };
+ // Elements whose text IS their label (buttons with icon spans, links).
+ var LEAFY = { BUTTON: 1, A: 1, SUMMARY: 1, OPTION: 1, TH: 1, TD: 1, DT: 1, DD: 1, CAPTION: 1, LEGEND: 1, FIGCAPTION: 1, LABEL: 1, MARK: 1, TIME: 1, CODE: 1, ABBR: 1, H1: 1, H2: 1, H3: 1, H4: 1, H5: 1, H6: 1 };
+ // Roles whose own text is their name (their subtree adds nothing).
+ var NAMED_BY_CONTENT = { button: 1, link: 1, tab: 1, option: 1, menuitem: 1, menuitemcheckbox: 1, menuitemradio: 1, switch: 1, checkbox: 1, radio: 1, listitem: 1, treeitem: 1, cell: 1, gridcell: 1, heading: 1, columnheader: 1, rowheader: 1, tooltip: 1, status: 1, alert: 1 };
+ var LEAF_ROLES = { button: 1, link: 1, option: 1, menuitem: 1, menuitemcheckbox: 1, menuitemradio: 1, tab: 1, heading: 1, switch: 1, checkbox: 1, radio: 1, textbox: 1, combobox: 1, searchbox: 1, slider: 1, spinbutton: 1 };
+ // Containers are never named from their own text (no `navigation "·"`).
+ var CONTAINER = { navigation: 1, main: 1, form: 1, list: 1, table: 1, region: 1, complementary: 1, banner: 1, contentinfo: 1, group: 1, article: 1, listbox: 1, menu: 1, menubar: 1, tablist: 1, toolbar: 1, dialog: 1, alertdialog: 1, grid: 1, tree: 1, radiogroup: 1, row: 1, rowgroup: 1, tabpanel: 1, feed: 1, search: 1 };
+ var INLINE = { A: 1, B: 1, STRONG: 1, EM: 1, I: 1, SPAN: 1, CODE: 1, SMALL: 1, MARK: 1, ABBR: 1, TIME: 1, KBD: 1, SUB: 1, SUP: 1, U: 1, S: 1, BR: 1, Q: 1, CITE: 1 };
+
+ function clip(t, max) {
+ max = max || MAX_TEXT;
+ t = (t == null ? "" : String(t)).replace(/\s+/g, " ").trim();
+ return t.length > max ? t.slice(0, max) + "…" : t;
+ }
+ function q(t) { return String(t).replace(/"/g, "'"); }
+ function directText(el) {
+ var s = "";
+ for (var i = 0; i < el.childNodes.length; i++) {
+ var c = el.childNodes[i];
+ if (c.nodeType === 3) s += c.nodeValue;
+ }
+ return clip(s);
+ }
+ function roleOf(el, tag) {
+ var explicit = el.getAttribute("role");
+ if (explicit) {
+ explicit = explicit.trim().split(/\s+/)[0];
+ if (explicit === "presentation" || explicit === "none" || explicit === "generic") return null;
+ return explicit;
+ }
+ switch (tag) {
+ case "BUTTON": return "button";
+ case "A": return el.hasAttribute("href") ? "link" : null;
+ case "SELECT": return el.multiple ? "listbox" : "combobox";
+ case "TEXTAREA": return "textbox";
+ case "INPUT": {
+ var t = (el.getAttribute("type") || "text").toLowerCase();
+ if (t === "hidden") return null;
+ if (t === "checkbox") return "checkbox";
+ if (t === "radio") return "radio";
+ if (t === "submit" || t === "button" || t === "reset" || t === "image" || t === "file") return "button";
+ if (t === "range") return "slider";
+ if (t === "number") return "spinbutton";
+ if (t === "search") return "searchbox";
+ if (el.getAttribute("list")) return "combobox";
+ return "textbox";
+ }
+ case "IMG": return (el.getAttribute("alt") || el.getAttribute("aria-label")) ? "img" : null;
+ case "H1": case "H2": case "H3": case "H4": case "H5": case "H6": return "heading";
+ case "LI": return "listitem";
+ case "UL": case "OL": return "list";
+ case "TABLE": return "table";
+ case "FORM": return "form";
+ case "NAV": return "navigation";
+ case "MAIN": return "main";
+ case "DIALOG": return el.open ? "dialog" : null;
+ case "SECTION": return (el.getAttribute("aria-label") || el.getAttribute("aria-labelledby")) ? "region" : null;
+ case "ASIDE": return "complementary";
+ case "ARTICLE": return "article";
+ case "DETAILS": return "group";
+ case "SUMMARY": return "button";
+ case "FIELDSET": return "group";
+ case "PROGRESS": return "progressbar";
+ case "METER": return "meter";
+ case "CANVAS": return "canvas";
+ case "VIDEO": return "video";
+ case "AUDIO": return "audio";
+ default: return null;
+ }
+ }
+ function byIds(el, ids) {
+ var root = el.getRootNode ? el.getRootNode() : document;
+ var out = [];
+ String(ids).split(/\s+/).forEach(function (id) {
+ if (!id) return;
+ var t = (root && root.getElementById ? root.getElementById(id) : null) || document.getElementById(id);
+ if (!t) return;
+ if (t === el) out.push(el.getAttribute("aria-label") || directText(el));
+ else out.push(t.innerText || t.textContent || "");
+ });
+ return out.join(" ");
+ }
+ function nameOf(el, tag, role) {
+ var s = "";
+ var lb = el.getAttribute("aria-labelledby");
+ if (lb) s = byIds(el, lb);
+ if (!s) s = el.getAttribute("aria-label") || "";
+ if (!s && tag === "IMG") s = el.getAttribute("alt") || "";
+ if (!s && (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT")) {
+ try {
+ if (el.labels && el.labels.length) s = el.labels[0].innerText || el.labels[0].textContent;
+ } catch (e) {}
+ if (!s) {
+ var ty = (el.getAttribute("type") || "").toLowerCase();
+ if (ty === "submit" || ty === "button" || ty === "reset") s = el.value || ty;
+ }
+ if (!s) s = el.getAttribute("placeholder") || el.getAttribute("title") || "";
+ return clip(s);
+ }
+ if (!s && tag === "FIELDSET") { var lg = el.querySelector("legend"); if (lg) s = lg.innerText; }
+ if (!s && tag === "TABLE") { var cap = el.querySelector("caption"); if (cap) s = cap.innerText; }
+ if (!s && role && CONTAINER[role]) return clip(el.getAttribute("title") || "");
+ if (!s) s = directText(el);
+ if (!s && (LEAFY[tag] || NAMED_BY_CONTENT[role])) s = el.innerText;
+ if (!s) s = el.getAttribute("title") || "";
+ return clip(s);
+ }
+ // Accessibility STATES — what makes a switch/tab/option actionable.
+ function stateAttrs(el, tag, role, attrs) {
+ var a = function (k) { return el.getAttribute(k); };
+ if (tag === "INPUT" && (role === "checkbox" || role === "radio" || role === "switch")) {
+ attrs.push(el.checked ? "checked" : "unchecked");
+ } else {
+ var ch = a("aria-checked");
+ if (ch !== null) attrs.push(ch === "true" ? "checked" : ch === "mixed" ? "mixed" : "unchecked");
+ }
+ var pr = a("aria-pressed"); if (pr !== null) attrs.push("pressed=" + pr);
+ if (a("aria-selected") === "true" || (tag === "OPTION" && el.selected)) attrs.push("selected");
+ var ex = a("aria-expanded"); if (ex !== null) attrs.push("expanded=" + ex);
+ var hp = a("aria-haspopup"); if (hp && hp !== "false") attrs.push(hp === "true" ? "haspopup" : "haspopup=" + hp);
+ var cu = a("aria-current"); if (cu && cu !== "false") attrs.push(cu === "true" ? "current" : "current=" + cu);
+ if (el.disabled || a("aria-disabled") === "true") attrs.push("disabled");
+ if (el.required || a("aria-required") === "true") attrs.push("required");
+ if (el.readOnly && (tag === "INPUT" || tag === "TEXTAREA")) attrs.push("readonly");
+ if (a("aria-invalid") === "true") attrs.push("invalid");
+ var vn = a("aria-valuenow"); if (vn !== null) attrs.push("value=" + (a("aria-valuetext") || vn));
+ if (role === "heading") { var lv = a("aria-level") || (/^H[1-6]$/.test(tag) ? tag.slice(1) : ""); if (lv) attrs.push("level=" + lv); }
+ if (el.isContentEditable && tag !== "INPUT" && tag !== "TEXTAREA") {
+ attrs.push("editable");
+ var tx = clip(el.innerText); if (tx) attrs.push('value="' + q(tx) + '"');
+ }
+ }
+ function visible(el) {
+ if (el.hidden || el.getAttribute("aria-hidden") === "true") return false;
+ var r = el.getBoundingClientRect();
+ if (r.width > 0 || r.height > 0) {
+ var cs = getComputedStyle(el);
+ return cs.visibility !== "hidden" && cs.visibility !== "collapse";
+ }
+ // display:contents wrappers have no box but render their children.
+ return getComputedStyle(el).display === "contents";
+ }
+ function push(line) {
+ if (chars + line.length > MAX_CHARS) { truncated = true; return; }
+ lines.push(line);
+ chars += line.length;
+ }
+ function emitText(t, depth, kind) {
+ var tl = "- " + (kind || "text") + ' "' + q(t) + '"';
+ push(" ".repeat(depth) + tl);
+ if (!truncated) lines[lines.length - 1] = { s: lines[lines.length - 1], tl: tl, t: q(t), kind: kind || "text" };
+ }
+ function cellText(cell) {
+ var t = (cell.innerText || cell.textContent || "").replace(/\s+/g, " ").trim();
+ if (!t) {
+ var f = cell.querySelector && cell.querySelector("input,select,textarea");
+ if (f && f.value) t = '"' + f.value + '"';
+ }
+ return t.length > 80 ? t.slice(0, 80) + "…" : t;
+ }
+
+ // quiet=true: inside a container whose text was already emitted (table
+ // row, inline paragraph, named leaf) — only actionable descendants print.
+ function walk(node, depth, quiet) {
+ if (truncated || !node || !node.childNodes) return;
+ var kids = node.childNodes;
+ for (var i = 0; i < kids.length; i++) {
+ var c = kids[i];
+ if (c.nodeType !== 1) continue;
+ if (c.tagName === "SLOT") {
+ var as = c.assignedElements ? c.assignedElements({ flatten: true }) : [];
+ if (as.length) { for (var k = 0; k < as.length; k++) one(as[k], depth, quiet); }
+ else walk(c, depth, quiet);
+ continue;
+ }
+ one(c, depth, quiet);
+ if (truncated) return;
+ }
+ }
+
+ function one(c, depth, quiet) {
+ var tag = c.tagName;
+ if (SKIP[tag]) return;
+ if (!visible(c)) return;
+
+ // Table rows: one compact line per row; actionable cells still get ref
+ // lines underneath.
+ if (tag === "TR") {
+ if (!quiet) {
+ var cells = [];
+ for (var j = 0; j < c.children.length; j++) {
+ var ce = c.children[j];
+ if (ce.tagName === "TD" || ce.tagName === "TH") cells.push(cellText(ce));
+ }
+ var rt = cells.join(" | ");
+ if (rt.length > ROW_TEXT) rt = rt.slice(0, ROW_TEXT) + "…";
+ if (rt.replace(/[|\s]/g, "")) emitText(rt, depth, "row");
+ }
+ walk(c, depth + 1, true);
+ return;
+ }
+
+ var role = roleOf(c, tag);
+ var editableRoot = c.isContentEditable && (!c.parentElement || !c.parentElement.isContentEditable);
+ if (editableRoot && !role) role = "textbox";
+ var interesting = !!role || editableRoot || (c.tabIndex >= 0 && tag !== "HTML" && tag !== "BODY" && !c.isContentEditable);
+ if (tag === "IFRAME") { interesting = true; role = "iframe"; }
+ // Inside an already-described container, structural roles are noise.
+ if (quiet && role && (CONTAINER[role] || role === "listitem")) interesting = false;
+ // Lists are structure, not content: their items carry the information.
+ if (role === "list") interesting = false;
+ // Unnamed generic containers (article/group/row…) add a line and a ref
+ // per item with no information — stay transparent unless focusable.
+ if (interesting && (role === "article" || role === "group" || role === "row" || role === "rowgroup" || role === "region" || role === "feed" || role === "complementary") && c.tabIndex < 0
+ && !c.getAttribute("aria-label") && !c.getAttribute("aria-labelledby") && !(tag === "FIELDSET" && c.querySelector("legend"))) interesting = false;
+
+ var shadow = c.shadowRoot;
+
+ if (interesting) {
+ if (n >= MAX_NODES || truncated) { truncated = true; return; }
+ n++;
+ var ref = REG.get(c);
+ if (!ref) { regSeq++; ref = "e" + regSeq; REG.set(c, ref); }
+ refs[ref] = c;
+ var name = nameOf(c, tag, role);
+ var attrs = [];
+ if (tag === "A" && c.href) {
+ attrs.push("href=" + clip(new URL(c.href, location.href).href));
+ if (c.target === "_blank") attrs.push("new-tab");
+ }
+ if (tag === "INPUT" || tag === "TEXTAREA") {
+ var ty = (c.getAttribute("type") || "text").toLowerCase();
+ var boolish = ty === "checkbox" || ty === "radio";
+ if (ty !== "text" && ty !== "search" && !boolish && ty !== "submit" && ty !== "button") attrs.push("type=" + ty);
+ if (!boolish && ty !== "submit" && ty !== "button" && ty !== "password" && c.value) attrs.push('value="' + q(clip(c.value)) + '"');
+ if (boolish && c.value && c.value !== "on" && c.value !== name) attrs.push('value="' + q(clip(c.value)) + '"');
+ var ph = c.getAttribute("placeholder");
+ if (ph && ph !== name) attrs.push('placeholder="' + q(clip(ph)) + '"');
+ }
+ if (tag === "SELECT") {
+ var so = c.selectedIndex >= 0 ? c.options[c.selectedIndex] : null;
+ if (so) attrs.push('value="' + q(clip(so.text || so.value)) + '"');
+ var ol = [];
+ for (var o = 0; o < c.options.length && o < 25; o++) ol.push(q(clip(c.options[o].text || c.options[o].value, 40)));
+ if (ol.length) attrs.push("options={" + ol.join(", ") + (c.options.length > 25 ? ", …+" + (c.options.length - 25) : "") + "}");
+ }
+ stateAttrs(c, tag, role, attrs);
+ if (tag === "CANVAS" || tag === "VIDEO") {
+ var br = c.getBoundingClientRect();
+ attrs.push("box=" + Math.round(br.left) + "," + Math.round(br.top) + "," + Math.round(br.width) + "x" + Math.round(br.height) + " viewport px");
+ if (tag === "CANVAS") attrs.push("pixels-only: ax_screenshot, then ax_click {x,y} in screenshot pixels");
+ }
+ var walkInline = null;
+ if (tag === "IFRAME") {
+ try {
+ var fdoc = c.contentDocument;
+ if (fdoc && fdoc.body) walkInline = fdoc.body;
+ } catch (e) { /* cross-origin */ }
+ if (!walkInline) attrs.push("cross-origin");
+ }
+ var line =
+ " ".repeat(depth) + "- " + (role || tag.toLowerCase()) +
+ (name ? ' "' + q(name) + '"' : "") +
+ (attrs.length ? " (" + attrs.join(", ") + ")" : "") +
+ " [ref=" + ref + "]";
+ push(line);
+ if (!truncated) lines[lines.length - 1] = { s: line, name: q(name) };
+ entries.push({ ref: ref, line: line });
+ if (walkInline) walk(walkInline, depth + 1);
+ var leaf = !!(LEAFY[tag] || LEAF_ROLES[role] || editableRoot);
+ if (shadow) walk(shadow, depth + 1, quiet || leaf);
+ walk(c, depth + 1, quiet || leaf);
+ return;
+ }
+
+ if (shadow) { walk(shadow, depth, quiet); return; }
+ if (quiet) { walk(c, depth, true); return; }
+ // Paragraph-like element with only inline children: its FULL text once
+ // (link text stays in the sentence), then only actionable inline kids.
+ var dt = directText(c);
+ if (dt && c.children.length) {
+ var inlineOnly = true;
+ for (var m = 0; m < c.children.length; m++) if (!INLINE[c.children[m].tagName]) { inlineOnly = false; break; }
+ if (inlineOnly) {
+ var full = clip(c.innerText, 400);
+ if (full) emitText(full, depth);
+ walk(c, depth, true);
+ return;
+ }
+ }
+ if (dt) emitText(dt, depth);
+ walk(c, depth);
+ }
+
+ try {
+ // ACP-1 (2026-10-17): during early load some pages briefly expose no
+ // document.body (observed live on ag-grid.com) — serialize the document
+ // element instead of crashing the whole observation, and null-guard the
+ // walk (defensive: nodes can detach mid-walk on mutating pages).
+ walk(document.body || document.documentElement, 0);
+ } catch (e) {
+ return { ok: false, error: String(e && e.stack || e) };
+ }
+ window.__axuseRefSeq = regSeq;
+ // Drop label-echo text: a plain text line that merely repeats the name of
+ // the adjacent element (label → control, legend → group) costs tokens and
+ // invites the model to "click the label".
+ var out = [];
+ for (var li = 0; li < lines.length; li++) {
+ var L = lines[li];
+ if (typeof L === "string") { out.push(L); continue; }
+ if (L.tl) {
+ if (L.kind === "text") {
+ var prev = lines[li - 1], next = lines[li + 1];
+ var echo = function (o) { return o && typeof o === "object" && o.name && (o.name === L.t || o.name.indexOf(L.t + " ") === 0); };
+ if (echo(prev) || echo(next)) continue;
+ }
+ out.push(L.s); textLines.push(L.tl);
+ } else out.push(L.s);
+ }
+ lines = out;
+ return {
+ ok: true,
+ url: location.href,
+ title: clip(document.title),
+ text: lines.join("\n"),
+ entries: entries,
+ textLines: textLines,
+ truncated: truncated,
+ refCount: n,
+ scroll: { x: window.scrollX, y: window.scrollY },
+ };
+}
+
+/** Build the Runtime.evaluate payload that runs the serializer in a tab. */
+export function serializeExpression(opts) {
+ return `(${pageSerializer.toString()})(${JSON.stringify(opts ?? {})})`;
+}
diff --git a/src/desktop/index.js b/src/desktop/index.js
new file mode 100644
index 0000000..e8f969d
--- /dev/null
+++ b/src/desktop/index.js
@@ -0,0 +1,287 @@
+/**
+ * axuse — desktop (computer use) driver layer.
+ *
+ * Lineage: ZCode's desktop CUA is an AX-tree-first actuator behind a native
+ * permission-brokered Helper process; on Windows it uses a native N-API
+ * addon. axuse stays zero-dependency by using each OS's scriptable surface:
+ *
+ * - The BROWSER (ax_*) is structure-first: refs, diffed AX snapshots,
+ * trusted input. Use it whenever the target is a web page.
+ * - The DESKTOP (ax_desktop_*) is now ALSO structure-first on macOS:
+ * System Events exposes the platform AX tree (same Accessibility grant
+ * as input synthesis), so ax_desktop_ax_snapshot gives refs, roles,
+ * titles, values and bounds; ax_desktop_ax_click/set/read act on them
+ * (trusted AXPress with a CGEvent coordinate fallback). Coordinates and
+ * screenshots remain the fallback mode for canvas/games — and the only
+ * mode on Windows today.
+ *
+ * Driver matrix (fail-closed where permissions are not granted):
+ * - Windows: resident PowerShell + SendInput/GDI driver — verified live
+ * (coordinate+vision; no AX tree yet).
+ * - macOS: JXA/CoreGraphics/System Events + screencapture/sips driver;
+ * loads with AXUSE_ENABLE_MACOS_CUA=1; reports TCC failures clearly.
+ * AX-tree ops need the Accessibility grant; capture needs Screen
+ * Recording.
+ * - Linux: no driver yet (browser tools still work).
+ *
+ * The driver interface is the seam: a Windows UIA driver slots in behind
+ * the same tools without touching the contract.
+ */
+import { spawn } from "node:child_process";
+import { fileURLToPath } from "node:url";
+import { join, dirname } from "node:path";
+import { AxError, Codes } from "../core/errors.js";
+import { KEYS, MOD, parseCombo } from "../core/actuate.js";
+import { DEFAULT_BUDGET_BYTES } from "../core/screenshot.js";
+
+const PS1 = join(dirname(fileURLToPath(import.meta.url)), "windows.ps1");
+const OP_TIMEOUT_MS = 15_000;
+
+/** Exact payload size of a base64 string (padding-aware; the ×¾/4 estimate
+ * over-reports by up to 2 bytes per image and skews budget decisions). */
+function exactBase64Bytes(b64) {
+ return Buffer.byteLength(Buffer.from(b64, "base64"));
+}
+
+/** Resident Windows driver: one PowerShell process, one op at a time. */
+class WindowsDriver {
+ constructor() {
+ this.proc = null;
+ this.dead = true; // set synchronously on exit AND on dispose
+ this.chain = Promise.resolve(); // input ops are strictly ordered
+ }
+
+ ensure() {
+ // Respawn only when the old process is really gone. `exitCode` alone
+ // is racy (it stays null until the exit event is processed), so
+ // `dead` is set synchronously in dispose() and in the exit handler.
+ if (this.proc && !this.dead && this.proc.exitCode === null) return;
+ this.dead = false;
+ const proc = spawn("powershell", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", PS1], {
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ this.proc = proc;
+ this.buffer = "";
+ this.waiters = [];
+ // Guard every handler against superseded processes: the OLD proc's
+ // events can arrive after a respawn and would poison the new state.
+ proc.stdout.on("data", (d) => { if (this.proc === proc) this.onStdout(d); });
+ proc.stderr.on("data", (d) => {
+ if (this.proc !== proc) return;
+ const s = String(d).trim();
+ if (s) process.stderr.write(`[axuse:desktop] ${s}\n`);
+ });
+ proc.on("exit", () => {
+ if (this.proc !== proc) return; // a newer process owns this driver
+ this.dead = true;
+ for (const w of this.waiters.splice(0)) w.reject(new AxError(Codes.DESKTOP_OP_FAILED, "Desktop driver exited"));
+ });
+ }
+
+ onStdout(d) {
+ this.buffer += String(d);
+ let idx;
+ while ((idx = this.buffer.indexOf("\n")) >= 0) {
+ const line = this.buffer.slice(0, idx).trim();
+ this.buffer = this.buffer.slice(idx + 1);
+ if (!line) continue;
+ const w = this.waiters.shift();
+ if (!w) continue;
+ try {
+ w.resolve(JSON.parse(line));
+ } catch {
+ w.reject(new AxError(Codes.DESKTOP_OP_FAILED, `Driver protocol garbage: ${line.slice(0, 200)}`));
+ }
+ }
+ }
+
+ /** Ops are serialized: input ordering must never interleave. */
+ op(payload, timeoutMs = OP_TIMEOUT_MS) {
+ this.ensure();
+ const run = () =>
+ new Promise((resolve, reject) => {
+ // Ops are strictly serialized, so this op's waiter is the only
+ // outstanding one — on timeout, reject and drop the oldest.
+ const timer = setTimeout(() => {
+ const w = this.waiters.shift();
+ if (w) w.reject(new AxError(Codes.TIMEOUT, `Desktop op "${payload.op}" timed out`, { retry: "retry" }));
+ else reject(new AxError(Codes.TIMEOUT, `Desktop op "${payload.op}" timed out`, { retry: "retry" }));
+ }, timeoutMs);
+ this.waiters.push({
+ resolve: (v) => { clearTimeout(timer); resolve(v); },
+ reject: (e) => { clearTimeout(timer); reject(e); },
+ });
+ try {
+ this.proc.stdin.write(JSON.stringify(payload) + "\n");
+ } catch (e) {
+ clearTimeout(timer);
+ this.waiters.shift();
+ reject(new AxError(Codes.DESKTOP_OP_FAILED, `Driver write failed: ${e.message}`));
+ }
+ });
+ this.chain = this.chain.then(run, run);
+ return this.chain;
+ }
+
+ async check(op) {
+ const res = await op;
+ if (!res || res.ok === false) {
+ throw new AxError(Codes.DESKTOP_OP_FAILED, res?.error ?? "op failed", { retry: "retry" });
+ }
+ return res;
+ }
+
+ /* ------------------------------------------------------------ operations */
+
+ async screenInfo() {
+ return this.check(this.op({ op: "screen_info" }));
+ }
+
+ async screenshot({ x, y, w, h, budgetBytes = DEFAULT_BUDGET_BYTES, quality = 80 } = {}) {
+ let res = await this.check(this.op({ op: "screenshot", x, y, w, h, quality }));
+ let bytes = exactBase64Bytes(res.base64);
+ if (bytes > budgetBytes) {
+ res = await this.check(this.op({ op: "screenshot", x, y, w, h, quality: 45 }));
+ bytes = exactBase64Bytes(res.base64);
+ }
+ if (bytes > budgetBytes) {
+ throw new AxError(Codes.SCREENSHOT_BUDGET_EXCEEDED,
+ `Desktop screenshot is ${bytes} bytes, over the ${budgetBytes} byte budget.`,
+ { hint: "Pass a crop region ({x,y,w,h} in physical pixels from screen_info).", retry: "never" });
+ }
+ return { base64: res.base64, mime: res.mime, bytes, budget_bytes: budgetBytes, quality };
+ }
+
+ async move(x, y) {
+ await this.check(this.op({ op: "move", x, y }));
+ return { action_sent: "sent" };
+ }
+
+ async click({ x, y, button = "left", double = false } = {}) {
+ await this.check(this.op({ op: "click", x, y, button, double }));
+ return { action_sent: "sent" };
+ }
+
+ async down(button = "left") {
+ await this.check(this.op({ op: "down", button }));
+ return { action_sent: "sent" };
+ }
+
+ async up(button = "left") {
+ await this.check(this.op({ op: "up", button }));
+ return { action_sent: "sent" };
+ }
+
+ async wheel(dx = 0, dy = 0) {
+ await this.check(this.op({ op: "wheel", dx, dy }));
+ return { action_sent: "sent" };
+ }
+
+ async keyTap(vk) {
+ await this.check(this.op({ op: "key_tap", vk }));
+ return { action_sent: "sent" };
+ }
+
+ async keyDown(vk) {
+ await this.check(this.op({ op: "key_down", vk }));
+ return { action_sent: "sent" };
+ }
+
+ async keyUp(vk) {
+ await this.check(this.op({ op: "key_up", vk }));
+ return { action_sent: "sent" };
+ }
+
+ async type(text) {
+ await this.check(this.op({ op: "key_text", text: String(text) }));
+ return { action_sent: "sent" };
+ }
+
+ async windows() {
+ const res = await this.check(this.op({ op: "windows" }));
+ return { windows: res.windows };
+ }
+
+ async activate({ title, hwnd } = {}) {
+ const res = await this.op({ op: "activate", title, hwnd });
+ if (!res.ok) {
+ throw new AxError(Codes.DESKTOP_OP_FAILED, res.error, { hint: "List windows with ax_desktop_windows and retry with an exact title or hwnd.", retry: "retry" });
+ }
+ return { activated: true };
+ }
+
+ /** Combo press ("ctrl+s") mapped through the shared KEYS table. */
+ async press(combo) {
+ const { mods, main } = parseCombo(combo);
+ for (const m of mods) await this.keyDown(KEYS[m].vk);
+ await this.keyTap(main.vk);
+ for (let i = mods.length - 1; i >= 0; i--) await this.keyUp(KEYS[mods[i]].vk);
+ return { action_sent: "sent", combo };
+ }
+
+ /** Drag via move/down/move/up (interpolated like the browser actuator). */
+ async drag({ from, to, steps = 12 } = {}) {
+ await this.move(from.x, from.y);
+ await this.down("left");
+ for (let i = 1; i <= steps; i++) {
+ const x = Math.round(from.x + ((to.x - from.x) * i) / steps);
+ const y = Math.round(from.y + ((to.y - from.y) * i) / steps);
+ await this.move(x, y);
+ }
+ await this.up("left");
+ return { action_sent: "sent" };
+ }
+
+ dispose() {
+ this.dead = true;
+ if (this.proc) { try { this.proc.kill(); } catch {} }
+ }
+}
+
+let cached = null;
+
+/** Get the platform driver, or null when unsupported. Tools hide when null.
+ * macOS remains explicitly opt-in because it can synthesize OS input. */
+export function getDesktopDriver() {
+ if (process.platform === "win32") {
+ if (!cached) cached = new WindowsDriver();
+ return cached;
+ }
+ if (process.platform === "darwin") {
+ if (!/^(1|true)$/i.test(process.env.AXUSE_ENABLE_MACOS_CUA ?? "")) return null;
+ if (!cached) {
+ // Lazy import keeps the permissioned macOS module out of the default path.
+ // (Synchronous require is avoided; this is a single controlled load.)
+ // eslint-disable-next-line no-async-promise-executor
+ cached = macosDriverPromise().catch((e) => {
+ cached = null;
+ throw e;
+ });
+ }
+ return cached;
+ }
+ return null;
+}
+
+async function macosDriverPromise() {
+ const { MacDriver } = await import("./macos.js");
+ return new MacDriver();
+}
+
+/** Desktop dispatch needs sync availability in the MCP layer; the macOS
+ * driver is the one async case — pre-resolve it once at server start. */
+export async function resolveDesktopDriver() {
+ const d = getDesktopDriver();
+ return d instanceof Promise ? await d : d;
+}
+
+export function desktopUnavailable() {
+ const macNote = process.platform === "darwin"
+ ? " The macOS driver is disabled: set AXUSE_ENABLE_MACOS_CUA=1; desktop input/capture also needs Accessibility and Screen Recording grants for the host."
+ : "";
+ throw new AxError(Codes.DESKTOP_DRIVER_UNAVAILABLE,
+ process.platform === "darwin"
+ ? `Desktop control is disabled on macOS until explicitly enabled.${macNote}`
+ : `Desktop control is not implemented for ${process.platform} yet.${macNote}`,
+ { hint: "Prefer the ax_* browser tools whenever the target is a web page.", retry: "never" });
+}
diff --git a/src/desktop/macos.js b/src/desktop/macos.js
new file mode 100644
index 0000000..54acbe0
--- /dev/null
+++ b/src/desktop/macos.js
@@ -0,0 +1,1027 @@
+/**
+ * axuse — macOS desktop driver.
+ *
+ * macOS deliberately keeps the driver behind AXUSE_ENABLE_MACOS_CUA=1. OS
+ * input and screen capture are permissioned capabilities, so the driver must
+ * fail with a useful, typed fact when the host has not been granted
+ * Accessibility or Screen Recording access. The implementation itself is
+ * dependency-free: JXA bridges CoreGraphics/System Events and the native
+ * `screencapture` + `sips` tools handle pixels.
+ *
+ * Coordinate contract:
+ * - x/y/w/h are macOS global display points (the same units used by
+ * CGDisplayBounds and CGEvent mouse events).
+ * - returned JPEGs are resized to the requested point dimensions, so a
+ * pixel read from the image maps directly to a click coordinate even on
+ * a Retina display.
+ */
+import { execFile } from "node:child_process";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { AxError, Codes } from "../core/errors.js";
+import { DEFAULT_BUDGET_BYTES } from "../core/screenshot.js";
+
+const COMMAND_TIMEOUT_MS = 15_000;
+/** Probe results are cached briefly: a screenshot used to cost four process
+ * spawns (screen_info + permissions + screencapture + sips); caching the two
+ * JXA probes halves it. Every DESKTOP_PERMISSION_REQUIRED failure
+ * invalidates both caches, so a just-granted permission is picked up on the
+ * next call without restarting the host. */
+const PROBE_CACHE_TTL_MS = 5_000;
+const PERMISSION_HINT =
+ "Grant the host running axuse Accessibility and Screen Recording in System Settings → Privacy & Security, then retry. Keep AXUSE_ENABLE_MACOS_CUA=1 enabled for desktop control.";
+const STALE_PERMISSION_HINT =
+ "The TCC grant may be stale (binary moved/updated, or the grant predates this host process). Quit and restart the host running axuse; if it persists, run `tccutil reset ScreenCapture` (and `tccutil reset Accessibility`) from Terminal, then re-grant in System Settings → Privacy & Security.";
+
+function appleScriptLiteral(value) {
+ return `"${String(value).replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
+}
+
+/** Run a native macOS command without invoking a shell. */
+function run(file, args, { timeout = COMMAND_TIMEOUT_MS, hint = PERMISSION_HINT } = {}) {
+ return new Promise((resolve, reject) => {
+ execFile(file, args, { timeout, maxBuffer: 64 * 1024 * 1024 }, (err, stdout, stderr) => {
+ if (err) {
+ const detail = String(stderr || err.message || `${file} failed`).trim().slice(0, 600);
+ const permission = /not allowed assistive access|not allowed to send|not authorized|could not create image from (rect|display)|screen recording|accessibility|kCGErrorFailure|operation not permitted/i.test(detail);
+ // A capture that fails after a *passing* preflight is the classic
+ // stale-grant signature (TCC still trusts an old binary path).
+ const stale = permission && /could not create image from (rect|display)|operation not permitted/i.test(detail);
+ reject(new AxError(permission ? Codes.DESKTOP_PERMISSION_REQUIRED : Codes.DESKTOP_OP_FAILED,
+ `${file} failed: ${detail}`,
+ { hint: stale ? STALE_PERMISSION_HINT : hint, retry: "retry" }));
+ } else {
+ resolve(String(stdout));
+ }
+ });
+ });
+}
+
+function parseJson(out, operation) {
+ try {
+ return JSON.parse(String(out).trim());
+ } catch {
+ throw new AxError(Codes.DESKTOP_OP_FAILED,
+ `macOS ${operation} returned invalid JSON`,
+ { hint: "Retry the operation; if it persists, check the host's osascript installation and permissions.", retry: "retry" });
+ }
+}
+
+function finite(value, name) {
+ if (typeof value !== "number" || !Number.isFinite(value)) {
+ throw new AxError(Codes.BAD_COORDS, `${name} must be a finite number`, { retry: "never" });
+ }
+ return value;
+}
+
+function positive(value, name) {
+ const n = finite(value, name);
+ if (n < 1) throw new AxError(Codes.BAD_COORDS, `${name} must be ≥ 1`, { retry: "never" });
+ return n;
+}
+
+function rectValues(rect, info) {
+ const supplied = rect && Object.values(rect).some((v) => v !== undefined);
+ if (supplied && (!rect || ["x", "y", "w", "h"].some((k) => rect[k] === undefined))) {
+ throw new AxError(Codes.BAD_COORDS, "Desktop screenshot requires x, y, w, and h together", { retry: "never" });
+ }
+ const source = supplied ? rect : info;
+ const x = Math.round(finite(source.x, "x"));
+ const y = Math.round(finite(source.y, "y"));
+ const w = Math.round(positive(source.w, "w"));
+ const h = Math.round(positive(source.h, "h"));
+ if (w < 1 || h < 1) throw new AxError(Codes.BAD_COORDS, "Screenshot width and height must round to at least 1", { retry: "never" });
+ // Refusing an out-of-bounds rectangle is safer than asking screencapture to
+ // silently clamp it. The bounds are the union of active displays.
+ if (x < info.x || y < info.y || x + w > info.x + info.w || y + h > info.y + info.h) {
+ throw new AxError(Codes.BAD_COORDS,
+ `Screenshot rect (${x},${y},${w},${h}) is outside the active display layout (${info.x},${info.y},${info.w},${info.h})`,
+ { hint: "Call ax_desktop_screen_info and keep the crop within the reported display bounds.", retry: "never" });
+ }
+ return { x, y, w, h };
+}
+
+function buttonSpec(button) {
+ const b = String(button ?? "left").toLowerCase();
+ if (!new Set(["left", "right", "middle"]).has(b)) {
+ throw new AxError(Codes.COMMAND_REJECTED, `Unknown mouse button "${button}"`, { retry: "never" });
+ }
+ return b;
+}
+
+/** Exact payload size of a base64 string (padding-aware). */
+function exactBase64Bytes(b64) {
+ return Buffer.byteLength(Buffer.from(b64, "base64"));
+}
+
+/** AppleScript key codes for a US-independent physical key layout. */
+export const MACOS_KEY_CODES = Object.freeze({
+ enter: 36, return: 36, tab: 48, escape: 53, esc: 53,
+ backspace: 51, delete: 117, del: 117, space: 49,
+ up: 126, down: 125, left: 123, right: 124,
+ home: 115, end: 119, pageup: 116, pagedown: 121,
+ f1: 122, f2: 120, f3: 99, f4: 118, f5: 96, f6: 97,
+ f7: 98, f8: 100, f9: 101, f10: 109, f11: 103, f12: 111,
+ f13: 105, f14: 107, f15: 113, f16: 106, f17: 64, f18: 79, f19: 80, f20: 90,
+ help: 114, insert: 114, forwarddelete: 117,
+});
+
+const MODIFIERS = Object.freeze({
+ ctrl: "control down", control: "control down",
+ alt: "option down", option: "option down",
+ shift: "shift down",
+ meta: "command down", cmd: "command down", command: "command down",
+});
+
+/** Parse a desktop key combo once, with the same aliases on every macOS call. */
+export function parseMacCombo(combo) {
+ const parts = String(combo ?? "").toLowerCase().split("+").map((s) => s.trim()).filter(Boolean);
+ const mods = [];
+ let main = null;
+ for (const part of parts) {
+ if (MODIFIERS[part]) mods.push(MODIFIERS[part]);
+ else if (main === null) main = part;
+ else throw new AxError(Codes.COMMAND_REJECTED, `More than one non-modifier key in combo "${combo}"`, { retry: "never" });
+ }
+ if (!main) throw new AxError(Codes.COMMAND_REJECTED, `No non-modifier key in combo "${combo}"`, { retry: "never" });
+ return { mods, main, keyCode: MACOS_KEY_CODES[main] };
+}
+
+/** CGEvent-based trusted mouse synthesis (JXA ObjC bridge). */
+const MOUSE_EVENTS = Object.freeze({
+ down: "$.kCGEventLeftMouseDown",
+ up: "$.kCGEventLeftMouseUp",
+ moved: "$.kCGEventMouseMoved",
+ rdown: "$.kCGEventRightMouseDown",
+ rup: "$.kCGEventRightMouseUp",
+ mdown: "$.kCGEventOtherMouseDown",
+ mup: "$.kCGEventOtherMouseUp",
+ drag: "$.kCGEventLeftMouseDragged",
+});
+
+const MOUSE_BUTTONS = Object.freeze({
+ left: "$.kCGMouseButtonLeft",
+ right: "$.kCGMouseButtonRight",
+ center: "$.kCGMouseButtonCenter",
+});
+
+function mouseButtonFor(kind) {
+ return kind === "rdown" || kind === "rup" ? MOUSE_BUTTONS.right
+ : kind === "mdown" || kind === "mup" ? MOUSE_BUTTONS.center
+ : MOUSE_BUTTONS.left;
+}
+
+function nativeEventCode(events, { post = true } = {}) {
+ const body = events.map((item, i) => {
+ if (item.kind === "scroll") {
+ const horizontal = item.dx !== 0;
+ const wheelCount = horizontal ? 2 : 1;
+ const wheelArgs = horizontal ? `${-item.dy}, ${-item.dx}` : `${-item.dy}`;
+ return `
+ var e${i} = $.CGEventCreateScrollWheelEvent(null, $.kCGScrollEventUnitPixel, ${wheelCount}, ${wheelArgs});
+ if (!e${i}) throw new Error('CGEventCreateScrollWheelEvent returned null');
+ ${post ? `$.CGEventPost($.kCGHIDEventTap, e${i});` : ""}`;
+ }
+ const event = MOUSE_EVENTS[item.kind];
+ if (!event) throw new AxError(Codes.DESKTOP_OP_FAILED, `Unknown macOS mouse event "${item.kind}"`, { retry: "never" });
+ const button = mouseButtonFor(item.kind);
+ // kCGMouseEventClickState = 1 (CGEventField, CGEventTypes.h). Cocoa reads
+ // the click state from the event, not from inter-event timing alone: two
+ // rapid clicks without clickState=2 register as two single clicks.
+ const clickState = item.clickState ? `
+ $.CGEventSetIntegerValueField(e${i}, 1, ${item.clickState});` : "";
+ return `
+ var e${i} = $.CGEventCreateMouseEvent(null, ${event}, $.CGPointMake(${item.x}, ${item.y}), ${button});
+ if (!e${i}) throw new Error('CGEventCreateMouseEvent returned null');${clickState}
+ ${post ? `$.CGEventPost($.kCGHIDEventTap, e${i});` : ""}`;
+ }).join("\n");
+ return `
+ ${post ? "ObjC.import('ApplicationServices'); if (!$.AXIsProcessTrusted()) throw new Error('Accessibility permission required');" : ""}
+ ObjC.import('CoreGraphics');
+ (function () {
+ ${body}
+ return "ok";
+ })()`;
+}
+
+function mouseCode(kind, x, y, options) {
+ return nativeEventCode([{ kind, x, y }], options);
+}
+
+/*
+ * Keep the public operations cheap on macOS: spawning osascript once per
+ * mouse event made a drag take dozens of process launches and introduced
+ * avoidable gaps between down/move/up. The event builder remains injectable
+ * through jxa(), while normal actions post an ordered native sequence.
+ */
+function mouseSequenceCode(events, options) {
+ return nativeEventCode(events, options);
+}
+
+const SCREEN_INFO_SCRIPT = `
+ ObjC.import('CoreGraphics');
+ ObjC.import('AppKit');
+ (function () {
+ var main = Number($.CGMainDisplayID()), screens = $.NSScreen.screens, displays = [];
+ for (var i = 0; i < screens.count; i++) {
+ var screen = screens.objectAtIndex(i), number = null;
+ try { number = screen.deviceDescription.objectForKey('NSScreenNumber').intValue; } catch (_) {}
+ var id = Number(number);
+ if (!Number.isFinite(id)) continue;
+ var b = $.CGDisplayBounds(id);
+ var width = Number(b.size.width), height = Number(b.size.height);
+ // CGDisplayPixelsWide can report the logical mode on scaled desktop
+ // sessions. AppKit's backingScaleFactor is the authoritative mapping
+ // between display points (input) and capture pixels (raster).
+ var scale = Number(screen.backingScaleFactor) || 1;
+ displays.push({
+ id: id, x: Number(b.origin.x), y: Number(b.origin.y), w: width, h: height,
+ scale_x: scale, scale_y: scale, pixels_w: Math.round(width * scale), pixels_h: Math.round(height * scale)
+ });
+ }
+ if (!displays.length) {
+ var fallback = $.CGDisplayBounds(main);
+ displays.push({ id: main, x: Number(fallback.origin.x), y: Number(fallback.origin.y), w: Number(fallback.size.width), h: Number(fallback.size.height), scale_x: 1, scale_y: 1, pixels_w: Number(fallback.size.width), pixels_h: Number(fallback.size.height) });
+ }
+ var primary = displays[0];
+ for (var j = 0; j < displays.length; j++) if (displays[j].id === main) primary = displays[j];
+ var left = displays[0].x, top = displays[0].y, right = displays[0].x + displays[0].w, bottom = displays[0].y + displays[0].h;
+ for (var k = 1; k < displays.length; k++) {
+ left = Math.min(left, displays[k].x); top = Math.min(top, displays[k].y);
+ right = Math.max(right, displays[k].x + displays[k].w); bottom = Math.max(bottom, displays[k].y + displays[k].h);
+ }
+ return JSON.stringify({
+ display_id: primary.id, x: left, y: top, w: right - left, h: bottom - top,
+ pixels_w: primary.pixels_w, pixels_h: primary.pixels_h,
+ scale_x: primary.scale_x, scale_y: primary.scale_y, display_count: displays.length, displays: displays
+ });
+ })()`;
+
+const PERMISSIONS_SCRIPT = `
+ ObjC.import('ApplicationServices');
+ ObjC.import('CoreGraphics');
+ (function () {
+ var accessibility = false;
+ var screenRecording = null;
+ try { accessibility = Boolean($.AXIsProcessTrusted()); } catch (_) {}
+ try {
+ // JXA does not expose this C symbol until it is explicitly bound. The
+ // preflight call is non-interactive: it never opens the TCC prompt.
+ ObjC.bindFunction('CGPreflightScreenCaptureAccess', ['bool', []]);
+ screenRecording = Boolean($.CGPreflightScreenCaptureAccess());
+ } catch (_) {}
+ return JSON.stringify({ accessibility: accessibility, screen_recording: screenRecording });
+ })()`;
+
+/* -------------------------------------------------------- AX (System Events)
+ *
+ * Structure-first desktop automation on macOS: the same Accessibility grant
+ * already required for input lets System Events read the platform AX tree.
+ * One Apple Event per node (`properties`), path-based refs (re-resolved
+ * live at action time, browser-ref discipline), and hard budgets so huge
+ * trees (Xcode, browsers) degrade to honest truncation facts.
+ */
+
+/** Locate a System Events process by pid / name-or-window-title / frontmost
+ * and dump a budgeted AX subtree as flat JSON nodes. */
+const AX_SNAPSHOT_SCRIPT = `
+ (function () {
+ var se = Application('System Events');
+ var wantPid = __WANT_PID__, wantName = __WANT_NAME__, wantFront = __WANT_FRONT__;
+ var maxNodes = __MAX_NODES__, maxDepth = __MAX_DEPTH__;
+ var procs = se.processes.whose({ backgroundOnly: false })();
+ var p = null;
+ for (var i = 0; i < procs.length; i++) {
+ var q = procs[i], pid = 0, name = '', front = false;
+ try { pid = Number(q.unixId()); } catch (_) {}
+ try { name = String(q.name()); } catch (_) {}
+ try { front = Boolean(q.frontmost()); } catch (_) {}
+ if (wantPid ? pid === wantPid : (String(wantName) ? (name === wantName || name.toLowerCase() === String(wantName).toLowerCase()) : front)) { p = q; break; }
+ }
+ if (!p) return JSON.stringify({ error: 'no_process', want: wantPid || wantName || 'frontmost' });
+ var nodes = [], truncatedChildren = 0, hitDepth = 0;
+ function describe(el, path, parent, depth) {
+ if (nodes.length >= maxNodes || depth > maxDepth) { if (depth > hitDepth) hitDepth = depth; return null; }
+ var pr = {};
+ try { pr = el.properties(); } catch (e) { return null; }
+ var row = { path: path, p: parent, d: depth };
+ try { row.role = String(pr.role || el.role() || ''); } catch (_) {}
+ try { row.subrole = pr.subrole ? String(pr.subrole) : null; } catch (_) {}
+ try { row.title = pr.title != null ? String(pr.title).slice(0, 120) : null; } catch (_) {}
+ try { if (row.title == null && pr.description != null) row.title = String(pr.description).slice(0, 120); } catch (_) {}
+ try { row.value = pr.value != null ? String(pr.value).slice(0, 200) : null; } catch (_) {}
+ try { var pos = pr.position || el.position(); row.x = Number(pos[0]); row.y = Number(pos[1]); } catch (_) {}
+ try { var sz = pr.size || el.size(); row.w = Number(sz[0]); row.h = Number(sz[1]); } catch (_) {}
+ try { row.enabled = pr.enabled === undefined ? null : Boolean(pr.enabled); } catch (_) {}
+ var idx = nodes.length;
+ nodes.push(row);
+ var kids = [];
+ try { kids = el.uiElements(); } catch (_) {}
+ var shown = 0;
+ for (var k = 0; k < kids.length && nodes.length < maxNodes; k++) {
+ if (shown >= 60) { truncatedChildren += (kids.length - shown); break; }
+ var child = describe(kids[k], path + '/' + k, idx, depth + 1);
+ shown++;
+ if (child === null && depth + 1 > maxDepth) break;
+ }
+ return idx;
+ }
+ var wins = [];
+ try { wins = p.windows(); } catch (e) { return JSON.stringify({ error: 'no_windows_access', app: String(p.name()), hint: 'Accessibility grant missing for window access' }); }
+ for (var w = 0; w < wins.length && nodes.length < maxNodes; w++) {
+ describe(wins[w], String(w), null, 0);
+ }
+ return JSON.stringify({
+ app: String(p.name()), pid: Number(p.unixId()), nodes: nodes,
+ truncated_children: truncatedChildren, hit_max_nodes: nodes.length >= maxNodes,
+ hit_max_depth: hitDepth > maxDepth, window_count: wins.length,
+ });
+ })()`;
+
+/** Re-resolve a ref path against the live tree and return its properties
+ * (plus available AX actions for actuation decisions). */
+const AX_RESOLVE_SCRIPT = `
+ (function () {
+ var se = Application('System Events');
+ var wantPid = __WANT_PID__, wantName = __WANT_NAME__, wantFront = __WANT_FRONT__;
+ var path = String(__PATH__).split('/');
+ var procs = se.processes.whose({ backgroundOnly: false })();
+ var p = null;
+ for (var i = 0; i < procs.length; i++) {
+ var q = procs[i], pid = 0, name = '', front = false;
+ try { pid = Number(q.unixId()); } catch (_) {}
+ try { name = String(q.name()); } catch (_) {}
+ try { front = Boolean(q.frontmost()); } catch (_) {}
+ if (wantPid ? pid === wantPid : (String(wantName) ? (name === wantName || name.toLowerCase() === String(wantName).toLowerCase()) : front)) { p = q; break; }
+ }
+ if (!p) return JSON.stringify({ error: 'no_process' });
+ var el = null;
+ try {
+ el = p.windows()[Number(path[0])];
+ for (var j = 1; j < path.length && el; j++) el = el.uiElements()[Number(path[j])];
+ } catch (e) { el = null; }
+ if (!el) return JSON.stringify({ error: 'stale_path', path: path.join('/') });
+ var out = {};
+ try { var pr = el.properties(); out.role = String(pr.role || ''); out.title = pr.title != null ? String(pr.title) : null;
+ out.value = pr.value != null ? String(pr.value) : null; out.subrole = pr.subrole ? String(pr.subrole) : null;
+ out.enabled = pr.enabled === undefined ? null : Boolean(pr.enabled);
+ var pos = pr.position; if (pos) { out.x = Number(pos[0]); out.y = Number(pos[1]); }
+ var sz = pr.size; if (sz) { out.w = Number(sz[0]); out.h = Number(sz[1]); }
+ } catch (e) {}
+ var acts = [];
+ try { var as = el.actions(); for (var a = 0; a < as.length; a++) { try { acts.push(String(as[a].name())); } catch (_) {} } } catch (_) {}
+ out.actions = acts;
+ return JSON.stringify({ app: String(p.name()), pid: Number(p.unixId()), element: out });
+ })()`;
+
+/** Act on a resolved element: AXPress via System Events' click (with an
+ * optional CGEvent coordinate fallback handled driver-side). */
+const AX_PRESS_SCRIPT = `
+ (function () {
+ var se = Application('System Events');
+ var wantPid = __WANT_PID__, wantName = __WANT_NAME__, wantFront = __WANT_FRONT__;
+ var path = String(__PATH__).split('/');
+ var procs = se.processes.whose({ backgroundOnly: false })();
+ var p = null;
+ for (var i = 0; i < procs.length; i++) {
+ var q = procs[i], pid = 0, name = '', front = false;
+ try { pid = Number(q.unixId()); } catch (_) {}
+ try { name = String(q.name()); } catch (_) {}
+ try { front = Boolean(q.frontmost()); } catch (_) {}
+ if (wantPid ? pid === wantPid : (String(wantName) ? (name === wantName || name.toLowerCase() === String(wantName).toLowerCase()) : front)) { p = q; break; }
+ }
+ if (!p) return JSON.stringify({ error: 'no_process' });
+ var el = null;
+ try {
+ el = p.windows()[Number(path[0])];
+ for (var j = 1; j < path.length && el; j++) el = el.uiElements()[Number(path[j])];
+ } catch (e) { el = null; }
+ if (!el) return JSON.stringify({ error: 'stale_path', path: path.join('/') });
+ var center = null;
+ try { var pos = el.position(), sz = el.size(); center = [Number(pos[0]) + Number(sz[0]) / 2, Number(pos[1]) + Number(sz[1]) / 2]; } catch (_) {}
+ try { el.click(); return JSON.stringify({ ok: true, via: 'AXPress', center: center }); }
+ catch (e) { return JSON.stringify({ ok: false, error: String(e), center: center, actions: (function(){ var a=[]; try { var as=el.actions(); for (var i2=0;i2<as.length;i2++) a.push(String(as[i2].name())); } catch(_){} return a; })() }); }
+ })()`;
+
+/** Set an AX-writable value (text fields/areas); read-back verified. */
+const AX_SET_SCRIPT = `
+ (function () {
+ var se = Application('System Events');
+ var wantPid = __WANT_PID__, wantName = __WANT_NAME__, wantFront = __WANT_FRONT__;
+ var path = String(__PATH__).split('/'), value = __VALUE__;
+ var procs = se.processes.whose({ backgroundOnly: false })();
+ var p = null;
+ for (var i = 0; i < procs.length; i++) {
+ var q = procs[i], pid = 0, name = '', front = false;
+ try { pid = Number(q.unixId()); } catch (_) {}
+ try { name = String(q.name()); } catch (_) {}
+ try { front = Boolean(q.frontmost()); } catch (_) {}
+ if (wantPid ? pid === wantPid : (String(wantName) ? (name === wantName || name.toLowerCase() === String(wantName).toLowerCase()) : front)) { p = q; break; }
+ }
+ if (!p) return JSON.stringify({ error: 'no_process' });
+ var el = null;
+ try {
+ el = p.windows()[Number(path[0])];
+ for (var j = 1; j < path.length && el; j++) el = el.uiElements()[Number(path[j])];
+ } catch (e) { el = null; }
+ if (!el) return JSON.stringify({ error: 'stale_path', path: path.join('/') });
+ try { el.value = value; } catch (e) { return JSON.stringify({ error: 'not_writable', detail: String(e) }); }
+ var back = null;
+ try { back = String(el.value()); } catch (_) {}
+ return JSON.stringify({ ok: true, set: value, readBack: back, verified: back === value });
+ })()`;
+
+/** Fill the __X__ placeholders of an AX script template (numeric or JSON).
+ * Split/join fills: `$`-sequences in user strings must never be
+ * interpreted as replacement patterns. */
+function axScript(template, { pid, name, front, path, value, maxNodes, maxDepth }) {
+ let out = template;
+ const fill = (ph, v) => { out = out.split(ph).join(v); };
+ fill("__WANT_PID__", String(Number(pid) || 0));
+ fill("__WANT_NAME__", JSON.stringify(String(name ?? "")));
+ fill("__WANT_FRONT__", String(front === true));
+ fill("__PATH__", JSON.stringify(String(path ?? "")));
+ fill("__VALUE__", JSON.stringify(value === undefined ? "" : String(value)));
+ fill("__MAX_NODES__", String(Number(maxNodes) || 250));
+ fill("__MAX_DEPTH__", String(Number(maxDepth) || 10));
+ return out;
+}
+
+/** Friendly role names for the snapshot text (raw roles kept in JSON). */
+const AX_ROLE_NAMES = {
+ AXButton: "button", AXCheckBox: "checkbox", AXRadioButton: "radio", AXMenu: "menu",
+ AXMenuItem: "menuitem", AXTextField: "textfield", AXTextArea: "textarea",
+ AXStaticText: "text", AXImage: "image", AXSlider: "slider", AXComboBox: "combobox",
+ AXPopUpButton: "popup", AXTabGroup: "tabs", AXTab: "tab", AXTable: "table",
+ AXRow: "row", AXCell: "cell", AXScrollArea: "scroll", AXGroup: "group",
+ AXWindow: "window", AXSheet: "sheet", AXToolbar: "toolbar", AXLink: "link",
+ AXList: "list", AXOutline: "outline", AXValueIndicator: "indicator", AXProgressIndicator: "progress",
+ AXMenuBar: "menubar", AXMenuBarItem: "menubaritem", AXSplitGroup: "splitter",
+};
+
+function axRef(path) {
+ // "0/1/0" → "ax1.2.1": 1-based indices only. Paths are unique, so no
+ // depth prefix is needed (a concatenated prefix made refs ambiguous).
+ return `ax${path.split("/").map((n) => String(Number(n) + 1)).join(".")}`;
+}
+
+/** Render the flat node array as browser-observe-style indented text. */
+export function axRenderTree(nodes) {
+ const lines = [];
+ const byRef = new Map();
+ const walk = (idx, indent) => {
+ const n = nodes[idx];
+ if (!n) return;
+ const ref = axRef(n.path);
+ byRef.set(ref, n);
+ const role = AX_ROLE_NAMES[n.role] ?? String(n.role ?? "element").replace(/^AX/, "").toLowerCase();
+ const bits = [];
+ if (n.title) bits.push(`"${n.title}"`);
+ if (n.value != null && n.value !== "" && n.value !== n.title) bits.push(`value=${JSON.stringify(String(n.value).slice(0, 60))}`);
+ if (n.enabled === false) bits.push("disabled");
+ if (n.w != null && n.h != null && n.x != null && n.y != null) bits.push(`box=${Math.round(n.x)},${Math.round(n.y)},${Math.round(n.w)}x${Math.round(n.h)}`);
+ lines.push(`${" ".repeat(indent)}${role}${bits.length ? ` ${bits.join(" ")}` : ""}${["button", "checkbox", "radio", "menuitem", "textfield", "textarea", "popup", "tab", "link"].includes(role) ? " [act]" : ""} [ref=${ref}]`);
+ for (let i = 0; i < nodes.length; i++) if (nodes[i]?.p === idx) walk(i, indent + 1);
+ };
+ for (let i = 0; i < nodes.length; i++) if (nodes[i]?.p == null) walk(i, 0);
+ return { text: lines.join("\n"), byRef };
+}
+
+const WINDOWS_SCRIPT = ` (function () {
+ var se = Application('System Events');
+ var processes = se.processes.whose({ backgroundOnly: false })();
+ var out = [], windowAccess = true, frontmost = null;
+ for (var i = 0; i < processes.length; i++) {
+ var p = processes[i], name = '', pid = null, windows = [], isFront = false;
+ try { name = String(p.name()); } catch (_) {}
+ try { pid = Number(p.unixId()); } catch (_) {}
+ try { isFront = Boolean(p.frontmost()); if (isFront) frontmost = pid; } catch (_) {}
+ // Reading process.windows requires Accessibility. Keep a process-level
+ // fallback so window discovery remains useful before that grant exists.
+ try {
+ var ws = p.windows();
+ for (var j = 0; j < ws.length; j++) {
+ try {
+ var row = { title: String(ws[j].name()) || null };
+ try { var pos = ws[j].position(); row.x = Number(pos[0]); row.y = Number(pos[1]); } catch (_) {}
+ try { var size = ws[j].size(); row.w = Number(size[0]); row.h = Number(size[1]); } catch (_) {}
+ windows.push(row);
+ } catch (_) {}
+ }
+ } catch (_) { windowAccess = false; }
+ out.push({ name: name, pid: pid, windows: windows, frontmost: isFront });
+ }
+ return JSON.stringify({ window_access: windowAccess, frontmost_pid: frontmost, processes: out });
+ })()`;
+
+export class MacDriver {
+ /** `runFn` is injectable for deterministic unit tests of the protocol. */
+ constructor({ runFn = run } = {}) {
+ this.runFn = runFn;
+ this._infoCache = null;
+ this._permCache = null;
+ // Gestures must never interleave: a click issued while a drag holds the
+ // button would post down/up pairs in arbitrary order (same discipline as
+ // the resident Windows driver's op chain).
+ this._opChain = Promise.resolve();
+ }
+
+ /** Serialize an operation against all other input gestures. Probes
+ * (screen_info/permissions) run outside the chain — they post nothing. */
+ _serialized(fn) {
+ const run = () => fn();
+ this._opChain = this._opChain.then(run, run);
+ return this._opChain;
+ }
+
+ /** Drop cached probe state so the next call re-probes TCC and displays.
+ * Called after every permission-classified failure: a grant made after a
+ * denial is visible on the very next operation (recovery without restart). */
+ invalidateCaches() {
+ this._infoCache = null;
+ this._permCache = null;
+ this._naturalScroll = null;
+ }
+
+ command(file, args, options) {
+ return this.runFn(file, args, options);
+ }
+
+ jxa(code) {
+ return this.command("osascript", ["-l", "JavaScript", "-e", code]);
+ }
+
+ applescript(code) {
+ return this.command("osascript", ["-e", code]);
+ }
+
+ async screenInfo({ refresh = false } = {}) {
+ const hit = !refresh && this._infoCache && Date.now() - this._infoCache.ts < PROBE_CACHE_TTL_MS;
+ if (hit) return this._infoCache.value;
+ let info;
+ try {
+ info = parseJson(await this.jxa(SCREEN_INFO_SCRIPT), "screen_info");
+ } catch (e) {
+ // A headless macOS session (SSH, CI without WindowServer) has no
+ // display server to talk to — report that specifically instead of a
+ // generic op failure.
+ if (/WindowServer|screen server|cannot open|connection.*invalid|no GUI/i.test(e.message)) {
+ throw new AxError(Codes.DESKTOP_OP_FAILED,
+ `macOS display probes are unavailable in this session (${e.message.slice(0, 200)})`,
+ { hint: "Desktop tools need a logged-in GUI session (WindowServer). In SSH/CI contexts use the ax_* browser tools, which work headless.", retry: "never" });
+ }
+ throw e;
+ }
+ if (!["x", "y", "w", "h"].every((key) => Number.isFinite(Number(info[key]))) || Number(info.w) < 1 || Number(info.h) < 1) {
+ throw new AxError(Codes.DESKTOP_OP_FAILED, "macOS returned incomplete display bounds",
+ { hint: "Retry after the display session is ready. If this is an SSH/headless session, desktop tools are unavailable — use the ax_* browser tools.", retry: "retry" });
+ }
+ const value = {
+ x: Number(info.x), y: Number(info.y), w: Number(info.w), h: Number(info.h),
+ display_id: Number(info.display_id),
+ pixels_w: Number(info.pixels_w), pixels_h: Number(info.pixels_h),
+ scale_x: Number(info.scale_x) || 1, scale_y: Number(info.scale_y) || 1,
+ coordinate_space: "macOS global display points",
+ display_count: Number(info.display_count) || 1,
+ displays: Array.isArray(info.displays) ? info.displays : undefined,
+ note: "active display layout; screenshots are resized to point dimensions for direct coordinate mapping",
+ };
+ this._infoCache = { ts: Date.now(), value };
+ return value;
+ }
+
+ async permissions({ refresh = false } = {}) {
+ const hit = !refresh && this._permCache && Date.now() - this._permCache.ts < PROBE_CACHE_TTL_MS;
+ if (hit) return this._permCache.value;
+ let out;
+ try {
+ out = parseJson(await this.jxa(PERMISSIONS_SCRIPT), "permissions");
+ } catch (e) {
+ // Probe failure (e.g. headless session): unknown, not "denied" — the
+ // operations themselves still fail closed with their own typed errors.
+ return { accessibility: false, screen_recording: null, error: e.message };
+ }
+ const value = { accessibility: Boolean(out.accessibility), screen_recording: out.screen_recording === null || out.screen_recording === undefined ? null : Boolean(out.screen_recording) };
+ this._permCache = { ts: Date.now(), value };
+ return value;
+ }
+
+ /** EXPLICIT, user-initiated only: ask macOS to open the TCC prompts for
+ * this binary (AXIsProcessTrustedWithOptions with the prompt option and
+ * CGRequestScreenCaptureAccess). Never called by probes or ops — the
+ * doctor exposes it behind --request-tcc so nothing ever prompts
+ * silently. Returns the state AFTER the request (the prompt itself is
+ * answered by the human, possibly later). */
+ async requestPermissions() {
+ const out = parseJson(await this.jxa(`
+ ObjC.import('ApplicationServices');
+ ObjC.import('CoreGraphics');
+ (function () {
+ var opts = $.CFDictionaryCreate(null, [$.kAXTrustedCheckOptionPrompt], [true], 1, null, null);
+ var accessibility = Boolean($.AXIsProcessTrustedWithOptions(opts));
+ var requested = false;
+ try {
+ ObjC.bindFunction('CGRequestScreenCaptureAccess', ['bool', []]);
+ requested = Boolean($.CGRequestScreenCaptureAccess());
+ } catch (_) {}
+ return JSON.stringify({ accessibility: accessibility, screen_capture_prompt: requested });
+ })()`), "request_permissions");
+ this._permCache = null; // re-probe next time (the human may grant async)
+ return {
+ accessibility: Boolean(out.accessibility),
+ screen_recording_prompt_opened: Boolean(out.screen_capture_prompt),
+ note: "If the prompts were dismissed, grant manually in System Settings → Privacy & Security; Screen Recording requires restarting this host after granting.",
+ };
+ }
+
+ /** Construct, but never post, native input events. Safe for doctor/CI. */
+ async probe() {
+ const events = ["moved", "down", "up", "rdown", "rup", "mdown", "mup", "drag"]
+ .map((kind) => ({ kind, x: 0, y: 0 }));
+ events.push({ kind: "scroll", dx: 0, dy: 1 }, { kind: "scroll", dx: 1, dy: 0 });
+ await this.jxa(mouseSequenceCode(events, { post: false }));
+ return { native_events: "ok" };
+ }
+
+ async screenshot({ x, y, w, h, budgetBytes = DEFAULT_BUDGET_BYTES, quality = 80 } = {}) {
+ let info = await this.screenInfo();
+ let rect;
+ try {
+ rect = rectValues({ x, y, w, h }, info);
+ } catch (e) {
+ // The cached layout may predate a display change (resolution, monitor
+ // plugged in): re-probe once before rejecting the caller's coordinates.
+ if (e.code !== Codes.BAD_COORDS || !this._infoCache) throw e;
+ info = await this.screenInfo({ refresh: true });
+ rect = rectValues({ x, y, w, h }, info);
+ }
+ const budget = positive(budgetBytes, "budgetBytes");
+ const requestedQuality = Math.round(finite(quality, "quality"));
+ if (requestedQuality < 1 || requestedQuality > 100) {
+ throw new AxError(Codes.COMMAND_REJECTED, "quality must be between 1 and 100", { retry: "never" });
+ }
+ const permissions = await this.permissions();
+ if (permissions.screen_recording === false) {
+ throw new AxError(Codes.DESKTOP_PERMISSION_REQUIRED,
+ "macOS Screen Recording permission is not granted",
+ { hint: PERMISSION_HINT, retry: "retry" });
+ }
+ const dir = mkdtempSync(join(tmpdir(), "axuse-shot-"));
+ const png = join(dir, "capture.png");
+ const jpg = join(dir, "capture.jpg");
+ const fallbackQuality = Math.min(requestedQuality, 45);
+ const sipsHint = "The screenshot was captured, but macOS could not encode it. Check that /usr/bin/sips is available.";
+ try {
+ try {
+ await this.command("screencapture", ["-x", "-t", "png", "-R", `${rect.x},${rect.y},${rect.w},${rect.h}`, png]);
+ } catch (e) {
+ if (e.code === Codes.DESKTOP_PERMISSION_REQUIRED) this.invalidateCaches();
+ throw e;
+ }
+ let usedQuality = requestedQuality;
+ await this.command("sips", [
+ "-s", "format", "jpeg", "-s", "formatOptions", String(usedQuality),
+ "-z", String(rect.h), String(rect.w), png, "--out", jpg,
+ ], { hint: sipsHint });
+ let base64 = readFileSync(jpg, "base64");
+ let bytes = exactBase64Bytes(base64);
+ if (bytes > budget && fallbackQuality !== usedQuality) {
+ usedQuality = fallbackQuality;
+ await this.command("sips", [
+ "-s", "format", "jpeg", "-s", "formatOptions", String(usedQuality),
+ "-z", String(rect.h), String(rect.w), png, "--out", jpg,
+ ], { hint: sipsHint });
+ base64 = readFileSync(jpg, "base64");
+ bytes = exactBase64Bytes(base64);
+ }
+ if (bytes > budget) {
+ throw new AxError(Codes.SCREENSHOT_BUDGET_EXCEEDED,
+ `Desktop screenshot is ${bytes} bytes, over the ${budget} byte budget even at quality ${usedQuality}.`,
+ { hint: "Pass a smaller crop region in macOS display points or raise budget_bytes.", retry: "never" });
+ }
+ return {
+ base64, mime: "image/jpeg", bytes, budget_bytes: budget, quality: usedQuality,
+ geometry: `image ${rect.w}x${rect.h} = macOS display points; pass ax_desktop_click coordinates in the same space`,
+ };
+ } finally {
+ try { rmSync(dir, { recursive: true, force: true }); } catch {}
+ }
+ }
+
+ async move(x, y) {
+ x = finite(x, "x"); y = finite(y, "y");
+ await this._serialized(() => this.jxa(mouseCode("moved", x, y)));
+ return { action_sent: "sent" };
+ }
+
+ async click({ x, y, button = "left", double = false } = {}) {
+ x = finite(x, "x"); y = finite(y, "y");
+ const b = buttonSpec(button);
+ const down = b === "right" ? "rdown" : b === "middle" ? "mdown" : "down";
+ const up = b === "right" ? "rup" : b === "middle" ? "mup" : "up";
+ // One osascript for the whole gesture — including the double click, whose
+ // second pair carries clickState=2 (what Cocoa reads as a double click).
+ const events = [
+ { kind: "moved", x, y },
+ { kind: down, x, y, clickState: 1 }, { kind: up, x, y, clickState: 1 },
+ ];
+ if (double) events.push({ kind: down, x, y, clickState: 2 }, { kind: up, x, y, clickState: 2 });
+ await this._serialized(() => this.jxa(mouseSequenceCode(events)));
+ return { action_sent: "sent" };
+ }
+
+ async drag({ from, to, steps = 12 } = {}) {
+ const start = { x: finite(from?.x, "from.x"), y: finite(from?.y, "from.y") };
+ const end = { x: finite(to?.x, "to.x"), y: finite(to?.y, "to.y") };
+ const requestedSteps = finite(steps, "steps");
+ if (requestedSteps < 1) throw new AxError(Codes.COMMAND_REJECTED, "steps must be ≥ 1", { retry: "never" });
+ const count = Math.round(requestedSteps);
+ if (count < 1) throw new AxError(Codes.COMMAND_REJECTED, "steps must round to at least 1", { retry: "never" });
+ if (count > 200) throw new AxError(Codes.COMMAND_REJECTED, "steps must be ≤ 200", { retry: "never" });
+ await this._serialized(async () => {
+ let held = false;
+ try {
+ // Hover + press in one script: the gesture stays atomic up to the hold.
+ await this.jxa(mouseSequenceCode([
+ { kind: "moved", x: start.x, y: start.y }, { kind: "down", x: start.x, y: start.y },
+ ]));
+ held = true;
+ const moves = [];
+ for (let i = 1; i <= count; i++) moves.push({
+ kind: "drag",
+ x: Math.round(start.x + ((end.x - start.x) * i) / count),
+ y: Math.round(start.y + ((end.y - start.y) * i) / count),
+ });
+ await this.jxa(mouseSequenceCode(moves));
+ } finally {
+ // The release runs in the SAME chain slot — a held button can never
+ // leak past this call, and no queued gesture can interleave with it.
+ if (held) await this.jxa(mouseSequenceCode([{ kind: "up", x: end.x, y: end.y }]));
+ }
+ });
+ return { action_sent: "sent" };
+ }
+
+ /** True when the user's Natural Scrolling preference is on (the macOS
+ * default). Wheel semantics then invert: the SAME content direction needs
+ * the opposite CG delta. Cached for the process; injectable for tests. */
+ async _naturalScrolling({ refresh = false } = {}) {
+ if (!refresh && this._naturalScroll !== null && this._naturalScroll !== undefined) return this._naturalScroll;
+ let natural = false;
+ try {
+ const out = await this.command("defaults", ["read", "-g", "com.apple.swipescrolldirection"]);
+ natural = String(out).trim() === "1";
+ } catch {
+ natural = true; // macOS default when the key is unset/unreadable
+ }
+ this._naturalScroll = natural;
+ return natural;
+ }
+
+ async wheel(dx = 0, dy = 0) {
+ dx = finite(dx, "dx"); dy = finite(dy, "dy");
+ if (dx !== 0 || dy !== 0) {
+ // Contract (matches ax_scroll in the browser): dy>0 scrolls content
+ // DOWN, dy<0 UP; dx>0 LEFT-to-right. CG deltas encode the wheel, not
+ // the content: under Natural Scrolling a negative delta moves content
+ // down; under traditional scrolling a positive one does.
+ const natural = await this._naturalScrolling();
+ const map = (v) => (natural ? -v : v);
+ const events = dy !== 0 || dx !== 0 ? [{
+ kind: "scroll",
+ dx: dx !== 0 ? map(dx) : 0,
+ dy: dy !== 0 ? map(dy) : 0,
+ }] : [];
+ await this._serialized(() => this.jxa(mouseSequenceCode(events)));
+ }
+ return { action_sent: "sent" };
+ }
+
+ async type(text) {
+ if (typeof text !== "string") {
+ throw new AxError(Codes.COMMAND_REJECTED, "text must be a string", { retry: "never" });
+ }
+ if (text.length === 0) {
+ // Nothing to type: do not spawn osascript (and never trigger the
+ // Accessibility path) for a guaranteed no-op.
+ return { action_sent: "sent", note: "empty string: no events posted" };
+ }
+ const value = JSON.stringify(text);
+ await this._serialized(() => this.jxa(`ObjC.import('ApplicationServices'); if (!$.AXIsProcessTrusted()) throw new Error('Accessibility permission required'); const se = Application("System Events"); se.keystroke(${value}); "ok"`));
+ return { action_sent: "sent" };
+ }
+
+ async press(combo) {
+ const { mods, main, keyCode } = parseMacCombo(combo);
+ const using = mods.length ? ` using {${mods.join(", ")}}` : "";
+ if (keyCode !== undefined) {
+ await this._serialized(() => this.applescript(`tell application "System Events" to key code ${keyCode}${using}`));
+ } else if (main.length === 1) {
+ await this._serialized(() => this.applescript(`tell application "System Events" to keystroke ${appleScriptLiteral(main)}${using}`));
+ } else {
+ throw new AxError(Codes.COMMAND_REJECTED, `Unknown key "${main}" in combo`, { retry: "never" });
+ }
+ return { action_sent: "sent", combo };
+ }
+
+ async windows() {
+ // System Events walk (needs Accessibility for window rows; process-level
+ // rows come back without it). Costs one Apple Event per window attribute
+ // — ~1 s with many processes — so agents should treat this as an anchor
+ // call, not a poll. Row bounds (global display points) let an agent
+ // target a window's content directly.
+ const payload = parseJson(await this.jxa(WINDOWS_SCRIPT), "windows_ax");
+ const axRows = Array.isArray(payload?.processes) ? payload.processes : [];
+ const axAccessFull = payload?.window_access === true;
+ const axAccess = Array.isArray(payload) ? "unknown" : axAccessFull ? "full" : "process-fallback";
+
+ const windows = [];
+ for (const row of axRows) {
+ if (!row || !row.name) continue;
+ const pid = Number(row.pid);
+ if (!Number.isFinite(pid)) continue;
+ const rows = Array.isArray(row.windows) ? row.windows : [];
+ if (rows.length) {
+ for (const w of rows) {
+ windows.push({
+ title: String(w?.title ?? row.name),
+ pid,
+ application: String(row.name),
+ hwnd: null,
+ ...(row.frontmost ? { frontmost: true } : {}),
+ ...(Number.isFinite(w?.x) && Number.isFinite(w?.w)
+ ? { bounds: { x: w.x, y: w.y ?? 0, w: w.w, h: w.h ?? 0 }, coordinates: "macOS global display points" }
+ : {}),
+ });
+ }
+ } else if (!axAccessFull) {
+ windows.push({ title: String(row.name), pid, application: String(row.name), hwnd: null, ...(row.frontmost ? { frontmost: true } : {}) });
+ }
+ }
+ // Frontmost app's windows first — the row an agent almost always wants.
+ windows.sort((a, b) => Number(b.frontmost ?? false) - Number(a.frontmost ?? false));
+ return {
+ windows,
+ coordinate_space: "macOS global display points",
+ window_access: axAccess,
+ frontmost_pid: Number.isFinite(Number(payload?.frontmost_pid)) ? Number(payload.frontmost_pid) : null,
+ note: axAccessFull
+ ? "titles + bounds via System Events (Accessibility granted); bounds are global display points you can click within"
+ : "Accessibility not granted: process-level rows only (no per-window titles/bounds) — grant Accessibility for window-level rows",
+ };
+ }
+
+ async activate({ title, pid, windowId } = {}) {
+ const wantPid = Number.isFinite(Number(pid)) ? Number(pid) : null;
+ if (!title && !wantPid && !windowId) {
+ throw new AxError(Codes.COMMAND_REJECTED, "activate: title, pid, or window_id is required on macOS (use ax_desktop_windows first)", { retry: "never" });
+ }
+ const want = JSON.stringify(String(title ?? "").trim());
+ const wantWindowId = Number(windowId) || 0;
+ const out = parseJson(await this.jxa(`
+ ObjC.import('ApplicationServices');
+ if (!$.AXIsProcessTrusted()) throw new Error('Accessibility permission required');
+ (function () {
+ var se = Application("System Events"), want = ${want}, wantPid = ${wantPid ?? 0}, wantWindowId = ${wantWindowId};
+ var lower = want.toLowerCase();
+ var processes = se.processes.whose({ backgroundOnly: false })();
+ for (var i = 0; i < processes.length; i++) {
+ var p = processes[i], name = "", pid = 0;
+ try { name = String(p.name()); } catch (_) {}
+ try { pid = Number(p.unixId()); } catch (_) {}
+ var match = wantPid ? pid === wantPid : false;
+ if (!match && want) {
+ match = name === want || name.toLowerCase() === lower;
+ if (!match) {
+ try {
+ var ws = p.windows();
+ for (var j = 0; j < ws.length; j++) {
+ var wt = String(ws[j].name());
+ if (wt === want || wt.toLowerCase() === lower) { match = true; break; }
+ }
+ } catch (_) {}
+ }
+ }
+ if (match) { p.frontmost = true; return JSON.stringify({ ok: true, application: name, pid: pid }); }
+ }
+ return JSON.stringify({ ok: false, error: "window or application not found" });
+ })()`), "activate");
+ if (!out.ok) {
+ throw new AxError(Codes.DESKTOP_OP_FAILED, `macOS activate failed: ${out.error}`, { hint: `${PERMISSION_HINT} Use an exact application name, window title, or the pid from ax_desktop_windows.`, retry: "retry" });
+ }
+ return { activated: true, application: out.application, pid: out.pid };
+ }
+
+
+ async down() { throw unsupported("mouse down (hold)"); }
+ async up() { throw unsupported("mouse up (release)"); }
+
+ /* ------------------------------------------------------------ AX layer */
+
+ /** Structure-first snapshot of one app's AX tree (browser-observe style).
+ * Refs are path-encoded (axD<i>.<j>…) and re-resolved LIVE by the act
+ * ops — the same discipline as browser refs. */
+ async axSnapshot({ pid, name, front, maxNodes = 250, maxDepth = 10 } = {}) {
+ if (!Number.isFinite(Number(pid)) && !name && front !== true) {
+ throw new AxError(Codes.COMMAND_REJECTED, "ax_snapshot: one of pid, name, or front=true is required", { retry: "never" });
+ }
+ const useFront = front ?? (!pid && !name);
+ const out = parseJson(await this.jxa(axScript(AX_SNAPSHOT_SCRIPT, { pid, name, front: useFront, maxNodes, maxDepth })), "ax_snapshot");
+ if (out.error === "no_process") {
+ throw new AxError(Codes.REF_NOT_FOUND, `no running app matches ${out.want}`,
+ { hint: "List apps with ax_desktop_windows, or use front:true for the active app.", retry: "reobserve" });
+ }
+ if (out.error === "no_windows_access") {
+ throw new AxError(Codes.DESKTOP_PERMISSION_REQUIRED, `cannot read ${out.app}'s windows — Accessibility is not granted`,
+ { hint: PERMISSION_HINT, retry: "retry" });
+ }
+ const nodes = Array.isArray(out.nodes) ? out.nodes : [];
+ const { text, byRef } = axRenderTree(nodes);
+ return {
+ app: out.app, pid: out.pid, window_count: out.window_count,
+ nodes: nodes.length,
+ truncated_children: out.truncated_children || 0,
+ hit_max_nodes: !!out.hit_max_nodes,
+ hit_max_depth: !!out.hit_max_depth,
+ text,
+ refs: [...byRef.keys()].length,
+ note: "refs are live-re-resolved at action time; bounds are in macOS global display points",
+ };
+ }
+
+ /** Decode an ax ref back to a tree path ("ax1.2.1" → "0/1/0"). */
+ static axRefToPath(ref) {
+ const m = /^ax(\d+(?:\.\d+)*)$/.exec(String(ref ?? "").trim());
+ if (!m) return null;
+ const parts = m[1].split(".").map((n) => Number(n) - 1);
+ if (parts.some((n) => !Number.isInteger(n) || n < 0)) return null;
+ return parts.join("/");
+ }
+
+ _axTarget({ pid, name, front = true } = {}) {
+ return { pid, name, front };
+ }
+
+ async axRead({ ref, pid, name, front } = {}) {
+ const path = MacDriver.axRefToPath(ref);
+ if (!path) throw new AxError(Codes.COMMAND_REJECTED, `ax_read: malformed ref "${ref}"`, { retry: "never" });
+ const useFront = front ?? (!pid && !name);
+ const out = parseJson(await this.jxa(axScript(AX_RESOLVE_SCRIPT, { pid, name, front: useFront, path })), "ax_read");
+ if (out.error === "stale_path" || out.error === "no_process") {
+ throw new AxError(Codes.REF_NOT_FOUND, `ref "${ref}" no longer resolves (${out.error})`,
+ { hint: "The UI changed under you — take a fresh ax_snapshot.", retry: "reobserve" });
+ }
+ return { app: out.app, pid: out.pid, ref, ...out.element };
+ }
+
+ async axClick({ ref, pid, name, front, fallbackToCoords = true } = {}) {
+ const path = MacDriver.axRefToPath(ref);
+ if (!path) throw new AxError(Codes.COMMAND_REJECTED, `ax_click: malformed ref "${ref}"`, { retry: "never" });
+ const useFront = front ?? (!pid && !name);
+ const out = parseJson(await this.jxa(axScript(AX_PRESS_SCRIPT, { pid, name, front: useFront, path })), "ax_click");
+ if (out.error === "stale_path" || out.error === "no_process") {
+ throw new AxError(Codes.REF_NOT_FOUND, `ref "${ref}" no longer resolves (${out.error})`,
+ { hint: "The UI changed under you — take a fresh ax_snapshot.", retry: "reobserve" });
+ }
+ if (out.ok) return { action_sent: "sent", via: "AXPress", ref };
+ // AXPress failed (some apps refuse programmatic press): fall back to a
+ // trusted CGEvent click at the element's live center — geometry came
+ // from the SAME resolve call, so it cannot be stale.
+ if (fallbackToCoords && Array.isArray(out.center) && Number.isFinite(out.center[0]) && Number.isFinite(out.center[1])) {
+ await this.click({ x: out.center[0], y: out.center[1] });
+ return { action_sent: "sent", via: "coordinate-fallback (AXPress refused)", ref };
+ }
+ throw new AxError(Codes.DESKTOP_OP_FAILED,
+ `AXPress refused for "${ref}" and no bounds for a coordinate fallback`,
+ { hint: `Element actions: ${(out.actions ?? []).join(", ") || "none reported"}. Use ax_read to re-observe.`, retry: "retry" });
+ }
+
+ async axSet({ ref, value, pid, name, front } = {}) {
+ if (value === undefined || value === null) {
+ throw new AxError(Codes.COMMAND_REJECTED, "ax_set: value is required", { retry: "never" });
+ }
+ const path = MacDriver.axRefToPath(ref);
+ if (!path) throw new AxError(Codes.COMMAND_REJECTED, `ax_set: malformed ref "${ref}"`, { retry: "never" });
+ const useFront = front ?? (!pid && !name);
+ const out = parseJson(await this.jxa(axScript(AX_SET_SCRIPT, { pid, name, front: useFront, path, value: String(value) })), "ax_set");
+ if (out.error === "stale_path" || out.error === "no_process") {
+ throw new AxError(Codes.REF_NOT_FOUND, `ref "${ref}" no longer resolves (${out.error})`,
+ { hint: "The UI changed under you — take a fresh ax_snapshot.", retry: "reobserve" });
+ }
+ if (out.error === "not_writable") {
+ throw new AxError(Codes.COMMAND_REJECTED, `element "${ref}" is not AX-writable (${out.detail?.slice(0, 120) ?? "no settable value"})`,
+ { hint: "Text fields/areas are writable; for others use ax_click.", retry: "never" });
+ }
+ return { action_sent: "sent", ref, set: out.set, readBack: out.readBack, verified: !!out.verified,
+ ...(out.verified ? {} : { note: "read-back mismatch reported, never assumed" }) };
+ }
+
+ dispose() {}
+}
+
+function unsupported(op) {
+ return new AxError(Codes.DESKTOP_OP_FAILED,
+ `Op "${op}" is not implemented on the macOS driver.`,
+ { hint: "Use ax_desktop_drag for a complete drag gesture; file an issue for a separately held button gesture.", retry: "never" });
+}
diff --git a/src/desktop/windows.ps1 b/src/desktop/windows.ps1
new file mode 100644
index 0000000..2fbbca1
--- /dev/null
+++ b/src/desktop/windows.ps1
@@ -0,0 +1,234 @@
+# axuse Windows desktop driver.
+# Lineage: ZCode's Computer Use Helper — a separate native-privileged process
+# that owns input/screen grants while the agent-side stays credential-free.
+# Here: a resident PowerShell process with a line-delimited JSON protocol.
+# Input uses SendInput (trusted OS input events); screenshots are physical-pixel
+# JPEG via GDI+ (DPI-aware). 64-bit PowerShell required (INPUT union layout).
+#
+# One op per line in, one JSON object per line out. Ops:
+# screen_info | screenshot | move | click | down | up | wheel |
+# key_down | key_up | key_tap | key_text | windows | activate
+
+$ErrorActionPreference = 'Stop'
+try {
+ [Console]::InputEncoding = [System.Text.Encoding]::UTF8
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
+} catch {}
+
+if (-not [Environment]::Is64BitProcess) {
+ [Console]::Out.WriteLine(('{"ok":false,"error":"64-bit PowerShell required"}' | ConvertTo-Json -Compress))
+ exit 1
+}
+
+Add-Type -AssemblyName System.Drawing
+
+Add-Type -TypeDefinition @"
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using System.Text;
+
+public class AxWin {
+ [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
+ [DllImport("user32.dll")] public static extern int GetSystemMetrics(int nIndex);
+ [DllImport("user32.dll")] public static extern bool SetCursorPos(int X, int Y);
+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);
+ [DllImport("user32.dll")] public static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
+ [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd);
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr hWnd, StringBuilder sb, int max);
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowTextLength(IntPtr hWnd);
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);
+ public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
+ [DllImport("user32.dll")] public static extern bool EnumWindows(EnumWindowsProc cb, IntPtr lParam);
+
+ public const uint INPUT_MOUSE = 0, INPUT_KEYBOARD = 1;
+ public const uint MOUSEEVENTF_LEFTDOWN = 0x0002, MOUSEEVENTF_LEFTUP = 0x0004;
+ public const uint MOUSEEVENTF_RIGHTDOWN = 0x0008, MOUSEEVENTF_RIGHTUP = 0x0010;
+ public const uint MOUSEEVENTF_MIDDLEDOWN = 0x0020, MOUSEEVENTF_MIDDLEUP = 0x0040;
+ public const uint MOUSEEVENTF_WHEEL = 0x0800, MOUSEEVENTF_HWHEEL = 0x1000;
+ public const uint KEYEVENTF_KEYUP = 0x0002, KEYEVENTF_UNICODE = 0x0004;
+
+ [StructLayout(LayoutKind.Sequential)]
+ public struct MOUSEINPUT { public int dx; public int dy; public uint mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
+ [StructLayout(LayoutKind.Sequential)]
+ public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
+ [StructLayout(LayoutKind.Explicit)]
+ public struct INPUT { [FieldOffset(0)] public uint type; [FieldOffset(8)] public MOUSEINPUT mi; [FieldOffset(8)] public KEYBDINPUT ki; }
+
+ public static void Send(int type, MOUSEINPUT mi) {
+ INPUT[] inp = new INPUT[1];
+ inp[0].type = (uint)type; inp[0].mi = mi;
+ SendInput(1, inp, Marshal.SizeOf(typeof(INPUT)));
+ }
+ public static void SendKey(KEYBDINPUT ki) {
+ INPUT[] inp = new INPUT[1];
+ inp[0].type = INPUT_KEYBOARD; inp[0].ki = ki;
+ SendInput(1, inp, Marshal.SizeOf(typeof(INPUT)));
+ }
+ public static void Button(uint down, uint up) {
+ MOUSEINPUT m = new MOUSEINPUT();
+ m.dwFlags = down; Send((int)INPUT_MOUSE, m);
+ m.dwFlags = up; Send((int)INPUT_MOUSE, m);
+ }
+ public static void ClickButton(string button, bool dbl) {
+ uint down, up;
+ switch (button) {
+ case "right": down = MOUSEEVENTF_RIGHTDOWN; up = MOUSEEVENTF_RIGHTUP; break;
+ case "middle": down = MOUSEEVENTF_MIDDLEDOWN; up = MOUSEEVENTF_MIDDLEUP; break;
+ default: down = MOUSEEVENTF_LEFTDOWN; up = MOUSEEVENTF_LEFTUP; break;
+ }
+ Button(down, up);
+ if (dbl) { System.Threading.Thread.Sleep(30); Button(down, up); }
+ }
+ public static void Wheel(int dx, int dy) {
+ if (dy != 0) {
+ MOUSEINPUT m = new MOUSEINPUT();
+ m.dwFlags = MOUSEEVENTF_WHEEL;
+ unchecked { m.mouseData = (uint)dy; }
+ Send((int)INPUT_MOUSE, m);
+ }
+ if (dx != 0) {
+ MOUSEINPUT m = new MOUSEINPUT();
+ m.dwFlags = MOUSEEVENTF_HWHEEL;
+ unchecked { m.mouseData = (uint)dx; }
+ Send((int)INPUT_MOUSE, m);
+ }
+ }
+ public static void KeyTap(ushort vk) {
+ KEYBDINPUT k = new KEYBDINPUT();
+ k.wVk = vk; SendKey(k);
+ System.Threading.Thread.Sleep(10);
+ k.dwFlags = KEYEVENTF_KEYUP; SendKey(k);
+ }
+ public static void KeyUpDown(ushort vk, bool up) {
+ KEYBDINPUT k = new KEYBDINPUT();
+ k.wVk = vk; if (up) k.dwFlags = KEYEVENTF_KEYUP; SendKey(k);
+ }
+ public static void TypeText(string text) {
+ foreach (char c in text) {
+ KEYBDINPUT down = new KEYBDINPUT();
+ down.wScan = c; down.dwFlags = KEYEVENTF_UNICODE; SendKey(down);
+ KEYBDINPUT up = new KEYBDINPUT();
+ up.wScan = c; up.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP; SendKey(up);
+ System.Threading.Thread.Sleep(5);
+ }
+ }
+ public static string[] ListWindows() {
+ var list = new List<string>();
+ EnumWindows((h, l) => {
+ if (IsWindowVisible(h)) {
+ int len = GetWindowTextLength(h);
+ if (len > 0) {
+ var sb = new StringBuilder(len + 2);
+ GetWindowText(h, sb, sb.Capacity);
+ uint pid; GetWindowThreadProcessId(h, out pid);
+ string t = (sb.ToString() ?? "").Replace((char)9, ' ').Trim();
+ if (t.Length > 0) list.Add(h.ToInt64() + ((char)9).ToString() + pid + ((char)9).ToString() + t);
+ }
+ }
+ return true;
+ }, IntPtr.Zero);
+ return list.ToArray();
+ }
+}
+"@
+
+[void][AxWin]::SetProcessDPIAware()
+
+function Get-VirtualScreen {
+ $x = [AxWin]::GetSystemMetrics(76); $y = [AxWin]::GetSystemMetrics(77)
+ $w = [AxWin]::GetSystemMetrics(78); $h = [AxWin]::GetSystemMetrics(79)
+ @{ x = $x; y = $y; w = $w; h = $h }
+}
+
+function Invoke-Screenshot($req) {
+ $vs = Get-VirtualScreen
+ $x = if ($null -ne $req.x) { [int]$req.x } else { [int]$vs.x }
+ $y = if ($null -ne $req.y) { [int]$req.y } else { [int]$vs.y }
+ $w = if ($null -ne $req.w) { [int]$req.w } else { [int]$vs.w }
+ $h = if ($null -ne $req.h) { [int]$req.h } else { [int]$vs.h }
+ $quality = if ($null -ne $req.quality) { [int]$req.quality } else { 80 }
+ if ($w -lt 1 -or $h -lt 1) { return @{ ok = $false; error = "bad capture rect" } }
+ try {
+ $bmp = New-Object System.Drawing.Bitmap($w, $h)
+ $g = [System.Drawing.Graphics]::FromImage($bmp)
+ $g.CopyFromScreen($x, $y, 0, 0, (New-Object System.Drawing.Size($w, $h)))
+ $g.Dispose()
+ $ms = New-Object System.IO.MemoryStream
+ $codec = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where-Object { $_.MimeType -eq 'image/jpeg' }
+ $ep = New-Object System.Drawing.Imaging.EncoderParameters(1)
+ $ep.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter([System.Drawing.Imaging.Encoder]::Quality, [long]$quality)
+ $bmp.Save($ms, $codec, $ep)
+ $bmp.Dispose()
+ $ep.Dispose()
+ @{ ok = $true; base64 = [Convert]::ToBase64String($ms.ToArray()); mime = 'image/jpeg' }
+ } catch {
+ @{ ok = $false; error = "capture failed: $($_.Exception.Message)" }
+ }
+}
+
+function Invoke-Op($req) {
+ switch ($req.op) {
+ 'screen_info' {
+ $vs = Get-VirtualScreen
+ @{ ok = $true; x = [int]$vs.x; y = [int]$vs.y; w = [int]$vs.w; h = [int]$vs.h }
+ }
+ 'screenshot' { Invoke-Screenshot $req }
+ 'move' { [void][AxWin]::SetCursorPos([int]$req.x, [int]$req.y); @{ ok = $true } }
+ 'click' {
+ [void][AxWin]::SetCursorPos([int]$req.x, [int]$req.y)
+ [AxWin]::ClickButton([string]$req.button, [bool]$req.double)
+ @{ ok = $true }
+ }
+ 'down' {
+ if ($req.button -eq 'right') { [AxWin]::Button([AxWin]::MOUSEEVENTF_RIGHTDOWN, [AxWin]::MOUSEEVENTF_RIGHTDOWN) }
+ elseif ($req.button -eq 'middle') { [AxWin]::Button([AxWin]::MOUSEEVENTF_MIDDLEDOWN, [AxWin]::MOUSEEVENTF_MIDDLEDOWN) }
+ else { [AxWin]::Button([AxWin]::MOUSEEVENTF_LEFTDOWN, [AxWin]::MOUSEEVENTF_LEFTDOWN) }
+ @{ ok = $true }
+ }
+ 'up' {
+ if ($req.button -eq 'right') { [AxWin]::Button([AxWin]::MOUSEEVENTF_RIGHTUP, [AxWin]::MOUSEEVENTF_RIGHTUP) }
+ elseif ($req.button -eq 'middle') { [AxWin]::Button([AxWin]::MOUSEEVENTF_MIDDLEUP, [AxWin]::MOUSEEVENTF_MIDDLEUP) }
+ else { [AxWin]::Button([AxWin]::MOUSEEVENTF_LEFTUP, [AxWin]::MOUSEEVENTF_LEFTUP) }
+ @{ ok = $true }
+ }
+ 'wheel' { [AxWin]::Wheel([int]$req.dx, [int]$req.dy); @{ ok = $true } }
+ 'key_down' { [AxWin]::KeyUpDown([int]$req.vk, $false); @{ ok = $true } }
+ 'key_up' { [AxWin]::KeyUpDown([int]$req.vk, $true); @{ ok = $true } }
+ 'key_tap' { [AxWin]::KeyTap([int]$req.vk); @{ ok = $true } }
+ 'key_text' { [AxWin]::TypeText([string]$req.text); @{ ok = $true } }
+ 'windows' {
+ $rows = [AxWin]::ListWindows() | ForEach-Object {
+ $p = $_ -split "`t", 3
+ [ordered]@{ hwnd = [int64]$p[0]; pid = [int]$p[1]; title = [string]$p[2] }
+ }
+ @{ ok = $true; windows = @($rows) }
+ }
+ 'activate' {
+ $ok = $false
+ if ($null -ne $req.hwnd) { $ok = [AxWin]::SetForegroundWindow([IntPtr][int64]$req.hwnd) }
+ elseif ($null -ne $req.title) {
+ $match = [AxWin]::ListWindows() | ForEach-Object {
+ $p = $_ -split "`t", 3
+ [pscustomobject]@{ hwnd = [int64]$p[0]; title = [string]$p[2] }
+ } | Where-Object { $_.title -like "*$($req.title)*" } | Select-Object -First 1
+ if ($match) { $ok = [AxWin]::SetForegroundWindow([IntPtr][int64]$match.hwnd) }
+ }
+ if ($ok) { @{ ok = $true } } else { @{ ok = $false; error = 'activate failed (window not found or foreground lock)' } }
+ }
+ default { @{ ok = $false; error = "unknown op $($req.op)" } }
+ }
+}
+
+while ($true) {
+ $line = [Console]::In.ReadLine()
+ if ($null -eq $line) { break }
+ if ([string]::IsNullOrWhiteSpace($line)) { continue }
+ $res = $null
+ try { $res = Invoke-Op ($line | ConvertFrom-Json) }
+ catch { $res = @{ ok = $false; error = "$_" } }
+ try {
+ [Console]::Out.WriteLine(($res | ConvertTo-Json -Compress -Depth 6))
+ [Console]::Out.Flush()
+ } catch { break }
+}
diff --git a/src/mcp/manifest.js b/src/mcp/manifest.js
new file mode 100644
index 0000000..bfded9c
--- /dev/null
+++ b/src/mcp/manifest.js
@@ -0,0 +1,299 @@
+/**
+ * axuse — MCP tool manifest.
+ *
+ * The browser tools are GENERATED from the frozen command contract
+ * (commands.js), so the schema the model sees can never drift from what the
+ * controller executes — ZCode's "one discriminated union" property, but
+ * mechanically enforced. Desktop tools are added when a platform driver
+ * exists and hidden otherwise (capability-conditional surface, like Codex's
+ * `getInfo → capabilities`).
+ */
+
+import { Contract } from "../core/commands.js";
+
+const POLICY = {};
+
+function paramSchema(key, spec) {
+ switch (spec.t) {
+ case "string":
+ return { type: "string", description: spec.desc };
+ case "boolean":
+ return { type: "boolean", description: spec.desc };
+ case "number":
+ return { type: "number", description: spec.desc };
+ case "enum":
+ if (spec.multi) {
+ return { type: "array", items: { type: "string", enum: spec.values }, description: spec.desc };
+ }
+ return { type: "string", enum: spec.values, description: spec.desc };
+ case "target":
+ // Flat object (not oneOf): same semantics, a fraction of the schema
+ // tokens the model re-reads every turn. Validation is in commands.js.
+ return { type: "object", properties: { ref: { type: "string" }, x: { type: "number" }, y: { type: "number" } }, description: spec.desc };
+ case "rect":
+ return {
+ type: "object",
+ properties: { x: { type: "number" }, y: { type: "number" }, w: { type: "number" }, h: { type: "number" } },
+ required: ["x", "y", "w", "h"],
+ additionalProperties: false,
+ description: spec.desc,
+ };
+ case "paths":
+ return { type: "array", items: { type: "string" }, description: spec.desc };
+ case "urls":
+ return { type: "array", items: { type: "string" }, description: spec.desc };
+ case "fields":
+ return {
+ type: "array",
+ description: spec.desc,
+ items: {
+ type: "object",
+ properties: { ref: { type: "string" }, value: { type: ["string", "boolean"] } },
+ required: ["ref", "value"],
+ additionalProperties: false,
+ },
+ };
+ default:
+ return { description: spec.desc };
+ }
+}
+
+/** Browser tools from the contract. */
+export function browserTools() {
+ const tools = [];
+ for (const [name, entry] of Object.entries(Contract)) {
+ const properties = {};
+ const required = [];
+ for (const [key, spec] of Object.entries(entry.params)) {
+ properties[key] = paramSchema(key, spec);
+ if (spec.req) required.push(key);
+ }
+ const schema = { type: "object", properties, required, additionalProperties: false };
+ tools.push({
+ name: `ax_${name}`,
+ description: entry.desc + (POLICY[name] ?? ""),
+ inputSchema: schema,
+ _command: name,
+ _group: "browser",
+ _observed: entry.observed,
+ });
+ }
+ return tools;
+}
+
+/** Desktop tools — only when a driver exists for this platform.
+ * AX-structure tools mount additionally when the driver exposes the
+ * AX layer (macOS System Events today). */
+export function desktopTools(driverAvailable, axCapable = false) {
+ if (!driverAvailable) return [];
+ const tools = [
+ {
+ name: "ax_desktop_screenshot",
+ description: "Budgeted JPEG screenshot of the active display layout or a region. Use the coordinate space reported by ax_desktop_screen_info (physical pixels on Windows, display points on macOS). Desktop tools are coordinate+vision based — prefer the ax_* browser tools whenever the target is a web page.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ x: { type: "number", description: "Region left in the screen_info coordinate space (optional = full active display layout)." },
+ y: { type: "number", description: "Region top in the screen_info coordinate space." },
+ w: { type: "number", description: "Region width." },
+ h: { type: "number", description: "Region height." },
+ budget_bytes: { type: "number", description: "Default 200000." },
+ quality: { type: "number", description: "JPEG quality 1-100 (default 80)." },
+ },
+ additionalProperties: false,
+ },
+ _op: "screenshot",
+ },
+ {
+ name: "ax_desktop_screen_info",
+ description: "Active display layout bounds and coordinate units, plus a cheap description of what the desktop driver supports.",
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
+ _op: "screen_info",
+ },
+ {
+ name: "ax_desktop_click",
+ description: "Trusted OS click in the coordinate space reported by ax_desktop_screen_info. Resolve coordinates from a screenshot in the same turn — never reuse coordinates from before a screen change.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ x: { type: "number" }, y: { type: "number" },
+ button: { type: "string", enum: ["left", "right", "middle"] },
+ double: { type: "boolean" },
+ },
+ required: ["x", "y"], additionalProperties: false,
+ },
+ _op: "click",
+ },
+ {
+ name: "ax_desktop_type",
+ description: "Type Unicode text at the caret through trusted OS input. Focus the target first (ax_desktop_click).",
+ inputSchema: { type: "object", properties: { text: { type: "string" } }, required: ["text"], additionalProperties: false },
+ _op: "type",
+ },
+ {
+ name: "ax_desktop_press",
+ description: 'Press a key combo, e.g. "enter", "ctrl+s", "alt+f4", "meta+space". Trusted OS input; macOS maps meta/cmd to Command.',
+ inputSchema: { type: "object", properties: { combo: { type: "string" } }, required: ["combo"], additionalProperties: false },
+ _op: "press",
+ },
+ {
+ name: "ax_desktop_scroll",
+ description: "Mouse wheel scroll deltas at the current cursor position (screen units are platform-native).",
+ inputSchema: {
+ type: "object",
+ properties: { dx: { type: "number", description: "Horizontal pixels (negative = left)." }, dy: { type: "number", description: "Vertical pixels (negative = up)." } },
+ required: ["dx", "dy"], additionalProperties: false,
+ },
+ _op: "wheel",
+ },
+ {
+ name: "ax_desktop_windows",
+ description: "List visible windows as {title, pid, application, bounds:{x,y,w,h}} rows (bounds in the screen_info coordinate space; macOS needs the Accessibility grant for per-window rows — without it you get process-level rows and window_access says so). Windows rows carry hwnd instead of bounds. One Apple-Event walk (~1s on a busy Mac) — treat as an anchor call, not a poll.",
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
+ _op: "windows",
+ },
+ {
+ name: "ax_desktop_activate",
+ description: "Bring a window/application to the foreground. macOS accepts an exact title, a pid, or a window_id from ax_desktop_windows (pid is the most robust); Windows accepts title substring or hwnd.",
+ inputSchema: {
+ type: "object",
+ properties: { title: { type: "string" }, hwnd: { type: "number" }, pid: { type: "number" }, window_id: { type: "number" } },
+ additionalProperties: false,
+ },
+ _op: "activate",
+ },
+ {
+ name: "ax_desktop_drag",
+ description: "Drag between two points in the screen_info coordinate space with interpolated moves.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ from: { type: "object", properties: { x: { type: "number" }, y: { type: "number" } }, required: ["x", "y"], additionalProperties: false },
+ to: { type: "object", properties: { x: { type: "number" }, y: { type: "number" } }, required: ["x", "y"], additionalProperties: false },
+ },
+ required: ["from", "to"],
+ additionalProperties: false,
+ },
+ _op: "drag",
+ },
+ ...((axCapable) ? [{
+ name: "ax_desktop_ax_snapshot",
+ description: "STRUCTURE-FIRST desktop snapshot (macOS): the app's accessibility tree with roles, titles, values, bounds, and live refs — the desktop twin of ax_observe. Pick the app by pid (from ax_desktop_windows), exact name, or front:true for the active app. Budgeted (250 nodes / depth 10 defaults; truncation reported as facts). Refs re-resolve at action time; act with ax_desktop_ax_click / set / read.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ pid: { type: "number", description: "Target process id (most robust)." },
+ name: { type: "string", description: "Exact application name." },
+ front: { type: "boolean", description: "Snapshot the frontmost app (default true when pid/name absent)." },
+ max_nodes: { type: "number", description: "Node budget (default 250)." },
+ max_depth: { type: "number", description: "Depth budget (default 10)." },
+ },
+ additionalProperties: false,
+ },
+ _op: "ax_snapshot",
+ }, {
+ name: "ax_desktop_ax_click",
+ description: "Click a native UI element by ref from ax_desktop_ax_snapshot (trusted AXPress via System Events; falls back to a trusted CGEvent click at the element's live center when an app refuses programmatic press). Refs are stale → typed REF_NOT_FOUND with a reobserve hint.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ ref: { type: "string", description: "Ref from ax_desktop_ax_snapshot (e.g. ax01.4.2)." },
+ pid: { type: "number" }, name: { type: "string" }, front: { type: "boolean" },
+ fallback_to_coords: { type: "boolean", description: "Allow the coordinate fallback (default true)." },
+ },
+ required: ["ref"],
+ additionalProperties: false,
+ },
+ _op: "ax_click",
+ }, {
+ name: "ax_desktop_ax_set",
+ description: "Set an AX-writable value (text fields/areas) by ref, verified by read-back — the desktop twin of ax_fill for native apps. Non-writable elements fail typed COMMAND_REJECTED with the element's available actions.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ ref: { type: "string" },
+ value: { type: "string" },
+ pid: { type: "number" }, name: { type: "string" }, front: { type: "boolean" },
+ },
+ required: ["ref", "value"],
+ additionalProperties: false,
+ },
+ _op: "ax_set",
+ }, {
+ name: "ax_desktop_ax_read",
+ description: "Re-read one element by ref (role, title, value, bounds, enabled, available AX actions) — fresh facts for a known target without a new snapshot.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ ref: { type: "string" },
+ pid: { type: "number" }, name: { type: "string" }, front: { type: "boolean" },
+ },
+ required: ["ref"],
+ additionalProperties: false,
+ },
+ _op: "ax_read",
+ }] : []),
+ ];
+ return tools;
+}
+
+/** Solver tools — always present; a missing solver is a typed NO_SOLVER
+ * result with an install hint, not a hidden tool (discoverability beats
+ * a shorter tool list for a paid add-on surface). */
+export function solverTools(loaded) {
+ const providers = [...new Set(loaded.flatMap((s) => s.providers))];
+ const ids = loaded.map((s) => `${s.id}@${s.version}`).join(", ") || "none";
+ return [
+ {
+ name: "ax_solve_captcha",
+ description: `Solve a CAPTCHA on the current tab (optionally opening url first) using the loaded solver plugins: ${ids}. ` +
+ "Solvers are separate packages (open core ships none); they own their own configuration. Returns facts only: solved, token, attempts, rounds, elapsed_ms, notes — never a fabricated token.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ provider: {
+ type: "string",
+ ...(providers.length ? { enum: providers } : {}),
+ description: 'Provider slug, e.g. "turnstile", "recaptcha-v2", "hcaptcha" (from loaded solver plugins).',
+ },
+ url: { type: "string", description: "Open this URL in a new tab first (else solve on the active tab)." },
+ headless: { type: "boolean", description: "Launch headless when url is given (default headed)." },
+ max_attempts: { type: "number", description: "Solver retry budget (plugin-specific default)." },
+ deadline_ms: { type: "number", description: "Overall deadline in ms (plugin-specific default)." },
+ },
+ required: ["provider"],
+ additionalProperties: false,
+ },
+ _group: "solver",
+ _op: "solve",
+ },
+ {
+ name: "ax_plugins",
+ description: "List loaded solver plugins (id, version, providers) and any plugins that failed to load. The open core ships no solvers; plugins are separate (paid) packages dropped into plugins/ or listed in AXUSE_PLUGINS.",
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
+ _group: "solver",
+ _op: "plugins",
+ },
+ ];
+}
+
+/** Plugin-contributed tools (core prerequisite A1): validated at load time
+ * (src/plugins/index.js validatePluginTools) against the same shape this
+ * manifest generates. Tool names never shadow core tools; a broken plugin
+ * tool definition fails the plugin at load, never the server. */
+export function pluginTools(loaded) {
+ const out = [];
+ for (const s of loaded) {
+ for (const t of s.tools ?? []) {
+ out.push({
+ name: t.name,
+ description: `[${s.id}@${s.version}] ${t.description}`,
+ inputSchema: t.inputSchema,
+ _group: "plugin",
+ _plugin: s.id,
+ _handle: t.handle,
+ });
+ }
+ }
+ return out;
+}
diff --git a/src/mcp/render.js b/src/mcp/render.js
new file mode 100644
index 0000000..00b8467
--- /dev/null
+++ b/src/mcp/render.js
@@ -0,0 +1,45 @@
+/**
+ * axuse — model-facing rendering of command results.
+ *
+ * Observations are text trees; wrapping them in JSON escapes every newline
+ * and quote (`\n`, `\"`) and repeats url/title/state fields the tree header
+ * already carries. That is pure token tax on every single step. Results with
+ * an observation render as plain text: a short facts line, notes, then the
+ * tree/diff verbatim. Everything else stays compact JSON.
+ */
+
+function obsBlock(obs) {
+ if (!obs) return "";
+ if (obs.dialog) return `dialog open: ${obs.dialog.type} "${obs.dialog.message}"\n${obs.hint ?? ""}`.trim();
+ if (obs.skipped) return `observation skipped (${obs.skipped}): ${obs.hint ?? ""}`;
+ const head = (obs.mode === "diff" && !/^no changes/.test(obs.text ?? "")) || obs.mode === "find" ? `state: ${obs.state_id}\n` : "";
+ const trunc = obs.truncated && !/truncated/.test(obs.text ?? "") ? "\nnote: truncated by budget — pass max_nodes/max_chars" : "";
+ const suppressed = obs.diff_suppressed ? "(full snapshot — the diff would have been larger)\n" : "";
+ return `${suppressed}${head}${obs.text ?? ""}${trunc}`;
+}
+
+export function renderResult(command, result) {
+ if (!result || typeof result !== "object") return String(result);
+ const { observation, meta, new_tab, ...rest } = result;
+ if (!observation && !new_tab) {
+ const { meta: _m, ...plain } = result;
+ return JSON.stringify(plain);
+ }
+ const facts = [];
+ if (rest.action_sent && rest.action_sent !== "sent") facts.push(`action: ${rest.action_sent}`);
+ if (rest.tab_id && command !== "observe") facts.push(`tab: ${rest.tab_id}`);
+ if (rest.frame) facts.push(`frame: ${rest.frame}`);
+ if (rest.value !== undefined) facts.push(`value: ${JSON.stringify(rest.value)}`);
+ if (rest.answered) facts.push(`dialog ${rest.answered}ed`);
+ if (rest.uploaded) facts.push(`uploaded: ${rest.uploaded.join(", ")}`);
+ if (rest.ok !== undefined) facts.push(rest.ok ? `ok after ${rest.elapsed_ms}ms` : "timeout");
+ if (rest.filled !== undefined) facts.push(`filled: ${[].concat(rest.filled).join("; ")}${rest.submitted ? `; then clicked ${rest.submitted}` : ""}`);
+ if (rest.dialog) facts.push(`dialog open: ${rest.dialog.type} "${rest.dialog.message}" — answer with ax_dialog`);
+ const parts = [];
+ if (facts.length) parts.push(facts.join(" · "));
+ if (rest.note) parts.push(`note: ${rest.note}`);
+ if (rest.tab_note) parts.push(`note: ${rest.tab_note}`);
+ parts.push(obsBlock(observation));
+ if (new_tab) parts.push(`--- new tab ${new_tab.tab_id} ---\n${obsBlock(new_tab.observation)}`);
+ return parts.filter(Boolean).join("\n");
+}
diff --git a/src/mcp/server.js b/src/mcp/server.js
new file mode 100644
index 0000000..bc1ffdd
--- /dev/null
+++ b/src/mcp/server.js
@@ -0,0 +1,231 @@
+/**
+ * axuse — MCP server over stdio, zero-dependency (hand-rolled JSON-RPC 2.0).
+ *
+ * Why MCP is the universal layer: Codex, Claude Code, OpenCode and
+ * Antigravity all speak MCP, so one server covers every harness — the same
+ * insight ZCode made in reverse (its model surface is one `js` tool; ours is
+ * one MCP surface). The server layer is deliberately thin: tool calls are
+ * stateless adapters, every durable fact lives in the Controller (Codex's
+ * native-host pattern / ZCode's host-owned registry).
+ */
+import readline from "node:readline";
+import { Controller } from "../core/controller.js";
+import { renderResult } from "./render.js";
+
+// MCP server instructions: the usage contract in a few lines (the full
+// version is SKILL.md). Harnesses surface this to the model once.
+const INSTRUCTIONS = [
+ "axuse: browser control via accessibility snapshots with element refs ([ref=e7]).",
+ "Workflow: ax_open → act on refs → read the diff each action returns (no need to re-observe).",
+ "For bounded source lists, use ax_open_many {urls:[...]} for compact title/status/excerpt results; it closes temporary tabs by default.",
+ "Forms: ONE ax_fill call with all fields (+submit). Big pages: ax_observe {find:\"text\"}. Infinite feeds/lazy lists: ax_scroll {until:\"text\"}.",
+ "New tabs/popups and JS dialogs opened by an action are reported in its result (answer dialogs with ax_dialog).",
+ "Screenshots only for pixels (canvas): then click {x,y} page coords.",
+ "Loaded plugins may contribute extra capability tools (ax_vault, ax_net, ax_guard, ax_extract, …): ax_plugins lists them with their tool names.",
+].join("\n");
+import { AxError } from "../core/errors.js";
+import { browserTools, desktopTools, solverTools, pluginTools } from "./manifest.js";
+import { resolveDesktopDriver, desktopUnavailable } from "../desktop/index.js";
+import { loadSolvers, buildSolveContext, solveWith, pluginDirs } from "../plugins/index.js";
+
+const VERSION = "0.1.0";
+const SUPPORTED_PROTOCOL = "2025-03-26";
+
+/** `desktop` resolves once (the macOS driver is the one async case). */
+export async function createServer({ controller = new Controller(), desktop, solvers } = {}) {
+ const driver = desktop !== undefined ? desktop : await resolveDesktopDriver().catch(() => null);
+ // Solver plugins (paid add-ons) load once at server start: one import per
+ // plugin dir, typed failures collected for ax_plugins — never fatal.
+ const loaded = solvers !== undefined
+ ? solvers
+ : await loadSolvers(process.env.AXUSE_PLUGINS === "" ? [] : pluginDirs());
+ const registry = loaded.solvers ?? loaded;
+ const loadErrors = loaded.errors ?? [];
+ const tools = [...browserTools(), ...desktopTools(!!driver, !!(driver && typeof driver.axSnapshot === "function")), ...solverTools(registry), ...pluginTools(registry)];
+
+ const byName = new Map(tools.map((t) => [t.name, t]));
+
+ async function handleRequest(msg) {
+ const { id, method, params = {} } = msg;
+ try {
+ switch (method) {
+ case "initialize": {
+ return reply(id, {
+ protocolVersion: typeof params.protocolVersion === "string" ? params.protocolVersion : SUPPORTED_PROTOCOL,
+ capabilities: { tools: { listChanged: false } },
+ serverInfo: { name: "axuse", version: VERSION },
+ instructions: INSTRUCTIONS,
+ });
+ } case "ping":
+ return reply(id, {});
+ case "tools/list":
+ return reply(id, {
+ tools: tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })),
+ });
+ case "tools/call": {
+ const tool = byName.get(params.name);
+ if (!tool) {
+ return reply(id, { content: [{ type: "text", text: `Unknown tool "${params.name}"` }], isError: true });
+ }
+ const result = await dispatch(tool, params.arguments ?? {});
+ return reply(id, result);
+ }
+ default:
+ return replyErr(id, -32601, `Method not found: ${method}`);
+ }
+ } catch (e) {
+ // Structured errors become tool results, not protocol errors. Plugin
+ // errors (AxError and plugin-typed errors like LICENSE_INVALID) carry
+ // toJSON(); anything else is an internal string.
+ const text = (e instanceof AxError || typeof e.toJSON === "function") ? JSON.stringify(e.toJSON()) : `internal: ${e.message}`;
+ return reply(id, { content: [{ type: "text", text }], isError: true });
+ }
+ }
+
+ async function dispatch(tool, args) {
+ if (tool._group === "browser") {
+ const result = await controller.execute(tool._command, args);
+ if (tool._command === "screenshot" && result?.image) {
+ return {
+ content: [
+ { type: "text", text: `${result.note} · ${result.image.bytes} bytes q${result.image.quality}` },
+ { type: "image", data: result.image.base64, mimeType: result.image.mime },
+ ],
+ };
+ }
+ return { content: [{ type: "text", text: renderResult(tool._command, result) }] };
+ }
+ if (tool._group === "solver") {
+ if (tool._op === "plugins") {
+ const text = JSON.stringify({
+ loaded: registry.map((s) => ({
+ id: s.id, version: s.version, providers: s.providers, dir: s.dir,
+ ...(s.tools?.length ? { tools: s.tools.map((t) => t.name) } : {}),
+ })),
+ failed: loadErrors,
+ search: pluginDirs(),
+ });
+ return { content: [{ type: "text", text }] };
+ }
+ // ax_solve_captcha: optionally open the url, then dispatch to the
+ // loaded solver through the narrow ctx — never the raw controller.
+ if (typeof args.url === "string") {
+ await controller.execute("open", {
+ url: args.url,
+ ...(args.headless ? { headless: true } : {}),
+ settle_ms: 4000,
+ });
+ }
+ const opts = {};
+ for (const k of ["max_attempts", "deadline_ms"]) {
+ if (args[k] !== undefined) opts[k === "max_attempts" ? "maxAttempts" : "deadlineMs"] = args[k];
+ }
+ const ctx = buildSolveContext(controller);
+ const result = await solveWith(registry, args.provider, ctx, opts);
+ return { content: [{ type: "text", text: JSON.stringify(result) }] };
+ }
+ if (tool._group === "plugin") {
+ // A1 dispatch: the plugin tool's validated handle(args, ctx) — the
+ // same trusted, narrow capability context solvers get (incl. the
+ // Wave-1 cdp/cdpBroadcast plumbing). Typed failures (AxError) become
+ // tool results via the outer catch, exactly like core commands.
+ const ctx = buildSolveContext(controller);
+ const result = await tool._handle(args, ctx);
+ return { content: [{ type: "text", text: JSON.stringify(result) }] };
+ }
+ if (!driver) desktopUnavailable();
+ const d = driver;
+ switch (tool._op) {
+ case "screenshot": {
+ const shot = await d.screenshot({ x: args.x, y: args.y, w: args.w, h: args.h, budgetBytes: args.budget_bytes, quality: args.quality });
+ return {
+ content: [
+ { type: "text", text: JSON.stringify({ bytes: shot.bytes, budget_bytes: shot.budget_bytes, quality: shot.quality }) },
+ { type: "image", data: shot.base64, mimeType: shot.mime },
+ ],
+ };
+ }
+ case "screen_info": {
+ const info = await d.screenInfo();
+ const note = `${info.note ? `${info.note}; ` : ""}coordinates are in the driver's native units (physical pixels on Windows, macOS global display points on macOS); v1 desktop is coordinate+vision based (no OS AX tree) — prefer ax_* browser tools for web pages.`;
+ return { content: [{ type: "text", text: JSON.stringify({ ...info, note }) }] };
+ }
+ case "click": {
+ const r = await d.click({ x: args.x, y: args.y, button: args.button, double: args.double });
+ return { content: [{ type: "text", text: JSON.stringify(r) }] };
+ }
+ case "type":
+ return { content: [{ type: "text", text: JSON.stringify(await d.type(args.text)) }] };
+ case "press":
+ return { content: [{ type: "text", text: JSON.stringify(await d.press(args.combo)) }] };
+ case "scroll":
+ return { content: [{ type: "text", text: JSON.stringify(await d.wheel(args.dx ?? 0, args.dy ?? 0)) }] };
+ case "windows":
+ return { content: [{ type: "text", text: JSON.stringify(await d.windows()) }] };
+ case "activate":
+ return { content: [{ type: "text", text: JSON.stringify(await d.activate({ title: args.title, hwnd: args.hwnd, pid: args.pid, windowId: args.window_id })) }] };
+ case "ax_snapshot":
+ return { content: [{ type: "text", text: JSON.stringify(await d.axSnapshot({ pid: args.pid, name: args.name, front: args.front, maxNodes: args.max_nodes, maxDepth: args.max_depth })) }] };
+ case "ax_read":
+ return { content: [{ type: "text", text: JSON.stringify(await d.axRead({ ref: args.ref, pid: args.pid, name: args.name, front: args.front })) }] };
+ case "ax_click":
+ return { content: [{ type: "text", text: JSON.stringify(await d.axClick({ ref: args.ref, pid: args.pid, name: args.name, front: args.front, fallbackToCoords: args.fallback_to_coords })) }] };
+ case "ax_set":
+ return { content: [{ type: "text", text: JSON.stringify(await d.axSet({ ref: args.ref, value: args.value, pid: args.pid, name: args.name, front: args.front })) }] };
+ case "drag":
+ return { content: [{ type: "text", text: JSON.stringify(await d.drag({ from: args.from, to: args.to })) }] };
+ default:
+ throw new AxError("INTERNAL", `unroutable desktop op ${tool._op}`);
+ }
+ }
+
+ function reply(id, result) {
+ return { jsonrpc: "2.0", id, result };
+ }
+ function replyErr(id, code, message) {
+ return { jsonrpc: "2.0", id, error: { code, message } };
+ }
+
+ return {
+ tools,
+ /** @param {NodeJS.ReadableStream} input @param {NodeJS.WritableStream} output */
+ async run(input, output) {
+ const rl = readline.createInterface({ input, crlfDelay: Infinity });
+ rl.on("line", (line) => {
+ const s = line.trim();
+ if (!s) return;
+ let msg;
+ try {
+ msg = JSON.parse(s);
+ } catch {
+ return;
+ }
+ // Notifications (no id): notifications/initialized, notifications/cancelled.
+ if (msg.id === undefined || msg.id === null) return;
+ handleRequest(msg).then((resp) => {
+ if (resp) output.write(JSON.stringify(resp) + "\n");
+ }).catch((e) => {
+ output.write(JSON.stringify(replyErr(msg.id, -32603, `internal: ${e.message}`)) + "\n");
+ });
+ });
+ return new Promise((resolve) => rl.on("close", resolve));
+ },
+ };
+}
+
+export async function runStdio() {
+ const controller = new Controller();
+ const server = await createServer({ controller });
+ // Harnesses end MCP servers by closing stdin or signalling: either way,
+ // stop launched browsers and delete their ephemeral profiles first.
+ let exiting = false;
+ const shutdown = async () => {
+ if (exiting) return;
+ exiting = true;
+ await Promise.race([controller.dispose(), new Promise((ok) => setTimeout(ok, 5000))]);
+ process.exit(0);
+ };
+ for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) process.on(sig, shutdown);
+ await server.run(process.stdin, process.stdout);
+ await shutdown();
+}
diff --git a/src/plugins/index.js b/src/plugins/index.js
new file mode 100644
index 0000000..827d6f8
--- /dev/null
+++ b/src/plugins/index.js
@@ -0,0 +1,359 @@
+/**
+ * axuse — solver plugin system (the thin seam).
+ *
+ * Design stance: axuse core is (and stays) free for noncommercial use
+ * (PolyForm Noncommercial 1.0.0, copyright CTOL Digital Solutions) and
+ * CAPTCHA-agnostic. It knows nothing about Turnstile, hCaptcha or reCAPTCHA.
+ * What it ships is a minimal, frozen plugin ABI:
+ *
+ * a solver plugin = one ESM module exporting
+ * {
+ * id: "captcha-pro", // unique, stable
+ * version: "1.0.0",
+ * providers: ["turnstile", "recaptcha-v2", "hcaptcha"],
+ * solve: async (provider, ctx, opts) => solve result (see below)
+ * }
+ *
+ * Discovery: every directory listed in AXUSE_PLUGINS (path.delimiter-separated)
+ * plus "<repo>/plugins/". Drop a paid solver package in plugins/ and it is
+ * live on the next `axuse mcp` / `axuse solve` start. Nothing else changes.
+ *
+ * The plugin never touches the Controller. It receives a narrow capability
+ * context (ctx) — the four primitives a solver needs, shaped by the same
+ * lessons the core commands encode:
+ *
+ * ctx.evaluate(expr) → parsed JSON value of the in-page expression
+ * (single-encoded: the raw ax_evaluate JSON string
+ * is parsed for you — a real trap we hit live)
+ * ctx.click({x,y}|{ref}, {settleMs})
+ * ctx.screenshot({crop:{x,y,w,h}, quality, budgetBytes})
+ * → { base64, mime, bytes, quality, crop }
+ * (crop-first: never vision-tax a whole page)
+ * ctx.waitFor({selector|expression|text, timeoutMs}) → { ok }
+ * ctx.wait(ms)
+ * ctx.meta → { startedAt }
+ *
+ * Solve result contract (what ax_solve_captcha returns to the model):
+ * {
+ * solved: boolean,
+ * provider: string,
+ * token: string|null, // null when unsolved (never fabricated)
+ * attempts, rounds, elapsedMs, // solver-chosen accounting facts
+ * notes: string, // one honest sentence
+ * ...solver-specific facts (visionCalls, etc.)
+ * }
+ *
+ * Like desktop drivers, plugins run in-process and are trusted code: the seam
+ * is for packaging/licensing separation (open core ↔ paid solvers), not
+ * sandboxing. Plugins keep their own configuration (e.g. vision API keys) in
+ * their own env vars — the core never sees them.
+ */
+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
+import { join, dirname, resolve } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { AxError, Codes } from "../core/errors.js";
+import { Contract } from "../core/commands.js";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+export const DEFAULT_PLUGIN_DIR = join(HERE, "..", "..", "plugins");
+
+/** Validate one plugin module against the frozen ABI. Fail closed, typed. */
+export function validateSolver(mod, source) {
+ const where = source ?? "plugin";
+ const fail = (msg) => new AxError(Codes.PLUGIN_LOAD_FAILED, `${where}: ${msg}`, { retry: "never" });
+ if (!mod || typeof mod !== "object") throw fail("exports nothing (expected a solver object)");
+ const { id, version, providers, solve } = mod;
+ if (typeof id !== "string" || !/^[a-z0-9][a-z0-9._-]{1,63}$/i.test(id)) {
+ throw fail(`id must be a short slug string (got ${JSON.stringify(id)})`);
+ }
+ if (typeof version !== "string" || !version) throw fail("version must be a non-empty string");
+ if (!Array.isArray(providers) || !providers.length || providers.some((p) => typeof p !== "string" || !p)) {
+ throw fail("providers must be a non-empty array of provider slugs, e.g. [\"turnstile\",\"recaptcha-v2\"]");
+ }
+ if (typeof solve !== "function" || solve.length < 2) {
+ throw fail("solve must be an async function (provider, ctx, opts) — arity >= 2");
+ }
+ return { id, version, providers, solve, label: typeof mod.label === "string" ? mod.label : id };
+}
+
+/** Tool names the core already owns — a plugin tool may never shadow them. */
+const RESERVED_TOOL_NAMES = new Set([
+ "ax_solve_captcha", "ax_plugins",
+ ...Object.keys(Contract).map((n) => `ax_${n}`),
+]);
+
+/** Validate a plugin's extra MCP tools (core prerequisite A1): same shape the
+ * core manifest generates — name/description/schema/handle — fail-closed so
+ * a broken paid package is reported by `axuse plugins`, never silently
+ * mounted on the MCP surface. */
+export function validatePluginTools(id, tools, source) {
+ const where = source ?? id;
+ const fail = (msg) => new AxError(Codes.PLUGIN_LOAD_FAILED, `${where}: ${msg}`, { retry: "never" });
+ if (!Array.isArray(tools) || !tools.length) throw fail("tools() must return a non-empty array of tool definitions");
+ const seen = new Set();
+ for (const t of tools) {
+ if (!t || typeof t !== "object") throw fail("tools: every entry must be an object");
+ if (typeof t.name !== "string" || !/^ax_[a-z0-9_]{2,48}$/.test(t.name)) {
+ throw fail(`tools: name must be an ax_<slug> string (got ${JSON.stringify(t.name)})`);
+ }
+ if (RESERVED_TOOL_NAMES.has(t.name)) {
+ throw fail(`tools: name "${t.name}" is reserved by the core — pick a plugin-specific name`);
+ }
+ if (seen.has(t.name)) throw fail(`tools: duplicate tool name "${t.name}"`);
+ seen.add(t.name);
+ if (typeof t.description !== "string" || !t.description.trim() || t.description.length > 2000) {
+ throw fail(`tools: "${t.name}" needs a non-empty description (<= 2000 chars)`);
+ }
+ const s = t.inputSchema;
+ if (!s || typeof s !== "object" || Array.isArray(s) || s.type !== "object" || typeof s.properties !== "object" || s.properties === null) {
+ throw fail(`tools: "${t.name}" inputSchema must be { type:"object", properties:{…} } (same generator shape as core tools)`);
+ }
+ for (const [k, v] of Object.entries(s.properties)) {
+ if (!v || typeof v !== "object" || typeof v.type !== "string") {
+ throw fail(`tools: "${t.name}" property "${k}" must be a JSON-schema fragment with a type`);
+ }
+ }
+ if (s.required !== undefined && (!Array.isArray(s.required) || s.required.some((r) => typeof r !== "string" || !s.properties[r]))) {
+ throw fail(`tools: "${t.name}" required must list declared property names`);
+ }
+ if (typeof t.handle !== "function" || t.handle.length < 1) {
+ throw fail(`tools: "${t.name}" handle must be an async function (args, ctx) — arity >= 1`);
+ }
+ }
+ return tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema, handle: t.handle }));
+}
+
+/** Resolve a plugin directory to its entry module (index.js or package main). */
+function entryOf(dir) {
+ const idx = join(dir, "index.js");
+ if (existsSync(idx)) return idx;
+ const pkgPath = join(dir, "package.json");
+ if (existsSync(pkgPath)) {
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
+ const main = pkg.main ?? pkg.exports?.["."]?.import;
+ if (typeof main === "string" && existsSync(join(dir, main))) return join(dir, main);
+ }
+ return null;
+}
+
+/** Load every valid solver from the given dirs. A search dir may be either
+ * a CONTAINER of plugin subdirectories (e.g. the default plugins/) or a
+ * plugin directory itself (index.js / package.json at its root — the shape
+ * AXUSE_PLUGINS entries and docs point at). Invalid plugins fail typed
+ * but never abort the server: one broken paid package must not take the
+ * whole MCP surface down (same posture as a failed browser locate). */
+export async function loadSolvers(dirs) {
+ const search = [...new Set((dirs ?? pluginDirs()).filter(Boolean))];
+ const solvers = [];
+ const errors = [];
+ for (const dir of search) {
+ let candidates = [];
+ try {
+ const isItselfPlugin = existsSync(join(dir, "index.js")) || existsSync(join(dir, "package.json"));
+ candidates = isItselfPlugin
+ ? [dir]
+ : readdirSync(dir).filter((n) => !n.startsWith(".") && !n.startsWith("_")).map((n) => join(dir, n));
+ } catch {
+ continue; // dir absent: normal for a fresh install
+ }
+ for (const full of candidates) {
+ try {
+ if (!statSync(full).isDirectory()) continue;
+ const entry = entryOf(full);
+ if (!entry) continue;
+ const mod = await import(pathToFileURL(entry).href);
+ const solver = validateSolver(mod.solver ?? mod.default ?? mod, full.split(/[\\/]/).pop());
+ // Core prerequisite A1: plugins may register extra MCP tools from a
+ // validated `tools()` export (same schema shape the core generates).
+ // A broken tools() fails the whole plugin, typed — never the server.
+ let tools = [];
+ if (mod.tools !== undefined) {
+ if (typeof mod.tools !== "function") {
+ throw new AxError(Codes.PLUGIN_LOAD_FAILED,
+ `${solver.id}: tools must be a function returning tool definitions`,
+ { retry: "never" });
+ }
+ tools = validatePluginTools(solver.id, await mod.tools(), solver.id);
+ }
+ solvers.push({ ...solver, dir: full, ...(tools.length ? { tools } : {}) });
+ } catch (e) {
+ errors.push({
+ plugin: full.split(/[\\/]/).pop(),
+ code: e instanceof AxError ? e.code : Codes.PLUGIN_LOAD_FAILED,
+ message: e.message,
+ });
+ }
+ }
+ }
+ return { solvers, errors };
+}
+
+/** Default search path: AXUSE_PLUGINS list, then the repo's plugins/ dir. */
+export function pluginDirs() {
+ const env = process.env.AXUSE_PLUGINS;
+ const list = env ? env.split(process.platform === "win32" ? ";" : ":").filter(Boolean) : [];
+ list.push(DEFAULT_PLUGIN_DIR);
+ return list.map((p) => resolve(p));
+}
+
+/** The narrow capability context handed to solver.solve(). Frozen surface,
+ * JSON-parsed evaluate (kills the double-encoding trap), crop-first pixels. */
+export function buildSolveContext(controller, tabId) {
+ const meta = { startedAt: Date.now() };
+ const withTab = (extra = {}) => (tabId ? { tab_id: tabId, ...extra } : extra);
+ return Object.freeze({
+ meta,
+ /** The tab this ctx is bound to (null: active/none). */
+ tabId: tabId ?? null,
+ async evaluate(expression) {
+ const r = await controller.execute("evaluate", { expression, ...(tabId ? { tab_id: tabId } : {}) });
+ try {
+ return JSON.parse(r.value ?? "null");
+ } catch {
+ return r.value ?? null; // truncated / non-JSON: hand back the raw string
+ }
+ },
+ async click(target, { settleMs } = {}) {
+ const r = await controller.execute("click", {
+ target: "ref" in target ? { ref: target.ref } : { x: target.x, y: target.y },
+ ...(settleMs !== undefined ? { settle_ms: settleMs } : {}),
+ ...(tabId ? { tab_id: tabId } : {}),
+ });
+ return { actionSent: r.action_sent ?? null };
+ },
+ async screenshot({ crop, quality, budgetBytes } = {}) {
+ const r = await controller.execute("screenshot", {
+ ...(crop ? { crop } : {}),
+ ...(quality !== undefined ? { quality } : {}),
+ ...(budgetBytes !== undefined ? { budget_bytes: budgetBytes } : {}),
+ ...(tabId ? { tab_id: tabId } : {}),
+ });
+ return { ...r.image, crop: crop ?? null };
+ },
+ async waitFor(what) {
+ const r = await controller.execute("wait_for", { ...what, ...(tabId ? { tab_id: tabId } : {}) });
+ return { ok: !!r.ok, timeout: !!r.timeout };
+ },
+ async wait(ms) {
+ await new Promise((res) => setTimeout(res, Math.min(Math.max(ms, 0), 30_000)));
+ },
+ /* ------------------------------------ Wave-1 plumbing (R1-R4 / A2) */
+ /** Typed CDP passthrough on the tab's connection (Storage, Browser,
+ * WebAuthn, Fetch, Network, raw Input.* — the plugin-owned domains). */
+ async cdp(method, params = {}, sessionId) {
+ return controller.cdpSend(tabId, method, params, sessionId);
+ },
+ /** Send to the tab session + every OOPIF frame session, and replay the
+ * send on future frame attaches (R2 enable-on-frame-session). */
+ async cdpBroadcast(method, params = {}) {
+ return controller.cdpBroadcast(tabId, method, params);
+ },
+ /** Subscribe to raw CDP events on the tab's connection (R2 event
+ * delivery: Fetch.requestPaused, Network.requestWillBeSent, ...).
+ * Frame-session events are included — match msg.sessionId against
+ * tabs().frame_sessions to scope. Returns an unsubscribe function. */
+ cdpOn(method, handler) {
+ return controller.cdpOn(tabId, method, handler);
+ },
+ async press(combo, { settleMs, tab_id, platform } = {}) {
+ const r = await controller.execute("press", withTab({
+ combo,
+ ...(platform !== undefined ? { platform } : {}),
+ ...(settleMs !== undefined ? { settle_ms: settleMs } : {}),
+ ...(tab_id ? { tab_id } : {}),
+ }));
+ return { actionSent: r.action_sent ?? null };
+ },
+ async type({ target, text, replace, submit, settleMs, tab_id } = {}) {
+ const r = await controller.execute("type", withTab({
+ text: String(text),
+ ...(target !== undefined ? { target } : {}),
+ ...(replace !== undefined ? { replace } : {}),
+ ...(submit !== undefined ? { submit } : {}),
+ ...(settleMs !== undefined ? { settle_ms: settleMs } : {}),
+ ...(tab_id ? { tab_id } : {}),
+ }));
+ return { actionSent: r.action_sent ?? null };
+ },
+ async drag({ from, to, steps, settleMs, tab_id } = {}) {
+ const r = await controller.execute("drag", withTab({
+ from, to,
+ ...(steps !== undefined ? { steps } : {}),
+ ...(settleMs !== undefined ? { settle_ms: settleMs } : {}),
+ ...(tab_id ? { tab_id } : {}),
+ }));
+ return { actionSent: r.action_sent ?? null };
+ },
+ async scroll({ direction, amount, dx, dy, until, target, settleMs, tab_id } = {}) {
+ return controller.execute("scroll", withTab({
+ ...(direction !== undefined ? { direction } : {}),
+ ...(amount !== undefined ? { amount } : {}),
+ ...(dx !== undefined ? { dx } : {}),
+ ...(dy !== undefined ? { dy } : {}),
+ ...(until !== undefined ? { until } : {}),
+ ...(target !== undefined ? { target } : {}),
+ ...(settleMs !== undefined ? { settle_ms: settleMs } : {}),
+ ...(tab_id ? { tab_id } : {}),
+ }));
+ },
+ async upload({ ref, paths, settleMs, tab_id } = {}) {
+ return controller.execute("upload", withTab({
+ paths,
+ ...(ref !== undefined ? { ref } : {}),
+ ...(settleMs !== undefined ? { settle_ms: settleMs } : {}),
+ ...(tab_id ? { tab_id } : {}),
+ }));
+ },
+ /** AX snapshot (diff by default; find: contract matching on big pages). */
+ async observe({ mode, find, maxNodes, maxChars, tab_id } = {}) {
+ return controller.execute("observe", withTab({
+ ...(mode !== undefined ? { mode } : {}),
+ ...(find !== undefined ? { find } : {}),
+ ...(maxNodes !== undefined ? { max_nodes: maxNodes } : {}),
+ ...(maxChars !== undefined ? { max_chars: maxChars } : {}),
+ ...(tab_id ? { tab_id } : {}),
+ }));
+ },
+ /** Open a URL in a new tab (profileDir: persistent A2 profile). */
+ async open(url, { headless, profileDir, settleMs, executablePath } = {}) {
+ const r = await controller.execute("open", {
+ url: String(url),
+ ...(headless !== undefined ? { headless } : {}),
+ ...(profileDir !== undefined ? { profile_dir: profileDir } : {}),
+ ...(settleMs !== undefined ? { settle_ms: settleMs } : {}),
+ ...(executablePath !== undefined ? { executable_path: executablePath } : {}),
+ });
+ return { tabId: r.tab_id, browserId: r.browser_id, observation: r.observation, dialog: r.dialog ?? null };
+ },
+ async navigate(url, { settleMs, tab_id } = {}) {
+ const r = await controller.execute("navigate", withTab({
+ url: String(url),
+ ...(settleMs !== undefined ? { settle_ms: settleMs } : {}),
+ ...(tab_id ? { tab_id } : {}),
+ }));
+ return { tabId: r.tab_id, observation: r.observation };
+ },
+ /** Controlled tabs (incl. per-tab frame/session facts for cdp routing). */
+ async tabs() {
+ return controller.execute("tabs", {});
+ },
+ /** Event-ring tail (navigations, dialogs, downloads (R1), frame churn). */
+ async events({ after = 0, limit = 50, tab_id } = {}) {
+ return controller.execute("events", withTab({
+ after_sequence: after, limit,
+ ...(tab_id ? { tab_id } : {}),
+ }));
+ },
+ });
+}
+
+/** Dispatch: registry lookup + typed NO_SOLVER with an install hint. */
+export async function solveWith(solvers, provider, ctx, opts = {}) {
+ const match = solvers.find((s) => s.providers.includes(provider));
+ if (!match) {
+ throw new AxError(Codes.NO_SOLVER,
+ `No loaded solver handles provider "${provider}" (loaded: ${solvers.map((s) => s.id).join(", ") || "none"}).`,
+ { hint: "Solver plugins are separate packages. Drop one into the plugins/ directory (or list dirs in AXUSE_PLUGINS), then run `axuse plugins` to verify.", retry: "never" });
+ }
+ return match.solve(provider, ctx, opts);
+}
diff --git a/src/workflows/url-batch.js b/src/workflows/url-batch.js
new file mode 100644
index 0000000..8ee8cf8
--- /dev/null
+++ b/src/workflows/url-batch.js
@@ -0,0 +1,66 @@
+import { existsSync, readFileSync } from "node:fs";
+
+/** Read a URL source from a file, stdin (-), a single URL, or Markdown text. */
+export function readUrlSource(source) {
+ if (source === "-") return readFileSync(0, "utf8");
+ if (existsSync(source)) return readFileSync(source, "utf8");
+ return String(source ?? "");
+}
+
+/** Extract and de-duplicate web URLs from plain text or Markdown. */
+export function extractUrls(text) {
+ const seen = new Set();
+ const out = [];
+ for (const match of String(text).matchAll(/https?:\/\/[^\s<>"'`\)\]}]+/gi)) {
+ const url = match[0].replace(/[),.;:!?]+$/g, "");
+ if (!seen.has(url)) {
+ seen.add(url);
+ out.push(url);
+ }
+ }
+ return out;
+}
+
+function mdText(value) {
+ return String(value ?? "").replace(/```/g, "''' ").replace(/\r/g, "");
+}
+
+/** Render compact ax_open_many results as a useful, honest Markdown report. */
+export function renderUrlReport({ results, backend, source }) {
+ const opened = results.filter((r) => r.status === "opened").length;
+ const failed = results.length - opened;
+ const lines = [
+ "# axuse URL inspection report",
+ "",
+ `Generated: ${new Date().toISOString()}`,
+ `Backend: ${backend ?? "cdp"}`,
+ `Source: ${source}`,
+ `Results: ${opened} opened, ${failed} failed`,
+ "",
+ "> This report contains page titles, access status, and bounded accessibility-text excerpts. It is not an LLM-generated factual summary.",
+ "",
+ ];
+
+ results.forEach((row, i) => {
+ const title = row.title || row.final_url || row.url;
+ lines.push(`## ${i + 1}. ${mdText(title)}`);
+ lines.push(`- Source: <${row.url}>`);
+ if (row.status === "opened") {
+ lines.push(`- Status: opened (${row.ref_count ?? 0} accessibility refs)`);
+ if (row.final_url && row.final_url !== row.url) lines.push(`- Final URL: <${row.final_url}>`);
+ if (row.truncated) lines.push("- Note: snapshot excerpt was truncated by the page budget.");
+ if (row.excerpt) {
+ lines.push("", "```text", mdText(row.excerpt), "```");
+ }
+ } else {
+ lines.push(`- Status: failed`);
+ const error = row.error?.code
+ ? `${row.error.code}: ${row.error.message ?? "unknown error"}`
+ : row.error?.message ?? "unknown error";
+ lines.push(`- Error: ${mdText(error)}`);
+ if (row.error?.hint) lines.push(`- Hint: ${mdText(row.error.hint)}`);
+ }
+ lines.push("");
+ });
+ return lines.join("\n");
+}
diff --git a/test/a1-tools.test.js b/test/a1-tools.test.js
new file mode 100644
index 0000000..989d847
--- /dev/null
+++ b/test/a1-tools.test.js
@@ -0,0 +1,149 @@
+/**
+ * A1 (plugin-contributed MCP tools) — core-level protocol test.
+ *
+ * Spawns the REAL MCP server with a fixture plugin directory that
+ * contributes a `tools()` export, then exercises the full path:
+ * load → validate → tools/list (schema intact) → tools/call dispatch →
+ * typed-error serialization for a throwing handle. No browser needed
+ * (the fixture tools only touch ctx.evaluate on a data: page... actually
+ * they return static facts — zero browser involvement at all).
+ */
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "src", "cli.js");
+
+/** A fixture plugin: solver ABI + a tools() export (one well-formed tool,
+ * one that throws a typed PluginError-style error with toJSON). */
+function fixturePluginDir() {
+ const dir = mkdtempSync(join(tmpdir(), "axuse-a1-plugin-"));
+ mkdirSync(join(dir, "demo"));
+ writeFileSync(join(dir, "demo", "index.js"), `
+export const solver = {
+ id: "a1-demo", version: "1.0.0",
+ providers: ["demo"],
+ async solve(provider, ctx) { return { solved: true, provider, token: "t" }; },
+};
+export function tools() {
+ return [{
+ name: "ax_demo_ping",
+ description: "Demo capability tool (A1 test fixture).",
+ inputSchema: {
+ type: "object",
+ properties: { op: { type: "string", enum: ["ping", "boom"] } },
+ required: ["op"], additionalProperties: false,
+ },
+ handle: async (args, ctx) => {
+ if (args.op === "boom") {
+ const e = new Error("demo typed failure");
+ e.code = "DEMO_BOOM"; e.retry = "never"; e.hint = "deliberate";
+ e.toJSON = () => ({ code: e.code, message: e.message, hint: e.hint, retry: e.retry, side_effect: "none" });
+ throw e;
+ }
+ return { ok: true, op: "ping", pong: true, elapsedMs: 0, notes: "fixture", usage: { visionCalls: 0, promptTokens: 0, completionTokens: 0 } };
+ },
+ }];
+}
+export default solver;
+`);
+ return dir;
+}
+
+function startServer(env) {
+ const proc = spawn(process.execPath, [CLI, "mcp"], { stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ...env } });
+ const buffer = { text: "", waiters: [] };
+ proc.stdout.on("data", (d) => {
+ buffer.text += String(d);
+ let i;
+ while ((i = buffer.text.indexOf("\n")) >= 0) {
+ const line = buffer.text.slice(0, i).trim();
+ buffer.text = buffer.text.slice(i + 1);
+ if (!line) continue;
+ const w = buffer.waiters.shift();
+ if (w) w(JSON.parse(line));
+ }
+ });
+ return {
+ proc,
+ async call(msg) {
+ const p = new Promise((resolve, reject) => {
+ buffer.waiters.push(resolve);
+ setTimeout(() => reject(new Error("MCP response timeout")), 30_000);
+ });
+ proc.stdin.write(JSON.stringify(msg) + "\n");
+ return p;
+ },
+ end() { proc.kill(); },
+ };
+}
+
+test("A1: plugin tools() export → validated → tools/list → tools/call → typed errors", async (t) => {
+ const dir = fixturePluginDir();
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ // Point the loader ONLY at the fixture dir (skip the paid tree).
+ const srv = startServer({ AXUSE_PLUGINS: dir, AXUSE_LICENSE_A1_DEMO: "x" });
+ t.after(() => srv.end());
+
+ await srv.call({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "t", version: "0" } } });
+ srv.proc.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) + "\n");
+
+ // tools/list carries the plugin tool with its schema intact.
+ const list = await srv.call({ jsonrpc: "2.0", id: 2, method: "tools/list" });
+ const names = list.result.tools.map((x) => x.name);
+ assert.ok(names.includes("ax_demo_ping"), `plugin tool missing from tools/list (have: ${names.join(", ")})`);
+ const tool = list.result.tools.find((x) => x.name === "ax_demo_ping");
+ assert.equal(tool.inputSchema.type, "object");
+ assert.deepEqual(tool.inputSchema.required, ["op"]);
+ assert.match(tool.description, /^\[a1-demo@1\.0\.0\] /);
+
+ // tools/call dispatches to the plugin handle with the real ctx.
+ const ok = await srv.call({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "ax_demo_ping", arguments: { op: "ping" } } });
+ assert.equal(ok.result.isError, undefined);
+ const payload = JSON.parse(ok.result.content[0].text);
+ assert.equal(payload.ok, true);
+ assert.equal(payload.pong, true);
+
+ // A throwing handle serializes as a typed tool result (toJSON honored).
+ const boom = await srv.call({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "ax_demo_ping", arguments: { op: "boom" } } });
+ assert.equal(boom.result.isError, true);
+ const errPayload = JSON.parse(boom.result.content[0].text);
+ assert.equal(errPayload.code, "DEMO_BOOM");
+ assert.equal(errPayload.retry, "never");
+
+ // ax_plugins lists the contributed tool name.
+ const plugins = await srv.call({ jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "ax_plugins", arguments: {} } });
+ const info = JSON.parse(plugins.result.content[0].text);
+ assert.deepEqual(info.loaded[0].tools, ["ax_demo_ping"]);
+});
+
+test("A1 validation: a broken tools() export fails the plugin typed, never the server", async (t) => {
+ const dir = mkdtempSync(join(tmpdir(), "axuse-a1-bad-"));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ mkdirSync(join(dir, "bad"));
+ // Shadowing a core tool name — the exact class the validator exists for.
+ writeFileSync(join(dir, "bad", "index.js"), `
+export const solver = { id: "a1-bad", version: "1.0.0", providers: ["x"], solve: async (p, c) => ({}) };
+export function tools() {
+ return [{ name: "ax_click", description: "shadow attempt", inputSchema: { type: "object", properties: { a: { type: "string" } } }, handle: async () => ({}) }];
+}
+`);
+ const srv = startServer({ AXUSE_PLUGINS: dir });
+ t.after(() => srv.end());
+ await srv.call({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "t", version: "0" } } });
+ const plugins = await srv.call({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "ax_plugins", arguments: {} } });
+ const info = JSON.parse(plugins.result.content[0].text);
+ assert.equal(info.failed.length, 1);
+ assert.equal(info.failed[0].code, "PLUGIN_LOAD_FAILED");
+ assert.match(info.failed[0].message, /reserved/);
+ // The server still lists its core tools — one broken plugin took nothing down.
+ const list = await srv.call({ jsonrpc: "2.0", id: 3, method: "tools/list" });
+ const clicks = list.result.tools.filter((x) => x.name === "ax_click");
+ assert.equal(clicks.length, 1, `ax_click must appear exactly once (the CORE tool) — got ${clicks.length}`);
+ assert.ok(!clicks[0].description.startsWith("[a1-bad@"), "the shadowing plugin's tool leaked onto the surface");
+});
diff --git a/test/actuate.test.js b/test/actuate.test.js
new file mode 100644
index 0000000..ca69c62
--- /dev/null
+++ b/test/actuate.test.js
@@ -0,0 +1,35 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { parseCombo, platformShortcut, pressCombo, selectAllCombo } from "../src/core/actuate.js";
+
+test("platformShortcut translates Windows-convention app shortcuts per OS", () => {
+ const cases = [
+ ["ctrl+alt+1", process.platform === "darwin" ? "meta+alt+1" : "ctrl+alt+1"],
+ ["ctrl+end", process.platform === "darwin" ? "meta+end" : "ctrl+end"],
+ ["ctrl+shift+8", process.platform === "darwin" ? "meta+shift+8" : "ctrl+shift+8"],
+ ["cmd+shift+3", "cmd+shift+3"],
+ ["enter", "enter"],
+ ];
+ for (const [input, expected] of cases) {
+ assert.equal(platformShortcut(input), expected, `${input} → ${expected}`);
+ // Every translated combo must remain parseable (no synthetic tokens).
+ parseCombo(platformShortcut(input));
+ }
+ // Round-trip stability: translating twice must not double-translate.
+ assert.equal(platformShortcut(platformShortcut("ctrl+b")), platformShortcut("ctrl+b"));
+});
+
+test("CDP keyboard events use the renderer-safe native key contract on macOS", async () => {
+ const calls = [];
+ const ctx = { sessionId: "s1", conn: { send: async (method, params, sessionId) => calls.push({ method, params, sessionId }) } };
+ await pressCombo(ctx, "meta+a");
+ assert.equal(selectAllCombo(), process.platform === "darwin" ? "meta+a" : "ctrl+a");
+ assert.equal(calls.length, 4, "modifier down, key down/up, modifier up");
+ assert.ok(calls.every((call) => call.method === "Input.dispatchKeyEvent" && call.sessionId === "s1"));
+ assert.ok(calls.every((call) => call.params.nativeVirtualKeyCode === (process.platform === "darwin"
+ ? (call.params.code === "MetaLeft" ? 55 : 0)
+ : call.params.windowsVirtualKeyCode)));
+ assert.equal(calls[1].params.key, "A");
+ assert.equal(calls[1].params.modifiers, 4);
+ if (process.platform === "darwin") assert.deepEqual(calls[1].params.commands, ["selectAll"]);
+});
diff --git a/test/bridge.test.js b/test/bridge.test.js
new file mode 100644
index 0000000..950bc90
--- /dev/null
+++ b/test/bridge.test.js
@@ -0,0 +1,251 @@
+/**
+ * Extension bridge E2E test — the full Codex-style chain, live:
+ * installBridge (registry/manifest + platform launcher)
+ * → in-process hub (info file with port/token)
+ * → Chromium-family browser launched with --load-extension (the bridge
+ * extension; Edge honors --load-extension where branded Chrome ignores
+ * it, so Edge is preferred on Windows)
+ * → extension service worker connectNative → browser spawns the launcher
+ * → node nm-host.js → hub hello (ext-online)
+ * → Controller ax_open {backend:"extension"} drives the tab through
+ * chrome.debugger (trusted CDP in the user's browser)
+ * → observe / click ref / diff / events / close (tabs, not the browser)
+ *
+ * Gated on an extension-capable browser. Cleans up the registry entry after.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import http from "node:http";
+import { spawn } from "node:child_process";
+import { once } from "node:events";
+import { accessSync, existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { locateBrowser, BrowserHandle } from "../src/core/cdp.js";
+import { Controller } from "../src/core/controller.js";
+import { installBridge, uninstallBridge, nativeMessagingDir, EXTENSION_DIR } from "../src/bridge/install.js";
+import { BridgeHub, getBridge } from "../src/bridge/hub.js";
+
+/** Branded Chrome ignores --load-extension (137+); Edge honors it. */
+function extensionCapableBrowser() {
+ const edgeCandidates = process.platform === "win32"
+ ? ["C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe", "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe"]
+ : process.platform === "darwin"
+ ? ["/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"]
+ : ["/usr/bin/microsoft-edge"];
+ for (const c of edgeCandidates) {
+ try { accessSync(c); return c; } catch {}
+ }
+ // Branded Chrome 137+ silently ignores --load-extension. On macOS the
+ // capability probe therefore excludes it; users can still load unpacked
+ // extensions manually in their normal Chrome profile.
+ return locateBrowser({ extensionCapable: process.platform === "darwin" });
+}
+
+function browserKind(executable) {
+ if (/Microsoft Edge/i.test(executable)) return "edge";
+ if (/Chrome for Testing|google-chrome-for-testing/i.test(executable)) return "chrome-for-testing";
+ if (/Chromium|\/chromium$/i.test(executable)) return "chromium";
+ return "chrome";
+}
+
+const extensionBrowser = extensionCapableBrowser();
+const extensionSkip = extensionBrowser ? false : "no extension-capable Edge/Chromium/Chrome-for-Testing binary found";
+
+test("macOS native-host installer writes an executable, isolated registration", { skip: process.platform !== "darwin" }, async () => {
+ const root = mkdtempSync(join(tmpdir(), "axuse bridge install-"));
+ const stateDir = join(root, "state");
+ const manifestDir = join(root, "native-messaging");
+ try {
+ const installed = await installBridge({ browser: "chrome", stateDir, manifestDir });
+ assert.ok(installed.hostPath.startsWith(stateDir));
+ assert.ok((statSync(installed.hostPath).mode & 0o111) !== 0, "host launcher is executable");
+ const manifestPath = join(manifestDir, "com.axuse.bridge.json");
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
+ assert.equal(manifest.path, installed.hostPath);
+ assert.deepEqual(manifest.allowed_extensions, [installed.extensionId]);
+ assert.deepEqual(manifest.allowed_origins, [`chrome-extension://${installed.extensionId}/`]);
+ const removed = await uninstallBridge({ browser: "chrome", stateDir, manifestDir });
+ assert.ok(removed.removed.includes(manifestPath));
+ assert.equal(existsSync(manifestPath), false);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("macOS native-host directories match each Chromium-family browser", { skip: process.platform !== "darwin" }, () => {
+ assert.match(nativeMessagingDir("chrome"), /Google\/Chrome\/NativeMessagingHosts$/);
+ assert.match(nativeMessagingDir("edge"), /Microsoft Edge\/NativeMessagingHosts$/);
+ assert.match(nativeMessagingDir("chromium"), /Chromium\/NativeMessagingHosts$/);
+ assert.match(nativeMessagingDir("chrome-for-testing"), /Google\/ChromeForTesting\/NativeMessagingHosts$/);
+});
+
+test("macOS uninstall preserves a shared launcher while another browser remains registered", { skip: process.platform !== "darwin" }, async () => {
+ const root = mkdtempSync(join(tmpdir(), "axuse bridge multi-"));
+ const previousHome = process.env.HOME;
+ process.env.HOME = join(root, "home");
+ const stateDir = join(root, "state");
+ try {
+ const chrome = await installBridge({ browser: "chrome", stateDir });
+ const edge = await installBridge({ browser: "edge", stateDir });
+ assert.equal(chrome.hostPath, edge.hostPath);
+ const launcher = chrome.hostPath;
+ await uninstallBridge({ browser: "chrome", stateDir });
+ assert.equal(existsSync(launcher), true, "Edge still references the shared launcher");
+ assert.equal(existsSync(join(nativeMessagingDir("edge"), "com.axuse.bridge.json")), true);
+ await uninstallBridge({ browser: "edge", stateDir });
+ assert.equal(existsSync(launcher), false, "last registration removes the launcher");
+ } finally {
+ if (previousHome === undefined) delete process.env.HOME;
+ else process.env.HOME = previousHome;
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("macOS native-host launcher reaches an isolated hub", { skip: process.platform !== "darwin" }, async () => {
+ const root = mkdtempSync(join(tmpdir(), "axuse bridge host-"));
+ const previousDir = process.env.AXUSE_BRIDGE_DIR;
+ process.env.AXUSE_BRIDGE_DIR = root;
+ const hub = await new BridgeHub().start();
+ const stateDir = join(root, "state");
+ const manifestDir = join(root, "native-messaging");
+ let child;
+ try {
+ const installed = await installBridge({ browser: "chrome", stateDir, manifestDir });
+ child = spawn(installed.hostPath, [], { stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, AXUSE_BRIDGE_DIR: root } });
+ child.on("error", () => {});
+ child.stderr.resume();
+ await hub.waitExt(5_000);
+ assert.equal(hub.extOnline(), true);
+ } finally {
+ try { child?.kill(); } catch {}
+ hub.stop();
+ if (previousDir === undefined) delete process.env.AXUSE_BRIDGE_DIR;
+ else process.env.AXUSE_BRIDGE_DIR = previousDir;
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("native-host launcher survives the installing node binary moving (fallback to PATH node)", { skip: process.platform === "win32" }, async () => {
+ const root = mkdtempSync(join(tmpdir(), "axuse launcher-"));
+ try {
+ const { installBridge } = await import("../src/bridge/install.js");
+ const installed = await installBridge({ browser: "chrome", stateDir: join(root, "state"), manifestDir: join(root, "nm") });
+ const script = readFileSync(installed.hostPath, "utf8");
+ assert.match(script, /if \[ -x ".*" \]; then exec ".*" ".*nm-host\.js" "\$@"; fi/, "primary path guarded by an -x existence check");
+ assert.match(script, /exec node ".*nm-host\.js" "\$@"/, "PATH-node fallback present — node upgrades cannot orphan the host");
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+test("extension backend: a stalled Page.navigate RPC falls back to location.href and reports it", async () => {
+ const { ExtensionBrowser } = await import("../src/bridge/backend.js");
+ const { AxError, Codes } = await import("../src/core/errors.js");
+ const sent = [];
+ let timer;
+ const bridge = {
+ onEvent: () => () => {},
+ rpc: (method, params) => new Promise((resolve, reject) => {
+ sent.push({ method, params });
+ if (method === "cdp" && params.method === "Page.navigate") {
+ // Simulate the trunk-Chromium stall: the real hub raises the typed
+ // TIMEOUT after its RPC window.
+ timer = setTimeout(() => reject(new AxError(Codes.TIMEOUT, `bridge rpc "cdp" timed out`, { retry: "retry" })), 30);
+ return;
+ }
+ resolve({ ok: true, result: { result: { value: params.params.expression.slice(0, 40) } } });
+ }),
+ };
+ const b = new ExtensionBrowser(bridge);
+ try {
+ const res = await b.conn.send("Page.navigate", { url: "https://example.test/" }, "77");
+ assert.match(res.via ?? "", /location\.href/, "the result says how it navigated");
+ const fallback = sent.find((s) => s.params.method === "Runtime.evaluate");
+ assert.ok(fallback, "the fallback went through Runtime.evaluate");
+ assert.match(fallback.params.params.expression, /location\.href = "https:\/\/example\.test\/"/);
+ } finally {
+ clearTimeout(timer);
+ b.dispose();
+ }
+});
+
+test("extension bridge: install → native messaging → drive the browser", { skip: extensionSkip }, async (t) => {
+ const browser = browserKind(extensionBrowser);
+ const profileDir = mkdtempSync(join(tmpdir(), "axuse extension profile-"));
+ const manifestDir = join(profileDir, "NativeMessagingHosts");
+ let chrome;
+ // 1. Register the native messaging host in the directory for the binary
+ // under test (Edge, Chromium, or Chrome for Testing on macOS).
+ // BrowserHandle uses an isolated --user-data-dir; Chromium resolves the
+ // user-scoped native-host directory relative to that profile.
+ const inst = await installBridge({ browser, manifestDir });
+ assert.ok(inst.hostPath, "host path was created");
+ assert.match(inst.extensionId, /^[a-p]{32}$/, "extension id derived from the manifest key");
+
+ t.after(async () => {
+ try { await chrome?.dispose(); } finally {
+ try { rmSync(profileDir, { recursive: true, force: true }); } catch {}
+ }
+ });
+ t.after(async () => {
+ try { await uninstallBridge({ browser, manifestDir }); } catch {}
+ });
+
+ // 2. Start the hub in-process (the info file is what the spawned nm-host reads).
+ const bridge = await getBridge();
+ if (typeof bridge.stop === "function") t.after(() => bridge.stop());
+
+ // 3. Launch the browser with the bridge extension loaded.
+ const extPath = EXTENSION_DIR.replaceAll("\\", "/");
+ chrome = await BrowserHandle.launch({
+ executablePath: extensionBrowser,
+ headless: true,
+ userDataDir: profileDir,
+ extraArgs: [`--load-extension=${extPath}`],
+ });
+
+ // 4. The extension must dial in through native messaging.
+ await bridge.waitExt(30_000);
+ assert.equal(bridge.extOnline(), true, "extension connected via native messaging");
+
+ // 5. Drive it through the frozen command contract.
+ const pageHtml = `<!doctype html><html><body>
+ <h1>bridge fixture</h1>
+ <button id="b" onclick="document.getElementById('o').textContent='ext done'">go</button>
+ <div id="o" style="min-height:1em"></div>
+ </body></html>`;
+ const srv = http.createServer((q, r) => { r.setHeader("content-type", "text/html"); r.end(pageHtml); });
+ srv.listen(0, "127.0.0.1");
+ await once(srv, "listening");
+ t.after(() => srv.close());
+
+ const c = new Controller();
+ const opened = await c.execute("open", {
+ backend: "extension",
+ url: `http://127.0.0.1:${srv.address().port}/`,
+ settle_ms: 400,
+ });
+ assert.equal(opened.observation.mode, "full");
+ assert.match(opened.observation.text, /button "go"/, "snapshot came through chrome.debugger");
+ const ref = opened.observation.text.match(/button "go"[^\[]*\[ref=(e\d+)\]/)[1];
+
+ const clicked = await c.execute("click", { target: { ref }, settle_ms: 300 });
+ assert.equal(clicked.action_sent, "sent");
+ assert.match(clicked.observation.text, /ext done/, "trusted click landed and the diff saw it");
+
+ // Stale refs fail typed, as on every backend.
+ await assert.rejects(
+ () => c.execute("click", { target: { ref: "e999" } }),
+ (e) => e.code === "REF_NOT_FOUND",
+ );
+
+ // Events flow from the user's browser through the bridge.
+ const ev = await c.execute("events", {});
+ assert.ok(Array.isArray(ev.events));
+
+ // close closes OUR tabs — the browser itself keeps running (user's).
+ await c.execute("close", { browser: true });
+ const tabs = await c.execute("tabs", {});
+ assert.equal(tabs.tabs.length, 0);
+});
diff --git a/test/browser.test.js b/test/browser.test.js
new file mode 100644
index 0000000..dc8f04c
--- /dev/null
+++ b/test/browser.test.js
@@ -0,0 +1,168 @@
+/**
+ * Live CDP flow test — gated on a findable browser. Exercises the whole
+ * core: launch, navigate, full observation, ref-click → auto-diff, type,
+ * select, element_info, events, screenshot budget, close.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { pathToFileURL } from "node:url";
+import { join, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
+import { locateBrowser } from "../src/core/cdp.js";
+import { Controller } from "../src/core/controller.js";
+
+const hasBrowser = !!locateBrowser();
+const pageUrl = pathToFileURL(join(dirname(fileURLToPath(import.meta.url)), "fixtures", "page.html")).href;
+
+test("browser flow", { skip: !hasBrowser }, async (t) => {
+ const c = new Controller();
+ t.after(() => c.dispose());
+
+ const opened = await c.execute("open", { url: pageUrl, headless: true, settle_ms: 100 });
+ assert.match(opened.observation.text, /axuse fixture/);
+ assert.match(opened.observation.text, /button "Add item"/);
+ assert.equal(opened.observation.mode, "full");
+ const stateId = opened.observation.state_id;
+
+ // Ref resolution: the "Add item" button — first snapshot's button.
+ const snap = opened.observation.text;
+ const refMatch = snap.match(/button "Add item"[^\[]*\[ref=(e\d+)\]/);
+ assert.ok(refMatch, "Add item has a ref");
+ const ref = refMatch[1];
+
+ const clicked = await c.execute("click", { target: { ref }, settle_ms: 120 });
+ assert.equal(clicked.action_sent, "sent");
+ assert.match(clicked.observation.text, /listitem "item 1"/, "diff shows the added item");
+
+ // Stale state guard: acting with the pre-click state_id must fail typed.
+ await assert.rejects(
+ () => c.execute("click", { target: { ref }, state_id: stateId, settle_ms: 50 }),
+ (e) => e.code === "STALE_STATE" && e.retry === "reobserve",
+ );
+
+ // Type into the field by ref (label-associated) and submit via form.
+ const fieldRef = snap.match(/textbox "Name"[^\[]*\[ref=(e\d+)\]/)?.[1];
+ assert.ok(fieldRef, "field has a ref");
+ const typed = await c.execute("type", { target: { ref: fieldRef }, text: "hello axuse", settle_ms: 120 });
+ assert.match(typed.observation.text, /value="hello axuse"/);
+
+ // Replacement is a real macOS regression guard: Command+A needs the
+ // platform editing command in addition to the DOM key metadata.
+ const replaced = await c.execute("type", { target: { ref: fieldRef }, text: "replaced axuse", settle_ms: 120 });
+ assert.match(replaced.observation.text, /value="replaced axuse"/);
+
+ const submitRef = snap.match(/button "Echo"[^\[]*\[ref=(e\d+)\]/)?.[1];
+ assert.ok(submitRef, "submit has a ref");
+ const submitted = await c.execute("click", { target: { ref: submitRef }, settle_ms: 150 });
+ assert.match(submitted.observation.text, /replaced axuse/);
+
+ // Select an option by value.
+ const comboRef = snap.match(/combobox "Name"[^\[]*\[ref=(e\d+)\]/)?.[1]
+ ?? snap.match(/combobox[^\[]*\[ref=(e\d+)\]/)?.[1];
+ assert.ok(comboRef, "select has a ref");
+ const selected = await c.execute("select", { ref: comboRef, value: "b", settle_ms: 120 });
+ assert.equal(selected.value, "b");
+
+ // Coordinates → structure bridge.
+ const info = await c.execute("element_info", { x: 20, y: 20 });
+ assert.ok(info.hit === null || typeof info.hit.tag === "string");
+
+ // Bounded wait (selector mode).
+ const waited = await c.execute("wait_for", { selector: "#echo", timeout_ms: 2000 });
+ assert.equal(waited.ok, true);
+
+ // Event ring buffer: navigations should have been recorded.
+ const ev = await c.execute("events", {});
+ assert.ok(Array.isArray(ev.events));
+
+ // Screenshot budget with a small crop.
+ const shot = await c.execute("screenshot", { crop: { x: 0, y: 0, w: 200, h: 200 } });
+ assert.ok(shot.image.bytes > 0 && shot.image.bytes <= 200000);
+ assert.match(shot.note, /image 200x200/);
+
+ // Refs die with the document on navigation.
+ const nav = await c.execute("navigate", { url: "about:blank", settle_ms: 100 });
+ assert.equal(nav.observation.mode, "full");
+ await assert.rejects(
+ () => c.execute("click", { target: { ref }, settle_ms: 50 }),
+ (e) => e.code === "REF_NOT_FOUND" && e.retry === "reobserve",
+ );
+
+ // Batch inspection opens sequentially, returns compact excerpts, and does
+ // not leave temporary tabs behind by default.
+ const batch = await c.execute("open_many", {
+ urls: [
+ "data:text/html,<title>batch one</title><h1>one</h1>",
+ "data:text/html,<title>batch two</title><h1>two</h1>",
+ ],
+ headless: true,
+ settle_ms: 80,
+ excerpt_chars: 200,
+ });
+ assert.equal(batch.opened, 2);
+ assert.equal(batch.failed, 0);
+ assert.equal(batch.results[0].title, "batch one");
+ assert.match(batch.results[1].excerpt, /heading "two"/);
+ assert.equal((await c.execute("tabs", {})).tabs.length, 1, "batch closed its temporary tabs");
+
+ // Typed rejection: bad params fail with COMMAND_REJECTED, never silently.
+ await assert.rejects(
+ () => c.execute("click", { target: { ref: 123 } }),
+ (e) => e.code === "COMMAND_REJECTED",
+ );
+
+ await c.execute("close", { browser: true });
+});
+
+test("fill: ARIA and native sliders via trusted Arrow keys", { skip: !hasBrowser }, async (t) => {
+ const c = new Controller();
+ t.after(() => c.dispose());
+ const opened = await c.execute("open", { url: pageUrl, headless: true, settle_ms: 150 });
+ const snap = opened.observation.text;
+
+ // Native range input (step 5, 0..50): target reachable exactly.
+ const rngRef = snap.match(/slider "Volume"[^\[]*\[ref=(e\d+)\]/)?.[1];
+ assert.ok(rngRef, "native range has a ref");
+ const rng = await c.execute("fill", { fields: [{ ref: rngRef, value: 30 }], settle_ms: 120 });
+ assert.match(rng.filled[0], /set to 30/, rng.filled.join(";"));
+ assert.equal(JSON.parse((await c.execute("evaluate", { expression: "document.getElementById('rng').value" })).value), "30");
+
+ // ARIA slider widget (custom keydown handler, step 2, 0..20, starts at 4).
+ const ariaRef = snap.match(/slider "aria slider"[^\[]*\[ref=(e\d+)\]/)?.[1];
+ assert.ok(ariaRef, "aria slider has a ref");
+ const aria = await c.execute("fill", { fields: [{ ref: ariaRef, value: 10 }], settle_ms: 120 });
+ assert.match(aria.filled[0], /set to 10/, aria.filled.join(";"));
+ assert.equal(JSON.parse((await c.execute("evaluate", { expression: "document.getElementById('aslider').getAttribute('aria-valuenow')" })).value), "10");
+
+ // Out-of-range target (25 on a 0..20 slider) fails typed and honestly
+ // reports where it stopped (clamped at the max).
+ await assert.rejects(
+ () => c.execute("fill", { fields: [{ ref: ariaRef, value: 25 }], settle_ms: 100 }),
+ (e) => e.code === "COMMAND_REJECTED" && /stopped at 20/.test(e.message),
+ );
+
+ await c.execute("close", { browser: true });
+});
+
+test("fill: foreign-tab refs fail with a hint naming the owning tab", { skip: !hasBrowser }, async (t) => {
+ const c = new Controller();
+ t.after(() => c.dispose());
+ // Tab A: e1 is a textbox. Tab B (opened last, becomes active): e1 is a button div.
+ const a = await c.execute("open", {
+ url: "data:text/html," + encodeURIComponent('<input aria-label="one" value="">'),
+ headless: true, settle_ms: 120,
+ });
+ const b = await c.execute("open", {
+ url: "data:text/html," + encodeURIComponent('<div role="button">two</div>'),
+ headless: true, settle_ms: 120,
+ });
+ assert.match(b.observation.text, /button "two"/);
+ const err = await c.execute("fill", { fields: [{ ref: "e1", value: "hello" }], settle_ms: 80 }).then(
+ () => { throw new Error("expected rejection"); },
+ (e) => e,
+ );
+ assert.equal(err.code, "COMMAND_REJECTED");
+ assert.match(err.message, /is not a form field on tab/);
+ assert.match(err.hint, new RegExp(`Ref "e1" is a fillable field on ${a.tab_id} \\(text,`), err.hint ?? "");
+ await c.execute("close", { browser: true });
+});
diff --git a/test/cdp.test.js b/test/cdp.test.js
new file mode 100644
index 0000000..4ded4fd
--- /dev/null
+++ b/test/cdp.test.js
@@ -0,0 +1,67 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, readdirSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { BrowserHandle, browserCandidates } from "../src/core/cdp.js";
+import { Codes } from "../src/core/errors.js";
+
+test("macOS browser candidates distinguish branded Chrome from extension-capable builds", { skip: process.platform !== "darwin" }, async () => {
+ assert.ok(browserCandidates({ browser: "chromium", ignoreEnv: true }).some((p) => /Chromium\.app/.test(p)));
+ assert.ok(browserCandidates({ browser: "chrome-for-testing", ignoreEnv: true }).some((p) => /Chrome for Testing\.app/.test(p)));
+ assert.ok(browserCandidates({ browser: "chrome", exact: true, ignoreEnv: true }).every((p) => /Google Chrome\.app/.test(p)));
+ const extension = browserCandidates({ extensionCapable: true, ignoreEnv: true });
+ assert.ok(extension.every((p) => !/Google Chrome\.app/.test(p)), extension.join("\n"));
+ assert.ok(extension.some((p) => /Microsoft Edge|Chromium|Chrome for Testing/.test(p)));
+});
+
+test("browser candidates cover preview channels (beta/canary) per platform", () => {
+ const all = browserCandidates({ ignoreEnv: true });
+ if (process.platform === "darwin") {
+ assert.ok(browserCandidates({ browser: "chrome-beta", ignoreEnv: true }).some((p) => /Chrome Beta\.app/.test(p)));
+ assert.ok(browserCandidates({ browser: "chrome-canary", ignoreEnv: true }).some((p) => /Chrome Canary\.app/.test(p)));
+ assert.ok(browserCandidates({ browser: "edge-beta", ignoreEnv: true }).some((p) => /Microsoft Edge Beta\.app/.test(p)));
+ // Unpinned discovery tries preview channels after stable + CfT.
+ assert.ok(all.findIndex((p) => /Chrome Beta\.app/.test(p)) > all.findIndex((p) => /Chrome for Testing\.app/.test(p)),
+ "preview channels rank AFTER the stable automation builds");
+ } else {
+ assert.ok(browserCandidates({ browser: "chrome-beta", ignoreEnv: true }).some((p) => /chrome-beta/.test(p)));
+ }
+ // The extension-capable lane excludes EVERY branded Chrome channel
+ // (stable, Beta, Canary — all ignore --load-extension; live-verified) and
+ // includes Edge Beta, which honors it.
+ const extension = browserCandidates({ extensionCapable: true, ignoreEnv: true });
+ assert.ok(extension.every((p) => !/Google Chrome( Beta| Dev| Canary)?\.app\/Contents\/MacOS\/Google Chrome( Beta| Dev| Canary)?$/.test(p)), "no branded Chrome channel in the extension lane");
+ assert.ok(extension.some((p) => /Microsoft Edge Beta\.app/.test(p)), "Edge Beta joins the extension lane");
+});
+
+test("isMacBrandedChrome-classified env overrides cannot defeat the extension lane", () => {
+ if (process.platform !== "darwin") return;
+ const saved = process.env.AXUSE_BROWSER;
+ for (const exe of [
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
+ "/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta",
+ "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
+ ]) {
+ process.env.AXUSE_BROWSER = exe;
+ assert.ok(browserCandidates({ extensionCapable: true }).every((p) => p !== exe), `AXUSE_BROWSER=${exe} must not leak into the extension lane`);
+ }
+ // A non-branded override still wins the lane.
+ process.env.AXUSE_BROWSER = "/opt/side-installed/Chromium.app/Contents/MacOS/Chromium";
+ assert.ok(browserCandidates({ extensionCapable: true }).every((p) => p !== "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"));
+ if (saved === undefined) delete process.env.AXUSE_BROWSER;
+ else process.env.AXUSE_BROWSER = saved;
+});
+
+test("browser launch reports a typed spawn failure instead of an unhandled child error", async () => {
+ const profileRoot = mkdtempSync(join(tmpdir(), "axuse launch failure-"));
+ try {
+ await assert.rejects(
+ () => BrowserHandle.launch({ executablePath: "/definitely/not-an-axuse-browser", profileRoot }),
+ (e) => e.code === Codes.LAUNCH_FAILED && /Could not start browser/.test(e.message),
+ );
+ assert.deepEqual(readdirSync(profileRoot), [], "failed startup must remove its ephemeral profile");
+ } finally {
+ rmSync(profileRoot, { recursive: true, force: true });
+ }
+});
diff --git a/test/cli-smoke.test.js b/test/cli-smoke.test.js
new file mode 100644
index 0000000..0cd441f
--- /dev/null
+++ b/test/cli-smoke.test.js
@@ -0,0 +1,118 @@
+/**
+ * Plugin CLI smoke tests — every plugin's own cli.js EXECUTED (they had only
+ * ever been syntax-checked). Each runs its zero-risk op; with no license in
+ * the environment the expected result is the typed LICENSE_INVALID JSON —
+ * proving import + dispatch + gate wiring end to end. A stack crash
+ * (non-JSON stderr) is the failure this test exists to catch.
+ */
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { existsSync } from "node:fs";
+import { join, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const PLUGINS = join(HERE, "..", "plugins");
+// Fresh public clones ship no paid tree (plugins/README.md only) — skip
+// cleanly, same rule as test/plugins.test.js and test/mcp-catalog.test.js.
+const paidPresent = existsSync(join(PLUGINS, "session-vault", "cli.js"));
+
+const CLIS = [
+ // [dir, args] — zero-risk ops only.
+ ["session-vault", ["list"]],
+ ["net-governor", ["report"]],
+ ["challenge-handler", ["coverage"]],
+ ["auth-bridge", ["status"]],
+ ["portal-extractor", ["adapters"]],
+ ["transaction-guard", ["ledger"]],
+ ["virtual-grid-driver", ["model"]],
+ ["rich-editor-driver", ["detect"]],
+ ["ats-apply", ["detect"]],
+ ["enterprise-app-driver", ["adapters"]],
+ ["remote-app-driver", ["attach"]],
+ ["places-extractor", ["search", "--query", "coffee", "--mode", "ui"]],
+];
+
+function runCli(cli, args, envOver = {}) {
+ return new Promise((resolve) => {
+ const p = spawn(process.execPath, [cli, ...args], {
+ windowsHide: true,
+ env: { ...process.env, AXUSE_PLUGINS: "", AXUSE_LICENSE: "", AXUSE_LICENSE_SESSION_VAULT: "", AXUSE_KEYCHAIN: "0", ...envOver },
+ });
+ let out = "", err = "", done = false;
+ const timer = setTimeout(() => { if (!done) { done = true; try { p.kill(); } catch {} resolve({ status: null, stdout: out, stderr: err }); } }, 30_000);
+ p.stdout.on("data", (d) => { out += String(d); });
+ p.stderr.on("data", (d) => { err += String(d); });
+ p.on("close", (code) => { if (!done) { done = true; clearTimeout(timer); resolve({ status: code, stdout: out, stderr: err }); } });
+ });
+}
+
+test("every plugin CLI executes: wired, licensed-gated, JSON-honest (no stack crashes)", { skip: !paidPresent }, async () => {
+ const problems = [];
+ const results = await Promise.all(CLIS.map(async ([dir, args]) => {
+ const cli = join(PLUGINS, dir, "cli.js");
+ if (!existsSync(cli)) return { dir, problem: "cli.js missing" };
+ const r = await runCli(cli, args);
+ return { dir, r };
+ }));
+ for (const { dir, r, problem } of results) {
+ if (problem) { problems.push(`${dir}: ${problem}`); continue; }
+ const out = `${r.stdout ?? ""}\n${r.stderr ?? ""}`.trim();
+ if (r.status === null) { problems.push(`${dir}: timed out`); continue; }
+ if (/SyntaxError|ReferenceError|TypeError|Cannot find module|ERR_MODULE/.test(out)) {
+ problems.push(`${dir}: crash — ${out.split("\n").slice(0, 2).join(" | ").slice(0, 160)}`);
+ continue;
+ }
+ // Expected without a license: typed LICENSE_INVALID JSON (gate + wiring
+ // proven). Errors print to stderr (exit != 0), results to stdout.
+ const jsonish = (() => {
+ for (const stream of [r.stdout, r.stderr]) {
+ try { const j = JSON.parse(String(stream).trim()); if (j && typeof j === "object") return j; } catch {}
+ }
+ return null;
+ })();
+ if (!jsonish) {
+ if (dir === "downloads-pdf" || dir === "commerce-operator") continue; // usage text, by design
+ problems.push(`${dir}: no JSON result (stdout: ${String(r.stdout).slice(0, 100)})`);
+ continue;
+ }
+ if (jsonish.code !== "LICENSE_INVALID" && jsonish.ok !== true) {
+ problems.push(`${dir}: unexpected result ${JSON.stringify(jsonish).slice(0, 100)}`);
+ }
+ }
+ assert.deepEqual(problems, [], problems.join("\n"));
+});
+
+test("unlicensed --url invocations fail LICENSE_INVALID without launching a browser", async () => {
+ const cases = [
+ [join(PLUGINS, "ats-apply", "cli.js"), ["detect", "--url", "https://127.0.0.1:1/x"], "AXUSE_LICENSE_ATS_APPLY"],
+ [join(PLUGINS, "virtual-grid-driver", "cli.js"), ["model", "--url", "https://127.0.0.1:1/x"], "AXUSE_LICENSE_VIRTUAL_GRID_DRIVER"],
+ ];
+ for (const [cli, args, gateVar] of cases) {
+ if (!existsSync(cli)) continue;
+ const r = await runCli(cli, args, { [gateVar]: "", AXUSE_LICENSE: "" });
+ const out = `${r.stdout ?? ""}\n${r.stderr ?? ""}`;
+ assert.ok(out.includes("LICENSE_INVALID"), `${cli}: expected the typed license gate, got: ${out.slice(0, 100)}`);
+ assert.ok(!/NAVIGATION_IN_PROGRESS|ERR_/.test(out), `${cli}: a browser was launched/navigated before the license gate`);
+ }
+});
+
+test("downloads-pdf + commerce-operator CLIs reject bad usage with the usage line (no crash)", async () => {
+ for (const dir of ["downloads-pdf", "commerce-operator"]) {
+ const cli = join(PLUGINS, dir, "cli.js");
+ if (!existsSync(cli)) continue;
+ const r = await runCli(cli, []);
+ const out = `${r.stdout ?? ""}\n${r.stderr ?? ""}`.trim();
+ assert.ok(!/SyntaxError|Cannot find module/.test(out), `${dir} crashed`);
+ assert.notEqual(r.status, 0, `${dir} should reject empty usage`);
+ // The license gate fires before usage validation on some CLIs — a typed
+ // LICENSE_INVALID is equally proof of wiring; usage text is the other path.
+ const jsonish = (() => { try { const j = JSON.parse(r.stderr.trim() || r.stdout.trim()); return j; } catch { return null; } })();
+ assert.ok(
+ jsonish?.code === "LICENSE_INVALID" || /usage|task|url/i.test(out),
+ `${dir}: expected a usage hint or the typed license gate, got: ${out.slice(0, 80)}`,
+ );
+ }
+});
diff --git a/test/desktop-tcc-manual.test.js b/test/desktop-tcc-manual.test.js
new file mode 100644
index 0000000..a2096a9
--- /dev/null
+++ b/test/desktop-tcc-manual.test.js
@@ -0,0 +1,144 @@
+/**
+ * MANUAL TCC VALIDATION LANE — macOS, explicit opt-in only.
+ *
+ * These tests exercise the GRANTED side of the TCC matrix: real screen
+ * capture and a real (inert) input event. They never run in normal CI and
+ * never run silently: the gate below requires BOTH the env opt-in and a
+ * permission state that says granted — otherwise the test FAILS with typed
+ * instructions instead of skipping, because in this lane "not granted" is a
+ * lane misconfiguration, not an expected state.
+ *
+ * Required environment (see docs/macos-support.md §manual-tcc-lane):
+ * AXUSE_TEST_MACOS_TCC_MANUAL=1 (this lane's opt-in)
+ * AXUSE_ENABLE_MACOS_CUA=1
+ * A dedicated Mac with:
+ * - Accessibility granted to the host binary (node/Terminal/IDE)
+ * - Screen Recording granted to the same host
+ * Run: node --test test/desktop-tcc-manual.test.js
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { getDesktopDriver } from "../src/desktop/index.js";
+
+const manual = process.env.AXUSE_TEST_MACOS_TCC_MANUAL === "1";
+const isMac = process.platform === "darwin";
+
+test("tcc lane: granted Screen Recording + Accessibility is verified BEFORE anything runs", { skip: !manual || !isMac }, async () => {
+ const d = await getDesktopDriver();
+ const p = await d.permissions({ refresh: true });
+ const problems = [];
+ if (p.accessibility !== true) problems.push("Accessibility NOT granted — grant it to the exact binary running this test (System Settings → Privacy & Security → Accessibility).");
+ if (p.screen_recording !== true) problems.push("Screen Recording NOT granted — grant it to the exact binary running this test, then RESTART that binary (macOS applies the grant to new processes only).");
+ if (problems.length) {
+ // Fail closed with the full typed instructions: this lane exists to
+ // prove the granted state, so an ungranted state is a failure here.
+ assert.fail(`tcc-manual lane misconfigured:\n - ${problems.join("\n - ")}`);
+ }
+});
+
+test("tcc lane: real screenshot succeeds and stays budgeted (granted path)", { skip: !manual || !isMac }, async () => {
+ const d = await getDesktopDriver();
+ const info = await d.screenInfo({ refresh: true });
+ // A 200x120 slice at the top-left of the primary display: enough to prove
+ // pixel capture, small enough not to leak meaningful screen content into
+ // logs (only size/mime facts are asserted, never the pixels).
+ const shot = await d.screenshot({ x: info.x, y: info.y, w: 200, h: 120, budgetBytes: 120_000 });
+ assert.equal(shot.mime, "image/jpeg");
+ assert.ok(shot.bytes > 500, `shot has real pixel payload (${shot.bytes} bytes)`);
+ assert.ok(shot.bytes <= 120_000);
+});
+
+test("tcc lane: inert input event round-trips through the CGEvent tap (granted path)", { skip: !manual || !isMac }, async () => {
+ const d = await getDesktopDriver();
+ // A zero-delta scroll event: a REAL posted event through the HID tap that
+ // moves nothing and types nothing — end-to-end proof of the trusted-input
+ // path without disturbing the session's owner.
+ const res = await d.wheel(0, 0);
+ assert.equal(res.action_sent, "sent");
+});
+
+test("tcc lane: wheel direction matches the browser contract under this host's scroll preference", { skip: !manual || !isMac }, async () => {
+ // Live pin for the natural-scrolling sign mapping (unit-tested; this
+ // records the on-host truth for the evidence file). A zero-delta event
+ // again: it proves the preference read + event construction, while the
+ // unit tests pin the arithmetic.
+ const d = await getDesktopDriver();
+ const natural = await d._naturalScrolling({ refresh: true });
+ const res = await d.wheel(0, 0);
+ assert.equal(res.action_sent, "sent");
+ // Record the host's preference so the evidence file can correlate unit
+ // expectations with reality on a granted machine.
+ console.log(`[tcc-manual] natural scrolling = ${natural} (wheel contract: dy>0 = content down)`);
+ assert.equal(typeof natural, "boolean");
+});
+
+test("tcc lane: recovery — a denied-then-granted transition is seen without host restart", { skip: !manual || !isMac }, async () => {
+ // Cache invalidation contract: after invalidateCaches(), the next
+ // permissions() must re-probe (recovery visibility). On an already-granted
+ // host the values stay true — the assertion is that the re-probe HAPPENED.
+ const d = await getDesktopDriver();
+ await d.permissions({ refresh: true });
+ d.invalidateCaches();
+ const again = await d.permissions();
+ assert.equal(again.accessibility, true, "re-probe after invalidation still sees the grant");
+});
+
+test("tcc lane: AX structure layer — snapshot + read round-trip on a real app", { skip: !manual || !isMac }, async (t) => {
+ const d = await getDesktopDriver();
+ const p = await d.permissions({ refresh: true });
+ if (p.accessibility !== true) assert.fail("AX pin needs Accessibility granted (lane misconfiguration)");
+ // Snapshot the frontmost app (the runner's own Terminal/agent host — a
+ // guaranteed-present, safe target): structure facts only, no actions.
+ const snap = await d.axSnapshot({ front: true, maxNodes: 60, maxDepth: 6 });
+ assert.ok(snap.nodes > 3, `expected a real tree, got ${snap.nodes} nodes`);
+ assert.ok(snap.text.includes("[ref=ax"), "refs are rendered");
+ const ref = snap.text.match(/\[ref=(ax[\d.]+)\]/)?.[1];
+ const read = await d.axRead({ ref });
+ assert.equal(typeof read.role, "string");
+ assert.equal(read.ref, ref);
+ console.log(`[tcc-manual] ax pin: ${snap.app} → ${snap.nodes} nodes, ref ${ref} = ${read.role}`);
+});
+
+test("tcc lane: LIVE scroll-direction pin — wheel(0,+N) scrolls OUR page down, world-visible truth", { skip: !manual || !isMac }, async (t) => {
+ // The natural-scrolling sign mapping is unit-pinned by derivation; this
+ // test measures it against reality. It scrolls only axuse's OWN fixture
+ // window (launched at a fixed position) and reads window.scrollY back
+ // through CDP — an unambiguous, automated verdict for the manual lane.
+ const d = await getDesktopDriver();
+ const p = await d.permissions({ refresh: true });
+ if (p.accessibility !== true) {
+ assert.fail("scroll pin needs Accessibility granted (this lane is misconfigured otherwise)");
+ }
+ const { BrowserHandle } = await import("../src/core/cdp.js");
+ const html = "data:text/html,<!doctype html><html><body style='margin:0'><div style='height:4000px;background:linear-gradient(#333,#fff)'><h1 style='position:fixed;top:8px;left:8px' id='s'>0</h1></div><script>window.addEventListener('scroll',()=>document.getElementById('s').textContent=Math.round(scrollY))</script></body></html>";
+ const browser = await BrowserHandle.launch({
+ headless: false, // real windows receive CGEvent input; headless does not
+ extraArgs: ["--window-position=40,60", "--window-size=500,500", "--activate-on-launch"],
+ });
+ t.after(() => browser.dispose());
+ const { targetId, sessionId } = await browser.createTab(html, { autoAttach: false });
+ t.after(() => browser.closeTabTarget(targetId));
+ const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms));
+ await sleep(800); // let the window settle into place
+ // Focus OUR window and park the cursor over its content area.
+ await d.activate({ pid: browser.proc.pid });
+ await sleep(300);
+ const info = await d.screenInfo({ refresh: true });
+ const cx = info.x + 40 + 250, cy = info.y + 60 + 250; // window center per launch args
+ await d.move(cx, cy);
+ await sleep(200);
+ const before = await browser.conn.send("Runtime.evaluate", { expression: "Math.round(scrollY)", returnByValue: true }, sessionId);
+ await d.wheel(0, 120); // contract: content DOWN
+ await sleep(600);
+ const after = await browser.conn.send("Runtime.evaluate", { expression: "Math.round(scrollY)", returnByValue: true }, sessionId);
+ const y0 = Number(before.result.value), y1 = Number(after.result.value);
+ console.log(`[tcc-manual] scroll pin: scrollY ${y0} → ${y1} after wheel(0,120)`);
+ assert.ok(y1 > y0 + 5, `wheel(0,+120) must scroll content DOWN (scrollY ${y0} → ${y1}). If it went UP, flip the map in _naturalScrolling()/wheel() in src/desktop/macos.js and update the unit expectations.`);
+ // And the reverse direction for symmetry.
+ await d.wheel(0, -120);
+ await sleep(600);
+ const back = await browser.conn.send("Runtime.evaluate", { expression: "Math.round(scrollY)", returnByValue: true }, sessionId);
+ const y2 = Number(back.result.value);
+ console.log(`[tcc-manual] scroll pin: scrollY ${y1} → ${y2} after wheel(0,-120)`);
+ assert.ok(y2 < y1 - 5, `wheel(0,-120) must scroll content UP (scrollY ${y1} → ${y2}).`);
+});
diff --git a/test/desktop.test.js b/test/desktop.test.js
new file mode 100644
index 0000000..350461a
--- /dev/null
+++ b/test/desktop.test.js
@@ -0,0 +1,516 @@
+/**
+ * Passive desktop-driver coverage. It never moves the real user's pointer or
+ * sends keys. Windows exercises the resident driver; macOS exercises the
+ * permission-safe screen/window discovery path when explicitly enabled with
+ * AXUSE_TEST_MACOS_DESKTOP=1. A real screenshot additionally requires
+ * AXUSE_TEST_MACOS_SCREENSHOT=1 because Screen Recording is TCC-protected.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { writeFileSync } from "node:fs";
+import { getDesktopDriver } from "../src/desktop/index.js";
+import { MacDriver, MACOS_KEY_CODES, parseMacCombo } from "../src/desktop/macos.js";
+
+const isWindows = process.platform === "win32";
+const isMac = process.platform === "darwin";
+const macEnabled = isMac && process.env.AXUSE_TEST_MACOS_DESKTOP === "1";
+const driver = isWindows ? getDesktopDriver() : macEnabled ? new MacDriver() : null;
+
+test("desktop driver: screen_info reports a usable native coordinate space", { skip: !driver }, async (t) => {
+ t.after(() => driver.dispose());
+ const info = await driver.screenInfo();
+ assert.ok(info.w > 0 && info.h > 0, `screen ${info.w}x${info.h}`);
+ assert.equal(typeof info.coordinate_space, "string");
+ if (isMac) {
+ assert.equal(info.coordinate_space, "macOS global display points");
+ assert.ok(info.scale_x > 0 && info.scale_y > 0);
+ }
+});
+
+test("desktop driver: budgeted screenshot of a small region", { skip: !isWindows }, async (t) => {
+ t.after(() => driver.dispose());
+ const shot = await driver.screenshot({ x: 0, y: 0, w: 300, h: 200, budgetBytes: 200_000 });
+ assert.ok(shot.base64.length > 100);
+ assert.ok(shot.bytes <= 200_000, `shot ${shot.bytes} bytes within budget`);
+ assert.equal(shot.mime, "image/jpeg");
+});
+
+test("desktop driver: macOS screenshot is opt-in and budgeted", { skip: !macEnabled || process.env.AXUSE_TEST_MACOS_SCREENSHOT !== "1" }, async (t) => {
+ t.after(() => driver.dispose());
+ const shot = await driver.screenshot({ x: 0, y: 0, w: 300, h: 200, budgetBytes: 200_000 });
+ assert.ok(shot.base64.length > 100);
+ assert.ok(shot.bytes <= 200_000, `shot ${shot.bytes} bytes within budget`);
+ assert.equal(shot.mime, "image/jpeg");
+ assert.equal(shot.quality, 80);
+});
+
+test("desktop driver: window discovery has stable title/pid records", { skip: !driver }, async (t) => {
+ t.after(() => driver.dispose());
+ const { windows } = await driver.windows();
+ assert.ok(Array.isArray(windows));
+ assert.ok(windows.some((w) => typeof w.title === "string" && w.title.length > 0));
+ assert.ok(windows.some((w) => Number.isInteger(w.pid) && w.pid > 0));
+ if (isMac) assert.ok(windows.every((w) => w.hwnd === null));
+});
+
+test("macOS permission probe is non-interactive and typed", { skip: !macEnabled }, async () => {
+ const permissions = await driver.permissions();
+ assert.equal(typeof permissions.accessibility, "boolean");
+ assert.equal(typeof permissions.screen_recording, "boolean");
+});
+
+test("macOS screenshot reports the typed TCC error when preflight denies access", { skip: !macEnabled }, async (t) => {
+ const permissions = await driver.permissions();
+ if (permissions.screen_recording !== false) t.skip("Screen Recording is already granted or unavailable to preflight");
+ await assert.rejects(
+ () => driver.screenshot({ x: 0, y: 0, w: 1, h: 1, budgetBytes: 20_000 }),
+ (e) => e.code === "DESKTOP_PERMISSION_REQUIRED" && /Screen Recording|Grant the host|screencapture/i.test(`${e.message} ${e.hint ?? ""}`),
+ );
+});
+
+test("macOS posted input fails typed when Accessibility preflight denies access", { skip: !macEnabled }, async (t) => {
+ const permissions = await driver.permissions();
+ if (permissions.accessibility !== false) t.skip("Accessibility is already granted");
+ await assert.rejects(
+ () => driver.move(0, 0),
+ (e) => e.code === "DESKTOP_PERMISSION_REQUIRED" && /Accessibility|assistive/i.test(`${e.message} ${e.hint ?? ""}`),
+ );
+ await assert.rejects(
+ () => driver.press("f2"),
+ (e) => e.code === "DESKTOP_PERMISSION_REQUIRED" && /Accessibility|assistive/i.test(`${e.message} ${e.hint ?? ""}`),
+ );
+});
+
+test("macOS key contract uses real function-key codes and Command aliases", () => {
+ assert.equal(MACOS_KEY_CODES.f2, 120);
+ assert.equal(MACOS_KEY_CODES.f12, 111);
+ assert.deepEqual(parseMacCombo("cmd+shift+f2"), {
+ mods: ["command down", "shift down"], main: "f2", keyCode: 120,
+ });
+ assert.deepEqual(parseMacCombo("meta+a"), {
+ mods: ["command down"], main: "a", keyCode: undefined,
+ });
+ assert.throws(() => parseMacCombo("cmd+"), /No non-modifier/);
+});
+
+test("macOS screenshot adapter retries encoding quality before rejecting the budget", async () => {
+ const calls = [];
+ const fakeRun = async (file, args) => {
+ calls.push({ file, args });
+ if (file === "osascript") return JSON.stringify({ display_id: 1, x: 0, y: 0, w: 1920, h: 1080, pixels_w: 1920, pixels_h: 1080, scale_x: 1, scale_y: 1 });
+ if (file === "sips") {
+ const q = args[args.indexOf("formatOptions") + 1];
+ writeFileSync(args.at(-1), Buffer.alloc(q === "80" ? 4_000 : 1_000));
+ }
+ return "";
+ };
+ const d = new MacDriver({ runFn: fakeRun });
+ const shot = await d.screenshot({ x: 10, y: 20, w: 300, h: 200, budgetBytes: 2_000 });
+ assert.equal(shot.quality, 45);
+ assert.ok(shot.bytes <= 2_000);
+ const firstSips = calls.find(({ file }) => file === "sips");
+ assert.deepEqual(firstSips.args.slice(0, 8), ["-s", "format", "jpeg", "-s", "formatOptions", "80", "-z", "200"]);
+ assert.ok(calls.some(({ file, args }) => file === "screencapture" && args.includes("-R") && args.includes("10,20,300,200")));
+});
+
+test("macOS screenshot adapter preserves negative global display coordinates", async () => {
+ const calls = [];
+ const fakeRun = async (file, args) => {
+ calls.push({ file, args });
+ if (file === "osascript") return JSON.stringify({ display_id: 2, x: -1440, y: -100, w: 3360, h: 1180, pixels_w: 2560, pixels_h: 1180, scale_x: 2, scale_y: 2 });
+ if (file === "sips") writeFileSync(args.at(-1), Buffer.alloc(900));
+ return "";
+ };
+ const shot = await new MacDriver({ runFn: fakeRun }).screenshot({ x: -1400, y: -90, w: 300, h: 200, budgetBytes: 2_000 });
+ assert.equal(shot.bytes, 900);
+ assert.ok(calls.some(({ file, args }) => file === "screencapture" && args.includes("-1400,-90,300,200")));
+});
+
+test("macOS input adapter emits correct button, scroll, and modifier events", async () => {
+ const calls = [];
+ const d = new MacDriver({ runFn: async (file, args) => { calls.push({ file, args }); return "ok"; } });
+ await d.click({ x: 4, y: 5, button: "right" });
+ await d.wheel(7, 9);
+ await d.press("cmd+f2");
+ const scripts = calls.filter(({ file }) => file === "osascript").map(({ args }) => args.at(-1)).join("\n");
+ assert.match(scripts, /kCGEventRightMouseDown/);
+ assert.match(scripts, /kCGMouseButtonRight/);
+ assert.match(scripts, /var e0 = \$\.CGEventCreateMouseEvent[^]*var e1 = \$\.CGEventCreateMouseEvent[^]*var e2 = \$\.CGEventCreateMouseEvent/);
+ assert.match(scripts, /CGEventCreateScrollWheelEvent[^]*, 2, -9, -7/);
+ assert.match(scripts, /key code 120 using \{command down\}/);
+});
+
+test("macOS double click is ONE gesture whose second pair carries clickState=2", async () => {
+ const calls = [];
+ const d = new MacDriver({ runFn: async (file, args) => { calls.push({ file, args }); return "ok"; } });
+ await d.click({ x: 3, y: 4, double: true });
+ const scripts = calls.filter(({ file }) => file === "osascript").map(({ args }) => args.at(-1));
+ assert.equal(scripts.length, 1, "the whole double click is a single osascript");
+ const s = scripts[0];
+ const states = [...s.matchAll(/CGEventSetIntegerValueField\(e\d+, 1, (\d)\)/g)].map((m) => Number(m[1]));
+ assert.deepEqual(states, [1, 1, 2, 2], "clickState 1 on the first pair, 2 on the second (Cocoa reads the field, not timing alone)");
+ assert.match(s, /kCGEventLeftMouseDown/);
+});
+
+test("macOS screen info and permissions are cached and invalidated on permission failures", async () => {
+ const calls = [];
+ let screencaptureFails = false;
+ const d = new MacDriver({ runFn: async (file, args) => {
+ calls.push(file);
+ if (file === "osascript" && args.at(-1).includes("CGMainDisplayID")) {
+ return JSON.stringify({ display_id: 1, x: 0, y: 0, w: 1920, h: 1080, pixels_w: 1920, pixels_h: 1080, scale_x: 1, scale_y: 1 });
+ }
+ if (file === "osascript") return JSON.stringify({ accessibility: true, screen_recording: true });
+ if (file === "screencapture" && screencaptureFails) {
+ const e = new Error("screencapture failed: screencapture: could not create image from display");
+ e.code = "DESKTOP_PERMISSION_REQUIRED";
+ screencaptureFails = false;
+ d.invalidateCaches();
+ throw e;
+ }
+ if (file === "sips") writeFileSync(args.at(-1), Buffer.alloc(500));
+ return "";
+ } });
+ await d.screenshot({ x: 0, y: 0, w: 100, h: 80, budgetBytes: 2_000 });
+ const first = calls.filter((f) => f === "osascript").length; // info + permissions probes
+ assert.equal(first, 2, "first screenshot probes screen info and permissions once each");
+ calls.length = 0;
+ await d.screenshot({ x: 0, y: 0, w: 100, h: 80, budgetBytes: 2_000 }); // warm: no probes
+ assert.equal(calls.filter((f) => f === "osascript").length, 0, "warm screenshot skips both JXA probes");
+ calls.length = 0;
+ screencaptureFails = true;
+ await assert.rejects(() => d.screenshot({ x: 0, y: 0, w: 100, h: 80, budgetBytes: 2_000 }), /could not create image/);
+ await d.screenshot({ x: 0, y: 0, w: 100, h: 80, budgetBytes: 2_000 });
+ assert.ok(calls.includes("osascript"), "permission-classified failure invalidates caches → next call re-probes");
+});
+
+test("macOS screenshot re-probes display layout once when a cached-bounds rejection could be stale", async () => {
+ let layout = { display_id: 1, x: 0, y: 0, w: 1920, h: 1080, pixels_w: 1920, pixels_h: 1080, scale_x: 1, scale_y: 1 };
+ const probeCount = { info: 0 };
+ const d = new MacDriver({ runFn: async (file, args) => {
+ if (file === "osascript" && args.at(-1).includes("CGMainDisplayID")) {
+ probeCount.info++;
+ return JSON.stringify(layout);
+ }
+ if (file === "osascript") return JSON.stringify({ accessibility: true, screen_recording: true });
+ if (file === "sips") writeFileSync(args.at(-1), Buffer.alloc(500));
+ return "";
+ } });
+ await d.screenshot({ x: 0, y: 0, w: 100, h: 80, budgetBytes: 2_000 }); // caches the 1920x1080 layout
+ layout = { display_id: 1, x: 0, y: 0, w: 3840, h: 2160, pixels_w: 3840, pixels_h: 2160, scale_x: 2, scale_y: 2 };
+ const shot = await d.screenshot({ x: 2000, y: 1000, w: 300, h: 200, budgetBytes: 8_000 }); // outside stale layout, inside new one
+ assert.equal(shot.bytes, 500);
+ assert.equal(probeCount.info, 2, "initial probe, then exactly one stale-layout re-probe");
+});
+
+test("macOS probe scripts never request a TCC prompt (first-run discipline)", async () => {
+ const d = new MacDriver({ runFn: async (file, args) => {
+ if (file === "osascript" && args.at(-1).includes("AXIsProcessTrusted")) {
+ assert.doesNotMatch(args.at(-1), /Options|kAXTrustedCheckOptionPrompt|CGRequestScreenCaptureAccess/,
+ "probes must stay non-interactive: AXIsProcessTrusted/CGPreflight only");
+ }
+ return "{}";
+ } });
+ await d.permissions();
+ await d.permissions({ refresh: true });
+});
+
+test("macOS requestPermissions is the ONLY path that opens the TCC prompt", async () => {
+ const calls = [];
+ const d = new MacDriver({ runFn: async (file, args) => {
+ calls.push(args.at(-1));
+ return JSON.stringify({ accessibility: false, screen_capture_prompt: true });
+ } });
+ const r = await d.requestPermissions();
+ assert.deepEqual(r, {
+ accessibility: false,
+ screen_recording_prompt_opened: true,
+ note: "If the prompts were dismissed, grant manually in System Settings → Privacy & Security; Screen Recording requires restarting this host after granting.",
+ });
+ assert.match(calls[0], /kAXTrustedCheckOptionPrompt/);
+ assert.match(calls[0], /CGRequestScreenCaptureAccess/);
+ // And the permission cache was dropped: the next probe re-reads TCC.
+ const probes = [];
+ const d2 = new MacDriver({ runFn: async (file, args) => { probes.push(args.at(-1)); return JSON.stringify({ accessibility: true, screen_recording: true }); } });
+ d2._permCache = { ts: Date.now(), value: { accessibility: false, screen_recording: false } };
+ await d2.requestPermissions();
+ await d2.permissions();
+ assert.equal(probes.length, 2, "request + re-probe (cache invalidated by the request)");
+ assert.match(probes[0], /kAXTrustedCheckOptionPrompt/);
+ assert.doesNotMatch(probes[1], /kAXTrustedCheckOptionPrompt|CGRequestScreenCaptureAccess/, "the follow-up probe stays non-interactive");
+});
+
+test("macOS drag batches moves and always releases after a move failure", async () => {
+ const calls = [];
+ let failMoves = true;
+ const d = new MacDriver({ runFn: async (file, args) => {
+ calls.push({ file, args });
+ if (file === "osascript" && failMoves && args.at(-1).includes("kCGEventLeftMouseDragged")) {
+ failMoves = false;
+ throw new Error("synthetic drag failure");
+ }
+ return "ok";
+ } });
+ await assert.rejects(() => d.drag({ from: { x: 1, y: 2 }, to: { x: 10, y: 20 }, steps: 3 }), /synthetic drag failure/);
+ const scripts = calls.filter(({ file }) => file === "osascript").map(({ args }) => args.at(-1));
+ assert.equal(scripts.length, 3, "hover+down, batched moves, release");
+ assert.match(scripts.at(-1), /kCGEventLeftMouseUp/);
+});
+
+test("macOS desktop inputs reject coercible coordinates and zero-length drags", async () => {
+ const d = new MacDriver({ runFn: async () => "ok" });
+ await assert.rejects(() => d.move(null, 1), (e) => e.code === "BAD_COORDS");
+ await assert.rejects(() => d.drag({ from: { x: 1, y: 1 }, to: { x: 2, y: 2 }, steps: 0.1 }), (e) => e.code === "COMMAND_REJECTED");
+ await assert.rejects(() => d.type(null), (e) => e.code === "COMMAND_REJECTED");
+});
+
+test("macOS native event probe never posts an event", async () => {
+ const calls = [];
+ const d = new MacDriver({ runFn: async (file, args) => { calls.push({ file, args }); return "ok"; } });
+ assert.deepEqual(await d.probe(), { native_events: "ok" });
+ const scripts = calls.map(({ args }) => args.at(-1)).join("\n");
+ assert.doesNotMatch(scripts, /CGEventPost/);
+});
+
+test("macOS native event construction runs on this host without posting input", { skip: !macEnabled }, async () => {
+ assert.deepEqual(await new MacDriver().probe(), { native_events: "ok" });
+});
+
+test("macOS gestures never interleave: concurrent click and drag serialize", async () => {
+ const order = [];
+ const d = new MacDriver({ runFn: async (file, args) => {
+ const script = args.at(-1);
+ // The click carries its unique coordinates; the drag starts at (10,10).
+ const label = script.includes("CGPointMake(1, 1)") ? "click"
+ : script.includes("LeftMouseDragged") ? "drag-moves"
+ : script.includes("kCGEventLeftMouseDown") ? "drag-press"
+ : script.includes("kCGEventLeftMouseUp") ? "drag-release" : "other";
+ order.push(`start:${label}`);
+ await new Promise((ok) => setTimeout(ok, 5));
+ order.push(`end:${label}`);
+ return "ok";
+ } });
+ // Fire both gestures without awaiting the first: the chain must serialize.
+ await Promise.all([
+ d.click({ x: 1, y: 1 }),
+ d.drag({ from: { x: 10, y: 10 }, to: { x: 30, y: 30 }, steps: 2 }),
+ ]);
+ const starts = order.filter((e) => e.startsWith("start:")).map((s) => s.slice(6));
+ assert.equal(starts[0], "click", "whichever gesture was issued first runs first");
+ assert.ok(order.indexOf("end:click") < order.indexOf("start:drag-press"), "the drag's first script starts only after the click's gesture fully finished");
+ assert.deepEqual(starts.slice(1), ["drag-press", "drag-moves", "drag-release"], "the drag's own scripts stay contiguous");
+});
+
+test("macOS wheel follows the Natural Scrolling preference (content-direction contract)", async () => {
+ const posted = (calls) => {
+ const s = calls.filter((c) => c.file === "osascript").map((c) => c.args.at(-1)).find((x) => x.includes("ScrollWheel"));
+ return /UnitPixel, (1|2), (-?\d+)(?:, (-?\d+))?\)/.exec(s);
+ };
+ const driverWithPref = (prefOut) => {
+ const calls = [];
+ const d = new MacDriver({ runFn: async (file, args) => {
+ calls.push({ file, args });
+ if (file === "defaults") return prefOut;
+ return "ok";
+ } });
+ return { d, calls };
+ };
+ // dy>0 = content DOWN regardless of the pref; only the CG delta flips.
+ const natural = driverWithPref("1\n");
+ await natural.d.wheel(0, 9);
+ let m = posted(natural.calls);
+ assert.equal(m[2], "9", "natural ON → positive CG delta moves content down (builder pre-negates)");
+ const traditional = driverWithPref("0\n");
+ await traditional.d.wheel(0, 9);
+ m = posted(traditional.calls);
+ assert.equal(m[2], "-9", "natural OFF → negative CG delta moves content down");
+ // Two-axis case keeps dx in wheel1 with the same mapping.
+ const nat2 = driverWithPref("1\n");
+ await nat2.d.wheel(7, 9);
+ m = posted(nat2.calls);
+ assert.equal(m[1], "2");
+ assert.equal(m[2], "9");
+ assert.equal(m[3], "7");
+});
+
+test("macOS windows(): full-AX rows carry titles and global-point bounds", async () => {
+ const axPayload = { window_access: true, processes: [
+ { name: "Google Chrome", pid: 101, windows: [
+ { title: "Docs - Chrome", x: 5, y: 38, w: 1200, h: 800 },
+ { title: null, x: 1300, y: 40, w: 600, h: 400 },
+ ] },
+ ] };
+ const d = new MacDriver({ runFn: async (file, args) => JSON.stringify(axPayload) });
+ const out = await d.windows();
+ assert.equal(out.windows.length, 2);
+ const first = out.windows[0];
+ assert.equal(first.title, "Docs - Chrome");
+ assert.deepEqual(first.bounds, { x: 5, y: 38, w: 1200, h: 800 }, "bounds are clickable global display points");
+ assert.equal(first.application, "Google Chrome");
+ assert.equal(out.windows[1].title, "Google Chrome", "untitled windows fall back to the app name");
+ assert.equal(out.window_access, "full");
+ assert.match(out.note, /Accessibility granted/);
+});
+
+test("macOS windows(): without Accessibility, process-level rows + honest hint", async () => {
+ const axPayload = { window_access: false, processes: [
+ { name: "Notes", pid: 55, windows: [] },
+ { name: "Finder", pid: 66, windows: [] },
+ ] };
+ const d = new MacDriver({ runFn: async (file, args) => JSON.stringify(axPayload) });
+ const out = await d.windows();
+ assert.equal(out.windows.length, 2);
+ assert.ok(out.windows.every((w) => w.bounds === undefined), "no geometry invented without the grant");
+ assert.equal(out.window_access, "process-fallback");
+ assert.match(out.note, /grant Accessibility/);
+});
+
+test("macOS activate accepts a pid (robust when titles are TCC-gated)", async () => {
+ const calls = [];
+ const d = new MacDriver({ runFn: async (file, args) => {
+ calls.push(args.at(-1));
+ return JSON.stringify({ ok: true, application: "Google Chrome", pid: 101 });
+ } });
+ const r = await d.activate({ pid: 101 });
+ assert.equal(r.activated, true);
+ assert.equal(r.application, "Google Chrome");
+ assert.match(calls[0], /wantPid = 101/);
+ await assert.rejects(() => d.activate({}), (e) => e.code === "COMMAND_REJECTED" && /title, pid, or window_id/.test(e.message) === true);
+});
+
+test("macOS type(\"\") is a guaranteed no-op: no spawn, no permission path", async () => {
+ const calls = [];
+ const d = new MacDriver({ runFn: async (file, args) => { calls.push({ file, args }); return "ok"; } });
+ const r = await d.type("");
+ assert.equal(r.action_sent, "sent");
+ assert.match(r.note, /no events posted/);
+ assert.equal(calls.length, 0, "an empty string must never spawn osascript or hit the AX gate");
+});
+
+test("macOS windows(): frontmost app's rows come first and are flagged", async () => {
+ const payload = { window_access: true, frontmost_pid: 202, processes: [
+ { name: "Finder", pid: 101, windows: [{ title: "Downloads", x: 0, y: 0, w: 500, h: 400 }], frontmost: false },
+ { name: "TextEdit", pid: 202, windows: [{ title: "notes.txt", x: 10, y: 10, w: 400, h: 300 }], frontmost: true },
+ ] };
+ const d = new MacDriver({ runFn: async () => JSON.stringify(payload) });
+ const out = await d.windows();
+ assert.equal(out.windows[0].title, "notes.txt");
+ assert.equal(out.windows[0].frontmost, true);
+ assert.equal(out.frontmost_pid, 202);
+ assert.equal(out.windows[1].frontmost, undefined, "only the frontmost app carries the flag");
+});
+
+/* ------------------------------------------------------- AX layer (mocked) */
+
+const axTree = {
+ app: "Notes", pid: 4242, window_count: 1,
+ truncated_children: 3, hit_max_nodes: false, hit_max_depth: false,
+ nodes: [
+ { path: "0", p: null, d: 0, role: "AXWindow", title: "Notes", x: 0, y: 0, w: 700, h: 500, enabled: true },
+ { path: "0/0", p: 0, d: 1, role: "AXButton", title: "New Note", x: 8, y: 8, w: 30, h: 24, enabled: true },
+ { path: "0/1", p: 0, d: 1, role: "AXTextArea", title: "Body", value: "hello", x: 10, y: 60, w: 600, h: 400 },
+ { path: "0/1/0", p: 2, d: 2, role: "AXStaticText", title: "hello", x: 12, y: 62, w: 40, h: 18 },
+ ],
+};
+
+test("macOS AX snapshot renders a browser-observe-style tree with live refs", async () => {
+ const d = new MacDriver({ runFn: async (file, args) => JSON.stringify(axTree) });
+ const snap = await d.axSnapshot({ pid: 4242 });
+ assert.equal(snap.app, "Notes");
+ assert.equal(snap.nodes, 4);
+ assert.equal(snap.truncated_children, 3);
+ assert.match(snap.text, /window "Notes" box=0,0,700x500 \[ref=ax1\]/);
+ assert.match(snap.text, /button "New Note" box=8,8,30x24 \[act\] \[ref=ax1\.1\]/);
+ assert.match(snap.text, /textarea "Body" value="hello" box=10,60,600x400 \[act\] \[ref=ax1\.2\]/);
+ assert.match(snap.text, / {4}text "hello" box=12,62,40x18 \[ref=ax1\.2\.1\]/);
+ // Ref ↔ path round-trip for every rendered ref (axD<i>.<j>… → <i-1>/<j-1>…).
+ assert.equal(MacDriver.axRefToPath("ax1"), "0");
+ assert.equal(MacDriver.axRefToPath("ax1.1"), "0/0");
+ assert.equal(MacDriver.axRefToPath("ax1.2"), "0/1");
+ assert.equal(MacDriver.axRefToPath("ax1.2.1"), "0/1/0");
+ for (const m of snap.text.matchAll(/\[ref=(ax[0-9.]+)\]/g)) {
+ assert.ok(MacDriver.axRefToPath(m[1]), `ref ${m[1]} decodes`);
+ }
+ // Malformed refs are rejected before any spawn.
+ await assert.rejects(() => d.axRead({ ref: "e1", pid: 1 }), (e) => e.code === "COMMAND_REJECTED");
+ await assert.rejects(() => d.axClick({ ref: "ax0x", pid: 1 }), (e) => e.code === "COMMAND_REJECTED");
+ await assert.rejects(() => d.axSet({ ref: "ax00" }), (e) => e.code === "COMMAND_REJECTED" && /value is required/.test(e.message) === true);
+});
+
+test("macOS AX click: AXPress first, coordinate fallback when refused, typed error without bounds", async () => {
+ const calls = [];
+ const makeD = (out) => new MacDriver({ runFn: async (file, args) => {
+ calls.push({ file, args });
+ if (file === "osascript" && args.at(-1).includes("AXPress") === false && args.at(-1).includes("uiElements")) return "ok";
+ return JSON.stringify(out());
+ } });
+ // 1. Clean AXPress.
+ let d = makeD(() => ({ ok: true, via: "AXPress", center: [100, 50] }));
+ let r = await d.axClick({ ref: "ax1.1", pid: 1 });
+ assert.deepEqual(r, { action_sent: "sent", via: "AXPress", ref: "ax1.1" });
+ // 2. Refused with center → one trusted CGEvent click at the live center.
+ calls.length = 0;
+ d = makeD(() => ({ ok: false, error: "not allowed", center: [220, 140], actions: ["AXShowMenu"] }));
+ r = await d.axClick({ ref: "ax1.1", pid: 1 });
+ assert.equal(r.via, "coordinate-fallback (AXPress refused)");
+ const fallback = calls.filter((c) => c.file === "osascript" && c.args.at(-1).includes("kCGEventLeftMouseDown"));
+ assert.ok(fallback.length === 1, "exactly one coordinate click");
+ assert.match(fallback[0].args.at(-1), /CGPointMake\(220, 140\)/);
+ // 3. Refused without bounds → typed, actionable, with the action list.
+ d = makeD(() => ({ ok: false, error: "nope", center: null, actions: ["AXShowMenu"] }));
+ await assert.rejects(() => d.axClick({ ref: "ax1.1", pid: 1 }), (e) => e.code === "DESKTOP_OP_FAILED" && /AXShowMenu/.test(e.hint) === true);
+ // 4. Stale path → REF_NOT_FOUND with a reobserve hint (browser discipline).
+ d = makeD(() => ({ error: "stale_path", path: "0/1" }));
+ await assert.rejects(() => d.axClick({ ref: "ax1.1", pid: 1 }), (e) => e.code === "REF_NOT_FOUND" && e.retry === "reobserve");
+});
+
+test("macOS AX set verifies read-back and reports mismatches; non-writable is typed", async () => {
+ const makeD = (out) => new MacDriver({ runFn: async () => JSON.stringify(out()) });
+ let d = makeD(() => ({ ok: true, set: "typed text", readBack: "typed text", verified: true }));
+ let r = await d.axSet({ ref: "ax1.2", value: "typed text", pid: 1 });
+ assert.equal(r.verified, true);
+ d = makeD(() => ({ ok: true, set: "x", readBack: "y", verified: false }));
+ r = await d.axSet({ ref: "ax1.2", value: "x", pid: 1 });
+ assert.equal(r.verified, false);
+ assert.match(r.note, /never assumed/);
+ d = makeD(() => ({ error: "not_writable", detail: "button has no settable value" }));
+ await assert.rejects(() => d.axSet({ ref: "ax1.1", value: "x", pid: 1 }), (e) => e.code === "COMMAND_REJECTED" && /not AX-writable/.test(e.message) === true);
+});
+
+test("macOS AX scripts inject targets safely ($-sequences and quotes never corrupt the script)", async () => {
+ const seen = [];
+ const d = new MacDriver({ runFn: async (file, args) => {
+ seen.push(args.at(-1));
+ return JSON.stringify(axTree);
+ } });
+ await d.axSnapshot({ name: `Notes "$& evil'` });
+ const script = seen[0];
+ assert.ok(script.includes('"Notes \\"$& evil\'"') || /Notes "\$& evil'/.test(script), "the name lands as one JSON string literal");
+ assert.doesNotMatch(script, /__WANT_|__PATH_|__MAX_|__VALUE_/, "no placeholder survives");
+ assert.match(script, /maxNodes = 250/, "defaults filled");
+ // pid + front default: explicit pid wins, front literal false.
+ seen.length = 0;
+ await d.axSnapshot({ pid: 99 });
+ assert.match(seen[0], /wantPid = 99, wantName = "", wantFront = false/);
+ seen.length = 0;
+ await d.axSnapshot({ front: true });
+ assert.match(seen[0], /wantFront = true/);
+});
+
+test("macOS ax_snapshot: no matching app is typed REF_NOT_FOUND; AX-missing is typed permission", async () => {
+ let d = new MacDriver({ runFn: async () => JSON.stringify({ error: "no_process", want: "Ghost" }) });
+ await assert.rejects(() => d.axSnapshot({ name: "Ghost" }), (e) => e.code === "REF_NOT_FOUND" && /Ghost/.test(e.message) === true);
+ d = new MacDriver({ runFn: async () => JSON.stringify({ error: "no_windows_access", app: "Notes" }) });
+ await assert.rejects(() => d.axSnapshot({ name: "Notes" }), (e) => e.code === "DESKTOP_PERMISSION_REQUIRED");
+ await assert.rejects(() => d.axSnapshot({}), (e) => e.code === "COMMAND_REJECTED");
+});
+
+test("macOS ax ops fail typed without Accessibility (live, denial path)", { skip: !macEnabled }, async (t) => {
+ const d = new MacDriver();
+ const p = await d.permissions();
+ if (p.accessibility === true) t.skip("Accessibility is granted here — granted paths run in the manual lane");
+ await assert.rejects(
+ () => d.axSnapshot({ front: true }),
+ (e) => e.code === "DESKTOP_PERMISSION_REQUIRED" && /Accessibility/.test(e.message) === true,
+ );
+});
diff --git a/test/diff.test.js b/test/diff.test.js
new file mode 100644
index 0000000..8be5423
--- /dev/null
+++ b/test/diff.test.js
@@ -0,0 +1,93 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { diffSnapshots, noChangeText } from "../src/core/diff.js";
+
+const snap = (entries, url = "https://x/", title = "t") => ({
+ stateId: 1, entries, url, title, truncated: false,
+});
+
+test("diff: removed / added / changed are classified per ref", () => {
+ const prev = snap([
+ { ref: "e1", line: '- link "Home" [ref=e1]' },
+ { ref: "e2", line: '- button "Add item" [ref=e2]' },
+ { ref: "e3", line: '- textbox "Name" (value="") [ref=e3]' },
+ ]);
+ const next = {
+ stateId: 2,
+ entries: [
+ { ref: "e2", line: '- button "Add item" [ref=e2]' },
+ { ref: "e3", line: '- textbox "Name" (value="hello") [ref=e3]' },
+ { ref: "e5", line: '- button "Remove item" [ref=e5]' },
+ ],
+ url: "https://x/", title: "t", truncated: false,
+ };
+ const d = diffSnapshots(prev, next);
+ assert.equal(d.mode, "diff");
+ assert.deepEqual(d.removed.map((e) => e.ref), ["e1"]);
+ assert.deepEqual(d.added.map((e) => e.ref), ["e5"]);
+ assert.deepEqual(d.changed.map((c) => c.ref), ["e3"]);
+ assert.match(d.text, /removed:/);
+ assert.match(d.text, /added:/);
+ assert.match(d.text, /changed:/);
+});
+
+test("diff: unchanged refs stay valid and produce no noise", () => {
+ const prev = snap([{ ref: "e1", line: "- button \"Go\" [ref=e1]" }]);
+ const next = {
+ stateId: 2, entries: [{ ref: "e1", line: "- button \"Go\" [ref=e1]" }],
+ url: "https://x/", title: "t", truncated: false,
+ };
+ const d = diffSnapshots(prev, next);
+ assert.equal(d.removed.length + d.added.length + d.changed.length, 0);
+ assert.match(noChangeText(prev, next), /no changes detected/);
+});
+
+test("diff: text lines participate (multiset)", () => {
+ const prev = {
+ stateId: 1, entries: [],
+ textLines: ['- text "hello"', '- text "world"'],
+ url: "https://x/", title: "t", truncated: false,
+ };
+ const next = {
+ stateId: 2, entries: [],
+ textLines: ['- text "world"', '- text "done"', '- text "done"'],
+ url: "https://x/", title: "t", truncated: false,
+ };
+ const d = diffSnapshots(prev, next);
+ assert.equal(d.mode, "diff");
+ assert.deepEqual(d.textAdded, ['- text "done"', '- text "done"']);
+ assert.deepEqual(d.textRemoved, ['- text "hello"']);
+ assert.match(d.text, /text added:/);
+ assert.match(d.text, /text removed:/);
+});
+
+test("diff: navigation-scale churn on a big tree falls back to full", () => {
+ const mk = (prefix, n) => ({
+ stateId: 1,
+ entries: Array.from({ length: n }, (_, i) => ({ ref: `${prefix}${i}`, line: `- item ${i} [ref=${prefix}${i}]` })),
+ url: "https://x/", title: "t", truncated: false,
+ text: Array.from({ length: n }, (_, i) => `- item ${i} [ref=${prefix}${i}]`).join("\n"),
+ });
+ const prev = mk("a", 25);
+ const next = { ...mk("z", 25), stateId: 2, url: "https://new/" };
+ const d = diffSnapshots(prev, next);
+ // 25 removed + 25 added ≈ twice the full tree → a full snapshot is cheaper.
+ assert.equal(d.mode, "full");
+});
+
+test("diff: churn on a small tree stays diff (ref addressing preserved)", () => {
+ const prev = {
+ stateId: 1,
+ entries: [{ ref: "a0", line: "- x [ref=a0]" }, { ref: "a1", line: "- y [ref=a1]" }],
+ url: "https://x/", title: "t", truncated: false,
+ };
+ const next = {
+ stateId: 2,
+ entries: [{ ref: "a1", line: "- y [ref=a1]" }, { ref: "z1", line: "- new [ref=z1]" }],
+ url: "https://x/", title: "t", truncated: false,
+ };
+ const d = diffSnapshots(prev, next);
+ assert.equal(d.mode, "diff");
+ assert.match(d.text, /removed:/);
+ assert.match(d.text, /added:/);
+});
diff --git a/test/fixtures/page.html b/test/fixtures/page.html
new file mode 100644
index 0000000..d031708
--- /dev/null
+++ b/test/fixtures/page.html
@@ -0,0 +1,58 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <title>axuse test page</title>
+ <style>
+ .hidden { display: none; }
+ </style>
+</head>
+<body>
+ <h1>axuse fixture</h1>
+ <nav><a id="link" href="#end">jump to end</a></nav>
+ <main>
+ <p id="para">Static paragraph text for the snapshot.</p>
+ <button id="add" onclick="addItem()">Add item</button>
+ <button id="toggle" onclick="toggleHidden()">Toggle hidden text</button>
+ <ul id="list"></ul>
+ <form onsubmit="event.preventDefault(); document.getElementById('echo').textContent = document.getElementById('field').value;">
+ <label for="field">Name</label>
+ <input id="field" type="text" value="" placeholder="type here" />
+ <select id="combo">
+ <option value="a">Alpha</option>
+ <option value="b">Beta</option>
+ <option value="c">Gamma</option>
+ </select>
+ <button id="submit" type="submit">Echo</button>
+ </form>
+ <div id="echo" style="min-height:1em"></div>
+ <section id="sliders">
+ <label for="rng">Volume</label>
+ <input id="rng" type="range" min="0" max="50" step="5" value="10" aria-label="Volume" />
+ <div id="aslider" role="slider" tabindex="0" aria-label="aria slider" aria-valuemin="0" aria-valuemax="20" aria-valuenow="4">aria slider</div>
+ </section>
+ <div class="hidden" id="secret" aria-hidden="false">hidden text</div>
+ <script>
+ function addItem() {
+ const ul = document.getElementById('list');
+ const li = document.createElement('li');
+ li.textContent = 'item ' + (ul.children.length + 1);
+ ul.appendChild(li);
+ }
+ function toggleHidden() {
+ const s = document.getElementById('secret');
+ s.classList.toggle('hidden');
+ }
+ (function () {
+ var el = document.getElementById('aslider');
+ el.addEventListener('keydown', function (e) {
+ var now = parseFloat(el.getAttribute('aria-valuenow')) || 0;
+ if (e.key === 'ArrowUp' || e.key === 'ArrowRight') el.setAttribute('aria-valuenow', String(Math.min(20, now + 2)));
+ else if (e.key === 'ArrowDown' || e.key === 'ArrowLeft') el.setAttribute('aria-valuenow', String(Math.max(0, now - 2)));
+ });
+ })();
+ </script>
+ </main>
+ <div id="end" style="height:2000px">end of page</div>
+</body>
+</html>
diff --git a/test/fixtures/server.js b/test/fixtures/server.js
new file mode 100644
index 0000000..0e18cb2
--- /dev/null
+++ b/test/fixtures/server.js
@@ -0,0 +1,754 @@
+/** Fixture HTTP server for gated plugin tests (first-party, in-repo,
+ * deterministic — gated tests never depend on third-party uptime except
+ * where a spec explicitly names a public demo).
+ *
+ * Routes (each a tiny, honest stand-in for the real-world surface the
+ * plugin drives — same shapes, none of the flakiness):
+ * /vault-demo sets a cookie + Web Storage; shows logged-in state
+ * /net-demo heavy page: 25 ad/tracker subresources (each with
+ * an artificial delay) + 5 first-party + /api/data.json
+ * /download/file.bin deterministic attachment download (known sha256)
+ * /download/html.pdf an HTML error page disguised as a download
+ * /print/report.html tall authenticated-style page (multi-page PDF)
+ * /auth/* fixture IdP: login → TOTP → consent → logged-in
+ * /webauthn-demo WebAuthn registration + assertion playground
+ * /portal/* fixture portal: login, paginated invoices, exports
+ * /store/* fixture store: checkout, confirmation, drift modes
+ * /ats/* fixture ATS: nested iframes, screening tree, review
+ * /commerce/* fixture store admin: grid, listing form, disputes
+ * /maps/* fixture maps tenant: virtualized feed, detail cards
+ */
+
+import http from "node:http";
+import { createHash } from "node:crypto";
+import { readFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+
+export const FIXTURE_BYTES = 512 * 1024; // /download/file.bin size
+export function fixtureFileSha256() {
+ return createHash("sha256").update(Buffer.alloc(FIXTURE_BYTES, 7)).digest("hex");
+}
+
+const PAGE = (title, body, head = "") => `<!doctype html>
+<html><head><meta charset="utf-8"><title>${title}</title>${head}</head>
+<body>${body}</body></html>`;
+
+/* ------------------------------------------------------------- vault demo */
+
+const vaultDemo = PAGE("vault demo", `
+ <h1>session-vault demo site</h1>
+ <div id="state">checking…</div>
+ <script>
+ // The site's own session logic: logged-in state = cookie + storage item.
+ const m = document.cookie.match(/(?:^|; )sv_session=([^;]+)/);
+ const token = m && m[1];
+ if (token) {
+ localStorage.setItem("sv_last_seen", String(Date.now()));
+ sessionStorage.setItem("sv_hits", String(Number(sessionStorage.getItem("sv_hits") || 0) + 1));
+ document.getElementById("state").textContent = "logged in as " + token;
+ window.__authEvents = 0;
+ } else {
+ document.getElementById("state").textContent = "logged out";
+ }
+ </script>`);
+
+/* -------------------------------------------------------------- net demo */
+
+// 25 delayed "ad/tracker" subresources + 5 first-party ones + one JSON API.
+const netAdResources = Array.from({ length: 25 }, (_, i) =>
+ `/ad-${i}.js?host=${i % 2 ? "doubleclick" : "googlesyndication"}.example`);
+const netFirstParty = ["/site-0.js", "/site-1.js", "/site-2.js", "/site-3.js", "/site-4.js"];
+const netDemo = PAGE("heavy demo", `
+ <h1>heavy page</h1><div id="content">loaded</div>
+ ${[...netAdResources, ...netFirstParty].map((s) => `<script src="${s}"></script>`).join("\n")}
+ <script>fetch("/api/data.json").then(r => r.json()).then(j => { document.getElementById("content").textContent = j.note; });</script>`);
+
+/* ------------------------------------------------------------- IdP (auth) */
+
+// A throwaway identity: password "hunter2butthrowaway", TOTP seed in the test.
+export const FIXTURE_IDP = {
+ email: "[email protected]",
+ password: "hunter2butthrowaway",
+ userCode: "u-4711",
+};
+const idpSessions = new Map(); // sid → { stage }
+
+const idpLogin = PAGE("fixture IdP — sign in", `
+ <h1>Sign in</h1>
+ <form method="POST" action="/auth/login">
+ <label>Email <input name="email" type="email" autocomplete="username" required></label><br>
+ <label>Password <input name="password" type="password" autocomplete="current-password" required></label><br>
+ <button type="submit" name="action" value="signin">Next</button>
+ </form>`, `<meta name="viewport" content="width=device-width">`);
+
+const idpOtp = (hint) => PAGE("fixture IdP — 2FA", `
+ <h1>Two-factor verification</h1>
+ <p id="otp-hint">${hint}</p>
+ <form method="POST" action="/auth/otp">
+ <label>Verification code <input name="code" inputmode="numeric" autocomplete="one-time-code" required></label>
+ <button type="submit" name="action" value="verify">Verify</button>
+ </form>`);
+
+const idpConsent = PAGE("fixture IdP — consent", `
+ <h1>Grant access</h1>
+ <p>axuse test client wants to access: <code id="scopes">profile, documents.read</code></p>
+ <form method="POST" action="/auth/consent">
+ <button type="submit" name="action" value="allow">Allow</button>
+ <button type="submit" name="action" value="deny">Deny</button>
+ </form>`);
+
+const idpDone = PAGE("fixture IdP — signed in", `
+ <h1>Signed in</h1>
+ <p id="who">[email protected]</p>
+ <img id="avatar" alt="avatar" src="/auth/avatar.svg" width="24" height="24">
+ <a id="exit" href="/auth/logout">Sign out</a>`);
+
+const webauthnDemo = PAGE("WebAuthn demo", `
+ <h1>WebAuthn demo (fixture)</h1>
+ <button id="register">Register passkey</button>
+ <button id="login" disabled>Login with passkey</button>
+ <div id="status">idle</div>
+ <script type="module">
+ window.__moduleRan = true;
+ const b64 = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\\+/g, "-").replace(/\\//g, "_").replace(/=+$/, "");
+ const un64 = (s) => Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/")), c => c.charCodeAt(0));
+ const setStatus = (t) => document.getElementById("status").textContent = t;
+ document.getElementById("register").addEventListener("click", async () => {
+ try {
+ const cred = await navigator.credentials.create({
+ publicKey: {
+ challenge: crypto.getRandomValues(new Uint8Array(32)),
+ rp: { name: "axuse fixture" }, user: { id: new TextEncoder().encode("u1"), name: "fixture-user", displayName: "Fixture User" },
+ pubKeyCredParams: [{ type: "public-key", alg: -7 }, { type: "public-key", alg: -257 }],
+ authenticatorSelection: { residentKey: "preferred", userVerification: "preferred" },
+ },
+ });
+ window.__credentialId = b64(cred.rawId);
+ setStatus("registered: " + window.__credentialId.slice(0, 16) + "…");
+ document.getElementById("login").disabled = false;
+ } catch (e) { setStatus("register failed: " + e.message); }
+ });
+ document.getElementById("login").addEventListener("click", async () => {
+ try {
+ await navigator.credentials.get({
+ publicKey: { challenge: crypto.getRandomValues(new Uint8Array(32)), allowCredentials: [{ type: "public-key", id: un64(window.__credentialId) }], userVerification: "preferred" },
+ });
+ setStatus("assertion OK");
+ } catch (e) { setStatus("assertion failed: " + e.message); }
+ });
+ </script>`);
+
+/* ------------------------------------------------------------ fixtures */
+
+function readBody(req) {
+ return new Promise((resolve) => {
+ let data = "";
+ req.on("data", (c) => { data += c; });
+ req.on("end", () => resolve(data));
+ });
+}
+const formParams = (body) => new URLSearchParams(body);
+
+function send(res, status, body, headers = {}) {
+ res.writeHead(status, {
+ "content-type": "text/html; charset=utf-8",
+ "content-length": Buffer.byteLength(body),
+ ...headers,
+ });
+ res.end(body);
+}
+
+/** Start the fixture server. @returns {Promise<{url:string, port:number, close():Promise<void>, requestCount():number, seenUrls():string[]}>} */
+export function startFixtureServer({ port = 0 } = {}) {
+ const seen = [];
+ const server = http.createServer(async (req, res) => {
+ const url = new URL(req.url, "http://127.0.0.1");
+ const p = url.pathname;
+ seen.push(`${req.method} ${p}`);
+
+ try {
+ /* -------------------------------------------------------- vault */
+ if (p === "/vault-demo") {
+ const token = (url.searchParams.get("as") || "sv-demo-token-1");
+ return send(res, 200, vaultDemo, {
+ "set-cookie": `sv_session=${token}; Path=/; Max-Age=3600; SameSite=Lax`,
+ });
+ }
+
+ /* ---------------------------------------------------------- net */
+ if (p === "/net-demo") return send(res, 200, netDemo);
+ if (p === "/api/data.json") {
+ const body = JSON.stringify({ note: "clean json from the platform's own endpoint", items: [1, 2, 3] });
+ return send(res, 200, body, { "content-type": "application/json", "content-length": Buffer.byteLength(body) });
+ }
+ if (p.startsWith("/ad-") || p.startsWith("/track/")) {
+ await new Promise((ok) => setTimeout(ok, 120)); // heavy third-party stand-in
+ return send(res, 200, "/* ad pixel */", { "content-type": "application/javascript" });
+ }
+ if (/^\/site-\d+\.js$/.test(p)) {
+ return send(res, 200, "/* first-party */", { "content-type": "application/javascript" });
+ }
+
+ /* ---------------------------------------------------- downloads */
+ if (p === "/download/file.bin") {
+ const buf = Buffer.alloc(FIXTURE_BYTES, 7);
+ return send(res, 200, buf, {
+ "content-type": "application/octet-stream",
+ "content-length": buf.length,
+ "content-disposition": `attachment; filename="report-${FIXTURE_BYTES}.bin"`,
+ });
+ }
+ if (p === "/download/html.pdf") {
+ // The classic portal failure: an HTML error page disguised as a PDF download.
+ const body = "<!doctype html><html><body><h1>Session expired</h1><p>Please sign in again.</p></body></html>";
+ return send(res, 200, body, {
+ "content-type": "text/html; charset=utf-8",
+ "content-disposition": `attachment; filename="invoice-2026-09.pdf"`,
+ });
+ }
+ if (p === "/download/slow.bin") {
+ // A genuinely slow large download: 40 x 256 KB chunks at 350 ms =
+ // ~10 MB over ~14 s — long enough that deadline-cancel fires
+ // mid-stream and partial bytes must be cleaned up after the ack.
+ const chunk = Buffer.alloc(256 * 1024, 7);
+ const total = 40;
+ res.writeHead(200, { "content-type": "application/octet-stream", "content-length": total * chunk.length, "content-disposition": 'attachment; filename="slow-10mb.bin"' });
+ for (let i = 0; i < total; i++) {
+ await new Promise((ok) => setTimeout(ok, 350));
+ if (!res.write(chunk)) await new Promise((ok) => res.once("drain", ok));
+ }
+ return res.end();
+ }
+
+ /* -------------------------------------------------------- print */
+ if (p === "/print/report.html") {
+ const body = PAGE("Statement 2026-09", `
+ <h1>Utility statement — September 2026</h1>
+ ${Array.from({ length: 60 }, (_, i) => `<section style="break-inside:avoid"><h3>Line item ${i + 1}</h3><p>usage ${i + 1} kWh — $${(i + 1) * 1.25}</p></section>`).join("\n")}
+ <p id="total">Total due: $2,295.00</p>`);
+ return send(res, 200, body);
+ }
+
+ /* ------------------------------------------------------ auth IdP */
+ if (req.method === "POST" && p === "/auth/login") {
+ const raw = await readBody(req);
+ const params = formParams(raw);
+ const email = params.get("email");
+ const password = params.get("password");
+ if (process.env.AXUSE_fixture_DEBUG) (await import("node:fs")).appendFileSync("fixture-debug.log", `POST /auth/login email=${JSON.stringify(email)} match=${email === FIXTURE_IDP.email}/${password === FIXTURE_IDP.password}\n`);
+ if (email === FIXTURE_IDP.email && password === FIXTURE_IDP.password) {
+ return send(res, 200, idpOtp("Enter the 6-digit code from your authenticator app."));
+ }
+ return send(res, 200, PAGE("fixture IdP — sign in", `
+ <h1>Sign in</h1><p id="error" role="alert">Wrong email or password. Try again.</p>
+ <form method="POST" action="/auth/login">
+ <label>Email <input name="email" type="email" required></label><br>
+ <label>Password <input name="password" type="password" required></label><br>
+ <button type="submit" name="action" value="signin">Next</button>
+ </form>`));
+ }
+ if (p === "/auth/login") return send(res, 200, idpLogin);
+ if (p === "/auth" || p === "/auth/") {
+ return send(res, 302, "", { location: "/auth/login" });
+ }
+ if (req.method === "POST" && p === "/auth/otp") {
+ const sid = `sid-${Math.random().toString(36).slice(2, 10)}`;
+ idpSessions.set(sid, { stage: "consent" });
+ return send(res, 200, idpConsent, { "set-cookie": `idp_flow=${sid}; Path=/; HttpOnly` });
+ }
+ if (req.method === "POST" && p === "/auth/consent") {
+ const sid = (req.headers.cookie || "").match(/idp_flow=([^;]+)/)?.[1];
+ const action = formParams(await readBody(req)).get("action");
+ if (!sid || !idpSessions.has(sid)) return send(res, 200, PAGE("expired", "<h1>Flow expired</h1>"));
+ if (action !== "allow") return send(res, 200, PAGE("denied", "<h1>Access denied</h1>"));
+ idpSessions.set(sid, { stage: "done" });
+ return send(res, 200, idpDone, { "set-cookie": `idp_flow=${sid}; Path=/; HttpOnly` });
+ }
+ if (p === "/auth/avatar.svg") {
+ return send(res, 200, `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"><circle cx="12" cy="12" r="12" fill="#4a7"/></svg>`, { "content-type": "image/svg+xml" });
+ }
+ if (p === "/auth/done") return send(res, 200, idpDone);
+ if (p === "/webauthn-demo") return send(res, 200, webauthnDemo);
+
+ /* ------------------------------------------------- portal (06) */
+ if (req.method === "POST" && p === "/portal/login") {
+ const f = formParams(await readBody(req));
+ if (f.get("user") === "[email protected]" && f.get("password") === "portal-pass-1") {
+ return send(res, 302, "", { location: "/portal/invoices", "set-cookie": "portal_session=ok; Path=/; HttpOnly" });
+ }
+ return send(res, 200, PAGE("Fixture portal", `<h1>Acme Supplier Portal</h1><p role="alert">Invalid credentials</p>
+ <form method="POST" action="/portal/login"><label>User <input name="user"></label><label>Password <input name="password" type="password"></label><button>Sign in</button></form>`));
+ }
+ if (p === "/portal/login" || p === "/portal/") {
+ return send(res, 200, PAGE("Fixture portal", `
+ <h1>Acme Supplier Portal</h1>
+ <form method="POST" action="/portal/login">
+ <label>User <input name="user" required></label>
+ <label>Password <input name="password" type="password" required></label>
+ <button type="submit">Sign in</button>
+ </form>`));
+ }
+ if (p === "/portal/invoices") {
+ const cookie = req.headers.cookie || "";
+ if (!cookie.includes("portal_session=ok")) return send(res, 302, "", { location: "/portal/" });
+ const page = Math.max(1, Math.min(3, Number(url.searchParams.get("p") || 1)));
+ const all = portalInvoices();
+ const slice = all.slice((page - 1) * 4, page * 4);
+ const body = PAGE(`Invoices — page ${page}`, `
+ <h1>Invoices</h1><p id="pager">Page ${page} of 3</p>
+ <table id="inv-table">
+ <thead><tr><th>Document</th><th>Date</th><th>Total</th></tr></thead>
+ <tbody>${slice.map((r) => `<tr><td>${r.document}</td><td>${r.date}</td><td class="total">${r.total}</td></tr>`).join("")}</tbody>
+ </table>
+ <nav>${page > 1 ? `<a id="prev" href="/portal/invoices?p=${page - 1}">Previous</a>` : ""} ${page < 3 ? `<a id="next" href="/portal/invoices?p=${page + 1}">Next</a>` : ""}</nav>
+ <a id="export-csv" href="/portal/export.csv">Export CSV</a>
+ <a id="export-pdf" href="/portal/export.pdf">Export PDF</a>`);
+ return send(res, 200, body);
+ }
+ if (p === "/portal/export.csv") {
+ if (!(req.headers.cookie || "").includes("portal_session=ok")) return send(res, 302, "", { location: "/portal/" });
+ const body = "document,date,total\n" + portalInvoices().map((r) => `${r.document},${r.date},${r.total}`).join("\n") + "\n";
+ return send(res, 200, body, { "content-type": "text/csv", "content-disposition": 'attachment; filename="invoices.csv"' });
+ }
+ if (p === "/portal/export.pdf") {
+ if (!(req.headers.cookie || "").includes("portal_session=ok")) return send(res, 302, "", { location: "/portal/" });
+ const body = `%PDF-1.4\n%fixture-portal-export\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]>>endobj\nxref\n0 4\ntrailer<</Size 4/Root 1 0 R>>\nstartxref\n9\n%%EOF\n`;
+ return send(res, 200, body, { "content-type": "application/pdf", "content-disposition": 'attachment; filename="invoices.pdf"' });
+ }
+
+ /* ------------------------------------------------- store (07) */
+ if (p === "/store/checkout") {
+ const wrong = url.searchParams.get("wrong") === "1";
+ const total = wrong ? "1,840.00" : "1,240.00";
+ return send(res, 200, PAGE("Checkout", `
+ <h1>Checkout</h1>
+ <p class="total" id="total">Total: $${total}</p>
+ <form method="POST" action="${url.searchParams.get("delayed") === "1" ? "/store/pay-delayed" : "/store/pay"}">
+ <button id="pay" type="submit">Pay $${total}</button>
+ </form>`));
+ }
+ if (p === "/store/pay" && req.method === "POST") {
+ const confirm = `#${Math.random().toString(36).slice(2, 10).toUpperCase()}`;
+ return send(res, 200, PAGE("Confirmation", `<h1>Payment received</h1><p id="confirmation">Confirmation ${confirm}</p>`));
+ }
+ if (p === "/store/pay-delayed" && req.method === "POST") {
+ const confirm = `#${Math.random().toString(36).slice(2, 10).toUpperCase()}`;
+ await new Promise((ok) => setTimeout(ok, 3000)); // the "possibly_sent" settle case
+ return send(res, 200, PAGE("Confirmation", `<h1>Payment received</h1><p id="confirmation">Confirmation ${confirm}</p>`));
+ }
+ if (p === "/store/rollback") {
+ return send(res, 200, PAGE("Order", `<h1>Order in progress</h1><button id="cancel">Cancel order</button>`));
+ }
+
+ /* --------------------------------------------------- ats (10) */
+ if (p === "/ats/apply") {
+ // The stage frame is served from a *different origin* (frames_base
+ // http://localhost:P vs the page's http://127.0.0.1:P) so the fixture
+ // exercises the real OOPIF frame machinery — the entry ticket per
+ // spec 10 (nested cross-origin iframes).
+ const base = url.searchParams.get("frames_base") || "";
+ return send(res, 200, PAGE("Workday-shaped application", `
+ <h1>Job application — Senior Widget Engineer</h1>
+ <iframe id="stage-frame" src="${base}/ats/frame/personal" title="Application stage"></iframe>`));
+ }
+ if (p.startsWith("/ats/frame/")) {
+ const stage = p.slice("/ats/frame/".length).split("?")[0];
+ const q = url.searchParams;
+ if (stage === "personal") {
+ return send(res, 200, PAGE("Personal", `
+ <h2>Your information</h2>
+ <form>
+ <label>First name <input id="wd-input-first" name="0" data-identity="first_name" required></label>
+ <label>Last name <input id="wd-input-last" name="1" data-identity="last_name" required></label>
+ <label>Email <input id="wd-input-email" name="2" data-identity="email" required></label>
+ <button id="next" type="button" onclick="location.href='/ats/frame/resume?x='+(window.__x=(window.__x||0)+1)">Next</button>
+ </form>
+ <script>
+ // Stage state persists client-side (Workday-shaped behavior):
+ // the review stage reads it back for the anti-typo gate.
+ document.getElementById("wd-input-first").addEventListener("input", (e) => sessionStorage.setItem("ats_first", e.target.value));
+ document.getElementById("wd-input-email").addEventListener("input", (e) => sessionStorage.setItem("ats_email", e.target.value));
+ </script>`));
+ }
+ if (stage === "resume") {
+ return send(res, 200, PAGE("Resume", `
+ <h2>Resume</h2>
+ <input id="wd-file-resume" type="file" name="resume" data-identity="resume">
+ <button id="next" type="button" onclick="location.href='/ats/frame/screening?x='+(window.__x=(window.__x||0)+1)">Next</button>`));
+ }
+ if (stage === "screening") {
+ const withSalary = q.get("salary") === "1";
+ return send(res, 200, PAGE("Screening", `
+ <h2>Screening questions</h2>
+ <form>
+ <fieldset><legend>How many years of widget experience?</legend>
+ <select data-question="years_experience"><option value="">Select</option><option value="5">5</option><option value="8">8</option></select></fieldset>
+ <fieldset><legend>Are you legally authorized to work in this country?</legend>
+ <input type="radio" name="authorized" data-question="authorized" value="yes"> Yes
+ <input type="radio" name="authorized" data-question="authorized" value="no"> No</fieldset>
+ <fieldset><legend>Will you now or in the future require sponsorship?</legend>
+ <input type="radio" name="sponsorship" data-question="sponsorship" value="yes"> Yes
+ <input type="radio" name="sponsorship" data-question="sponsorship" value="no"> No</fieldset>
+ ${withSalary ? `<fieldset><legend>What are your salary expectations?</legend><input data-question="salary_expectation"></fieldset>` : ""}
+ <button id="next" type="button" onclick="location.href='/ats/frame/review?x='+(window.__x=(window.__x||0)+1)">Next</button>
+ </form>`));
+ }
+ if (stage === "review") {
+ return send(res, 200, PAGE("Review", `
+ <h2>Review your application</h2>
+ <dl id="review">
+ <dt data-field="first_name">First name</dt><dd id="v-first"></dd>
+ <dt data-field="email">Email</dt><dd id="v-email"></dd>
+ </dl>
+ <button id="submit" type="button" onclick="location.href='/ats/frame/done?x='+(window.__x=(window.__x||0)+1)">Submit application</button>
+ <script>
+ // Values survive via sessionStorage within the fixture flow.
+ document.getElementById("v-first").textContent = sessionStorage.getItem("ats_first") || "";
+ document.getElementById("v-email").textContent = sessionStorage.getItem("ats_email") || "";
+ </script>`));
+ }
+ if (stage === "done") {
+ return send(res, 200, PAGE("Applied", `<h1>Application submitted</h1><p id="confirmation">Confirmation R-${Math.floor(Math.random() * 900000 + 100000)}</p>`));
+ }
+ }
+
+ /* ----------------------------------------------- commerce (12) */
+ if (p === "/commerce/admin") {
+ return send(res, 200, PAGE("Store admin", `
+ <h1>Products</h1>
+ <table id="catalog"><thead><tr><th>SKU</th><th>Name</th><th>Price</th><th>Qty</th></tr></thead>
+ <tbody>${commerceRows().map((r) => `<tr data-sku="${r.sku}"><td>${r.sku}</td><td>${r.name}</td><td class="price">${r.price}</td><td class="qty">${r.qty}</td></tr>`).join("")}</tbody></table>
+ <a id="new-listing" href="/commerce/listing">New listing</a>
+ <a id="dispute" href="/commerce/dispute">Disputes</a>`));
+ }
+ if (p === "/commerce/listing") {
+ return send(res, 200, PAGE("New listing", `
+ <h1>New listing</h1>
+ <form id="listing-form">
+ <label>Title <input name="title"></label>
+ <label>Price <input name="price"></label>
+ <label>Description <textarea name="description"></textarea></label>
+ <button id="publish" type="button">Publish</button>
+ <p id="validation-error" role="alert" hidden></p>
+ </form>
+ <script>
+ document.getElementById("publish").addEventListener("click", () => {
+ const f = document.getElementById("listing-form");
+ // Planted validation error: title < 3 chars → named-field error loop.
+ if (f.title.value.trim().length < 3) {
+ const e = document.getElementById("validation-error");
+ e.hidden = false;
+ e.textContent = "Title must be at least 3 characters (field: title)";
+ return;
+ }
+ location.href = "/commerce/listed";
+ });
+ </script>`));
+ }
+ if (p === "/commerce/listed") {
+ return send(res, 200, PAGE("Listed", `<h1>Listing published</h1><p id="case">case-778899</p>`));
+ }
+ if (p === "/commerce/dispute") {
+ return send(res, 200, PAGE("Dispute", `
+ <h1>Dispute case D-2026-113</h1>
+ <form>
+ <label>Evidence note <textarea name="note"></textarea></label>
+ <button id="submit-dispute" type="button">Submit evidence</button>
+ </form>
+ <script>
+ document.getElementById("submit-dispute").addEventListener("click", () => {
+ if (document.querySelector("textarea[name=note]").value.trim().length < 5) return;
+ location.href = "/commerce/dispute-done";
+ });
+ </script>`));
+ }
+ if (p === "/commerce/dispute-done") {
+ return send(res, 200, PAGE("Dispute", `<h1>Evidence submitted</h1><p id="case">case-778899</p>`));
+ }
+
+ /* ------------------------------------- AG Grid infinite model (08) */
+ if (p === "/grid/infinite") {
+ // The OFFICIAL AG Grid infinite-row-model example (the vendor's
+ // documented configuration + datasource pattern, the vendor's library
+ // from the vendor's CDN), hosted first-party because the v36 docs
+ // site lazy-mounts examples only on human interaction.
+ return send(res, 200, PAGE("AG Grid infinite model", `
+ <div id="grid" style="height:480px;width:860px"></div>
+ <div id="mark">unloaded</div>
+ <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ag-grid-community.min.js"></script>
+ <script>
+ (window => {
+ try {
+ window.__mark = "ag=" + typeof window.agGrid;
+ const AG = window.agGrid;
+ AG.ModuleRegistry.registerModules([AG.AllCommunityModule]);
+ const dataSource = {
+ rowCount: undefined,
+ getRows: (params) => {
+ if (!window.__paramsProbe) window.__paramsProbe = Object.keys(params).join(",");
+ const respond = params.onSuccess ?? params.success ?? params.successCallback;
+ setTimeout(() => {
+ const start = params.startRow;
+ const rows = [];
+ for (let i = start; i < start + 100; i++) {
+ if (i >= 1000) break;
+ rows.push({
+ athlete: "Athlete " + (i + 1),
+ age: 20 + (i % 15),
+ country: "Country " + (i % 60),
+ year: 2000 + (i % 20),
+ sport: "Sport " + (i % 10),
+ total: 1 + (i % 30),
+ });
+ }
+ const lastRow = rows.length < 100 ? start + rows.length : -1;
+ respond(rows, lastRow);
+ }, 40);
+ },
+ };
+ const api = AG.createGrid(document.getElementById("grid"), {
+ columnDefs: [
+ { field: "athlete" }, { field: "age" }, { field: "country" },
+ { field: "year" }, { field: "sport" }, { field: "total" },
+ ],
+ defaultColDef: { flex: 1, minWidth: 100, sortable: false },
+ rowBuffer: 0, rowModelType: "infinite", cacheBlockSize: 100,
+ maxConcurrentDatasourceRequests: 1, infiniteInitialRowCount: 1000,
+ maxBlocksInCache: 10,
+ });
+ api.updateGridOptions({ datasource: dataSource });
+ document.getElementById("mark").textContent = "grid created";
+ } catch (e) {
+ document.getElementById("mark").textContent = "err: " + e.message;
+ }
+ })(window);
+ </script>`));
+ }
+
+ /* ------------------------------------ streamed app canvas (13) */
+ if (p === "/remote/app") {
+ // A "streamed enterprise app" in a canvas: the record-replay driver's
+ // stand-in for an HTML5 gateway. State is page-fact backed (the same
+ // thing a VDI delivers visually); drift variant moves the button.
+ const drift = url.searchParams.get("drift") === "1";
+ const btnX = drift ? 520 : 120;
+ return send(res, 200, PAGE("Legacy ERP (streamed)", `
+ <h1 id="title">Legacy ERP — Customer Master</h1>
+ <canvas id="screen" width="800" height="600" style="width:800px;height:600px;border:1px solid #888"></canvas>
+ <!-- Real HTML5 gateways trap keyboard in a hidden contenteditable —
+ trusted Input.insertText lands here (per-key keydown too). -->
+ <div id="trap" contenteditable="true" style="position:absolute;left:-9999px;top:0"></div>
+ <div id="state"></div>
+ <script>
+ window.__events = [];
+ window.__screen = { form: "main", customer: "", order: "", qty: "", status: "idle" };
+ const canvas = document.getElementById("screen");
+ const trap = document.getElementById("trap");
+ const ctx = canvas.getContext("2d");
+ const fields = { customer: { x: 300, y: 150, label: "Customer" }, order: { x: 300, y: 200, label: "Order" }, qty: { x: 300, y: 250, label: "Qty" } };
+ const button = { x: ${btnX}, y: 330, w: 160, h: 34, label: "Confirm" };
+ let focus = null;
+ const draw = () => {
+ ctx.fillStyle = "#f4f4f4"; ctx.fillRect(0, 0, 800, 600);
+ ctx.fillStyle = "#222"; ctx.font = "16px sans-serif";
+ ctx.fillText("Legacy ERP — Customer Master", 30, 40);
+ for (const [k, f] of Object.entries(fields)) {
+ ctx.fillStyle = focus === k ? "#ffd" : "#fff";
+ ctx.fillRect(f.x, f.y - 18, 300, 26);
+ ctx.strokeStyle = "#888"; ctx.strokeRect(f.x, f.y - 18, 300, 26);
+ ctx.fillStyle = "#222"; ctx.fillText(f.label + ":", 140, f.y);
+ ctx.fillText(window.__screen[k] || "", f.x + 6, f.y);
+ }
+ ctx.fillStyle = "#4a7"; ctx.fillRect(button.x, button.y, button.w, button.h);
+ ctx.fillStyle = "#fff"; ctx.fillText(button.label, button.x + 50, button.y + 22);
+ ctx.fillStyle = "#666"; ctx.fillText("status: " + window.__screen.status, 30, 580);
+ };
+ draw();
+ const css = (e) => { const r = canvas.getBoundingClientRect(); return { x: e.clientX - r.x, y: e.clientY - r.y }; };
+ canvas.addEventListener("pointerdown", (e) => {
+ if (!e.isTrusted) return;
+ const p = css(e);
+ window.__events.push({ kind: "click", ...p });
+ const over = fields[Object.keys(fields).find((k) => p.x >= fields[k].x - 20 && p.x <= fields[k].x + 320 && p.y >= fields[k].y - 24 && p.y <= fields[k].y + 12)];
+ if (over) focus = Object.keys(fields).find((k) => fields[k] === over);
+ if (p.x >= button.x && p.x <= button.x + button.w && p.y >= button.y && p.y <= button.y + button.h) {
+ window.__screen.status = "confirmed #" + String(Math.floor(Math.random() * 900000) + 100000);
+ }
+ trap.focus();
+ draw();
+ });
+ const commit = (text, via) => {
+ if (!focus) return;
+ window.__events.push({ kind: "type", text, via, focus });
+ window.__screen[focus] = String(window.__screen[focus] || "") + text;
+ draw();
+ };
+ trap.addEventListener("keydown", (e) => {
+ if (!e.isTrusted || !focus) return;
+ // Text chars arrive via beforeinput (below); keydown owns only
+ // the non-printable keys (Backspace = erase).
+ if (e.key === "Backspace") { window.__screen[focus] = String(window.__screen[focus] || "").slice(0, -1); draw(); }
+ });
+ trap.addEventListener("beforeinput", (e) => {
+ if (e.inputType === "insertText" && e.data) { e.preventDefault(); commit(e.data, "beforeinput"); }
+ });
+ // CDP Input.insertText (the bulk-trusted channel gateways prefer)
+ // fires the "input" event with inputType insertText WITHOUT a
+ // beforeinput — commit it too (preventDefault on beforeinput
+ // suppresses the input event, so this path only fires for the
+ // bulk channel). NOTE: no backticks here — we are inside the
+ // server's template literal.
+ trap.addEventListener("input", (e) => {
+ if (e.inputType === "insertText" && e.data) commit(e.data, "input-insertText");
+ });
+ </script>`));
+ }
+
+ /* ------------------------------------------ slider challenge (04) */ if (p === "/slider-challenge") {
+ // A DataDome-shaped slider: drag the handle onto the target notch;
+ // graded like the real ones (terminal position + trajectory shape
+ // observed). A successful drop issues the clearance cookie.
+ const notch = 220 + Math.floor(Math.random() * 440); // px offset inside the 700px track
+ return send(res, 200, PAGE("Slider challenge", `
+ <h1>Verify you are human</h1>
+ <div class="slider-track" id="track" style="position:relative;width:700px;height:40px;background:#eee">
+ <div class="slider-target" id="target" style="position:absolute;left:${notch}px;top:0;width:40px;height:40px;background:#dfe"></div>
+ <div class="slider-handle btn slider-drag" id="handle" style="position:absolute;left:0;top:0;width:40px;height:40px;background:#4a7;cursor:grab"></div>
+ </div>
+ <div id="msg">Slide to verify</div>
+ <script>
+ window.__trajectory = [];
+ const handle = document.getElementById("handle");
+ const target = document.getElementById("target");
+ let drag = null;
+ const t0 = Date.now();
+ handle.addEventListener("pointerdown", (e) => {
+ if (!e.isTrusted) return "rejected";
+ drag = { startX: e.clientX, handleLeft: handle.offsetLeft, events: 0, monodrome: [] };
+ handle.setPointerCapture(e.pointerId);
+ });
+ handle.addEventListener("pointermove", (e) => {
+ if (!drag) return;
+ drag.events++;
+ const left = Math.max(0, Math.min(660, drag.handleLeft + (e.clientX - drag.startX)));
+ handle.style.left = left + "px";
+ window.__trajectory.push({ t: Date.now() - t0, x: e.clientX, y: e.clientY });
+ });
+ handle.addEventListener("pointerup", (e) => {
+ if (!drag) return;
+ const gap = Math.abs(handle.offsetLeft - target.offsetLeft);
+ const enoughEvents = drag.events >= 15;
+ const traj = window.__trajectory.map(p => p.t);
+ const spacingJitter = new Set(traj.slice(1).map((t, i) => Math.round((t - traj[i]) * 10))).size;
+ const events = drag.events;
+ drag = null;
+ if (gap <= 8 && enoughEvents && spacingJitter >= 5) {
+ document.cookie = "datadome=passed-" + Date.now() + "; path=/; max-age=3600";
+ document.getElementById("msg").textContent = "Verification complete";
+ document.getElementById("track").style.display = "none";
+ window.__solved = true;
+ } else {
+ document.getElementById("msg").textContent = "Try again (gap " + gap + ", events " + events + ")";
+ }
+ });
+ </script>`));
+ }
+
+ /* -------------------------------------------------- maps (14) */ if (p === "/maps/search") {
+ const q = (url.searchParams.get("q") || "coffee").toLowerCase();
+ const records = mapsRecords().filter((r) => r.name.toLowerCase().includes(q));
+ return send(res, 200, PAGE(`Search: ${q}`, `
+ <h1>Results for "${q}"</h1>
+ <div id="feed" role="feed">${records.map((r) => `
+ <div class="place-card" data-place-id="${r.id}">
+ <a class="place-name" href="/maps/place?id=${r.id}">${r.name}</a>
+ <span class="place-address">${r.address}</span>
+ </div>`).join("")}</div>`));
+ }
+ if (p === "/maps/place") {
+ const r = mapsRecords().find((x) => x.id === url.searchParams.get("id"));
+ if (!r) return send(res, 404, PAGE("Not found", "<h1>No such place</h1>"));
+ return send(res, 200, PAGE(r.name, `
+ <h1 id="place-name">${r.name}</h1>
+ <dl>
+ <dt>Address</dt><dd id="address">${r.address}</dd>
+ <dt>Phone</dt><dd id="phone">${r.phone}</dd>
+ <dt>Website</dt><dd id="website">${r.website ?? ""}</dd>
+ <dt>Hours</dt><dd id="hours">${r.hours ?? ""}</dd>
+ <dt>Rating</dt><dd id="rating">${r.rating ?? ""} (${r.reviewCount ?? ""} reviews)</dd>
+ </dl>`));
+ }
+
+ /* ------------------------------------------------ static files */
+ if (!p.includes("..")) {
+ try {
+ const file = await readFile(join(HERE, p.slice(1)));
+ const types = { ".html": "text/html", ".js": "application/javascript", ".json": "application/json", ".svg": "image/svg+xml", ".bin": "application/octet-stream" };
+ const ext = p.slice(p.lastIndexOf("."));
+ res.writeHead(200, { "content-type": types[ext] ?? "application/octet-stream", "content-length": file.length });
+ return res.end(file);
+ } catch { /* fall through to 404 */ }
+ }
+ return send(res, 404, PAGE("Not found", `<h1>404</h1><p>No fixture at ${p}</p>`));
+ } catch (e) {
+ send(res, 500, PAGE("Server error", `<h1>fixture server error</h1><pre>${String(e.message ?? e)}</pre>`));
+ }
+ });
+ return new Promise((resolve) => {
+ server.listen(port, "127.0.0.1", () => {
+ resolve({
+ url: `http://127.0.0.1:${server.address().port}`,
+ port: server.address().port,
+ requestCount: () => seen.length,
+ seenUrls: () => [...seen],
+ close: () => new Promise((ok) => server.close(ok)),
+ });
+ });
+ });
+}
+
+/* ----------------------------------------------------------- fixture data */
+
+export function portalInvoices() {
+ return Array.from({ length: 12 }, (_, i) => {
+ const n = i + 1;
+ const lines = [100.0, 75.5, 24.5];
+ const total = lines.reduce((s, x) => s + x, 0);
+ return {
+ document: `INV-2026-${String(n).padStart(3, "0")}`,
+ date: `2026-0${Math.ceil(n / 4)}-${String((n % 28) + 1).padStart(2, "0")}`,
+ total: `$${total.toFixed(2)}`,
+ totalNumber: total,
+ lines,
+ };
+ });
+}
+
+function commerceRows() {
+ return Array.from({ length: 10 }, (_, i) => ({
+ sku: `SKU-${1000 + i}`,
+ name: `Widget model ${i + 1}`,
+ price: `$${(19.99 + i * 5).toFixed(2)}`,
+ qty: String(10 + i),
+ }));
+}
+
+export function mapsRecords() {
+ const base = Array.from({ length: 29 }, (_, i) => ({
+ id: `place_${i + 1}`,
+ name: `Coffee House No. ${i + 1}`,
+ address: `${100 + i} Shoreditch High St, London`,
+ phone: `+44 20 ${String(7000 + i).padStart(4, "0")}`,
+ website: `https://coffee${i + 1}.example.test`,
+ hours: "Mon-Fri 08:00-18:00",
+ rating: (3.5 + (i % 15) / 10).toFixed(1),
+ reviewCount: 20 + i * 7,
+ }));
+ // One planted duplicate: same stable identity, different display — dedupe
+ // by placeId (not by content) must collapse it.
+ const dupe = { ...base[3], name: base[3].name + " (duplicate card)" };
+ return [...base, dupe];
+}
diff --git a/test/mcp-catalog.test.js b/test/mcp-catalog.test.js
new file mode 100644
index 0000000..387792a
--- /dev/null
+++ b/test/mcp-catalog.test.js
@@ -0,0 +1,78 @@
+/**
+ * End-to-end: the REAL MCP server with the REAL paid catalog loaded.
+ * Spawns `node src/cli.js mcp` with the repo's plugins/ dir (paid tree
+ * present locally; a fresh clone without it skips cleanly — same rule as
+ * test/plugins.test.js) and asserts the full capability surface is mounted.
+ */
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { existsSync } from "node:fs";
+import { join, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "src", "cli.js");
+const PLUGINS = join(dirname(fileURLToPath(import.meta.url)), "..", "plugins");
+const catalogPresent = existsSync(join(PLUGINS, "session-vault", "index.js"));
+
+const EXPECTED_TOOLS = [
+ "ax_vault", "ax_net", "ax_capture", "ax_challenge", "ax_auth", "ax_extract",
+ "ax_guard", "ax_grid", "ax_editor", "ax_ats", "ax_enterprise", "ax_commerce",
+ "ax_remote", "ax_places",
+];
+
+function startServer() {
+ const proc = spawn(process.execPath, [CLI, "mcp"], { stdio: ["pipe", "pipe", "pipe"] });
+ const buffer = { text: "", waiters: [] };
+ proc.stdout.on("data", (d) => {
+ buffer.text += String(d);
+ let i;
+ while ((i = buffer.text.indexOf("\n")) >= 0) {
+ const line = buffer.text.slice(0, i).trim();
+ buffer.text = buffer.text.slice(i + 1);
+ if (!line) continue;
+ const w = buffer.waiters.shift();
+ if (w) w(JSON.parse(line));
+ }
+ });
+ return {
+ proc,
+ async call(msg) {
+ const p = new Promise((resolve, reject) => {
+ buffer.waiters.push(resolve);
+ setTimeout(() => reject(new Error("MCP response timeout")), 45_000);
+ });
+ proc.stdin.write(JSON.stringify(msg) + "\n");
+ return p;
+ },
+ end() { proc.kill(); },
+ };
+}
+
+test("real MCP server + real catalog: every capability tool mounts; solve signposts honestly", { skip: !catalogPresent }, async (t) => {
+ const srv = startServer();
+ t.after(() => srv.end());
+ await srv.call({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "t", version: "0" } } });
+ srv.proc.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) + "\n");
+
+ const list = await srv.call({ jsonrpc: "2.0", id: 2, method: "tools/list" });
+ const names = list.result.tools.map((x) => x.name);
+ for (const expected of EXPECTED_TOOLS) {
+ assert.ok(names.includes(expected), `${expected} missing from the real MCP surface (have: ${names.join(", ")})`);
+ }
+ // The solve surface also grew: provider enum includes the new capability slugs.
+ const solve = list.result.tools.find((x) => x.name === "ax_solve_captcha");
+ for (const slug of ["session", "net", "guard", "grid", "challenge", "auth", "extract", "commerce", "places", "remote-app", "editor", "ats", "enterprise-app", "downloads", "print"]) {
+ assert.ok(solve.inputSchema.properties.provider.enum.includes(slug), `provider enum missing ${slug}`);
+ }
+
+ // A capability solve on the real surface: the honest signpost, typed-free.
+ const plugins = await srv.call({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "ax_plugins", arguments: {} } });
+ const info = JSON.parse(plugins.result.content[0].text);
+ // 14 spec plugins + captcha-pro (wave 0) = 15.
+ assert.equal(info.loaded.length, 15);
+ assert.deepEqual(info.failed, []);
+ const withTools = info.loaded.filter((s) => s.tools?.length);
+ assert.equal(withTools.length, 14, "captcha-pro has no tools() by design; the other 14 do");
+});
\ No newline at end of file
diff --git a/test/mcp.test.js b/test/mcp.test.js
new file mode 100644
index 0000000..aea1ad5
--- /dev/null
+++ b/test/mcp.test.js
@@ -0,0 +1,151 @@
+/**
+ * MCP protocol test — spawns the real CLI server, does a real handshake,
+ * lists tools, and drives a real browser through the MCP boundary.
+ * Gated on a findable browser.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { join, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
+import { locateBrowser } from "../src/core/cdp.js";
+
+const CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "src", "cli.js");
+const hasBrowser = !!locateBrowser();
+
+function startServer() {
+ const proc = spawn(process.execPath, [CLI, "mcp"], { stdio: ["pipe", "pipe", "pipe"] });
+ const buffer = { text: "", waiters: [] };
+ proc.stdout.on("data", (d) => {
+ buffer.text += String(d);
+ let i;
+ while ((i = buffer.text.indexOf("\n")) >= 0) {
+ const line = buffer.text.slice(0, i).trim();
+ buffer.text = buffer.text.slice(i + 1);
+ if (!line) continue;
+ const w = buffer.waiters.shift();
+ if (w) w(JSON.parse(line));
+ }
+ });
+ let err = "";
+ proc.stderr.on("data", (d) => { err += String(d); });
+ return {
+ proc,
+ async call(msg) {
+ const p = new Promise((resolve, reject) => {
+ buffer.waiters.push(resolve);
+ setTimeout(() => reject(new Error(`MCP response timeout\nstderr: ${err}`)), 60_000);
+ });
+ proc.stdin.write(JSON.stringify(msg) + "\n");
+ return p;
+ },
+ end() { proc.kill(); },
+ };
+}
+
+test("mcp: handshake, tools/list, tools/call end-to-end", { skip: !hasBrowser }, async (t) => {
+ const srv = startServer();
+ t.after(() => srv.end());
+
+ const init = await srv.call({
+ jsonrpc: "2.0", id: 1, method: "initialize",
+ params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "test", version: "0" } },
+ });
+ assert.equal(init.result.serverInfo.name, "axuse");
+ assert.ok(init.result.capabilities.tools);
+
+ srv.proc.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) + "\n");
+
+ const list = await srv.call({ jsonrpc: "2.0", id: 2, method: "tools/list" });
+ const names = list.result.tools.map((x) => x.name);
+ assert.ok(names.includes("ax_open"));
+ assert.ok(names.includes("ax_observe"));
+ assert.ok(names.includes("ax_click"));
+ assert.ok(names.includes("ax_screenshot"));
+ assert.ok(names.includes("ax_open_many"));
+ // Desktop tools are advertised when the platform driver is enabled.
+ const desktopExpected = process.platform === "win32" || (process.platform === "darwin" && process.env.AXUSE_ENABLE_MACOS_CUA === "1");
+ if (desktopExpected) {
+ assert.ok(names.includes("ax_desktop_screenshot"));
+ } else {
+ assert.ok(!names.includes("ax_desktop_screenshot"));
+ }
+ // The macOS AX-structure tools mount ONLY with the macOS driver;
+ // Windows (coordinate driver) must not advertise them.
+ if (process.platform === "darwin" && process.env.AXUSE_ENABLE_MACOS_CUA === "1") {
+ for (const t of ["ax_desktop_ax_snapshot", "ax_desktop_ax_click", "ax_desktop_ax_set", "ax_desktop_ax_read"]) {
+ assert.ok(names.includes(t), `${t} mounted with the macOS driver`);
+ }
+ } else {
+ for (const t of ["ax_desktop_ax_snapshot", "ax_desktop_ax_click", "ax_desktop_ax_set", "ax_desktop_ax_read"]) {
+ assert.ok(!names.includes(t), `${t} must not mount without the macOS AX layer`);
+ }
+ }
+
+ if (desktopExpected) {
+ const screen = await srv.call({
+ jsonrpc: "2.0", id: 20, method: "tools/call",
+ params: { name: "ax_desktop_screen_info", arguments: {} },
+ });
+ assert.equal(screen.result.isError, undefined);
+ const screenInfo = JSON.parse(screen.result.content[0].text);
+ assert.ok(screenInfo.w > 0 && screenInfo.h > 0);
+ if (process.platform === "darwin") assert.equal(screenInfo.coordinate_space, "macOS global display points");
+ }
+
+ const page = `data:text/html,<button id="b" onclick="document.getElementById('o').textContent='done'">go</button><div id="o" style="min-height:1em"></div>`;
+ const opened = await srv.call({
+ jsonrpc: "2.0", id: 3, method: "tools/call",
+ params: { name: "ax_open", arguments: { url: page, headless: true, settle_ms: 100 } },
+ });
+ assert.equal(opened.result.isError, undefined);
+ // Observations render as plain text (no JSON escaping of the tree).
+ const openText = opened.result.content[0].text;
+ assert.match(openText, /^tab: t\d+\nurl: /);
+ assert.match(openText, /button "go"/);
+
+ const ref = openText.match(/button "go"[^\[]*\[ref=(e\d+)\]/)[1];
+ const clicked = await srv.call({
+ jsonrpc: "2.0", id: 4, method: "tools/call",
+ params: { name: "ax_click", arguments: { target: { ref }, settle_ms: 150 } },
+ });
+ const clickText = clicked.result.content[0].text;
+ assert.doesNotMatch(clickText, /^action: /); // "sent" is the silent default
+ assert.match(clickText, /text "done"|changed/);
+
+ // Structured error surfaces as isError result, not a protocol crash.
+ const bad = await srv.call({
+ jsonrpc: "2.0", id: 5, method: "tools/call",
+ params: { name: "ax_click", arguments: { target: { ref: "e999" } } },
+ });
+ assert.equal(bad.result.isError, true);
+ const err = JSON.parse(bad.result.content[0].text);
+ assert.equal(err.code, "REF_NOT_FOUND");
+ assert.equal(err.retry, "reobserve");
+
+ const batch = await srv.call({
+ jsonrpc: "2.0", id: 7, method: "tools/call",
+ params: {
+ name: "ax_open_many",
+ arguments: {
+ urls: [
+ "data:text/html,<title>batch</title><h1>batch page</h1>",
+ "data:text/html,<h1>second page</h1>",
+ ],
+ headless: true,
+ settle_ms: 80,
+ excerpt_chars: 200,
+ },
+ },
+ });
+ assert.equal(batch.result.isError, undefined);
+ const batchPayload = JSON.parse(batch.result.content[0].text);
+ assert.equal(batchPayload.opened, 2);
+ assert.equal(batchPayload.failed, 0);
+ assert.match(batchPayload.results[0].excerpt, /heading "batch page"/);
+
+ await srv.call({
+ jsonrpc: "2.0", id: 8, method: "tools/call",
+ params: { name: "ax_close", arguments: { browser: true } },
+ });
+});
diff --git a/test/oopif.test.js b/test/oopif.test.js
new file mode 100644
index 0000000..a1a646a
--- /dev/null
+++ b/test/oopif.test.js
@@ -0,0 +1,71 @@
+/**
+ * OOPIF test — cross-origin loopback iframe (127.0.0.1 parent, localhost
+ * child) must be auto-attached, merged into the snapshot under f-slot refs,
+ * and actionable (click inside the frame via the frame's own session).
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import http from "node:http";
+import { once } from "node:events";
+import { locateBrowser } from "../src/core/cdp.js";
+import { Controller } from "../src/core/controller.js";
+
+const hasBrowser = !!locateBrowser();
+
+const childHtml = `<!doctype html><html><body>
+ <h2>child frame</h2>
+ <button id="cb" onclick="document.getElementById('co').textContent='child done'">child button</button>
+ <div id="co" style="min-height:1em"></div>
+ <script>window.__loaded = true;</script>
+</body></html>`;
+
+const parentHtml = (childPort) => `<!doctype html><html><body>
+ <h1>parent</h1>
+ <button id="pb" onclick="this.textContent='pclicked'">parent button</button>
+ <iframe id="ifr" src="http://localhost:${childPort}/child.html" style="width:400px;height:120px;margin:40px 0 0 60px"></iframe>
+ <div id="po" style="min-height:1em"></div>
+</body></html>`;
+
+test("oopif: auto-attach, merged snapshot, in-frame click", { skip: !hasBrowser }, async (t) => {
+ const childSrv = http.createServer((q, r) => { r.setHeader("content-type", "text/html"); r.end(childHtml); });
+ childSrv.listen(0, "localhost");
+ await once(childSrv, "listening");
+ const parentSrv = http.createServer((q, r) => { r.setHeader("content-type", "text/html"); r.end(parentHtml(childSrv.address().port)); });
+ parentSrv.listen(0, "127.0.0.1");
+ await once(parentSrv, "listening");
+ t.after(() => { childSrv.close(); parentSrv.close(); });
+
+ const c = new Controller();
+ t.after(() => c.dispose());
+
+ const opened = await c.execute("open", {
+ url: `http://127.0.0.1:${parentSrv.address().port}/`,
+ headless: true,
+ settle_ms: 500, // give the OOPIF time to attach and load
+ });
+
+ // Frame content must be merged under f1: refs and reachable.
+ const snapText = opened.observation.text;
+ if (!/--- frame f1/.test(snapText)) {
+ console.error("SNAPSHOT (no frame merged):\n" + snapText);
+ }
+ assert.match(snapText, /--- frame f1/, "frame f1 section is merged");
+ assert.match(snapText, /iframe.*cross-origin.*\[ref=e\d+\]/, "the OOPIF iframe itself has a ref + cross-origin marker");
+ assert.match(snapText, /button "child button" \[ref=f1:e\d+\]/, "frame button has an f-prefixed ref");
+
+ // Click the button inside the cross-origin frame, by frame ref.
+ const frameRef = snapText.match(/button "child button" \[ref=(f1:e\d+)\]/)[1];
+ const clicked = await c.execute("click", { target: { ref: frameRef }, settle_ms: 300 });
+ assert.equal(clicked.action_sent, "sent");
+ assert.match(clicked.observation.text, /child done/, "diff shows the in-frame text change");
+
+ // Frame-slot refs stay stable across observations.
+ const again = await c.execute("observe", { mode: "diff" });
+ assert.ok(again.observation.state_id > opened.observation.state_id);
+
+ // The events ring buffer saw the frame attach.
+ const ev = await c.execute("events", {});
+ assert.ok(ev.events.some((e) => e.method === "frame.attached" && e.data.frame === "f1"));
+
+ await c.execute("close", { browser: true });
+});
diff --git a/test/plugin.test.js b/test/plugin.test.js
new file mode 100644
index 0000000..c8a9377
--- /dev/null
+++ b/test/plugin.test.js
@@ -0,0 +1,121 @@
+/**
+ * Plugin system tests.
+ *
+ * Unit tests always run (loader, ABI validation, ctx JSON trap, dispatch).
+ * Live tests are gated like the other browser tests: they skip when no
+ * Chromium-family browser is found; the Turnstile demo (network) run is
+ * additionally gated on AXUSE_TEST_LIVE_CAPTCHA=1.
+ */
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { locateBrowser } from "../src/core/cdp.js";
+import { Controller } from "../src/core/controller.js";
+import {
+ validateSolver, loadSolvers, buildSolveContext, solveWith,
+} from "../src/plugins/index.js";
+
+const hasBrowser = !!locateBrowser();
+const liveOk = process.env.AXUSE_TEST_LIVE_CAPTCHA === "1";
+
+/* ---------------------------------------------------------------- unit */
+
+test("plugin ABI validation", () => {
+ const good = validateSolver({
+ id: "x-solver", version: "1.0.0", providers: ["turnstile"],
+ solve: async (provider, ctx) => ({ solved: false }),
+ }, "test");
+ assert.equal(good.id, "x-solver");
+
+ assert.throws(() => validateSolver({}, "t"), (e) => e.code === "PLUGIN_LOAD_FAILED");
+ assert.throws(() => validateSolver({ id: "x", version: "1", providers: [], solve: async (p, c) => {} }, "t"), (e) => e.code === "PLUGIN_LOAD_FAILED");
+ assert.throws(() => validateSolver({ id: "x", version: "1", providers: ["p"], solve: () => {} }, "t"), (e) => e.code === "PLUGIN_LOAD_FAILED"); // not async
+ assert.throws(() => validateSolver({ id: "x", version: "1", providers: ["p"], solve: async () => {} }, "t"), (e) => e.code === "PLUGIN_LOAD_FAILED"); // arity < 2
+});
+
+test("loader: discovers index.js and package.json main, isolates failures", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "axuse-plugins-"));
+ try {
+ mkdirSync(join(dir, "good"));
+ writeFileSync(join(dir, "good", "index.js"),
+ `export const solver = { id: "good", version: "1.0.0", providers: ["p1"], solve: async (provider, ctx) => ({ solved: true }) };`);
+ mkdirSync(join(dir, "pkgd"));
+ writeFileSync(join(dir, "pkgd", "package.json"), `{ "main": "entry.mjs" }`);
+ writeFileSync(join(dir, "pkgd", "entry.mjs"),
+ `export default { id: "pkgd", version: "2.0.0", providers: ["p2"], solve: async (provider, ctx) => ({}) };`);
+ mkdirSync(join(dir, "broken"));
+ writeFileSync(join(dir, "broken", "index.js"), `export const solver = { nope: true };`);
+
+ const { solvers, errors } = await loadSolvers([dir]);
+ assert.equal(solvers.length, 2);
+ assert.deepEqual(errors.map((e) => e.plugin), ["broken"]);
+ const ids = solvers.map((s) => s.id).sort();
+ assert.deepEqual(ids, ["good", "pkgd"]);
+ assert.ok(solvers.find((s) => s.id === "pkgd").providers.includes("p2"));
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("solveWith: typed NO_SOLVER with install hint", async () => {
+ await assert.rejects(
+ () => solveWith([], "turnstile", null),
+ (e) => e.code === "NO_SOLVER" && /plugins\//.test(e.hint ?? ""),
+ );
+});
+
+test("ctx.evaluate parses the JSON string (kills the double-encoding trap)", { skip: !hasBrowser }, async (t) => {
+ const c = new Controller();
+ t.after(() => c.dispose());
+ await c.execute("open", { url: "data:text/html,<h1>ctx test</h1>", headless: true, settle_ms: 100 });
+ const ctx = buildSolveContext(c);
+ const opened = await ctx.evaluate(`(() => ({ deep: { ok: 1 }, s: "x" }))()`);
+ assert.deepEqual(opened, { deep: { ok: 1 }, s: "x" });
+ const prim = await ctx.evaluate(`42`);
+ assert.equal(prim, 42);
+ const viaController = await c.execute("close", { browser: true });
+ assert.ok(viaController);
+});
+
+/* ------------------------------------------------- live (gated, opt-in) */
+
+test("example plugin solves the Turnstile demo end-to-end", { skip: !hasBrowser || !liveOk }, async (t) => {
+ const exampleDir = fileURLToPath(new URL("../examples/plugin-turnstile-demo/", import.meta.url));
+ const { solvers } = await loadSolvers([exampleDir]);
+ assert.equal(solvers.length, 1, "example solver loads");
+ const c = new Controller();
+ t.after(() => c.dispose());
+ await c.execute("open", { url: "https://demo.turnstile.workers.dev/", settle_ms: 4000 });
+ const ctx = buildSolveContext(c);
+ const result = await solveWith(solvers, "turnstile", ctx, {});
+ assert.equal(result.solved, true, JSON.stringify(result));
+ assert.ok(result.token && result.token.length > 0);
+ await c.execute("close", { browser: true });
+});
+
+test("captcha-pro loads and its Turnstile path solves the official demo (test keys)", { skip: !hasBrowser || !liveOk }, async (t) => {
+ const paidDir = fileURLToPath(new URL("../plugins/captcha-pro/", import.meta.url));
+ const { solvers, errors } = await loadSolvers([paidDir]);
+ assert.equal(errors.length, 0, JSON.stringify(errors));
+ const pro = solvers.find((s) => s.id === "captcha-pro");
+ assert.ok(pro, "captcha-pro loads");
+ assert.deepEqual(pro.providers.sort(), ["hcaptcha", "recaptcha-v2", "turnstile"]);
+ // captcha-pro is license-gated like every paid package: mint a throwaway
+ // test keypair + token and inject it through the opts.license QA seam.
+ const { genKeyPair, issueLicense } = await import("../plugins/_shared/license.js");
+ const kp = genKeyPair();
+ const license = {
+ token: issueLicense({ customer: "live-test", package: "captcha-pro", expires: Date.now() + 3600_000 }, kp.privateKey),
+ publicKey: kp.publicKey,
+ };
+ const c = new Controller();
+ t.after(() => c.dispose());
+ await c.execute("open", { url: "https://2captcha.com/demo/cloudflare-turnstile", settle_ms: 5000 });
+ const ctx = buildSolveContext(c);
+ const result = await solveWith(solvers, "turnstile", ctx, { license });
+ assert.equal(result.solved, true, JSON.stringify(result));
+ await c.execute("close", { browser: true });
+});
diff --git a/test/plugins.test.js b/test/plugins.test.js
new file mode 100644
index 0000000..f386366
--- /dev/null
+++ b/test/plugins.test.js
@@ -0,0 +1,90 @@
+/**
+ * Premium plugin catalog harness.
+ *
+ * The paid tree under plugins/ is gitignored (never part of the open repo):
+ * every entry below is conditional — a fresh clone without the paid packages
+ * simply skips; a checkout that HAS them runs their offline unit suites in
+ * child processes (env isolation per package: each plugin owns its env
+ * namespace) plus one whole-catalog loader test.
+ *
+ * Live acceptance gates live inside each plugin's own test files and
+ * self-gate on AXUSE_TEST_LIVE_<PKG>=1 (plus a located browser) — the same
+ * pattern as test/plugin.test.js.
+ */
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { existsSync } from "node:fs";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { loadSolvers } from "../src/plugins/index.js";
+
+const HERE = fileURLToPath(new URL(".", import.meta.url));
+const PLUGINS = join(HERE, "..", "plugins");
+
+/** The build-order catalog (ENGINEERING-PROMPT waves 1-4). */
+const CATALOG = [
+ { id: "session-vault", pkg: "VAULT" },
+ { id: "net-governor", pkg: "NET" },
+ { id: "downloads-pdf", pkg: "DLP" },
+ { id: "challenge-handler", pkg: "CHALLENGE" },
+ { id: "auth-bridge", pkg: "AUTH" },
+ { id: "portal-extractor", pkg: "EXTRACT" },
+ { id: "transaction-guard", pkg: "GUARD" },
+ { id: "virtual-grid-driver", pkg: "GRID" },
+ { id: "rich-editor-driver", pkg: "EDITOR" },
+ { id: "ats-apply", pkg: "ATS" },
+ { id: "enterprise-app-driver", pkg: "EA" },
+ { id: "commerce-operator", pkg: "COMMERCE" },
+ { id: "remote-app-driver", pkg: "REMOTE" },
+ { id: "places-extractor", pkg: "PLACES" },
+];
+
+test("catalog: the paid shared library's own gates pass (curve, ledger, license, vision)", () => {
+ const dir = join(PLUGINS, "_shared");
+ if (!existsSync(join(dir, "test"))) return; // fresh clone: no paid tree
+ const r = run(["--test", "test/"], dir);
+ assert.equal(r.status, 0, r.output);
+});
+
+test("catalog: every present plugin loads with zero loader errors (ABI + tools validated)", async () => {
+ if (!existsSync(PLUGINS)) return; // fresh clone
+ const { solvers, errors } = await loadSolvers();
+ assert.deepEqual(errors, [], JSON.stringify(errors));
+ const seenIds = solvers.map((s) => s.id);
+ assert.deepEqual(new Set(seenIds).size, seenIds.length, "duplicate plugin ids");
+ // If a plugin dir exists locally, it must have loaded.
+ for (const { id } of CATALOG) {
+ if (existsSync(join(PLUGINS, id, "index.js"))) {
+ assert.ok(seenIds.includes(id), `${id} exists under plugins/ but did not load`);
+ }
+ }
+ // The shared library is never a plugin (R0: `_`-prefixed dirs are skipped).
+ assert.ok(!seenIds.includes("_shared"));
+});
+
+for (const { id } of CATALOG) {
+ test(`catalog: ${id} offline unit suite`, () => {
+ const dir = join(PLUGINS, id);
+ if (!existsSync(join(dir, "index.js"))) {
+ return; // paid package not installed locally — skip cleanly
+ }
+ assert.ok(existsSync(join(dir, "test")), `${id} ships no tests`);
+ assert.ok(existsSync(join(dir, "README.md")), `${id} ships no README`);
+ const r = run(["--test", "test/"], dir);
+ assert.equal(r.status, 0, `${id} unit suite failed:\n${r.output}`);
+ });
+}
+
+/** Run `node --test` in a child process, capturing merged output.
+ * AXUSE_KEYCHAIN=0 severs the macOS Keychain fallback so unit suites are
+ * deterministic regardless of what the host has stored under service
+ * "axuse" (the fallback itself has its own injected-runner tests). */
+function run(args, cwd) {
+ const r = spawnSync(process.execPath, args, {
+ cwd, encoding: "utf8", timeout: 600_000, windowsHide: true,
+ env: { ...process.env, AXUSE_KEYCHAIN: "0" },
+ });
+ return { status: r.status, output: `${r.stdout ?? ""}\n${r.stderr ?? ""}` };
+}
diff --git a/test/prereqs.test.js b/test/prereqs.test.js
new file mode 100644
index 0000000..259fcb9
--- /dev/null
+++ b/test/prereqs.test.js
@@ -0,0 +1,169 @@
+/**
+ * Core prerequisite unit tests (the engineering prompt's own requirement:
+ * "each ships with its own unit test in test/plugin.test.js style").
+ *
+ * - R0: loadSolvers skips `_`-prefixed dirs (the shared paid library).
+ * - R1: download lifecycle events land in the ring + per-tab download map.
+ * - R2: cdpBroadcast reaches the tab + every frame session and REPLAYS on
+ * a later frame attach.
+ * - R3/R4: cdpSend is the typed passthrough lever (WebAuthn/Storage route
+ * with the tab's session by default, an explicit one when given).
+ * - A2: profile_dir launches a PERSISTENT profile that survives dispose
+ * (browser-gated — the ephemeral default is deleted, the persistent one
+ * is not; that difference is the whole point).
+ */
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { loadSolvers } from "../src/plugins/index.js";
+import { Controller } from "../src/core/controller.js";
+import { locateBrowser } from "../src/core/cdp.js";
+
+const hasBrowser = !!locateBrowser();
+
+/* ------------------------------------------------------------------- R0 */
+
+test("R0: the loader skips `_`-prefixed dirs (shared paid library is never a plugin)", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "axuse-r0-"));
+ try {
+ mkdirSync(join(dir, "good"));
+ writeFileSync(join(dir, "good", "index.js"),
+ `export const solver = { id: "good", version: "1.0.0", providers: ["p"], solve: async (p, c) => ({}) };`);
+ mkdirSync(join(dir, "_shared"));
+ writeFileSync(join(dir, "_shared", "index.js"),
+ `export const solver = { id: "should-never-load", version: "1.0.0", providers: ["x"], solve: async (p, c) => ({}) };`);
+ const { solvers, errors } = await loadSolvers([dir]);
+ assert.deepEqual(errors, []);
+ assert.deepEqual(solvers.map((s) => s.id), ["good"]);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+/* --------------------------------------------- fake conn / tab plumbing */
+
+function fakeControllerWithTab() {
+ const c = new Controller();
+ const sends = [];
+ const conn = { send: async (method, params, sessionId) => (sends.push({ method, params, sessionId }), {}) };
+ const tab = {
+ tabId: "t1", browserId: "b1", targetId: "tgt1", sessionId: "sess-tab",
+ url: "https://x/", title: "", stateId: 0, lastSnapshot: null,
+ events: [], eventSeq: 0, dialog: null, closed: false,
+ frames: new Map(), frameSeq: 0, downloads: new Map(), cdpBroadcasts: [],
+ browser: { browserId: "b1", handle: { conn }, tabs: new Set(["t1"]) },
+ };
+ c.tabs.set("t1", tab);
+ c.activeTabId = "t1";
+ return { c, tab, sends, conn };
+}
+
+/* ------------------------------------------------------------------- R1 */
+
+test("R1: downloadWillBegin/Progress land in the event ring + the tab download map", () => {
+ const { c, tab } = fakeControllerWithTab();
+ c.recordEvent(tab, "Page.downloadWillBegin", { guid: "g1", suggestedFilename: "invoice.pdf", url: "https://x/invoice.pdf" });
+ assert.equal(tab.downloads.get("g1").suggestedFilename, "invoice.pdf");
+ assert.equal(tab.downloads.get("g1").state, "inProgress");
+ c.recordEvent(tab, "Page.downloadProgress", { guid: "g1", state: "completed", receivedBytes: 42, totalBytes: 42 });
+ const dl = tab.downloads.get("g1");
+ assert.equal(dl.state, "completed");
+ assert.equal(dl.receivedBytes, 42);
+ // Ring entries carry the lifecycle facts, sequenced.
+ assert.equal(tab.events.length, 2);
+ assert.equal(tab.events[0].method, "Page.downloadWillBegin");
+ assert.deepEqual(tab.events[1].data, { guid: "g1", state: "completed", receivedBytes: 42, totalBytes: 42 });
+});
+
+/* ------------------------------------------------------------------- R2 */
+
+test("R2: cdpBroadcast reaches the tab + every frame session and replays on later attaches", async () => {
+ const { c, tab, sends } = fakeControllerWithTab();
+ // Two attached frames (as if OOPIFs registered earlier).
+ tab.frames.set("sess-f1", { slot: 1, sessionId: "sess-f1", targetId: "f1", url: "https://frame1/" });
+ tab.frames.set("sess-f2", { slot: 2, sessionId: "sess-f2", targetId: "f2", url: "https://frame2/" });
+
+ const r = await c.cdpBroadcast("t1", "Fetch.enable", { patterns: [] });
+ assert.deepEqual(r, { sent: 3, sessions: 3, replayedOnAttach: true });
+ // Sent once to the tab session and once per frame session.
+ assert.deepEqual(sends.map((s) => s.sessionId), ["sess-tab", "sess-f1", "sess-f2"]);
+ // Deduped registration.
+ await c.cdpBroadcast("t1", "Fetch.enable", { patterns: [] });
+ assert.equal(tab.cdpBroadcasts.length, 1);
+
+ // A NEW frame attaches later → the broadcast REPLAYS onto it (the R2 rule:
+ // enables must survive cross-origin frame churn).
+ sends.length = 0;
+ await c.registerFrame(tab, { sessionId: "sess-f3", targetInfo: { targetId: "f3", url: "https://frame3/" } });
+ const replay = sends.find((s) => s.method === "Fetch.enable" && s.sessionId === "sess-f3");
+ assert.ok(replay, "broadcast did not replay on the newly attached frame");
+ assert.deepEqual(replay.params, { patterns: [] });
+});
+
+/* ------------------------------------------------------------- R3 / R4 */
+
+test("R3/R4: cdpSend is the typed passthrough (tab session by default, explicit when given)", async () => {
+ const { c, sends } = fakeControllerWithTab();
+ // R4 shape: Storage.getCookies routes on the tab's session.
+ await c.cdpSend("t1", "Storage.getCookies", {});
+ assert.equal(sends.at(-1).method, "Storage.getCookies");
+ assert.equal(sends.at(-1).sessionId, "sess-tab");
+ // R3 shape: WebAuthn.addVirtualAuthenticator with an explicit session.
+ await c.cdpSend("t1", "WebAuthn.addVirtualAuthenticator", { options: { protocol: "ctap2" } }, "sess-f9");
+ assert.equal(sends.at(-1).method, "WebAuthn.addVirtualAuthenticator");
+ assert.equal(sends.at(-1).sessionId, "sess-f9");
+ assert.deepEqual(sends.at(-1).params, { options: { protocol: "ctap2" } });
+ // No tab → typed NO_TAB (fail closed).
+ const fresh = new Controller();
+ await assert.rejects(() => fresh.cdpSend(null, "Storage.getCookies", {}), (e) => e.code === "NO_TAB");
+});
+
+/* ------------------------------------------------------------------- A2 */
+
+test("A2: profile_dir is persistent — survives dispose; the ephemeral default does not", { skip: !hasBrowser }, async () => {
+ const profileDir = mkdtempSync(join(tmpdir(), "axuse-a2-profile-"));
+ const c = new Controller();
+ try {
+ const opened = await c.execute("open", { url: "about:blank", headless: true, profile_dir: profileDir, settle_ms: 200 });
+ assert.ok(opened.tab_id);
+ // The persistent profile accumulates state while alive.
+ await c.execute("navigate", { url: "data:text/html,<h1>aged</h1>", settle_ms: 100 });
+ } finally {
+ await c.dispose();
+ }
+ try {
+ assert.ok(existsSync(profileDir), "A2 profile was DELETED on dispose — persistent profiles must survive");
+ } finally {
+ // Windows: Chrome can hold profile-file locks briefly after dispose
+ // (process teardown) — retry the cleanup before failing the test.
+ for (let i = 0; ; i++) {
+ try {
+ rmSync(profileDir, { recursive: true, force: true });
+ break;
+ } catch (e) {
+ if ((e.code === "EPERM" || e.code === "EBUSY" || e.code === "ENOTEMPTY") && i < 20) {
+ await new Promise((ok) => setTimeout(ok, 250));
+ continue;
+ }
+ throw e;
+ }
+ }
+ }
+
+ // Contrast: the ephemeral default profile IS cleaned up on dispose.
+ const c2 = new Controller();
+ let ephemeralDir = null;
+ try {
+ await c2.execute("open", { url: "about:blank", headless: true, settle_ms: 200 });
+ const b = [...c2.browsers.values()][0];
+ ephemeralDir = b.handle.userDataDir;
+ assert.ok(ephemeralDir && b.handle.ephemeral === true);
+ } finally {
+ await c2.dispose();
+ }
+ await new Promise((ok) => setTimeout(ok, 300));
+ assert.ok(!existsSync(ephemeralDir), "ephemeral profile leaked (should be deleted on dispose)");
+});
diff --git a/test/skip-allowlist.json b/test/skip-allowlist.json
new file mode 100644
index 0000000..2e9a7d8
--- /dev/null
+++ b/test/skip-allowlist.json
@@ -0,0 +1,46 @@
+{
+ "$comment": "skip-audit allowlist. Every entry maps a skip token (test title, matched by prefix) to its documented reason category. Categories: platform-windows (test only runs on Windows), tcc-screen-recording (requires a granted Screen Recording TCC permission — manual/self-hosted lane), tcc-macos-desktop (requires AXUSE_TEST_MACOS_DESKTOP=1 on macOS), live-gate-external (requires an external live service and an explicit AXUSE_TEST_LIVE_* gate), live-gate-browser (requires a browser and an explicit AXUSE_TEST_LIVE_* gate). Prune entries when tests are removed; the audit fails on stale entries.",
+ "skips": {
+ "desktop driver: screen_info reports a usable native coordinate space": "platform-or-gate: Windows live driver, or macOS with AXUSE_TEST_MACOS_DESKTOP=1",
+ "desktop driver: budgeted screenshot of a small region": "platform-windows: Windows-only live screenshot",
+ "desktop driver: macOS screenshot is opt-in and budgeted": "tcc-screen-recording: needs AXUSE_TEST_MACOS_SCREENSHOT=1 with Screen Recording granted (manual lane)",
+ "desktop driver: window discovery has stable title/pid records": "platform-or-gate: Windows live driver, or macOS with AXUSE_TEST_MACOS_DESKTOP=1",
+ "macOS permission probe is non-interactive and typed": "tcc-macos-desktop: needs AXUSE_TEST_MACOS_DESKTOP=1",
+ "macOS screenshot reports the typed TCC error when preflight denies access": "tcc-macos-desktop: needs AXUSE_TEST_MACOS_DESKTOP=1; body self-skips when Screen Recording is already granted",
+ "macOS posted input fails typed when Accessibility preflight denies access": "tcc-macos-desktop: needs AXUSE_TEST_MACOS_DESKTOP=1; body self-skips when Accessibility is already granted",
+ "macOS native event construction runs on this host without posting input": "tcc-macos-desktop: needs AXUSE_TEST_MACOS_DESKTOP=1",
+ "macOS ax ops fail typed without Accessibility (live, denial path)": "tcc-macos-desktop: needs AXUSE_TEST_MACOS_DESKTOP=1; self-skips when Accessibility is granted",
+ "tcc lane: granted Screen Recording + Accessibility is verified BEFORE anything runs": "tcc-manual-lane: needs AXUSE_TEST_MACOS_TCC_MANUAL=1 and a pre-granted self-hosted runner",
+ "tcc lane: real screenshot succeeds and stays budgeted (granted path)": "tcc-manual-lane: needs AXUSE_TEST_MACOS_TCC_MANUAL=1 and a pre-granted self-hosted runner",
+ "tcc lane: inert input event round-trips through the CGEvent tap (granted path)": "tcc-manual-lane: needs AXUSE_TEST_MACOS_TCC_MANUAL=1 and a pre-granted self-hosted runner",
+ "tcc lane: wheel direction matches the browser contract under this host's scroll preference": "tcc-manual-lane: needs AXUSE_TEST_MACOS_TCC_MANUAL=1 and a pre-granted self-hosted runner",
+ "tcc lane: LIVE scroll-direction pin — wheel(0,+N) scrolls OUR page down, world-visible truth": "tcc-manual-lane: needs AXUSE_TEST_MACOS_TCC_MANUAL=1 and a pre-granted self-hosted runner",
+ "tcc lane: AX structure layer — snapshot + read round-trip on a real app": "tcc-manual-lane: needs AXUSE_TEST_MACOS_TCC_MANUAL=1 and a pre-granted self-hosted runner",
+ "tcc lane: recovery — a denied-then-granted transition is seen without host restart": "tcc-manual-lane: needs AXUSE_TEST_MACOS_TCC_MANUAL=1 and a pre-granted self-hosted runner",
+ "example plugin solves the Turnstile demo end-to-end": "live-gate-external: needs AXUSE_TEST_LIVE_CAPTCHA=1 and the public Turnstile demo",
+ "captcha-pro loads and its Turnstile path solves the official demo (test keys)": "live-gate-external: needs AXUSE_TEST_LIVE_CAPTCHA=1, a vision API key, and the public demo",
+ "extension bridge: install → native messaging → drive the browser": "live-gate-browser: needs an extension-capable Chromium-family browser",
+ "browser flow": "live-gate-browser: needs any Chromium-family browser (auto-detect or AXUSE_BROWSER)",
+ "fill: ARIA and native sliders via trusted Arrow keys": "live-gate-browser: needs any Chromium-family browser",
+ "fill: foreign-tab refs fail with a hint naming the owning tab": "live-gate-browser: needs any Chromium-family browser",
+ "mcp: handshake, tools/list, tools/call end-to-end": "live-gate-browser: needs any Chromium-family browser",
+ "oopif: auto-attach, merged snapshot, in-frame click": "live-gate-browser: needs any Chromium-family browser",
+ "A2: profile_dir is persistent — survives dispose; the ephemeral default does not": "live-gate-browser: needs any Chromium-family browser",
+ "catalog: the paid shared library's own gates pass": "paid-tree: present only in the private checkout",
+ "catalog: every present plugin loads with zero loader errors": "paid-tree: present only in the private checkout",
+ "catalog: ": "paid-tree: per-plugin offline unit suites (private checkout)",
+ "plugin ABI child suites": "paid-tree: present only in the private checkout",
+ "macos darwin browser candidates": "platform-macos: darwin-only candidate table",
+ "darwin extension-capable candidates exclude branded Chrome": "platform-macos: darwin-only candidate table",
+ "solver catalog tool schemas stay valid and plugin tool names never shadow core tools": "paid-tree: present only in the private checkout",
+ "every plugin CLI fails closed without a license": "paid-tree: present only in the private checkout",
+ "every plugin CLI executes: wired, licensed-gated, JSON-honest (no stack crashes)": "paid-tree: present only in the private checkout",
+ "real MCP server + real catalog: every capability tool mounts; solve signposts honestly": "paid-tree: present only in the private checkout",
+ "live: ": "live-gate-browser: plugin live gate (AXUSE_TEST_LIVE_* env + fixture site; self-skips without external services/keys)",
+ "live (public board)": "live-gate-external: exercises a real third-party site; opt-in only",
+ "live (public playground)": "live-gate-external: exercises a real third-party site; opt-in only",
+ "live E: ": "live-gate-external: challenge-handler public-demo gate; requires CHALLENGE_CF_DEMO_URL and a vision key",
+ "live B/C/D": "live-gate-external: challenge-handler public demo gates; require CHALLENGE_VISION_KEY",
+ "live A2": "live-gate-browser: fixture interstitial gate"
+ }
+}
diff --git a/test/workflows.test.js b/test/workflows.test.js
new file mode 100644
index 0000000..8a52cb2
--- /dev/null
+++ b/test/workflows.test.js
@@ -0,0 +1,23 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { extractUrls, renderUrlReport } from "../src/workflows/url-batch.js";
+
+test("url batch workflow extracts and de-duplicates Markdown links", () => {
+ const urls = extractUrls("[one](https://example.com/a)\nhttps://example.com/a\nhttps://example.com/b.");
+ assert.deepEqual(urls, ["https://example.com/a", "https://example.com/b"]);
+});
+
+test("url batch workflow renders honest status and excerpts", () => {
+ const report = renderUrlReport({
+ backend: "extension",
+ source: "sources.md",
+ results: [
+ { url: "https://example.com", title: "Example", status: "opened", ref_count: 3, excerpt: "heading \"Example\"" },
+ { url: "https://bad.example", status: "error", error: { code: "NAVIGATION_IN_PROGRESS", message: "blocked", hint: "inspect the page" } },
+ ],
+ });
+ assert.match(report, /1 opened, 1 failed/);
+ assert.match(report, /heading \"Example\"/);
+ assert.match(report, /NAVIGATION_IN_PROGRESS/);
+ assert.match(report, /inspect the page/);
+});
diff --git a/tools/macos-nm-probe.mjs b/tools/macos-nm-probe.mjs
new file mode 100644
index 0000000..e91903e
--- /dev/null
+++ b/tools/macos-nm-probe.mjs
@@ -0,0 +1,92 @@
+/**
+ * macOS browser-matrix probe: for each installed Chromium-family browser,
+ * verify the FULL native-messaging chain against the real (default)
+ * NativeMessagingHosts dir — install → launch with an isolated profile +
+ * --load-extension → hub → extension connectNative → drive a tab → cleanup.
+ *
+ * Usage: node tools/macos-nm-probe.mjs [browser-id ...]
+ * Browser ids: chrome, chrome-for-testing, chromium, edge
+ */
+import { mkdtempSync, rmSync, existsSync } from "node:fs";
+import http from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { installBridge, uninstallBridge } from "../src/bridge/install.js";
+import { getBridge } from "../src/bridge/hub.js";
+import { locateBrowser, BrowserHandle } from "../src/core/cdp.js";
+import { Controller } from "../src/core/controller.js";
+
+// Browser id (installBridge accepts chrome | edge | chromium |
+// chrome-for-testing) → discovery selector. Binaries resolve via the core's
+// own locateBrowser: an AXUSE_BIN_<ID> env override wins (matrix testing
+// against side-installed builds), then the standard discovery candidates.
+const SELECTORS = {
+ chrome: { browser: "chrome", exact: true },
+ "chrome-for-testing": { browser: "chrome-for-testing" },
+ chromium: { browser: "chromium" },
+ edge: { browser: "edge" },
+};
+
+function binaryFor(id) {
+ const override = process.env[`AXUSE_BIN_${id.replaceAll("-", "_").toUpperCase()}`];
+ if (override) return override;
+ return locateBrowser(SELECTORS[id] ?? {});
+}
+
+const want = process.argv.slice(2).length ? process.argv.slice(2) : Object.keys(MAC_BINARIES);
+process.env.AXUSE_BRIDGE_DIR = mkdtempSync(join(tmpdir(), "axuse-nm-probe-"));
+
+let failures = 0;
+for (const id of want) {
+ const exe = binaryFor(id);
+ if (!exe || !existsSync(exe)) { console.log(`SKIP ${id}: binary not present (set AXUSE_BIN_${id.replaceAll("-", "_").toUpperCase()} for side-installed builds)`); continue; }
+ const profile = mkdtempSync(join(tmpdir(), `axuse-nm-probe-${id}-`));
+ // Chromium resolves the user-scoped NativeMessagingHosts dir relative to
+ // the ACTIVE --user-data-dir, so an isolated launch needs a profile-local
+ // manifest (exactly what the E2E test does). The default-dir flow (the
+ // user's daily browser) is covered by `axuse bridge install` writing to
+ // the OS-default location, which the real profile resolves.
+ const manifestDir = join(profile, "NativeMessagingHosts");
+ let chrome = null, hub = null;
+ console.log(`\n=== ${id} (${exe}) ===`);
+ try {
+ const inst = await installBridge({ browser: id, manifestDir });
+ console.log(` manifest: ${inst.registry}`);
+ const hub = await getBridge();
+ console.log(` hub: 127.0.0.1:${hub.port} (${hub.constructor.name})`);
+ chrome = await BrowserHandle.launch({
+ executablePath: exe,
+ headless: true,
+ userDataDir: profile,
+ extraArgs: [`--load-extension=${inst.extensionDir.replaceAll("\\", "/")}`],
+ });
+ await hub.waitExt(25_000);
+ console.log(" ext: CONNECTED via native messaging (profile-local manifest)");
+ const page = `<!doctype html><html><body><button id=b onclick="this.textContent='ok'">go</button></body></html>`;
+ const srv = http.createServer((q, r) => { r.setHeader("content-type", "text/html"); r.end(page); });
+ srv.listen(0, "127.0.0.1");
+ await new Promise((ok) => srv.once("listening", ok));
+ const c = new Controller();
+ const opened = await c.execute("open", { backend: "extension", url: `http://127.0.0.1:${srv.address().port}/`, settle_ms: 400 });
+ const ref = opened.observation.text.match(/button "go"[^\[]*\[ref=(e\d+)\]/)?.[1];
+ const clicked = ref ? await c.execute("click", { target: { ref }, settle_ms: 300 }) : null;
+ const ok = /ok/.test(clicked?.observation?.text ?? "");
+ console.log(` drive: open+click via chrome.debugger ${ok ? "OK" : "OBSERVED (click diff empty)"}`);
+ await c.dispose();
+ srv.close();
+ if (!ok && !ref) throw new Error("could not observe or click through the extension");
+ } catch (e) {
+ failures++;
+ console.log(` FAIL: ${e.message}`);
+ } finally {
+ try { await chrome?.dispose(); } catch {}
+ try { hub?.stop(); } catch {}
+ try { await uninstallBridge({ browser: id, manifestDir }); } catch {}
+ try { rmSync(profile, { recursive: true, force: true }); } catch {}
+ // getBridge() caches per process; each iteration must start clean.
+ const { __resetBridgeForTests } = await import("../src/bridge/hub.js");
+ if (typeof __resetBridgeForTests === "function") __resetBridgeForTests();
+ }
+}
+try { rmSync(process.env.AXUSE_BRIDGE_DIR, { recursive: true, force: true }); } catch {}
+process.exit(failures ? 1 : 0);
diff --git a/tools/skip-audit.mjs b/tools/skip-audit.mjs
new file mode 100644
index 0000000..6fed5b0
--- /dev/null
+++ b/tools/skip-audit.mjs
@@ -0,0 +1,96 @@
+#!/usr/bin/env node
+/**
+ * skip-audit — every `# SKIP` in a test run must be EXPLICIT, TYPED, and
+ * CI-VISIBLE. This tool fails the lane when a skip is not in the allowlist
+ * (test/skip-allowlist.json), so a privilege- or environment-gated test can
+ * never silently vanish from coverage.
+ *
+ * Input: TAP output of `node --test` on stdin or as file argument(s).
+ * Exit: 0 = all skips accounted for; 1 = undocumented or stale skips.
+ */
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const ALLOWLIST_PATH = join(HERE, "..", "test", "skip-allowlist.json");
+
+const allow = JSON.parse(readFileSync(ALLOWLIST_PATH, "utf8"));
+// Map: normalized skip token (test name or gate env var) → reason category
+const allowed = new Map(Object.entries(allow.skips ?? allow));
+
+function normalize(skipToken) {
+ return String(skipToken).trim().replace(/\s+/g, " ");
+}
+
+/** A skip token is either a test title or a "requires X" reason string. */
+function classify(token) {
+ const t = normalize(token);
+ for (const key of allowed.keys()) {
+ if (t === key || t.startsWith(key)) return allowed.get(key);
+ }
+ return null;
+}
+
+async function main() {
+ const sources = process.argv.slice(2);
+ const chunks = [];
+ if (!sources.length) chunks.push(await new Promise((ok) => {
+ let buf = "";
+ process.stdin.setEncoding("utf8");
+ process.stdin.on("data", (d) => { buf += d; });
+ process.stdin.on("end", () => ok(buf));
+ }));
+ else for (const f of sources) chunks.push(readFileSync(f, "utf8"));
+ const tap = chunks.join("\n");
+
+ const skips = [];
+ for (const line of tap.split("\n")) {
+ // TAP: ok N - title # SKIP
+ // ok N - title # SKIP reason
+ const m = /^ok \d+ - (.+?) # SKIP\s*(.*)$/.exec(line);
+ if (m) skips.push({ title: normalize(m[1]), reason: m[2] || null });
+ }
+
+ const unaccounted = [];
+ const seen = new Set();
+ for (const s of skips) {
+ // The skip is accounted if the TEST TITLE or its REASON is allowlisted.
+ const cls = classify(s.title) ?? (s.reason ? classify(s.reason) : null);
+ if (!cls) unaccounted.push(s);
+ seen.add(cls ?? `UNLISTED:${s.title}`);
+ }
+
+ // Informational only: allowlist entries may legitimately match in other
+ // lanes (Windows, public checkout, browser-less hosts) than this run.
+ const stale = [...allowed.keys()].filter((k) => !k.endsWith("*") && ![...seen].some((c) => c === allowed.get(k)));
+
+ console.log(`skip-audit: ${skips.length} skip(s) observed.`);
+ for (const s of skips) {
+ const cls = classify(s.title) ?? (s.reason ? classify(s.reason) : null);
+ console.log(` ${cls ? "✔" : "✖"} ${s.title}${s.reason ? ` — ${s.reason}` : ""}${cls ? ` [${cls}]` : " [NOT IN ALLOWLIST]"}`);
+ }
+ if (stale.length) {
+ console.log(`skip-audit: ${stale.length} stale allowlist entr(ies) never matched:`);
+ for (const s of stale) console.log(` - ${s}`);
+ }
+ if (unaccounted.length) {
+ console.error(`\nskip-audit: FAIL — ${unaccounted.length} skip(s) are not in test/skip-allowlist.json.`);
+ console.error("Every skip must be explicit and typed. Add the test title with a reason category,");
+ console.error("or remove the skip. Never widen the allowlist to hide a regression.");
+ process.exit(1);
+ }
+ if (stale.length) {
+ console.log(`skip-audit: note — ${stale.length} allowlist entr(ies) not exercised in THIS lane (they gate other platforms/lanes):`);
+ for (const s of stale) console.log(` - ${s}`);
+ }
+ if (unaccounted.length) {
+ console.error(`\nskip-audit: FAIL — ${unaccounted.length} skip(s) are not in test/skip-allowlist.json.`);
+ console.error("Every skip must be explicit and typed. Add the test title with a reason category,");
+ console.error("or remove the skip. Never widen the allowlist to hide a regression.");
+ process.exit(1);
+ }
+ console.log("skip-audit: PASS — all skips explicit, typed, and accounted for.");
+}
+
+main().catch((e) => { console.error(e); process.exit(1); });