Skip to content

armgit / cua

Public Imported from GitHub
0

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

feat(cua-driver): consolidate type_text + remove get_accessibility_tree (#1416)

Francesco Bonacci604628fe4e62
diff --git a/docs/content/docs/cua-driver/reference/cli-reference.mdx b/docs/content/docs/cua-driver/reference/cli-reference.mdx
index 16034b4b8a..c5af31770c 100644
--- a/docs/content/docs/cua-driver/reference/cli-reference.mdx
+++ b/docs/content/docs/cua-driver/reference/cli-reference.mdx
@@ -182,7 +182,7 @@ Pipe to `pbcopy` to put any output on the clipboard, or pass the printed `claude
### cua-driver recording start
-Enable the trajectory recorder. Every subsequent action-tool call (`click`, `right_click`, `scroll`, `type_text`, `type_text_chars`, `press_key`, `hotkey`, `set_value`) writes a numbered turn folder under `<output-dir>`.
+Enable the trajectory recorder. Every subsequent action-tool call (`click`, `right_click`, `scroll`, `type_text`, `press_key`, `hotkey`, `set_value`) writes a numbered turn folder under `<output-dir>`.
```bash
cua-driver recording start ~/cua-trajectories/demo1
@@ -346,7 +346,6 @@ The following MCP tools are callable via `cua-driver <tool>`. For input schemas
- `check_permissions` — Accessibility + Screen Recording TCC status.
- `get_screen_size` — main display size in points + scale factor.
- `get_cursor_position` — current mouse cursor position.
-- `get_accessibility_tree` — lightweight desktop snapshot (apps + visible windows).
**App lifecycle**
@@ -368,8 +367,7 @@ The following MCP tools are callable via `cua-driver <tool>`. For input schemas
**Keyboard**
-- `type_text` — insert text via `AXSelectedText`. Pid-scoped.
-- `type_text_chars` — character-by-character via `CGEvent.postToPid`. Reaches Chromium/Electron inputs.
+- `type_text` — insert text via `AXSelectedText` with automatic CGEvent fallback for Chromium/Electron inputs. Pid-scoped.
- `press_key` — single key press. Pid-scoped.
- `hotkey` — modifier combo (e.g. `["cmd","c"]`). Pid-scoped.
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools.mdx b/docs/content/docs/cua-driver/reference/mcp-tools.mdx
index 0b19c1f3b7..2b110dfceb 100644
--- a/docs/content/docs/cua-driver/reference/mcp-tools.mdx
+++ b/docs/content/docs/cua-driver/reference/mcp-tools.mdx
@@ -58,16 +58,6 @@ Return the current mouse cursor position in screen points (top-left origin).
{}
```
-### get_accessibility_tree
-
-Lightweight desktop snapshot: running regular apps and on-screen visible windows with bounds, z-order, and owner pid. For a single window's internal UI, use `get_window_state`.
-
-**Arguments:** none.
-
-```json
-{}
-```
-
### screenshot
Raw ScreenCaptureKit capture. Full main display, or a single window when `window_id` is set. Returns an image content block plus a text summary listing on-screen windows.
@@ -271,7 +261,7 @@ Modifier combo as a single array, e.g. `["cmd", "c"]`. Requires at least two ent
### type_text
-Insert text at the target's current cursor via `AXSelectedText`. Fast (single AX write) but skipped by apps with custom text layers; for Chromium / Electron inputs use `type_text_chars`.
+Insert text at the target's current cursor. Attempts `AXSelectedText` write first (fast, single AX call); automatically falls back to character-by-character `CGEvent.postToPid` synthesis when the target input doesn't implement `AXSelectedText` — this makes it work for Chromium and Electron inputs without any manual switching.
**Arguments:**
@@ -279,22 +269,10 @@ Insert text at the target's current cursor via `AXSelectedText`. Fast (single AX
- `text` (string, required): Text to insert at the target's cursor.
- `element_index` (integer, optional): When present, the element is focused before the write. Requires `window_id`.
- `window_id` (integer, optional): Required when `element_index` is used.
+- `delay_ms` (integer, optional): Milliseconds between characters when the CGEvent fallback path is used, 0-200. Default 30.
```json
{"pid": 844, "window_id": 10725, "element_index": 12, "text": "hello"}
-```
-
-### type_text_chars
-
-Character-by-character input via `CGEvent.postToPid`. Slower than `type_text` but reaches Chromium and Electron inputs that ignore AX writes.
-
-**Arguments:**
-
-- `pid` (integer, required): Target process ID.
-- `text` (string, required): Text to type into the target's focused element.
-- `delay_ms` (integer, optional): Milliseconds between characters, 0-200. Default 30.
-
-```json
{"pid": 844, "text": "hello world", "delay_ms": 40}
```
@@ -450,7 +428,7 @@ Supported keys and ranges: see the [CLI reference](/cua-driver/reference/cli-ref
## Recording and replay
-The trajectory recorder captures every action-tool call (`click`, `right_click`, `scroll`, `type_text`, `type_text_chars`, `press_key`, `hotkey`, `set_value`) into numbered turn folders. Recordings can be replayed turn-by-turn.
+The trajectory recorder captures every action-tool call (`click`, `right_click`, `scroll`, `type_text`, `press_key`, `hotkey`, `set_value`) into numbered turn folders. Recordings can be replayed turn-by-turn.
### get_recording_state
diff --git a/libs/cua-driver/Skills/cua-driver/RECORDING.md b/libs/cua-driver/Skills/cua-driver/RECORDING.md
index 79fc526398..e60c3d2f8c 100644
--- a/libs/cua-driver/Skills/cua-driver/RECORDING.md
+++ b/libs/cua-driver/Skills/cua-driver/RECORDING.md
@@ -6,7 +6,7 @@ user explicitly asks to record — the skill does not auto-enable this.
`set_recording` turns on a session-scoped trajectory recorder. While
enabled, every action-tool call (`click`, `right_click`, `scroll`,
-`type_text`, `type_text_chars`, `press_key`, `hotkey`, `set_value`)
+`type_text`, `press_key`, `hotkey`, `set_value`)
writes a numbered turn folder under a caller-chosen output
directory. Read-only tools (`get_window_state`, `list_windows`,
`screenshot`, `list_apps`, permission probes, agent-cursor getters /
@@ -101,8 +101,7 @@ keyed on `(pid, window_id)`, so a recorded
resolve today — the pid is usually different, the window_id always
is. The call returns `Invalid element_index` or `No cached AX
state`. Pixel clicks (`click({pid, x, y})`) and keyboard tools
-(`press_key`, `type_text_chars`, `hotkey`, `type_text` without
-element_index) replay cleanly; element-indexed actions require a
+(`press_key`, `hotkey`, `type_text` without element_index) replay cleanly; element-indexed actions require a
live snapshot that replay doesn't currently re-emit (read-only tools
like `get_window_state` aren't recorded). For a reliable replay, either
compose the trajectory from pixel + keyboard primitives, or capture
diff --git a/libs/cua-driver/Skills/cua-driver/SKILL.md b/libs/cua-driver/Skills/cua-driver/SKILL.md
index 69d8177ccd..e442825136 100644
--- a/libs/cua-driver/Skills/cua-driver/SKILL.md
+++ b/libs/cua-driver/Skills/cua-driver/SKILL.md
@@ -420,8 +420,7 @@ you're interacting with a long-lived process). In the default
get_window_state → reason over PNG → pixel click`. When you need
`element_index` dispatch (AX-addressable elements, backgrounded
clicks), flip to `som` first: `cua-driver set_config '{"key":
-"capture_mode", "value": "som"}'`, or call `get_accessibility_tree`
-directly. The rest of this section walks through `som` mode, which
+"capture_mode", "value": "som"}'`. The rest of this section walks through `som` mode, which
is what you want once you've decided element-indexed addressing is
required.
@@ -505,7 +504,7 @@ anchor the conversion against a specific window):
| Focus + send key | `press_key({pid, key, window_id, element_index, modifiers})` | element_index sets AXFocused, then posts key |
| Send key to pid | `press_key({pid, key, modifiers})` | no focus change; key goes to pid's current focus |
| Modifier combo | `hotkey({pid, keys})` | e.g. `["cmd","c"]`; posted per-pid, not HID tap |
-| Unicode keystrokes | `type_text_chars({pid, text, delay_ms})` | CGEvent-to-pid; reaches Chromium/Electron inputs |
+| Unicode keystrokes | `type_text({pid, text, delay_ms})` | AX write with automatic CGEvent fallback; reaches Chromium/Electron inputs |
**All keyboard/text primitives require `pid`.** There is no
frontmost-routed variant — every key goes to the named target via
diff --git a/libs/cua-driver/Skills/cua-driver/TESTS.md b/libs/cua-driver/Skills/cua-driver/TESTS.md
index dde5fca226..fdc835b329 100644
--- a/libs/cua-driver/Skills/cua-driver/TESTS.md
+++ b/libs/cua-driver/Skills/cua-driver/TESTS.md
@@ -116,11 +116,11 @@ These are where CuaDriver's AX-activation trio matters:
### 8. Slack — sparse Electron, hotkey fallback
**Prompt:** `In Slack, jump to the #pr-reviews channel using the quick switcher (⌘K).`
-**Exercises:** "retry snapshot once, then `hotkey` + `type_text_chars`" fallback path.
+**Exercises:** "retry snapshot once, then `hotkey` + `type_text`" fallback path.
**Success:**
- Re-snapshot shows Slack's channel title area (AX role `AXStaticText` or similar) contains `pr-reviews`.
-- Claude uses `hotkey` and `type_text_chars` — NOT `simulate_click` / pixel coords.
+- Claude uses `hotkey` and `type_text` — NOT `simulate_click` / pixel coords.
**Fail signals:** Claude drops to `simulate_click` (guardrail violation — pixel fallback is not allowed on sparse AX trees), wrong channel joined, typed text echoes into the message composer instead of the switcher.
@@ -168,7 +168,7 @@ These are where CuaDriver's AX-activation trio matters:
### 12. Chrome proper — omnibox
**Prompt:** `In Google Chrome, open a new tab and navigate to https://trycua.com.`
-**Exercises:** `hotkey(["cmd","t"])` + `type_text_chars` + Return. Chrome's omnibox typically isn't AX-exposed even after activation.
+**Exercises:** `hotkey(["cmd","t"])` + `type_text` + Return. Chrome's omnibox typically isn't AX-exposed even after activation; `type_text` automatically falls back to CGEvent synthesis for Chromium/Electron inputs.
**Success:**
- A new Chrome tab whose AX title contains `Cua` or `trycua` is present.
diff --git a/libs/cua-driver/Skills/cua-driver/WEB_APPS.md b/libs/cua-driver/Skills/cua-driver/WEB_APPS.md
index 6fbaef9e21..312525d8af 100644
--- a/libs/cua-driver/Skills/cua-driver/WEB_APPS.md
+++ b/libs/cua-driver/Skills/cua-driver/WEB_APPS.md
@@ -46,10 +46,10 @@ pixels:
`hotkey({pid, keys: ["cmd", "enter"]})`, `hotkey({pid, keys:
["cmd", "k"]})`, etc. Posted via `CGEvent.postToPid`, reaches the
target regardless of AX state, no activation required.
-3. For typing into web inputs where `type_text` silently drops
- (input doesn't implement `AXSelectedText`), use `type_text_chars`
- — pure CGEvent keystrokes reach any focused keyboard receiver,
- including Unicode / emoji.
+3. For typing into web inputs, use `type_text` — it automatically
+ falls back to CGEvent synthesis when the input doesn't implement
+ `AXSelectedText`, reaching any focused keyboard receiver including
+ Unicode / emoji.
4. If none of the above reaches the target, tell the user this
interaction isn't reachable from the driver today and ask for
guidance.
@@ -86,7 +86,7 @@ documented only as historical context:
```
# DON'T DO THIS — ⌘L steals focus. Use launch_app above.
hotkey({pid, keys: ["cmd", "l"]})
-type_text_chars({pid, text: "https://cua.ai", delay_ms: 30})
+type_text({pid, text: "https://cua.ai", delay_ms: 30})
get_window_state({pid, window_id})
click({pid, window_id, element_index: <suggestion>})
```
@@ -157,7 +157,7 @@ When the target window is **minimized** (genie'd into the Dock):
`AXFocused=true` on a minimized window's descendants doesn't
propagate to real keyboard focus). Symptom: macOS system-alert
beep, or silent no-op. Example: `hotkey cmd+L` +
- `type_text_chars URL` + `press_key return` on minimized Chrome —
+ `type_text URL` + `press_key return` on minimized Chrome —
the URL lands in the omnibox AX value but Return doesn't commit
the navigation.
- **Primary workaround — use `set_value` to commit directly**: For
@@ -465,6 +465,7 @@ type_text({pid, window_id, element_index: <input_field>, text: "…"})
```
If it silently drops (some web inputs don't implement
-`AXSelectedText`), click the field first, then use
-`type_text_chars({pid, text})` — pure CGEvent keystrokes delivered
-to the pid, reaching any focused keyboard receiver.
+`AXSelectedText`), `type_text` automatically falls back to CGEvent
+synthesis — pure CGEvent keystrokes delivered to the pid, reaching
+any focused keyboard receiver. You can also click the field first
+to ensure focus before typing.
diff --git a/libs/cua-driver/Sources/CuaDriverCLI/CallCommand.swift b/libs/cua-driver/Sources/CuaDriverCLI/CallCommand.swift
index 46488d59b1..8320df85c3 100644
--- a/libs/cua-driver/Sources/CuaDriverCLI/CallCommand.swift
+++ b/libs/cua-driver/Sources/CuaDriverCLI/CallCommand.swift
@@ -113,7 +113,7 @@ struct CallCommand: AsyncParsableCommand {
arguments: arguments,
socketPath: daemon.resolvedSocketPath,
raw: raw,
- imageOut: screenshotOutFile,
+ screenshotOutFile: screenshotOutFile,
output: output
)
return
diff --git a/libs/cua-driver/Sources/CuaDriverCore/Capture/WindowCapture.swift b/libs/cua-driver/Sources/CuaDriverCore/Capture/WindowCapture.swift
index 631f3b9ab7..d29f1a16fd 100644
--- a/libs/cua-driver/Sources/CuaDriverCore/Capture/WindowCapture.swift
+++ b/libs/cua-driver/Sources/CuaDriverCore/Capture/WindowCapture.swift
@@ -100,7 +100,7 @@ public actor WindowCapture {
}
/// Capture a single window by its CGWindowID / kCGWindowNumber.
- /// Pairs with `get_accessibility_tree` which returns each window's `id`.
+ /// Get window ids from `list_windows`.
public func captureWindow(
windowID: UInt32,
format: ImageFormat = .png,
diff --git a/libs/cua-driver/Sources/CuaDriverServer/ToolRegistry.swift b/libs/cua-driver/Sources/CuaDriverServer/ToolRegistry.swift
index c5ef3cd6ca..6a152bf3e1 100644
--- a/libs/cua-driver/Sources/CuaDriverServer/ToolRegistry.swift
+++ b/libs/cua-driver/Sources/CuaDriverServer/ToolRegistry.swift
@@ -37,7 +37,6 @@ public struct ToolRegistry: Sendable {
"drag",
"scroll",
"type_text",
- "type_text_chars",
"press_key",
"hotkey",
"set_value",
@@ -219,12 +218,11 @@ public struct ToolRegistry: Sendable {
GetScreenSizeTool.handler,
CheckPermissionsTool.handler,
ScreenshotTool.handler,
- GetAccessibilityTreeTool.handler,
+
GetCursorPositionTool.handler,
MoveCursorTool.handler,
ScrollTool.handler,
TypeTextTool.handler,
- TypeTextCharsTool.handler,
PressKeyTool.handler,
HotkeyTool.handler,
GetWindowStateTool.handler,
diff --git a/libs/cua-driver/Sources/CuaDriverServer/Tools/GetAccessibilityTreeTool.swift b/libs/cua-driver/Sources/CuaDriverServer/Tools/GetAccessibilityTreeTool.swift
deleted file mode 100644
index 6636acea24..0000000000
--- a/libs/cua-driver/Sources/CuaDriverServer/Tools/GetAccessibilityTreeTool.swift
+++ /dev/null
@@ -1,48 +0,0 @@
-import CuaDriverCore
-import Foundation
-import MCP
-
-public enum GetAccessibilityTreeTool {
- public static let handler = ToolHandler(
- tool: Tool(
- name: "get_accessibility_tree",
- description: """
- Return a lightweight snapshot of the desktop: running regular apps and
- on-screen visible windows with their bounds, z-order, and owner pid.
-
- For the full AX subtree of a single window (with interactive element
- indices you can click by), use `get_window_state` instead — that's the
- heavy per-window tool. This one is a fast discovery read that needs no
- TCC grants.
- """,
- inputSchema: [
- "type": "object",
- "properties": [:],
- "additionalProperties": false,
- ],
- annotations: .init(
- readOnlyHint: true,
- destructiveHint: false,
- idempotentHint: true,
- openWorldHint: false
- )
- ),
- invoke: { _ in
- let apps = AppEnumerator.runningApps()
- let windows = WindowEnumerator.visibleWindows()
- var lines = ["✅ \(apps.count) running app(s), \(windows.count) visible window(s)"]
- for app in apps {
- lines.append("- \(app.name) (pid \(app.pid))")
- }
- let summary = lines.joined(separator: "\n")
- return CallTool.Result(
- content: [.text(text: summary, annotations: nil, _meta: nil)]
- )
- }
- )
-
- struct Output: Codable, Sendable {
- let applications: [AppInfo]
- let windows: [WindowInfo]
- }
-}
diff --git a/libs/cua-driver/Sources/CuaDriverServer/Tools/ScreenshotTool.swift b/libs/cua-driver/Sources/CuaDriverServer/Tools/ScreenshotTool.swift
index c11e7e1c1e..5c87622094 100644
--- a/libs/cua-driver/Sources/CuaDriverServer/Tools/ScreenshotTool.swift
+++ b/libs/cua-driver/Sources/CuaDriverServer/Tools/ScreenshotTool.swift
@@ -14,8 +14,7 @@ public enum ScreenshotTool {
image data in the requested format (default png).
Without `window_id`, captures the full main display. With `window_id`,
- captures just that window (pair with `get_accessibility_tree` which
- returns window ids).
+ captures just that window (get the id from `list_windows`).
Requires the Screen Recording TCC grant — call `check_permissions`
first if unsure.
diff --git a/libs/cua-driver/Sources/CuaDriverServer/Tools/TypeTextCharsTool.swift b/libs/cua-driver/Sources/CuaDriverServer/Tools/TypeTextCharsTool.swift
deleted file mode 100644
index 7d1da21bb5..0000000000
--- a/libs/cua-driver/Sources/CuaDriverServer/Tools/TypeTextCharsTool.swift
+++ /dev/null
@@ -1,111 +0,0 @@
-import CuaDriverCore
-import Foundation
-import MCP
-
-/// Character-by-character CGEvent typing, always targeting a specific pid.
-/// Previously this posted to the system HID tap (frontmost-routed), which
-/// was a footgun when a driver-backgrounded app typed characters into the
-/// user's real foreground app. Making pid mandatory and routing via
-/// `CGEvent.postToPid` removes the footgun.
-public enum TypeTextCharsTool {
- public static let handler = ToolHandler(
- tool: Tool(
- name: "type_text_chars",
- description: """
- Type `text` one character at a time, delivered directly to
- the target pid's event queue via `CGEvent.postToPid`. Each
- character is posted as a synthesized key-down/key-up pair
- whose Unicode payload is set via
- `CGEventKeyboardSetUnicodeString`, bypassing virtual-key
- mapping so accents, symbols, and emoji transmit verbatim.
-
- Use this when the AX-based `type_text` silently drops
- characters — typical for Chromium / Electron text inputs
- that don't expose `kAXSelectedText`. The target does NOT
- need to be frontmost; keyboard focus within the target pid
- determines where characters land, so focus the receiving
- element first (e.g. via `click` on the input).
-
- `delay_ms` (0-200) spaces successive characters so
- autocomplete and IME paths can keep up. Default 30.
- """,
- inputSchema: [
- "type": "object",
- "required": ["pid", "text"],
- "properties": [
- "pid": [
- "type": "integer",
- "description": "Target process ID.",
- ],
- "text": [
- "type": "string",
- "description": "Text to type into the target's focused element.",
- ],
- "delay_ms": [
- "type": "integer",
- "minimum": 0,
- "maximum": 200,
- "description":
- "Milliseconds between successive characters. Default 30.",
- ],
- ],
- "additionalProperties": false,
- ],
- annotations: .init(
- readOnlyHint: false,
- destructiveHint: true,
- idempotentHint: false,
- openWorldHint: true
- )
- ),
- invoke: { arguments in
- guard let rawPid = arguments?["pid"]?.intValue else {
- return errorResult("Missing required integer field pid.")
- }
- guard let text = arguments?["text"]?.stringValue else {
- return errorResult("Missing required string field text.")
- }
- let delayMs = arguments?["delay_ms"]?.intValue ?? 30
- guard let pid = Int32(exactly: rawPid) else {
- return errorResult(
- "pid \(rawPid) is outside the supported Int32 range.")
- }
-
- do {
- try KeyboardInput.typeCharacters(
- text,
- delayMilliseconds: delayMs,
- toPid: pid
- )
- let summary =
- "✅ Typed \(text.count) character(s) on pid \(rawPid) with \(delayMs)ms delay."
- return CallTool.Result(
- content: [.text(text: summary, annotations: nil, _meta: nil)]
- )
- } catch let error as KeyboardError {
- return errorResult(error.description)
- } catch {
- return errorResult("Unexpected error: \(error)")
- }
- }
- )
-
- struct Result: Codable, Sendable {
- let pid: Int
- let characterCount: Int
- let delayMilliseconds: Int
-
- private enum CodingKeys: String, CodingKey {
- case pid
- case characterCount = "character_count"
- case delayMilliseconds = "delay_ms"
- }
- }
-
- private static func errorResult(_ message: String) -> CallTool.Result {
- CallTool.Result(
- content: [.text(text: message, annotations: nil, _meta: nil)],
- isError: true
- )
- }
-}
diff --git a/libs/cua-driver/Sources/CuaDriverServer/Tools/TypeTextTool.swift b/libs/cua-driver/Sources/CuaDriverServer/Tools/TypeTextTool.swift
index 984474f842..16035c3599 100644
--- a/libs/cua-driver/Sources/CuaDriverServer/Tools/TypeTextTool.swift
+++ b/libs/cua-driver/Sources/CuaDriverServer/Tools/TypeTextTool.swift
@@ -3,31 +3,28 @@ import Foundation
import MCP
/// Unified text-insertion primitive — always targets a specific pid.
-/// Previously there were two tools (`type_text` which wrote to whatever
-/// was system-focused, and `type_text_in` which targeted a pid + element).
-/// The system-focused variant was a footgun because any driver-backgrounded
-/// app that triggered it would write characters into the user's real
-/// foreground app. Merging them under a mandatory-pid shape removes the
-/// footgun; the old `type_text_in` is gone.
///
-/// `element_index` is optional. When present, the element is looked up
-/// from the last `get_window_state` snapshot and focused before the write —
-/// the canonical path for "fill this specific text field." When absent,
-/// the write targets whatever element currently has focus within the
-/// target pid's AX tree (`AXUIElementCreateApplication(pid)` +
-/// `AXFocusedUIElement`), which is the cheaper path when focus was
-/// already established by a prior click.
+/// Tries `AXSetAttribute(kAXSelectedText)` first (fast, bulk insert).
+/// If the target element rejects the AX write (Chromium / Electron inputs
+/// that don't expose `kAXSelectedText`), automatically falls back to
+/// `KeyboardInput.typeCharacters` — character-by-character CGEvent synthesis
+/// via `CGEvent.postToPid`. The fallback path is noted in the response summary
+/// so callers can tell which path was taken.
public enum TypeTextTool {
public static let handler = ToolHandler(
tool: Tool(
name: "type_text",
description: """
- Insert text into the target pid via
- `AXSetAttribute(kAXSelectedText)`. Works for standard Cocoa
- text fields and text views. No keystrokes are synthesized —
- special keys (Return / Escape / arrows) go through
- `press_key` / `hotkey`. For Chromium / Electron inputs that
- don't implement `kAXSelectedText`, use `type_text_chars`.
+ Insert text into the target pid. Tries
+ `AXSetAttribute(kAXSelectedText)` first (fast bulk insert —
+ works for standard Cocoa text fields). If the target element
+ rejects the AX write, automatically falls back to
+ character-by-character `CGEvent.postToPid` synthesis —
+ reaches Chromium / Electron inputs and any surface that
+ doesn't implement `kAXSelectedText`.
+
+ Special keys (Return, Escape, arrows, Tab) go through
+ `press_key` / `hotkey` — they are not text.
Optional `element_index` + `window_id` (from the last
`get_window_state` snapshot of that window) pre-focuses
@@ -36,8 +33,11 @@ public enum TypeTextTool {
targets the pid's currently-focused element — useful
after a prior click already set focus.
- Requires Accessibility. Returns isError=true when the
- target element has no focus / rejects the attribute write.
+ `delay_ms` (0–200, default 30) spaces successive characters
+ in the CGEvent fallback path so autocomplete and IME can keep
+ up; ignored when the AX path succeeds.
+
+ Requires Accessibility.
""",
inputSchema: [
"type": "object",
@@ -61,6 +61,13 @@ public enum TypeTextTool {
"description":
"CGWindowID for the window whose get_window_state produced the element_index. Required when element_index is used.",
],
+ "delay_ms": [
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 200,
+ "description":
+ "Milliseconds between characters in the CGEvent fallback path. Default 30. Ignored when the AX path succeeds.",
+ ],
],
"additionalProperties": false,
],
@@ -80,6 +87,7 @@ public enum TypeTextTool {
}
let elementIndex = arguments?["element_index"]?.intValue
let rawWindowId = arguments?["window_id"]?.intValue
+ let delayMs = arguments?["delay_ms"]?.intValue ?? 30
guard let pid = Int32(exactly: rawPid) else {
return errorResult(
"pid \(rawPid) is outside the supported Int32 range.")
@@ -91,6 +99,9 @@ public enum TypeTextTool {
+ "the same window_id you used in `get_window_state`.")
}
+ // Attempt AX bulk-insert. On any AXInputError fall back to
+ // CGEvent character synthesis, which reaches Chromium / Electron
+ // inputs that don't expose kAXSelectedText.
do {
if let index = elementIndex, let rawWindowId {
guard let windowId = UInt32(exactly: rawWindowId) else {
@@ -101,38 +112,58 @@ public enum TypeTextTool {
pid: pid,
windowId: windowId,
elementIndex: index)
- try await AppStateRegistry.focusGuard.withFocusSuppressed(
- pid: pid, element: element
- ) {
+ do {
+ try await AppStateRegistry.focusGuard.withFocusSuppressed(
+ pid: pid, element: element
+ ) {
+ try AXInput.setAttribute(
+ "AXSelectedText",
+ on: element,
+ value: text as CFTypeRef
+ )
+ }
+ let target = AXInput.describe(element)
+ let summary =
+ "✅ Inserted \(text.count) char(s) into [\(index)] \(target.role ?? "?") \"\(target.title ?? "")\" on pid \(rawPid) via AX."
+ return CallTool.Result(
+ content: [.text(text: summary, annotations: nil, _meta: nil)]
+ )
+ } catch is AXInputError {
+ // AX rejected — fall through to CGEvent synthesis.
+ }
+ } else {
+ do {
+ let element = try AXInput.focusedElement(pid: pid)
try AXInput.setAttribute(
"AXSelectedText",
on: element,
value: text as CFTypeRef
)
+ let target = AXInput.describe(element)
+ let summary =
+ "✅ Inserted \(text.count) char(s) into focused \(target.role ?? "?") \"\(target.title ?? "")\" on pid \(rawPid) via AX."
+ return CallTool.Result(
+ content: [.text(text: summary, annotations: nil, _meta: nil)]
+ )
+ } catch is AXInputError {
+ // AX rejected — fall through to CGEvent synthesis.
}
- let target = AXInput.describe(element)
- let summary =
- "✅ Inserted \(text.count) char(s) into [\(index)] \(target.role ?? "?") \"\(target.title ?? "")\" on pid \(rawPid)."
- return CallTool.Result(
- content: [.text(text: summary, annotations: nil, _meta: nil)]
- )
- } else {
- let element = try AXInput.focusedElement(pid: pid)
- try AXInput.setAttribute(
- "AXSelectedText",
- on: element,
- value: text as CFTypeRef
- )
- let target = AXInput.describe(element)
- let summary =
- "✅ Inserted \(text.count) char(s) into focused \(target.role ?? "?") \"\(target.title ?? "")\" on pid \(rawPid)."
- return CallTool.Result(
- content: [.text(text: summary, annotations: nil, _meta: nil)]
- )
}
+
+ // CGEvent fallback path.
+ try KeyboardInput.typeCharacters(
+ text,
+ delayMilliseconds: delayMs,
+ toPid: pid
+ )
+ let summary =
+ "✅ Typed \(text.count) char(s) on pid \(rawPid) via CGEvent (AX fallback, \(delayMs)ms delay)."
+ return CallTool.Result(
+ content: [.text(text: summary, annotations: nil, _meta: nil)]
+ )
} catch let error as AppStateError {
return errorResult(error.description)
- } catch let error as AXInputError {
+ } catch let error as KeyboardError {
return errorResult(error.description)
} catch {
return errorResult("Unexpected error: \(error)")