Operate macOS desktop apps in the background using Codex's native Sky Computer Use engine (cua_repl) via `codex-cu-bridge` (CLI or `codex-cu` MCP). Uses zero Codex LLM tokens, supports persistent JavaScript execution for multi-step batching, and enforces a local App allowlist. Use when performing macOS GUI automation with Codex CUA or when fast batched desktop interaction is needed.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Codex Cu Bridge?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/dasungta-codex-cu-bridge)
---
name: codex-cu-bridge
description: Operate macOS desktop apps in the background using Codex's native Sky Computer Use engine (cua_repl) via `codex-cu-bridge` (CLI or `codex-cu` MCP). Uses zero Codex LLM tokens, supports persistent JavaScript execution for multi-step batching, and enforces a local App allowlist. Use when performing macOS GUI automation with Codex CUA or when fast batched desktop interaction is needed.
---
# codex-cu-bridge (Codex Sky Computer Use)
`codex-cu-bridge` exposes Codex's local Sky Computer Use runtime (`cua_repl` via an isolated `codex app-server`'s `mcpServer/tool/call`, **zero Codex model tokens**) through both a fast persistent-daemon CLI and a lightweight 7-tool MCP server (`codex-cu`).
> Note: If you are already running inside native Codex with `cua_repl` directly available, use native `cua_repl` directly instead of wrapping it through `codex-cu-bridge`.
## Speed rules (read first)
1. **Host-aware transport (eliminate Antigravity's 10s `run_command` async cutoff)**:
- **Inside Antigravity** (where `run_command` caps `WaitMsBeforeAsync` at `10000 ms`, backgrounding any >10s script and adding ~20–30s wakeup + re-thinking overhead):
- **Use the `codex-cu` MCP `js` tool (`call_mcp_tool` with `ServerName: "codex-cu"`, `ToolName: "js"`) for any batched GUI workflow expected to take >6 seconds** (e.g., TextEdit `NSSavePanel` saves, Finder multi-file tagging, Preview page navigation + screenshot + rotation, or cross-app Calculator -> TextEdit workflows). MCP `tools/call` blocks synchronously up to `timeout_ms` (`120000`) with **zero 10s backgrounding**, and saves screenshots to disk by default (`save_images_only: true`). Keep the default `"timeout_ms": 120000` (or omit `timeout_ms`) — never pass small `15000–30000` timeouts on multi-step GUI workflows.
- **Ready-to-call `codex-cu` MCP schemas (call directly — never spend a turn reading `mcp/codex-cu/*.json` first!)**:
- `ToolName: "js"` -> `Arguments: { "code": "<JS>", "title": "<short title>", "timeout_ms": 120000, "save_images_only": true, "full_output": false }` (pass `"save_images_only": false` only when you explicitly need inline base64 image blocks instead of reading the saved screenshot path).
- `ToolName: "end_turn"` -> `Arguments: {}`
- `ToolName: "status"` -> `Arguments: { "ensure_started": false }`
- `ToolName: "release"` -> `Arguments: { "apps": ["Finder"], "all": false, "dry_run": false }`
- Use CLI (`codex-cu-bridge js|status|end ...`) for fast `<5s` probes/actions or when combining fixture `open` + quick checks inside a single `<8s` shell command.
- **Inside Codex / Claude Code / Cursor / Terminal** (no 10s shell async cutoff): prefer CLI (`codex-cu-bridge js ...`), which connects to the warm Unix-socket daemon in **~200–350 ms**.
2. **No blind `setTimeout` + conditional polling (`cuaExt.waitFor`)**:
- **Rely on Sky's internal wait for normal actions**: `getAXState()`, `getScreenshot()`, and `getAXStateAndScreenshot()` automatically wait an appropriate amount of time before capturing new state. **Do NOT add `setTimeout(...)` or `cuaExt.wait(...)` after ordinary button clicks** (e.g., Calculator buttons, context menu items, normal text fields).
- **Use `cuaExt.waitFor` / brief settle ONLY for async AppKit window/sheet transitions (and NEVER inside XPC Save panels)**:
- `await cuaExt.waitFor(finder, "ID: ListView", { initialDelayMs: 300, timeoutMs: 2500, intervalMs: 350 })` — waits `initialDelayMs` once before polling every `intervalMs` and returns `{ found, index, ax }` immediately once the view/control appears. Note that every `getAXState()` performs a full Sky capture (~300–800 ms), so never tight-poll `waitFor` at `0ms` delay.
- **CRITICAL: NEVER call `cuaExt.waitFor(...)` on XPC `openAndSavePanelService` sheets (`NSSavePanel`, `ID: saveAsNameTextField`, `GoToWindow`, `ID: PathTextField`)!** Rapid `getAXState` polling inside `openAndSavePanelService` stalls 30–68 s per call and wedges with `-10005: timeoutReached`. Use a single `await cuaExt.wait(900)` + **one** `getAXState` per Save-panel step instead.
- Keep `await cuaExt.wait(800)` between `Cmd+N`/`ID: newDocument:` -> `Shift+Cmd+T` -> `click + paste()` -> `Cmd+S` in TextEdit so `_NSDocumentSerializationSemaphore` settles cleanly (and **never** call `setValue` on `First Text View`).
3. **One-task-one-batch & zero standalone verification turns**:
- Batch an entire task's UI loop + final state readback + `Date.now()` timing (`nodeRepl.write(JSON.stringify({ ..., elapsedMs: Date.now() - t0 }))`) into **ONE `js` call** whenever possible. Never do one click per LLM turn when the sequence or loop can be scripted.
- Open initial fixture files (`open -a TextEdit ...`, `open <dir>`, `open -a Preview ...`) in the same turn (or parallel tool call) rather than spending extra planning turns.
- **Never open a separate LLM turn just to run a read-only check** — verify inside the same `js` script or attach read-only verification in the same turn.
- Keep context lean: use `getAXState({ emit: false })` + `cuaExt.queryAX(ax, "...")` / `cuaExt.findIndex(ax, "...")` instead of writing custom indentation parsers from scratch; keep default incremental diffing for consecutive checks on the same window, passing `disableDiffing: true` only at the start of a new call on a reused handle or after `getScreenshot()`. Outputs exceeding 32 KB / 800 lines are automatically saved to disk (`~/Library/Caches/codex-cu-bridge/outputs/`) with a head/tail preview (pass `--full-output` / `full_output: true` to bypass).
4. **Use built-in `globalThis.cuaExt` helpers**:
- `cuaExt.queryAX(ax, "Save|Cancel")`: case-insensitive `|`-separated filter that preserves `Window:` / ancestor context and original numeric element indices without renumbering.
- `cuaExt.findIndex(ax, "Save|保存")`: finds the integer index of the first matching element line (supports `"|"` case-insensitive alternation, string, RegExp, or predicate), or `null`.
- `await cuaExt.waitFor(app, matcher, { initialDelayMs: 0, timeoutMs: 2500, intervalMs: 300 })`: conditional poll returning `{ found, index, ax }` immediately when matched.
- `await cuaExt.typeSafe(app, text)`: routes printable ASCII via `app.typeText()`, non-ASCII / CJK / Emoji via `app.paste()`, and `\n` / `\t` via `app.pressKey("Return" | "Tab")` (avoids `typeText` dropping non-ASCII characters under `openai/codex#27494`).
- `await cuaExt.wait(350)`: short async pause (default 350 ms) for AppKit document/sheet serialization transitions.
5. **Keep bindings alive with `globalThis.<name>` (or `var`)** across calls, and use `let` (or wrap local temps in `{ ... }`) inside `js` snippets to avoid `const` re-declaration warnings in the persistent REPL; call `codex-cu-bridge reset` (or MCP `js_reset`) to clear bindings.
6. **Always clean up when done**:
- Run `codex-cu-bridge end` (or MCP `end_turn`) after finishing desktop actions — this advances `cua_repl` turn state and **silently dismisses the macOS menu bar pink dot and `Software Cursor`** for apps touched by this session via `AXExtrasMenuBar` (`AXPress`, zero mouse movement, zero focus steal, no Apple Events needed, works across T3 Code / Cursor / Terminal / Accessibility-trusted hosts; automatically falls back to `cua-driver` if the host lacks Accessibility permission).
- Always check `pinkDotCleared: true` in the `end_turn` / `end` response. If `pinkDotCleared` is `false` (e.g., daemon already stopped with a lingering session, or host lacks Accessibility without `cua-driver`), call `codex-cu-bridge release --all` (or MCP `release` with `{"all": true}`).
7. **Web pages**: `codex-cu-bridge` exposes the **native macOS Sky surface** (`cua.getApp(...)`), not Codex's turn-scoped browser plugin. For ordinary web pages / router admin panels, prefer a DOM-native browser agent (`browser` subagent or Playwright) over scanning a huge Safari AX tree, unless the user explicitly asks to operate an already-open desktop browser window.
## macOS Reliability & Pitfall Playbook (avoid multi-minute retries)
1. **Refresh AX before acting on a reused handle**: At the start of a new `js` call on an already-bound `globalThis.<app>`, call `await app.getAXState({ emit: false, disableDiffing: true })` first so Sky does not throw `Re-query the latest state with get_app_state`. For subsequent reads within the same script on that window, keep default diffing (`disableDiffing: false`).
2. **Guard every index lookup**: Never pass `null`/`undefined` to `click()` or `setValue()`. Note that empty TextEdit views appear as `文本输入区 (settable) First Text View` (without the `ID:` prefix) — match `"First Text View"` instead of `"ID: First Text View"`. In macOS Calculator (`CalculatorKeypadView`), clear with `await calc.pressKey("Escape")` and **prefer clicking explicit AX keypad button IDs (`ID: Three`, `ID: Subtract`, `ID: Five`, `ID: Multiply`, `ID: Two`, `ID: Equals`; and in Scientific mode `ID: Sine`, `ID: Pi`, `ID: Divide`, `ID: Six`, `ID: Equals`) rather than `typeText(...)`** — `typeText` can be ignored on an unfocused cold-launched Calculator window or drop digits inside `sin(...)`. Do NOT blindly click `ID: AllClear` / `ID: Delete`, because SwiftUI keeps the inactive button in the AX tree with a `0x0` frame (`-10005: elementHasNoFrame`). In Scientific mode (`Cmd+2`), match exact `ID: Radians` / `ID: Degrees` / `ID: Pi` / `ID: Sine` (never match localized `"弧度|角度"`, which appears inside the `Help:` string of both toggle states). Pressing `ID: Radians` switches Calculator into Radians mode (the toggle button's ID then changes to `ID: Degrees`, meaning "click to return to Degrees", while an `弧度`/`Rad` indicator appears in the display area). **Never use JS RegExp `\b` word boundaries adjacent to CJK characters**: `\b` only matches ASCII `[A-Za-z0-9_]`, so patterns like `/\b文件\b/`, `/文本\b/`, or `/集合\b/` always fail on `zh-Hans` AX roles/labels (`文本`, `文件`, `集合`, `图像`); use `(?:\s|$|,)` or `.includes(...)` instead.
3. **macOS Save Panels (`NSSavePanel` / `openAndSavePanelService`)**:
- **NEVER call `app.setValue(tvIdx, ...)` on TextEdit's `First Text View` (`NSTextView`) before `Cmd+S`!** On macOS 26 (`TextEdit 1.20`), AX `setValue` on `First Text View` after `Shift+Cmd+T` deadlocks TextEdit's main thread inside `-[_NSDocumentSerializationSemaphore wait]` (`-10005: timeoutReached`). Always populate TextEdit's document body via **`await app.click(tvIdx); await app.paste(text); await cuaExt.wait(800);`** (and keep `await cuaExt.wait(800)` after `Cmd+N`/`ID: newDocument:` and `Shift+Cmd+T`). Use `setValue(...)` ONLY for single-line `NSSavePanel` fields (`ID: PathTextField` and `ID: saveAsNameTextField`).
- **Clean untitled doc + non-wedging Save As (`ID: newDocument:` -> `Cmd+S` / `Option+Shift+Cmd+S`) + single-shot `wait(900)`**: To create a clean untitled doc that opens `NSSavePanel` deterministically, click `文件`/`File` in `menu bar` -> `ID: newDocument:` (note: on macOS 26 `zh-Hans`, opening `文件` replaces Sky's AX root with the open dropdown `0 文件 -> 1 菜单 -> 2 新建`, where `新建` lacks `ID: newDocument:` and `menu bar` is absent, and `pressKey("Escape")` does not dismiss an open AppKit menu-bar dropdown — match `ID: newDocument:` with a fallback to `/^\t*\d+\s+(?:新建|New)(?:\s*,|\s*$)/i`, or dismiss via `performSecondaryAction(0, "Cancel")`; avoids `Cmd+N` reusing/auto-attaching an existing folder-bound doc), wait `800 ms`, convert to plain text (`Shift+Cmd+T` + `800 ms` if formatting toolbar exists), populate text via `click(tvIdx) + paste(...) + wait(800)`, then press `Cmd+S` (`super+s`) + `await cuaExt.wait(900)` + **one** `getAXState({ emit: false, disableDiffing: true })`. If `ID: saveAsNameTextField` is not present (e.g., iCloud auto-saved `未命名.txt`), immediately press `Option+Shift+Cmd+S` (`alt+shift+super+s`) + `await cuaExt.wait(900)` + **one** `getAXState` to open `NSSavePanel`. (Never call `cuaExt.waitFor(...)` inside `NSSavePanel`/`GoToWindow`.)
- **Fast 1-hop folder navigation recipe (`GoToWindow`) & safe fallback**: Once `ID: saveAsNameTextField` is visible, navigate with `await app.pressKey("shift+super+g")` -> `await cuaExt.wait(900)` -> **one** `getAXState` -> verify `ID: PathTextField` -> **`await app.setValue(pathIdx, "/abs/target/dir")`** atomically (never `typeText`/`Cmd+A`/`paste` for `/paths`, since Chinese IME turns `/` into `、`) -> `await cuaExt.wait(300)` -> **one** `pressKey("Return")` -> `await cuaExt.wait(900)` -> **one** `getAXState` (**ONLY** press `Return` a second time if `ID: GoToWindow` is still present — pressing `Return` blindly twice submits `Save` prematurely with `未命名.txt`!), verify `ID: where popup` shows the target folder & `ID: OKButton` is not `(disabled)`, then **`await app.setValue(nameIdx, "file.txt")`** on `ID: saveAsNameTextField` -> `await cuaExt.wait(250)` -> click `ID: OKButton`. Alternatively, expand the disclosure triangle (`显示更多选项` if `Value: 0`) and click folders in sidebar / `ID: ColumnView`. On `zh-Hans` overwrite confirmation sheets (`“...”已存在。你要替换它吗?`), match `ID: action-button-1` (or require role `按钮`/`button`) rather than bare `"替换"`, which hits the dialog's static description text first.
- **Avoid `Duplicate` (`Shift+Cmd+S`) on a single file opened via `open -a TextEdit <file>`**: App Sandbox often throws a permission alert (`未能将文稿保存...你没有权限`). Instead, read the content; if an Open dialog (`ID: open-panel`) is shown, dismiss it first (click `ID: CancelButton` or press `Escape`) and create a fresh in-memory doc via `文件`/`File` in `menu bar` -> `ID: newDocument:` (`新建`/`New`) — do NOT click `ID: NewDocumentButton` when iCloud Drive is selected, because `NewDocumentButton` creates an already-saved iCloud file where `Cmd+S` skips `NSSavePanel`. Convert to plain text (`Shift+Cmd+T` if formatting toolbar is shown), populate text via `click(tvIdx) + paste(...) + wait(800)`, then Save (`Cmd+S`, falling back to `Option+Shift+Cmd+S` if auto-saved).
- **Never save sandboxed app files into `/tmp`**: `openAndSavePanelService` disables `OKButton` (`保存`) and `NewFolderButton` for `/tmp`; use a directory under `$HOME`.
- If an `NSSavePanel` ever times out with `-10005: timeoutReached`, do not loop retries — dismiss with `Escape`/`CancelButton`; if `cua.getApp(...)` itself times out (`-10005: timeoutReached`), the app's main thread is wedged — force-kill with `pkill -9 -x TextEdit` (`-9` required) and reopen cleanly.
4. **Isolate turns across unrelated apps (especially after Save panels)**: After closing a native Save panel (e.g. TextEdit) and before attaching to Finder or another unrelated app, run `codex-cu-bridge end` (or MCP `end_turn`). This avoids Sky's `This application session has been explicitly stopped by the user for this turn` error while keeping the warm daemon running (~200 ms).
5. **Finder tagging (`zh-Hans` & `en`)**:
- Switch to List View (`Cmd+2`) so filenames and sizes appear in `ID: ListView`. Note that the List View header `row` emits literal newlines in `Value:` (`名称\n修改日期\n...` at column 0); `cuaExt.queryAX` handles multi-line `Value:` continuations automatically.
- **Do not use `文件` menu tag dots** (often disabled in AX) and **do not click the filename text field** (enters inline rename).
- Click a **non-filename cell** (date or size `文本`) to select a row cleanly, then either:
- Click the toolbar tag button (`Help: 编辑标签`, whose `Description` switches from `编辑标签` to `添加标签` once a row is selected) and select the color in the popover, **or**
- Right-click that non-filename cell and match exact `'添加“<颜色>”标签'` / `'Add "<Color>"'` radio button (e.g. `'添加“红色”标签'` — never match bare `'红色'`, which hits the sidebar tag item `28 红色` and navigates away from the folder).
6. **Preview, menus, screenshots & quitting**:
- Use **`Option+Cmd+G` (`alt+super+g`)** to jump straight to a page number in Preview (`alt+super+g` -> `typeText("2")` -> `pressKey("Return")`, avoids hunting localized `前往` menu item names like `向下` vs `下一页`). After jumping to Page 2, **click the Page 2 sidebar thumbnail (scope strictly to `图像`/`image` inside the sidebar `集合`/`collection`)** before pressing `Cmd+R` (`super+r`) — never match `"Page 2"` or `"页码:2"` globally across the whole AX tree (Page 1's PDF text may mention `"Page 2"`, and in `zh-Hans` the window title `0 标准窗口 ... – 页码:2/2` matches `"页码:2"` first and opens the titlebar rename popover), otherwise Page 1 rotates or title editing opens instead.
- Dismiss any open menu (`pressKey("Escape")` or `performSecondaryAction(0, "Cancel")`) before calling `getScreenshot()` (open menus cause `Screenshot unavailable`).
- If a zero-window app (like Preview after `Cmd+W`) ignores `Cmd+Q`, click the app menu (`预览`/`Preview` -> `退出预览`/`Quit Preview`) — **scope menu-bar searches strictly to lines after `menu bar`**, because Open-panel sidebars also contain rows named `文本编辑`/`预览`. Also avoid polling `getAXState()` immediately after `Cmd+W` closes an app's last document window (can hang on zero windows); re-attach or quit directly when needed, and if an Open panel (`ID: open-panel`) appears on re-attach, click `ID: CancelButton` before `Cmd+Q`.
## CLI commands
```bash
# Run JS in persistent cua_repl (pass '-' or --file <path> for multiline scripts)
codex-cu-bridge js 'const apps = await cua.listApps({emit:false}); nodeRepl.write(JSON.stringify(apps.filter(a=>a.isRunning).map(a=>({name:a.displayName,id:a.id}))));'
codex-cu-bridge js --full-output 'nodeRepl.write(await globalThis.finder.getAXState({emit:false,disableDiffing:true}));'
codex-cu-bridge js --title "Inspect Finder" - <<'JS'
globalThis.finder = await cua.getApp("com.apple.finder");
JS
# Dismiss active CU session, pink dot & Software Cursor silently (keeps JS bindings warm)
codex-cu-bridge end
# Explicitly release macOS menu bar pink dot & Software Cursor (silent AX press first, cua-driver fallback if needed)
codex-cu-bridge release # release apps touched by this session (or all if daemon already stopped)
codex-cu-bridge release Finder # release only matching app(s)
codex-cu-bridge release --dry-run # inspect active Stop Using items silently without clicking
codex-cu-bridge release --all # release all active Stop Using items
# Diagnostics / reset persistent JS variables / check daemon status / view full API docs / stop daemon
codex-cu-bridge doctor
codex-cu-bridge reset
codex-cu-bridge status
codex-cu-bridge docs
codex-cu-bridge stop
# Manage App allowlist (~/.config/codex-cu-bridge/allowlist.json, hot-reloaded immediately)
codex-cu-bridge allow list
codex-cu-bridge allow add "com.apple.Notes"
codex-cu-bridge allow remove "com.apple.Notes"
codex-cu-bridge allow deny "com.apple.systempreferences"
codex-cu-bridge allow mode allowlist # allowlist | ask | allow-all
codex-cu-bridge allow auth status # check/toggle Touch ID lock (`on` | `off`)
```
## App allowlist & approvals
- Accessing any macOS app triggers a `cua_repl` elicitation checked against `~/.config/codex-cu-bridge/allowlist.json`.
- Apps in `allowedApps` (supports exact bundle ID, display name, or `*` glob like `com.t3tools.*`) are auto-approved for the session.
- Unlisted or denied apps are **cancelled** (never permanently declined) and return `[APPROVAL_REQUIRED]`.
- **Rule**: Never add an app to `allowedApps` without explicit user confirmation. Report the `[APPROVAL_REQUIRED]` app name + bundle ID to the user and ask whether they want to allow it.
## Sky `cua` JavaScript API cheat sheet
```ts
// Discovery
await cua.listApps({ emit: false }); // -> AppInfo[] ({ id, displayName, isRunning, ... })
globalThis.app = await cua.getApp("Finder"); // display name, path, or bundle ID (auto-emits initial AX tree)
// Observation (getAXState returns diff by default; pass { emit: false } to process/filter in JS)
const ax = await app.getAXState({ emit: false, disableDiffing: false });
const img = await app.getScreenshot({ emit: true }); // CLI & MCP save PNG/JPG to ~/Library/Caches/codex-cu-bridge/screenshots/
const both = await app.getAXStateAndScreenshot({ emit: false });
// Actions (prefer numeric element index from AX tree; fallback to [x, y] coordinates)
await app.click(42); // or [x, y], optional { mouseButton: "left"|"right", clickCount: 2, key: "super" }
await app.drag([x1, y1], [x2, y2]);
await app.scroll(42, "down", 1); // direction: "up"|"down"|"left"|"right", pages count
await app.setValue(42, "text");
await app.selectText(42, "match", { prefix, suffix, selectionType: "text"|"cursor_before"|"cursor_after" });
await app.performSecondaryAction(42, "Expand"); // only actions explicitly listed in AX text
await app.typeText("hello");
await app.paste("multiline text"); // restores user clipboard automatically on macOS
await app.pressKey("Return"); // xdotool syntax: "Return", "Tab", "Escape", "super+c", "Up", etc.
// Output helpers
nodeRepl.write("text or JSON"); // don't wrap auto-emitting calls unless passing { emit: false }
await nodeRepl.emitImage(img);
```
## Batched script pattern (example)
```bash
codex-cu-bridge js --title "Calculate 17*23 in Calculator" - <<'JS'
globalThis.calc = await cua.getApp("com.apple.calculator");
const ax = await globalThis.calc.getAXState({ emit: false, disableDiffing: true });
const lines = ax.split("\n");
const idx = cuaExt.findIndex(ax, "ID: StandardInputView");
const displayLine = lines.findIndex((l) => l.includes("ID: StandardInputView"));
const displayed = displayLine >= 0 ? lines[displayLine + 1]?.trim() : null;
nodeRepl.write(JSON.stringify({ lines: lines.length, displayIdx: idx, displayed }));
JS
```
*(Note: In macOS Calculator, `ID: StandardInputView` is the parent container; the displayed text value sits on its immediate child `文本`/`text` line, i.e., `lines[displayLine + 1]`.)*