Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
docs: rewrite README with AX-first interaction chains and inline menu capture
Lahfira349bd9bc017
diff --git a/README.md b/README.mdindex 31e58dfe2..07f8bda84 100644--- a/README.md+++ b/README.md@@ -4,473 +4,206 @@[](LICENSE)[]()-A cross-platform Rust CLI that gives AI agents structured access to native desktop applications through OS accessibility trees. It outputs JSON with ref-based element identifiers (`@e1`, `@e2`, ...) so agents can observe UI state, act on elements, and drive any application programmatically. **agent-desktop is not an AI agent** — it is the tool AI agents invoke.+A cross-platform Rust CLI that gives AI agents structured access to native desktop applications through OS accessibility trees. Outputs JSON with ref-based element identifiers (`@e1`, `@e2`, ...) so agents can observe UI state, act on elements, and drive any application programmatically.-## Quick example--```bash-# 1. Observe: get the accessibility tree with interactive element refs-agent-desktop snapshot --app "TextEdit" -i--# 2. Act: click a button by ref-agent-desktop click @e3--# 3. Type into a text field-agent-desktop type @e5 "quarterly report"--# 4. Submit with a keyboard shortcut-agent-desktop press cmd+return--# 5. Re-observe after the UI changes-agent-desktop snapshot -i-```--The observation-action loop lives in the calling agent, not here.+**agent-desktop is not an AI agent** — it is the tool AI agents invoke. The observation-action loop lives in the calling agent.```AI Agent|- +-- agent-desktop snapshot -i → {"tree": {...}, "ref_count": 14}+ +-- agent-desktop snapshot --app "Finder" -i → { "tree": {...}, "ref_count": 83 }|- +-- agent-desktop click @e7 → {"ok": true, "data": {"action": "click"}}+ +-- agent-desktop right-click @e66 → { "action": "right_click", "menu": {...} }|- +-- agent-desktop snapshot -i → {"tree": {...}, "ref_count": 11}+ +-- agent-desktop click @e72 → { "action": "click" }```## Installation-### Build from source-```bashgit clone https://github.com/lahfir/agent-desktopcd agent-desktopcargo build --release-```--The binary is at `./target/release/agent-desktop`. Move it to your PATH:--```bashmv target/release/agent-desktop /usr/local/bin/```-### Requirements--- **Rust** 1.78+ (pinned via `rust-toolchain.toml`)-- **macOS** 13.0+ (Phase 1 — the only supported platform today)+**Requirements:** Rust 1.78+, macOS 13.0+## Permissions-macOS requires Accessibility permission for agent-desktop to read UI trees and perform actions.+macOS requires Accessibility permission to read UI trees and perform actions.```bash-# Check current permission status-agent-desktop permissions--# Trigger the system permission dialog-agent-desktop permissions --request+agent-desktop permissions # check status+agent-desktop permissions --request # trigger system dialog```-Or grant manually: **System Settings > Privacy & Security > Accessibility** and add your terminal application.+Or grant manually: **System Settings > Privacy & Security > Accessibility** — add your terminal app.-If permission is missing, commands return a `PERM_DENIED` error with guidance.--## Commands--### Observation--#### `snapshot`--Capture the accessibility tree of a window as structured JSON with `@eN` ref IDs.--```bash-agent-desktop snapshot [OPTIONS]-```--| Flag | Default | Description |-|------|---------|-------------|-| `--app <NAME>` | focused app | Filter to a specific application |-| `--window-id <ID>` | — | Filter to a specific window |-| `--max-depth <N>` | `10` | Maximum tree traversal depth |-| `--include-bounds` | off | Include pixel bounds for every node |-| `-i` / `--interactive-only` | off | Omit non-interactive elements from output |-| `--compact` | off | Omit empty structural nodes |-| `--surface <TYPE>` | `window` | Surface to snapshot: window, focused, menu, sheet, popover, alert |+## Quick start```bash+# observe: get the accessibility tree with interactive element refsagent-desktop snapshot --app "TextEdit" -i-agent-desktop snapshot --include-bounds --max-depth 15-agent-desktop snapshot --surface menu --app "Finder"-```--<details>-<summary>Example output</summary>--```json-{- "version": "1.0",- "ok": true,- "command": "snapshot",- "data": {- "ref_count": 8,- "tree": {- "role": "window",- "name": "Untitled",- "children": [- {- "role": "textfield",- "name": "Document body",- "ref": "@e1",- "value": "Hello"- },- {- "role": "button",- "name": "Save",- "ref": "@e2"- }- ]- }- }-}-```--</details>-#### `screenshot`--Capture a PNG screenshot of a window.--```bash-agent-desktop screenshot [--app <NAME>] [--window-id <ID>] [PATH]-```+# act: click a button by ref+agent-desktop click @e3-```bash-agent-desktop screenshot --app "Finder" ~/Desktop/finder.png-agent-desktop screenshot # base64 PNG to stdout-```+# type into a text field+agent-desktop type @e5 "quarterly report"-#### `find`+# keyboard shortcut+agent-desktop press cmd+return-Search the accessibility tree for elements matching a query.+# right-click returns the context menu inline+agent-desktop right-click @e8-```bash-agent-desktop find [OPTIONS]+# re-observe after the UI changes+agent-desktop snapshot -i```-| Flag | Description |-|------|-------------|-| `--app <NAME>` | Filter to application |-| `--role <ROLE>` | Match by role (button, textfield, checkbox ...) |-| `--name <TEXT>` | Match by accessible name or label |-| `--value <TEXT>` | Match by current value |-| `--text <TEXT>` | Match by text in name, value, title, or description |-| `--count` | Return match count only |-| `--first` | Return first match only |-| `--last` | Return last match only |-| `--nth <N>` | Return Nth match (0-indexed) |+## How interactions work-```bash-agent-desktop find --role button --name "Save"-agent-desktop find --app "TextEdit" --text "hello" --first-agent-desktop find --role textfield --count-```+agent-desktop uses an **AX-first** approach for all interactions. Every action exhausts multiple Accessibility API strategies before falling back to CGEvent (which moves the cursor and requires the window to be frontmost).-#### `get`+### Click chain (13 steps)-Read a property of an element by ref.+1. AXScrollToVisible (ensure element is in viewport)+2. AXPress+3. AXConfirm+4. AXOpen+5. AXPick+6. AXShowAlternateUI + retry children+7. Try child activation (first 3 children)+8. Set AXSelected=true+9. Set AXSelectedRows on parent table/outline/list+10. AXCustomActions+11. Set AXFocused + AXConfirm/AXPress+12. AXUIElementPostKeyboardEvent(Space) to app+13. Try parent activation (walk up 2 ancestors)+14. CGEvent click at center **(last resort)**-```bash-agent-desktop get <REF> --property <PROP>-```+### Right-click chain (7 steps)-Properties: `text` (default), `value`, `title`, `bounds`, `role`, `states`.+1. AXShowMenu on element+2. Focus app via AX + AXShowMenu (fixes -25204 CannotComplete)+3. Select element + AXShowMenu+4. Focus element + AXShowMenu+5. AXShowMenu on parent (walk up 3 ancestors)+6. AXShowMenu on child (first 5 children)+7. CGEvent right-click **(last resort)**-```bash-agent-desktop get @e3 --property value-agent-desktop get @e1 --property bounds-agent-desktop get @e5 --property states-```+The `right-click` command returns the full context menu tree inline with ref_ids on all items, so the agent can immediately click a menu item without a separate snapshot.-#### `is`+### Scroll chain (10 steps)-Check a boolean state of an element.+1. AXScrollToVisible on target element+2. AXIncrement/AXDecrement on AXScrollBar+3. AXScrollDownByPage/AXScrollUpByPage on AXScrollArea+4. Set AXValue (float 0.0-1.0) on AXScrollBar+5. AXPress on scroll bar sub-elements (page/arrow parts)+6. Set AXFocused=true on child in scroll direction+7. Set AXSelectedRows on parent table/outline/list+8. AXUIElementPostKeyboardEvent (Page Up/Down)+9. AXUIElementPostKeyboardEvent (arrow keys)+10. CGEventCreateScrollWheelEvent **(last resort)**-```bash-agent-desktop is <REF> --property <PROP>-```+Steps 1-7 are pure AX (no window focus required, works in background). Steps 8-9 use AX keyboard events (need app focus, no cursor movement). Step 10 uses CGEvent (needs focus + screen coordinates).-Properties: `visible` (default), `enabled`, `checked`, `focused`, `expanded`.--```bash-agent-desktop is @e4 --property enabled-agent-desktop is @e6 --property checked-```+All CGEvent fallbacks include a focus guard (`ensure_app_focused`) that brings the target app to front via AX before posting events.-#### `list-surfaces`+## Commands-List accessibility surfaces for an application (window, menu, sheet, popover, alert).+### Observation-```bash-agent-desktop list-surfaces [--app <NAME>]-```+| Command | Description |+|---------|-------------|+| `snapshot` | Capture accessibility tree as JSON with `@eN` refs |+| `screenshot` | Capture PNG screenshot of a window |+| `find` | Search tree for elements by role, name, value, or text |+| `get` | Read a property of an element (text, value, title, bounds, role, states) |+| `is` | Check a boolean state (visible, enabled, checked, focused, expanded) |+| `list-surfaces` | List open surfaces (menus, sheets, popovers, alerts) |### Interaction-#### `click` / `double-click` / `triple-click` / `right-click`--```bash-agent-desktop click <REF>-agent-desktop double-click <REF>-agent-desktop triple-click <REF> # select line or paragraph-agent-desktop right-click <REF> # open context menu-```--#### `type`--Focus an element and type text (simulates keyboard input).--```bash-agent-desktop type <REF> <TEXT>-```--```bash-agent-desktop type @e3 "[email protected]"-```--#### `set-value`--Set an element's value directly via the accessibility attribute (bypasses key events).--```bash-agent-desktop set-value <REF> <VALUE>-```--```bash-agent-desktop set-value @e3 "2026-02-20"-```--#### `clear`--Clear an element's value to an empty string.--```bash-agent-desktop clear <REF>-```--#### `focus`--Set keyboard focus on an element.--```bash-agent-desktop focus <REF>-```--#### `select`--Select an option in a list or dropdown.--```bash-agent-desktop select <REF> <VALUE>-```--```bash-agent-desktop select @e8 "Last 30 days"-```--#### `toggle` / `check` / `uncheck`--```bash-agent-desktop toggle <REF> # flip checkbox or switch state-agent-desktop check <REF> # set to checked (idempotent)-agent-desktop uncheck <REF> # set to unchecked (idempotent)-```--#### `expand` / `collapse`--Expand or collapse a disclosure triangle, tree item, or accordion.--```bash-agent-desktop expand <REF>-agent-desktop collapse <REF>-```--#### `scroll` / `scroll-to`--```bash-agent-desktop scroll <REF> [--direction up|down|left|right] [--amount <N>]-agent-desktop scroll-to <REF> # scroll element into visible area-```--```bash-agent-desktop scroll @e2 --direction down --amount 5-agent-desktop scroll-to @e14-```+| Command | Description |+|---------|-------------|+| `click` | Smart AX-first click (13-step chain) |+| `double-click` | AXOpen first, then double-activate chain |+| `triple-click` | Select line/paragraph |+| `right-click` | Open context menu via AX, returns menu tree inline |+| `type` | Focus element and type text via keyboard synthesis |+| `set-value` | Set element value directly via AX attribute |+| `clear` | Clear element value to empty string |+| `focus` | Set keyboard focus on element |+| `select` | Select option in list or dropdown |+| `toggle` | Flip checkbox or switch state |+| `check` / `uncheck` | Idempotent checked/unchecked |+| `expand` / `collapse` | Disclosure triangle, tree item, accordion |+| `scroll` | Scroll element (10-step AX-first chain) |+| `scroll-to` | Scroll element into visible area |### Keyboard-#### `press`+| Command | Description |+|---------|-------------|+| `press` | Send key combo (e.g. `cmd+s`, `cmd+shift+z`, `escape`) |+| `key-down` / `key-up` | Hold or release a key |-Send a key combo. Modifiers: `cmd`, `ctrl`, `alt`, `shift`. Combine with `+`.+### Mouse (raw coordinates)-```bash-agent-desktop press <COMBO> [--app <NAME>]-```--```bash-agent-desktop press cmd+s-agent-desktop press cmd+shift+z-agent-desktop press escape-agent-desktop press return-agent-desktop press tab-agent-desktop press cmd+c --app "TextEdit"-```--#### `key-down` / `key-up`--Hold or release a key or modifier.--```bash-agent-desktop key-down shift-agent-desktop key-up shift-```--### Mouse--#### `hover`--Move the cursor to an element or absolute coordinates.--```bash-agent-desktop hover <REF>-agent-desktop hover --xy 500,300-agent-desktop hover @e5 --duration 2000 # hold for 2s-```--#### `drag`--Drag from one element or point to another.--```bash-agent-desktop drag --from @e1 --to @e5-agent-desktop drag --from-xy 100,200 --to-xy 400,500 --duration 500-```--#### `mouse-move` / `mouse-click` / `mouse-down` / `mouse-up`--Low-level mouse operations at absolute screen coordinates.--```bash-agent-desktop mouse-move --xy 500,300-agent-desktop mouse-click --xy 500,300 --button left --count 2-agent-desktop mouse-down --xy 100,200 --button left-agent-desktop mouse-up --xy 400,500 --button left-```+| Command | Description |+|---------|-------------|+| `hover` | Move cursor to element or coordinates |+| `drag` | Drag from one point/element to another |+| `mouse-move` | Move cursor to absolute coordinates |+| `mouse-click` | Click at absolute coordinates |+| `mouse-down` / `mouse-up` | Press/release at coordinates |### App & window management-#### `launch`--Launch an application by name or bundle ID and wait for its window.--```bash-agent-desktop launch <APP> [--timeout <MS>]-```--```bash-agent-desktop launch "TextEdit"-agent-desktop launch "com.apple.finder" --timeout 10000-```--#### `close-app`--Quit an application.--```bash-agent-desktop close-app <APP> [--force]-```--```bash-agent-desktop close-app "TextEdit"-agent-desktop close-app "TextEdit" --force # SIGKILL-```--#### `list-apps`--List all running GUI applications.--```bash-agent-desktop list-apps-```--#### `list-windows`--List all visible windows.--```bash-agent-desktop list-windows [--app <NAME>]-```--#### `focus-window`--Bring a window to the foreground.--```bash-agent-desktop focus-window --app "Finder" --title "Documents"-agent-desktop focus-window --window-id "w-4521"-```--#### `resize-window`--```bash-agent-desktop resize-window --app "TextEdit" --width 800 --height 600-```--#### `move-window`--```bash-agent-desktop move-window --app "TextEdit" --x 100 --y 50-```--#### `minimize` / `maximize` / `restore`--```bash-agent-desktop minimize --app "TextEdit"-agent-desktop maximize --app "TextEdit"-agent-desktop restore --app "TextEdit"-```+| Command | Description |+|---------|-------------|+| `launch` | Launch app by name or bundle ID |+| `close-app` | Quit app (optional `--force` for SIGKILL) |+| `list-apps` | List running GUI applications |+| `list-windows` | List visible windows |+| `focus-window` | Bring window to foreground |+| `resize-window` | Resize a window |+| `move-window` | Move a window |+| `minimize` / `maximize` / `restore` | Window state |### Clipboard-```bash-agent-desktop clipboard-get # read plain-text clipboard-agent-desktop clipboard-set "text" # write text to clipboard-agent-desktop clipboard-clear # clear the clipboard-```+| Command | Description |+|---------|-------------|+| `clipboard-get` | Read plain-text clipboard |+| `clipboard-set` | Write text to clipboard |+| `clipboard-clear` | Clear the clipboard |### WaitBlock for a duration or until a condition is met.```bash-agent-desktop wait [MS] [OPTIONS]+agent-desktop wait 500 # sleep 500ms+agent-desktop wait --window "Save" --timeout 10000 # wait for window+agent-desktop wait --element @e3 --timeout 5000 # wait for element+agent-desktop wait --text "Loading complete" --app "Safari" # wait for text+agent-desktop wait --menu --timeout 3000 # wait for menu```-| Flag | Description |-|------|-------------|-| `<MS>` | Sleep for N milliseconds |-| `--element <REF>` | Block until element appears |-| `--window <TITLE>` | Block until window appears |-| `--text <TEXT>` | Block until text appears in the app's tree |-| `--menu` | Block until a context menu is open |-| `--menu-closed` | Block until a context menu is dismissed |-| `--app <NAME>` | Scope wait to a specific application |-| `--timeout <MS>` | Timeout (default 30000) |+### Batch++Run multiple commands in a single invocation.```bash-agent-desktop wait 500-agent-desktop wait --window "Save" --timeout 10000-agent-desktop wait --element @e3 --timeout 5000-agent-desktop wait --text "Loading complete" --app "Safari" --timeout 5000-agent-desktop wait --menu --timeout 3000+agent-desktop batch '[+ {"command":"click", "args":{"ref_id":"@e2"}},+ {"command":"type", "args":{"ref_id":"@e5","text":"hello"}},+ {"command":"press", "args":{"combo":"return"}}+]' --stop-on-error```### System@@ -480,26 +213,25 @@ agent-desktop status # adapter health, platform, permission staagent-desktop permissions # check accessibility permissionagent-desktop permissions --request # trigger system dialogagent-desktop version # version string-agent-desktop version --json # machine-readable version```-### Batch--Run multiple commands in a single invocation.+## Snapshot options```bash-agent-desktop batch <JSON> [--stop-on-error]+agent-desktop snapshot [OPTIONS]```-```bash-agent-desktop batch '[- {"command":"click", "args":{"ref_id":"@e2"}},- {"command":"type", "args":{"ref_id":"@e5","text":"hello"}},- {"command":"press", "args":{"combo":"return"}}-]' --stop-on-error-```+| Flag | Default | Description |+|------|---------|-------------|+| `--app <NAME>` | focused app | Filter to a specific application |+| `--window-id <ID>` | — | Filter to a specific window |+| `--max-depth <N>` | `10` | Maximum tree traversal depth |+| `--include-bounds` | off | Include pixel bounds for every node |+| `-i` / `--interactive-only` | off | Omit non-interactive elements from output |+| `--compact` | off | Omit empty structural nodes |+| `--surface <TYPE>` | `window` | Surface: window, focused, menu, menubar, sheet, popover, alert |-## JSON output format+## JSON outputEvery command produces a standard envelope:@@ -508,7 +240,29 @@ Every command produces a standard envelope:"version": "1.0","ok": true,"command": "click",- "data": { "action": "click", "ref": "@e3" }+ "data": { "action": "click" }+}+```++Right-click includes the context menu tree:++```json+{+ "version": "1.0",+ "ok": true,+ "command": "right-click",+ "data": {+ "action": "right_click",+ "menu": {+ "role": "menu",+ "children": [+ { "role": "menuitem", "name": "Open in New Tab", "ref_id": "@e71" },+ { "role": "menuitem", "name": "Open in New Window", "ref_id": "@e72" },+ { "role": "menuitem", "name": "Get Info", "ref_id": "@e78" },+ { "role": "menuitem", "name": "Rename", "ref_id": "@e80" }+ ]+ }+ }}```@@ -553,45 +307,45 @@ Errors include a machine-readable code and recovery hint:## Ref system-`snapshot` assigns identifiers to every interactive element in depth-first order: `@e1`, `@e2`, `@e3`, etc. These refs are valid for action commands **until the next snapshot replaces them**.+`snapshot` assigns identifiers to every interactive element in depth-first order: `@e1`, `@e2`, `@e3`, etc. These refs are valid for action commands until the next snapshot replaces them.-Only interactive roles receive refs:+Interactive roles that receive refs:-| | | |-|---|---|---|-| `button` | `textfield` | `checkbox` |-| `link` | `menuitem` | `tab` |-| `slider` | `combobox` | `treeitem` |-| `cell` | `radiobutton` | `incrementor` |+| | | | |+|---|---|---|---|+| `button` | `textfield` | `checkbox` | `link` |+| `menuitem` | `tab` | `slider` | `combobox` |+| `treeitem` | `cell` | `radiobutton` | `incrementor` |+| `menubutton` | `switch` | `colorwell` | `dockitem` |-Static elements (labels, groups, containers) appear in the tree for context but have no ref and cannot be acted upon.+Static elements (labels, groups, containers) appear in the tree for context but have no ref.-The refmap is stored at `~/.agent-desktop/last_refmap.json` (permissions `0600`) and fully replaced on every snapshot. Action commands perform optimistic re-identification — if the element has changed since the snapshot, they return `STALE_REF`.+The refmap is stored at `~/.agent-desktop/last_refmap.json` and fully replaced on every snapshot. Action commands perform optimistic re-identification using `(pid, role, name, bounds_hash)` — if the element has moved or changed, they return `STALE_REF`.-Stale ref recovery pattern:+Stale ref recovery:```-snapshot -> act -> if STALE_REF -> snapshot again -> retry+snapshot → act → if STALE_REF → snapshot again → retry```## Platform support| Feature | macOS | Windows | Linux ||---------|-------|---------|-------|-| Accessibility tree | Phase 1 | Planned (Phase 2) | Planned (Phase 2) |-| Click / type / keyboard | Phase 1 | Planned (Phase 2) | Planned (Phase 2) |-| Mouse input | Phase 1 | Planned (Phase 2) | Planned (Phase 2) |-| Screenshot | Phase 1 | Planned (Phase 2) | Planned (Phase 2) |-| Clipboard | Phase 1 | Planned (Phase 2) | Planned (Phase 2) |-| App launch / close | Phase 1 | Planned (Phase 2) | Planned (Phase 2) |-| Window management | Phase 1 | Planned (Phase 2) | Planned (Phase 2) |-| MCP server mode | Planned (Phase 3) | Planned (Phase 3) | Planned (Phase 3) |+| Accessibility tree | Phase 1 | Planned | Planned |+| Click / type / keyboard | Phase 1 | Planned | Planned |+| Mouse input | Phase 1 | Planned | Planned |+| Screenshot | Phase 1 | Planned | Planned |+| Clipboard | Phase 1 | Planned | Planned |+| App launch / close | Phase 1 | Planned | Planned |+| Window management | Phase 1 | Planned | Planned |+| MCP server mode | Planned | Planned | Planned |-macOS implementation uses `AXUIElement` for tree traversal and actions, `CGEvent` for keyboard and mouse input, `CGWindowListCreateImage` for screenshots, and `NSPasteboard` for clipboard.+macOS uses `AXUIElement` for tree traversal and actions, `CGEvent` for keyboard/mouse, `CGWindowListCreateImage` for screenshots, and `NSPasteboard` for clipboard.## Architecture-The workspace follows strict dependency inversion. `agent-desktop-core` defines the `PlatformAdapter` trait and all shared types. Platform crates (`macos`, `windows`, `linux`) implement the trait. Core never imports platform crates — the binary crate is the only wiring point. This constraint is enforced in CI via `cargo tree`.+Strict dependency inversion. `agent-desktop-core` defines the `PlatformAdapter` trait and all shared types. Platform crates implement the trait. Core never imports platform crates — the binary crate is the only wiring point. Enforced in CI via `cargo tree`.```agent-desktop/@@ -599,24 +353,21 @@ agent-desktop/└── crates/├── core/ # platform-agnostic types, commands, engine├── macos/ # macOS adapter (Phase 1)+ │ ├── tree/ # AX tree reading, element resolution, surfaces+ │ ├── actions/ # smart interaction chains (click, scroll, right-click)+ │ ├── input/ # keyboard, mouse, clipboard synthesis+ │ └── system/ # app lifecycle, windows, permissions├── windows/ # stub (Phase 2)└── linux/ # stub (Phase 2)```## Contributing-### Build--```bash-cargo build # debug-cargo build --release # optimized, stripped binary (<15MB)-```--### Test-```bash-cargo test --workspace-cargo clippy --all-targets -- -D warnings+cargo build # debug build+cargo build --release # optimized (<15MB)+cargo test --workspace # run tests+cargo clippy --all-targets -- -D warnings # lint```### Adding a command@@ -624,7 +375,7 @@ cargo clippy --all-targets -- -D warnings1. Create `crates/core/src/commands/{name}.rs` with an `execute()` function2. Register in `crates/core/src/commands/mod.rs`3. Add subcommand variant to `src/cli.rs`-4. Add match arm in `src/dispatch.rs`+4. Add match arm in dispatch5. If needed: add `Action` variant in `crates/core/src/action.rs`6. If needed: add adapter method to `PlatformAdapter` with default `not_supported()` impl