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): add checked state verification (#2705)

Francesco Bonacci84440ddc6d42
diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
index 8fb9c52158..d3c49bc809 100644
--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx
+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx
@@ -12,7 +12,7 @@ description: Reference for every MCP tool Cua Driver exposes
import { Callout } from 'fumadocs-ui/components/callout';
-`cua-driver` exposes 49 MCP tools through a single stdio server (`cua-driver mcp`). Every tool is also callable from the shell as `cua-driver <name> '<JSON-args>'`.
+`cua-driver` exposes 50 MCP tools through a single stdio server (`cua-driver mcp`). Every tool is also callable from the shell as `cua-driver <name> '<JSON-args>'`.
Tool names are `snake_case`. Responses are MCP `CallTool.Result` envelopes: a text content block prefixed with a `✅` summary (or the error reason on failure), plus optional image or structured-content blocks on tools that produce them. See the [CLI reference](/reference/cua-driver/cli-reference) for CLI-specific options like `--socket` and `--screenshot-out-file`.
@@ -75,8 +75,8 @@ Optional `max_elements` / `max_depth` bound the AX walk to mitigate context-wind
- `capture_mode` (string, optional): DEPRECATED and ignored. get_window_state always returns BOTH the element tree and a screenshot — ground on both. The modality is chosen at action time by how you address the target: an element ax action (element_index/element_token) or an element px action (x,y). Any value (including the old "som"/"screenshot" aliases) is accepted but has no effect.
- `include_screenshot` (boolean, optional): Default true — returns a grounding screenshot alongside the tree. Set false to skip the grab and return the tree only (the cheap path when you're just re-indexing before an element ax action; saves the image tokens + screen-grab latency). screenshot_out_file still forces a capture to disk.
-- `max_depth` (integer, optional): Cap on the AX-tree walk depth. Nodes whose rendered indent would exceed this are omitted. Omit for the default (25). Lower this for deep menu/Electron trees.
-- `max_elements` (integer, optional): Cap on the total number of AX nodes walked. Truncates depth-first; markdown and structured elements truncate together. Omit for the default (2 000). Lower this for Electron / Obsidian / large web apps that produce 10k+ element trees and blow context windows.
+- `max_depth` (integer, optional): Cap on the AX-tree walk depth. Nodes whose rendered indent would exceed this are omitted. Omit for the default (25). Lower this for deep menu/Electron trees. range: 1–unbounded
+- `max_elements` (integer, optional): Cap on the total number of AX nodes walked. Truncates depth-first; markdown and structured elements truncate together. Omit for the default (2 000). Lower this for Electron / Obsidian / large web apps that produce 10k+ element trees and blow context windows. range: 1–unbounded
- `pid` (integer, required): Target process ID.
- `query` (string, optional): Case-insensitive filter for tree_markdown.
- `screenshot_out_file` (string, optional): When set, write the PNG to this file path (~ expanded) instead of embedding base64 in the response. The structured output will contain screenshot_file_path instead.
@@ -297,15 +297,15 @@ When `from_zoom` is true, coordinates are in the last zoom image for this pid; t
- `button` (string, optional): Mouse button used for the drag. Default: left.
- `delivery_mode` (string, optional): Best-effort-background ladder rung (default "background"). "background": inject without fronting or raising the target — no focus steal. "foreground": briefly front the target, act, then restore the prior frontmost — the explicit last resort when a background attempt didn't land. Re-call with "foreground" only for the action that needs it.
-- `duration_ms` (integer, optional): Wall-clock duration of the drag path between mouseDown and mouseUp. Default: 500.
+- `duration_ms` (integer, optional): Wall-clock duration of the drag path between mouseDown and mouseUp. Default: 500. range: 0–10000
- `from_x` (number, required): Drag-start X in window-local screenshot pixels. Top-left origin.
- `from_y` (number, required): Drag-start Y in window-local screenshot pixels. Top-left origin.
- `from_zoom` (boolean, optional): When true, coordinates are in the last zoom image for this pid; driver maps back to window coordinates.
- `modifier` (array of string, optional): Modifier keys held across the entire gesture: cmd/shift/option/ctrl.
- `pid` (integer, optional): Target process ID.
-- `scope` (string, optional): Use desktop with no pid/window_id for native get_desktop_state screenshot coordinates.
+- `scope` (string, optional): Use desktop with no pid/window_id for native get_desktop_state screenshot coordinates. default: `"window"`
- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
-- `steps` (integer, optional): Number of intermediate mouseDragged events linearly interpolated along the path. Default: 20.
+- `steps` (integer, optional): Number of intermediate mouseDragged events linearly interpolated along the path. Default: 20. range: 1–200
- `to_x` (number, required): Drag-end X in window-local screenshot pixels.
- `to_y` (number, required): Drag-end Y in window-local screenshot pixels.
- `window_id` (integer, optional): CGWindowID for the window the pixel coordinates were measured against. Optional — when omitted the driver picks the frontmost window of pid.
@@ -324,12 +324,12 @@ WEB CONTENT (Chromium/WebKit/Electron — browser tabs, Slack, VS Code, X's comp
**Arguments:**
-- `delay_ms` (integer, optional): Milliseconds between characters in the CGEvent fallback path. Default 30. Ignored when the AX path succeeds.
+- `delay_ms` (integer, optional): Milliseconds between characters in the CGEvent fallback path. Default 30. Ignored when the AX path succeeds. range: 0–200
- `delivery_mode` (string, optional): Best-effort-background ladder rung (default "background"). "background": AX insert, then CGEvent keystrokes if needed — no focus steal; native controls can be verified via AXValue read-back, while web-content read-back remains unverified. "foreground": briefly front the window, type, restore the prior frontmost — the explicit last resort for focus-sensitive surfaces (e.g. WhatsApp/Catalyst) where background keystrokes don't land. Re-call with "foreground" when a background attempt returns `verified:false` and a screenshot shows the text didn't appear.
- `element_index` (integer, optional): Element index from last get_window_state. Directs the write to a specific field. REQUIRES `pid` and `window_id` to be passed alongside it — element_index alone (no pid) fails fast with "Missing required integer field: pid"; it is not a silent no-op.
- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Takes precedence over element_index when both supplied. Returns an explicit "stale" error if the snapshot has been superseded.
- `pid` (integer, optional): Target process ID.
-- `scope` (string, optional): Use desktop with no pid/window_id to type into the frontmost application.
+- `scope` (string, optional): Use desktop with no pid/window_id to type into the frontmost application. default: `"window"`
- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
- `text` (string, required): Text to insert at the target's cursor.
- `window_id` (integer, optional): CGWindowID. Required when element_index is used. Optional when element_token is supplied (the token carries it).
@@ -356,7 +356,7 @@ A key press is never driver-verifiable → effect:"unverifiable"; confirm via sc
- `key` (string, required): Key name: return, tab, escape, up, down, etc.
- `modifiers` (array of string, optional): Modifier keys: cmd, shift, option/alt, ctrl, fn.
- `pid` (integer, optional)
-- `scope` (string, optional): Use desktop with no pid/window_id to send the key to the frontmost application.
+- `scope` (string, optional): Use desktop with no pid/window_id to send the key to the frontmost application. default: `"window"`
- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
- `window_id` (integer, optional): Target window. Required for delivery_mode:"foreground". Does NOT itself raise the window — raising is gated on delivery_mode.
- `x` (number, optional): Screenshot-pixel X — the element px action form: pixel-click there to focus, then send the key. Use when the key must go to a Chromium/Electron surface the AX path can't focus. Pass with y, no element_index.
@@ -379,9 +379,9 @@ Recognized modifiers: cmd/command, shift, option/alt, ctrl/control, fn. Non-modi
**Arguments:**
- `delivery_mode` (string, optional): Best-effort-background ladder rung (default "background"). "background": inject without fronting or raising the target — no focus steal. "foreground": briefly front the target, act, then restore the prior frontmost — the explicit last resort when a background attempt didn't land. Re-call with "foreground" only for the action that needs it.
-- `keys` (array of string, required): Modifier(s) and one non-modifier key, e.g. ["cmd", "c"].
+- `keys` (array of string, required): Modifier(s) and one non-modifier key, e.g. ["cmd", "c"]. items: 2–unbounded
- `pid` (integer, optional): Target process ID.
-- `scope` (string, optional): Use desktop with no pid/window_id to send the chord to the frontmost application.
+- `scope` (string, optional): Use desktop with no pid/window_id to send the chord to the frontmost application. default: `"window"`
- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
- `window_id` (integer, optional): Target window. Required for delivery_mode:"foreground" (the NSMenu activation needs a window). Does NOT itself raise the window — raising is gated on delivery_mode.
- `x` (number, optional): Screenshot-pixel X — the element px action form: pixel-click there to focus, then send the combo (so e.g. Cmd+V pastes into that field). Pass with y. Use for Chromium/Electron surfaces the background combo can't reach.
@@ -426,14 +426,14 @@ Mapping: by='page' → larger step; by='line' → smaller step; amount = number
**Arguments:**
-- `amount` (integer, optional): Pixel-wheel path: number of wheel notches. Keystroke path: number of keystroke repetitions. Default: 3.
+- `amount` (integer, optional): Pixel-wheel path: number of wheel notches. Keystroke path: number of keystroke repetitions. Default: 3. range: 1–50
- `by` (string, optional): Scroll granularity. Default: line.
- `delivery_mode` (string, optional): Best-effort-background ladder rung (default "background"). "background": inject without fronting or raising the target — no focus steal. "foreground": briefly front the target, act, then restore the prior frontmost — the explicit last resort when a background attempt didn't land. Re-call with "foreground" only for the action that needs it.
- `direction` (string, required): Scroll direction.
- `element_index` (integer, optional): Element from last get_window_state. Routes through the pixel-wheel path AT this element's center — use it to scroll a nested overflow region you located in the AX tree.
- `element_token` (string, optional): Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Takes precedence over element_index when both supplied. Returns an explicit "stale" error if the snapshot has been superseded. Routes through the pixel-wheel path at the element's center.
- `pid` (integer, optional)
-- `scope` (string, optional): Use desktop with x,y and no pid/window_id for native get_desktop_state screenshot coordinates.
+- `scope` (string, optional): Use desktop with x,y and no pid/window_id for native get_desktop_state screenshot coordinates. default: `"window"`
- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
- `window_id` (integer, optional)
- `x` (number, optional): Window-local screenshot X (top-left origin of the PNG from get_window_state). With `y`, routes through the pixel-wheel path at this point — use for a scrollable surface that isn't in the AX tree. Requires window_id to anchor the window→screen conversion.
@@ -450,7 +450,7 @@ Move a cursor to (x, y). In window scope (default), moves only the agent cursor
**Arguments:**
- `cursor_id` (string, optional): Cursor instance to move. Default: 'default'.
-- `scope` (string, optional)
+- `scope` (string, optional): default: `"window"`
- `session` (string, optional): Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.
- `x` (number, required)
- `y` (number, required)
@@ -498,7 +498,7 @@ Actions:
- `action` (string, required): Action to perform.
- `attributes` (array of string, optional): Element attributes to include in query_dom results.
- `bundle_id` (string, optional): Bundle ID of the browser. Required for enable_javascript_apple_events (macOS only).
-- `cdp_port` (integer, optional): Optional, for execute_javascript/insert_text/type_keystrokes: use this exact CDP port instead of auto-discovering one from pid. Needed when the port was opened via the browser's own remote-debugging toggle rather than a launch-time flag, since that path may not answer the auto-discovery probe.
+- `cdp_port` (integer, optional): Optional, for execute_javascript/insert_text/type_keystrokes: use this exact CDP port instead of auto-discovering one from pid. Needed when the port was opened via the browser's own remote-debugging toggle rather than a launch-time flag, since that path may not answer the auto-discovery probe. range: 1–65535
- `css_selector` (string, optional): CSS selector for query_dom (e.g. 'a', 'button', 'input', 'h1'-'h6', 'p', 'img', 'select', '*').
- `javascript` (string, optional): JavaScript to execute. Required for execute_javascript.
- `pid` (integer, optional): Target process ID.
@@ -564,7 +564,7 @@ Caveats:
**Arguments:**
-- `delay_ms` (integer, optional): Milliseconds to sleep between turns, for human-observable pacing. Default 500.
+- `delay_ms` (integer, optional): Milliseconds to sleep between turns, for human-observable pacing. Default 500. range: 0–10000
- `dir` (string, required): Trajectory directory previously written by `start_recording`. Absolute or ~-rooted.
- `stop_on_error` (boolean, optional): Stop replay on the first tool-call error. Default true — set false to best-effort through the full trajectory.
@@ -594,8 +594,8 @@ Declare a session — a named, color-coded identity for THIS agent run. Pass a s
**Arguments:**
-- `capture_scope` (string, optional): Per-session perception/action modality. auto starts window-only and requires explicit escalation before desktop tools; window and desktop are strict. Immutable for the live session.
-- `cursor_theme` (object,null, optional): Optional initial cursor theme. The host applies it before the cursor is
+- `capture_scope` (string, optional): Per-session perception/action modality. auto starts window-only and requires explicit escalation before desktop tools; window and desktop are strict. Immutable for the live session. default: `"auto"`
+- `cursor_theme` (object or null, optional): Optional initial cursor theme. The host applies it before the cursor is
first made visible, avoiding a flash of the default theme.
- `session` (string, required): Stable session id for this run (e.g. "research-run-1").
@@ -634,16 +634,16 @@ Configure only movement physics and visibility timing for a session cursor.
**Arguments:**
-- `arc_flow` (number,null, optional)
-- `arc_size` (number,null, optional)
-- `dwell_after_click_ms` (number,null, optional)
-- `end_handle` (number,null, optional)
-- `glide_duration_ms` (number,null, optional)
-- `idle_hide_ms` (number,null, optional)
+- `arc_flow` (number or null, optional)
+- `arc_size` (number or null, optional)
+- `dwell_after_click_ms` (number or null, optional)
+- `end_handle` (number or null, optional)
+- `glide_duration_ms` (number or null, optional)
+- `idle_hide_ms` (number or null, optional)
- `session` (string, required)
-- `spring` (number,null, optional)
-- `start_handle` (number,null, optional)
-- `turn_radius` (number,null, optional)
+- `spring` (number or null, optional)
+- `start_handle` (number or null, optional)
+- `turn_radius` (number or null, optional)
```json
{"session":"example"}
@@ -660,7 +660,7 @@ Returns: `accessibility` + `screen_recording` (booleans from the TCC preflight A
**Arguments:**
- `probe_direct_capture` (boolean, optional): When prompting and Screen Recording is granted, also run the live ScreenCaptureKit probe that may raise Tahoe's direct-capture consent. Default true. Set false for a staged Accessibility/Screen Recording request.
-- `prompt` (boolean, optional): Raise the system permission prompts for missing grants. Default false; only a trusted host setup route may set true.
+- `prompt` (boolean, optional): Raise the system permission prompts for missing grants. Default false; only a trusted host setup route may set true. default: `false`
### `health_report`
@@ -728,13 +728,32 @@ Install the ffmpeg binary used by start_recording's video capture (Linux/Windows
## Other tools
+### `verify_state`
+
+Deterministically verify bounded predicates against one exact window. The driver evaluates structured window/accessibility state and may return the final screenshot as uninterpreted visual evidence for a multimodal caller. Predicate results are satisfied, unsatisfied, or unknown; unknown never implies success. Accessibility projections are conservative: absence remains unknown unless the observed search domain is proven exhaustive.
+
+**Arguments:**
+
+- `expect` (array of object, required): One to eight predicates, combined with logical AND. items: 1–8
+- `include_screenshot` (boolean or null, optional): Return the final window screenshot as image content for a multimodal
+caller. The driver does not interpret that image.
+- `pid` (integer, required): Exact process whose window may be observed. range: 1–unbounded
+- `session` (string, optional): Optional session id for capture-scope and authorization continuity.
+- `stable_samples` (integer, optional): Consecutive satisfied samples required before returning success. default: `2`; range: 1–5
+- `timeout_ms` (integer, optional): Bounded wait. Zero performs one sample. default: `5000`; range: 0–10000
+- `window_id` (integer, required): Exact native window identifier.
+
+```json
+{"expect":[{"window":{"exists":true}}],"pid":844,"window_id":10725}
+```
+
### `set_agent_cursor_theme`
Select an already-installed cursor theme for a session.
**Arguments:**
-- `reduced_motion` (string, optional)
+- `reduced_motion` (string, optional): default: `"auto"`
- `session` (string, required)
- `theme_id` (string, required)
@@ -749,7 +768,7 @@ Read-only browser inspection. Mode 1 (bind): pass pid + window_id of a native br
**Arguments:**
- `continuation` (string, optional): Opaque continuation minted by an earlier semantic_v2 response.
-- `include_screenshot` (boolean, optional): Capture the exact tab viewport as PNG through CDP without selecting the tab or foregrounding its native window. The request refuses if capture cannot be completed.
+- `include_screenshot` (boolean, optional): Capture the exact tab viewport as PNG through CDP without selecting the tab or foregrounding its native window. The request refuses if capture cannot be completed. default: `false`
- `pid` (integer, optional): Native browser process id (bind mode).
- `query` (string, optional): Read-only semantic match over role, accessible name, and visible text.
- `scope_ref` (string, optional): Current semantic/content ref whose subtree should be observed.
@@ -835,7 +854,7 @@ Inspect or resolve a page-owned JavaScript alert, confirm, prompt, or beforeunlo
**Arguments:**
- `action` (string, required)
-- `delivery_mode` (string, optional): Requested foreground posture for accept/dismiss. Linux Chromium requires foreground; inspect is read-only.
+- `delivery_mode` (string, optional): Requested foreground posture for accept/dismiss. Linux Chromium requires foreground; inspect is read-only. default: `"background"`
- `dialog_id` (string, optional): Opaque current dialog generation returned by action=inspect.
- `prompt_text` (string, optional): Sensitive response text, valid only when accepting a prompt dialog.
- `session` (string, optional): Stable caller-declared session id. Browser targets, tabs, and refs are scoped to this session.
@@ -852,7 +871,7 @@ Assign one or more explicit absolute local files to an exact live &lt;input type
**Arguments:**
-- `files` (array of string, required)
+- `files` (array of string, required): items: 1–32
- `ref` (string, required): Page element ref in the p&lt;snapshot&gt;:&lt;index&gt; namespace from get_browser_state. Refs are invalidated by navigation and by newer snapshots of the same tab.
- `session` (string, optional): Stable caller-declared session id. Browser targets, tabs, and refs are scoped to this session.
- `tab_id` (string, required): Opaque tab id from get_browser_state (session-scoped).
@@ -888,7 +907,7 @@ Perform hover, right-click, double-click, scroll, or drag in an exactly-bound br
- `delta_x` (number, optional): Horizontal scroll delta in CSS pixels.
- `delta_y` (number, optional): Vertical scroll delta in CSS pixels.
- `destination_ref` (string, optional): Drag destination page ref in the exact same frame.
-- `input_route` (string, optional)
+- `input_route` (string, optional): default: `"trusted"`
- `ref` (string, optional): Origin page ref. Alternative to x/y.
- `session` (string, required): Explicit caller session owning the browser capabilities.
- `tab_id` (string, required): Opaque tab id minted by get_browser_state.
diff --git a/libs/cua-driver/contract/README.md b/libs/cua-driver/contract/README.md
index 04a35f60eb..69d5b7ebac 100644
--- a/libs/cua-driver/contract/README.md
+++ b/libs/cua-driver/contract/README.md
@@ -44,6 +44,18 @@ Cursor artwork is selected by installed theme ID. Theme installation and
dotLottie compilation are intentionally local CLI operations, not SDK or MCP
tool calls.
+The checked-observation slice is also shared by MCP and both generated SDKs:
+
+- `verify_state` evaluates one to eight ANDed predicates against one exact
+ `(pid, window_id)`.
+- Window existence/bounds and semantic accessibility element
+ existence/value/enabled/selected predicates return `satisfied`,
+ `unsatisfied`, or `unknown`.
+- A bounded poll can require consecutive stable samples. `unknown` never
+ implies success.
+- `include_screenshot=true` adds final image content for a multimodal agent
+ harness to interpret. Cua Driver does not OCR or assign task meaning to it.
+
Session contracts are marked `canonical_runtime`: the same typed Rust input,
output, and metadata declaration builds the live MCP tool. Desktop contracts
are marked `portable_subset`: their typed Rust inputs are a deliberately
@@ -68,7 +80,7 @@ Compatibility is tracked separately at each boundary:
| Field | Current | Meaning |
| --- | --- | --- |
-| `contract_version` | `0.2.0` | Generated manifest and typed SDK shape |
+| `contract_version` | `0.3.0` | Generated manifest and typed SDK shape |
| `tools_list_schema_version` | `1` | cua-driver `tools/list` extension shape |
| `capability_version` | `1` | Additive capability-token vocabulary |
| `mcp_protocol_version` | `2025-06-18` | MCP initialization protocol served to agent runtimes |
diff --git a/libs/cua-driver/contract/manifest.json b/libs/cua-driver/contract/manifest.json
index cb0625ff78..772cec97ac 100644
--- a/libs/cua-driver/contract/manifest.json
+++ b/libs/cua-driver/contract/manifest.json
@@ -1,7 +1,7 @@
{
"generated_notice": "Generated by cua-contract-gen; do not edit by hand.",
"experimental": true,
- "contract_version": "0.2.0",
+ "contract_version": "0.3.0",
"tools_list_schema_version": "1",
"capability_version": "1",
"mcp_protocol_version": "2025-06-18",
@@ -1630,6 +1630,275 @@
},
"type": "object"
}
+ },
+ {
+ "name": "verify_state",
+ "description": "Deterministically verify bounded predicates against one exact window. The driver evaluates structured window/accessibility state and may return the final screenshot as uninterpreted visual evidence for a multimodal caller. Predicate results are satisfied, unsatisfied, or unknown; unknown never implies success. Accessibility projections are conservative: absence remains unknown unless the observed search domain is proven exhaustive.",
+ "platforms": [
+ "macos",
+ "windows",
+ "linux"
+ ],
+ "capabilities": [
+ "state.verify",
+ "state.verify.window",
+ "state.verify.element",
+ "state.observe.visual_evidence"
+ ],
+ "annotations": {
+ "read_only": true,
+ "destructive": false,
+ "idempotent": false,
+ "open_world": false
+ },
+ "schema_mode": "portable_subset",
+ "input_schema": {
+ "additionalProperties": false,
+ "properties": {
+ "expect": {
+ "description": "One to eight predicates, combined with logical AND.",
+ "items": {
+ "additionalProperties": false,
+ "properties": {
+ "element": {
+ "additionalProperties": false,
+ "properties": {
+ "enabled": {
+ "type": [
+ "boolean",
+ "null"
+ ]
+ },
+ "exists": {
+ "description": "Assert that at least one trusted element matches the selector.\n\nElement walks are not yet exhaustive on every platform, so absence\ncannot be proven. `false` is rejected instead of returning an\nindefinitely-unknown predicate.",
+ "enum": [
+ true
+ ],
+ "type": "boolean"
+ },
+ "selected": {
+ "type": [
+ "boolean",
+ "null"
+ ]
+ },
+ "selector": {
+ "additionalProperties": false,
+ "properties": {
+ "label_contains": {
+ "minLength": 1,
+ "type": "string"
+ },
+ "role": {
+ "minLength": 1,
+ "type": "string"
+ }
+ },
+ "required": [],
+ "type": "object"
+ },
+ "value_equals": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "selector"
+ ],
+ "type": [
+ "object",
+ "null"
+ ]
+ },
+ "window": {
+ "additionalProperties": false,
+ "properties": {
+ "bounds": {
+ "additionalProperties": false,
+ "properties": {
+ "height": {
+ "type": "number"
+ },
+ "tolerance_px": {
+ "maximum": 100,
+ "minimum": 0,
+ "type": "number"
+ },
+ "width": {
+ "type": "number"
+ },
+ "x": {
+ "type": "number"
+ },
+ "y": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "x",
+ "y",
+ "width",
+ "height"
+ ],
+ "type": [
+ "object",
+ "null"
+ ]
+ },
+ "exists": {
+ "type": [
+ "boolean",
+ "null"
+ ]
+ }
+ },
+ "type": [
+ "object",
+ "null"
+ ]
+ }
+ },
+ "required": [],
+ "type": "object"
+ },
+ "maxItems": 8,
+ "minItems": 1,
+ "type": "array"
+ },
+ "include_screenshot": {
+ "description": "Return the final window screenshot as image content for a multimodal\ncaller. The driver does not interpret that image.",
+ "type": [
+ "boolean",
+ "null"
+ ]
+ },
+ "pid": {
+ "description": "Exact process whose window may be observed.",
+ "minimum": 1,
+ "type": "integer"
+ },
+ "session": {
+ "description": "Optional session id for capture-scope and authorization continuity.",
+ "type": "string"
+ },
+ "stable_samples": {
+ "default": 2,
+ "description": "Consecutive satisfied samples required before returning success.",
+ "maximum": 5,
+ "minimum": 1,
+ "type": "integer"
+ },
+ "timeout_ms": {
+ "default": 5000,
+ "description": "Bounded wait. Zero performs one sample.",
+ "maximum": 10000,
+ "minimum": 0,
+ "type": "integer"
+ },
+ "window_id": {
+ "description": "Exact native window identifier.",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "pid",
+ "window_id",
+ "expect"
+ ],
+ "type": "object"
+ },
+ "success_output_schema": {
+ "additionalProperties": true,
+ "properties": {
+ "elapsed_ms": {
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "predicates": {
+ "items": {
+ "properties": {
+ "index": {
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "observed_json": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "status": {
+ "enum": [
+ "satisfied",
+ "unsatisfied",
+ "unknown"
+ ],
+ "type": "string"
+ },
+ "unknown_reason": {
+ "anyOf": [
+ {
+ "enum": [
+ "invalid_predicate",
+ "unsupported_predicate",
+ "untrusted_source",
+ "multi_match",
+ "target_missing",
+ "observation_unavailable",
+ "stability_unproven"
+ ],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "index",
+ "status",
+ "unknown_reason",
+ "observed_json"
+ ],
+ "type": "object"
+ },
+ "type": "array"
+ },
+ "samples": {
+ "format": "uint64",
+ "minimum": 0,
+ "type": "integer"
+ },
+ "stable": {
+ "type": "boolean"
+ },
+ "status": {
+ "enum": [
+ "satisfied",
+ "unsatisfied",
+ "unknown"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "status",
+ "stable",
+ "elapsed_ms",
+ "samples",
+ "predicates"
+ ],
+ "type": "object"
+ }
}
]
}
diff --git a/libs/cua-driver/python/src/cua_driver/__init__.py b/libs/cua-driver/python/src/cua_driver/__init__.py
index 8163b42b0e..9618fbb189 100644
--- a/libs/cua-driver/python/src/cua_driver/__init__.py
+++ b/libs/cua-driver/python/src/cua_driver/__init__.py
@@ -48,6 +48,7 @@ from ._native import (
request_mac_os_permissions,
)
from ._native_contract import (
+ BoundsExpectation,
CaptureScope,
ClickButton,
ClickInput,
@@ -56,6 +57,8 @@ from ._native_contract import (
CursorThemeSelection,
DesktopScope,
DragInput,
+ ElementPredicate,
+ ElementSelector,
EndSessionInput,
EndSessionOutput,
EffectiveScope,
@@ -69,6 +72,7 @@ from ._native_contract import (
HotkeyInput,
MoveCursorInput,
Platform,
+ PredicateOutcome,
PressKeyInput,
ScrollBy,
ScrollDirection,
@@ -79,7 +83,13 @@ from ._native_contract import (
SetAgentCursorThemeInput,
StartSessionInput,
StartSessionOutput,
+ StatePredicate,
TypeTextInput,
+ UnknownReason,
+ VerificationStatus,
+ VerifyStateInput,
+ VerifyStateOutput,
+ WindowPredicate,
)
from .wrapper import get_binary_path, run_cua_driver
@@ -148,6 +158,7 @@ CuaDriver = _NativeCuaDriver
__all__ = [
"ActionCompletion",
+ "BoundsExpectation",
"CaptureScope",
"ClickButton",
"ClickInput",
@@ -159,6 +170,8 @@ __all__ = [
"CursorThemeSelection",
"DesktopScope",
"DragInput",
+ "ElementPredicate",
+ "ElementSelector",
"DriverError",
"DriverActivityEvent",
"DriverActivityKind",
@@ -197,6 +210,7 @@ __all__ = [
"MacOsPermissionStatus",
"MoveCursorInput",
"Platform",
+ "PredicateOutcome",
"PrivateWorkerOptions",
"PressKeyInput",
"RuntimeAuthorizationOptions",
@@ -210,9 +224,15 @@ __all__ = [
"SetAgentCursorThemeInput",
"StartSessionInput",
"StartSessionOutput",
+ "StatePredicate",
"ToolResult",
"TrustedSessionOptions",
"TypeTextInput",
+ "UnknownReason",
+ "VerificationStatus",
+ "VerifyStateInput",
+ "VerifyStateOutput",
+ "WindowPredicate",
"__version__",
"create_trusted_session",
"current_mac_os_permission_status",
diff --git a/libs/cua-driver/python/src/cua_driver/_native.py b/libs/cua-driver/python/src/cua_driver/_native.py
index 023cbca6da..4aa44fc6f3 100644
--- a/libs/cua-driver/python/src/cua_driver/_native.py
+++ b/libs/cua-driver/python/src/cua_driver/_native.py
@@ -568,6 +568,8 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_type_text() != 25156:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_verify_state() != 26193:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_call_tool() != 52859:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_click() != 22303:
@@ -608,6 +610,8 @@ def _uniffi_check_api_checksums(lib):
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text() != 63241:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_verify_state() != 36472:
+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_driveractivityobserver_on_activity() != 9786:
raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
if lib.uniffi_cua_driver_sdk_checksum_method_driverauthorizationhost_authorize() != 10089:
@@ -1212,6 +1216,11 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_type_text.argtypes = (
cua_driver._native_contract._UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_type_text.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_verify_state.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_verify_state.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_call_tool.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -1313,6 +1322,11 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_type_text.argtypes =
cua_driver._native_contract._UniffiRustBuffer,
)
_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_type_text.restype = ctypes.c_uint64
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_verify_state.argtypes = (
+ ctypes.c_uint64,
+ cua_driver._native_contract._UniffiRustBuffer,
+)
+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_verify_state.restype = ctypes.c_uint64
_UniffiLib.uniffi_cua_driver_sdk_fn_method_driveractivityobserver_on_activity.argtypes = (
ctypes.c_uint64,
_UniffiRustBuffer,
@@ -1497,6 +1511,9 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_start_session.restype
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_type_text.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_type_text.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_verify_state.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_verify_state.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_call_tool.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_call_tool.restype = ctypes.c_uint16
@@ -1557,6 +1574,9 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_start_session.
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text.restype = ctypes.c_uint16
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_verify_state.argtypes = (
+)
+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_verify_state.restype = ctypes.c_uint16
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_driveractivityobserver_on_activity.argtypes = (
)
_UniffiLib.uniffi_cua_driver_sdk_checksum_method_driveractivityobserver_on_activity.restype = ctypes.c_uint16
@@ -4013,6 +4033,8 @@ class _UniffiFfiConverterTypeSdkClientKind(_UniffiConverterRustBuffer):
+
+
@@ -4086,6 +4108,8 @@ class CuaDriverProtocol(typing.Protocol):
raise NotImplementedError
async def type_text(self, input: cua_driver._native_contract.TypeTextInput) -> ToolResult:
raise NotImplementedError
+ async def verify_state(self, input: cua_driver._native_contract.VerifyStateInput) -> ToolResult:
+ raise NotImplementedError
class CuaDriver(CuaDriverProtocol):
@@ -4858,6 +4882,23 @@ class CuaDriver(CuaDriverProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def verify_state(self, input: cua_driver._native_contract.VerifyStateInput) -> ToolResult:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeVerifyStateInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeVerifyStateInput.lower(input),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeToolResult.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_verify_state(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
@@ -4937,6 +4978,8 @@ class CuaDriverSessionProtocol(typing.Protocol):
raise NotImplementedError
async def type_text(self, input: cua_driver._native_contract.TypeTextInput) -> ToolResult:
raise NotImplementedError
+ async def verify_state(self, input: cua_driver._native_contract.VerifyStateInput) -> ToolResult:
+ raise NotImplementedError
class CuaDriverSession(CuaDriverSessionProtocol):
@@ -5306,6 +5349,23 @@ class CuaDriverSession(CuaDriverSessionProtocol):
_uniffi_lift_return,
_uniffi_error_converter,
)
+ async def verify_state(self, input: cua_driver._native_contract.VerifyStateInput) -> ToolResult:
+
+ cua_driver._native_contract._UniffiFfiConverterTypeVerifyStateInput.check_lower(input)
+ _uniffi_lowered_args = (
+ self._uniffi_clone_handle(),
+ cua_driver._native_contract._UniffiFfiConverterTypeVerifyStateInput.lower(input),
+ )
+ _uniffi_lift_return = _UniffiFfiConverterTypeToolResult.lift
+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError
+ return await _uniffi_rust_call_async(
+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_verify_state(*_uniffi_lowered_args),
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ _uniffi_lift_return,
+ _uniffi_error_converter,
+ )
diff --git a/libs/cua-driver/python/src/cua_driver/_native_contract.py b/libs/cua-driver/python/src/cua_driver/_native_contract.py
index c80c37775b..52c47818f2 100644
--- a/libs/cua-driver/python/src/cua_driver/_native_contract.py
+++ b/libs/cua-driver/python/src/cua_driver/_native_contract.py
@@ -763,6 +763,85 @@ class _UniffiFfiConverterFloat64(_UniffiConverterPrimitiveFloat):
def write(value, buf):
buf.write_double(value)
+class _UniffiFfiConverterOptionalFloat64(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterFloat64.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterFloat64.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterFloat64.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class BoundsExpectation:
+ def __init__(self, *, x:float, y:float, width:float, height:float, tolerance_px:typing.Optional[float]):
+ self.x = x
+ self.y = y
+ self.width = width
+ self.height = height
+ self.tolerance_px = tolerance_px
+
+
+
+
+ def __str__(self):
+ return "BoundsExpectation(x={}, y={}, width={}, height={}, tolerance_px={})".format(self.x, self.y, self.width, self.height, self.tolerance_px)
+ def __eq__(self, other):
+ if self.x != other.x:
+ return False
+ if self.y != other.y:
+ return False
+ if self.width != other.width:
+ return False
+ if self.height != other.height:
+ return False
+ if self.tolerance_px != other.tolerance_px:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeBoundsExpectation(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return BoundsExpectation(
+ x=_UniffiFfiConverterFloat64.read(buf),
+ y=_UniffiFfiConverterFloat64.read(buf),
+ width=_UniffiFfiConverterFloat64.read(buf),
+ height=_UniffiFfiConverterFloat64.read(buf),
+ tolerance_px=_UniffiFfiConverterOptionalFloat64.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterFloat64.check_lower(value.x)
+ _UniffiFfiConverterFloat64.check_lower(value.y)
+ _UniffiFfiConverterFloat64.check_lower(value.width)
+ _UniffiFfiConverterFloat64.check_lower(value.height)
+ _UniffiFfiConverterOptionalFloat64.check_lower(value.tolerance_px)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterFloat64.write(value.x, buf)
+ _UniffiFfiConverterFloat64.write(value.y, buf)
+ _UniffiFfiConverterFloat64.write(value.width, buf)
+ _UniffiFfiConverterFloat64.write(value.height, buf)
+ _UniffiFfiConverterOptionalFloat64.write(value.tolerance_px, buf)
+
@@ -1626,34 +1705,40 @@ class _UniffiFfiConverterTypeDragInput(_UniffiConverterRustBuffer):
_UniffiFfiConverterOptionalSequenceString.write(value.modifier, buf)
@dataclass
-class EndSessionInput:
- def __init__(self, *, session:str):
- self.session = session
+class ElementSelector:
+ def __init__(self, *, role:typing.Optional[str], label_contains:typing.Optional[str]):
+ self.role = role
+ self.label_contains = label_contains
def __str__(self):
- return "EndSessionInput(session={})".format(self.session)
+ return "ElementSelector(role={}, label_contains={})".format(self.role, self.label_contains)
def __eq__(self, other):
- if self.session != other.session:
+ if self.role != other.role:
+ return False
+ if self.label_contains != other.label_contains:
return False
return True
-class _UniffiFfiConverterTypeEndSessionInput(_UniffiConverterRustBuffer):
+class _UniffiFfiConverterTypeElementSelector(_UniffiConverterRustBuffer):
@staticmethod
def read(buf):
- return EndSessionInput(
- session=_UniffiFfiConverterString.read(buf),
+ return ElementSelector(
+ role=_UniffiFfiConverterOptionalString.read(buf),
+ label_contains=_UniffiFfiConverterOptionalString.read(buf),
)
@staticmethod
def check_lower(value):
- _UniffiFfiConverterString.check_lower(value.session)
+ _UniffiFfiConverterOptionalString.check_lower(value.role)
+ _UniffiFfiConverterOptionalString.check_lower(value.label_contains)
@staticmethod
def write(value, buf):
- _UniffiFfiConverterString.write(value.session, buf)
+ _UniffiFfiConverterOptionalString.write(value.role, buf)
+ _UniffiFfiConverterOptionalString.write(value.label_contains, buf)
class _UniffiFfiConverterBoolean:
@classmethod
@@ -1676,6 +1761,115 @@ class _UniffiFfiConverterBoolean:
def write(cls, value, buf):
buf.write_u8(value)
+class _UniffiFfiConverterOptionalBoolean(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterBoolean.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterBoolean.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterBoolean.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class ElementPredicate:
+ def __init__(self, *, selector:ElementSelector, exists:typing.Optional[bool], value_equals:typing.Optional[str], enabled:typing.Optional[bool], selected:typing.Optional[bool]):
+ self.selector = selector
+ self.exists = exists
+ self.value_equals = value_equals
+ self.enabled = enabled
+ self.selected = selected
+
+
+
+
+ def __str__(self):
+ return "ElementPredicate(selector={}, exists={}, value_equals={}, enabled={}, selected={})".format(self.selector, self.exists, self.value_equals, self.enabled, self.selected)
+ def __eq__(self, other):
+ if self.selector != other.selector:
+ return False
+ if self.exists != other.exists:
+ return False
+ if self.value_equals != other.value_equals:
+ return False
+ if self.enabled != other.enabled:
+ return False
+ if self.selected != other.selected:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeElementPredicate(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return ElementPredicate(
+ selector=_UniffiFfiConverterTypeElementSelector.read(buf),
+ exists=_UniffiFfiConverterOptionalBoolean.read(buf),
+ value_equals=_UniffiFfiConverterOptionalString.read(buf),
+ enabled=_UniffiFfiConverterOptionalBoolean.read(buf),
+ selected=_UniffiFfiConverterOptionalBoolean.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterTypeElementSelector.check_lower(value.selector)
+ _UniffiFfiConverterOptionalBoolean.check_lower(value.exists)
+ _UniffiFfiConverterOptionalString.check_lower(value.value_equals)
+ _UniffiFfiConverterOptionalBoolean.check_lower(value.enabled)
+ _UniffiFfiConverterOptionalBoolean.check_lower(value.selected)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterTypeElementSelector.write(value.selector, buf)
+ _UniffiFfiConverterOptionalBoolean.write(value.exists, buf)
+ _UniffiFfiConverterOptionalString.write(value.value_equals, buf)
+ _UniffiFfiConverterOptionalBoolean.write(value.enabled, buf)
+ _UniffiFfiConverterOptionalBoolean.write(value.selected, buf)
+
+@dataclass
+class EndSessionInput:
+ def __init__(self, *, session:str):
+ self.session = session
+
+
+
+
+ def __str__(self):
+ return "EndSessionInput(session={})".format(self.session)
+ def __eq__(self, other):
+ if self.session != other.session:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeEndSessionInput(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return EndSessionInput(
+ session=_UniffiFfiConverterString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.session)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.session, buf)
+
@dataclass
class EndSessionOutput:
"""
@@ -2152,6 +2346,207 @@ class _UniffiFfiConverterTypeMoveCursorInput(_UniffiConverterRustBuffer):
_UniffiFfiConverterTypeDesktopScope.write(value.scope, buf)
_UniffiFfiConverterOptionalString.write(value.session, buf)
+
+
+
+
+
+class VerificationStatus(enum.Enum):
+
+ SATISFIED = 0
+
+ UNSATISFIED = 1
+
+ UNKNOWN = 2
+
+
+
+class _UniffiFfiConverterTypeVerificationStatus(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return VerificationStatus.SATISFIED
+ if variant == 2:
+ return VerificationStatus.UNSATISFIED
+ if variant == 3:
+ return VerificationStatus.UNKNOWN
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value == VerificationStatus.SATISFIED:
+ return
+ if value == VerificationStatus.UNSATISFIED:
+ return
+ if value == VerificationStatus.UNKNOWN:
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value == VerificationStatus.SATISFIED:
+ buf.write_i32(1)
+ if value == VerificationStatus.UNSATISFIED:
+ buf.write_i32(2)
+ if value == VerificationStatus.UNKNOWN:
+ buf.write_i32(3)
+
+
+
+
+
+
+
+
+class UnknownReason(enum.Enum):
+
+ INVALID_PREDICATE = 0
+
+ UNSUPPORTED_PREDICATE = 1
+
+ UNTRUSTED_SOURCE = 2
+
+ MULTI_MATCH = 3
+
+ TARGET_MISSING = 4
+
+ OBSERVATION_UNAVAILABLE = 5
+
+ STABILITY_UNPROVEN = 6
+
+
+
+class _UniffiFfiConverterTypeUnknownReason(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ variant = buf.read_i32()
+ if variant == 1:
+ return UnknownReason.INVALID_PREDICATE
+ if variant == 2:
+ return UnknownReason.UNSUPPORTED_PREDICATE
+ if variant == 3:
+ return UnknownReason.UNTRUSTED_SOURCE
+ if variant == 4:
+ return UnknownReason.MULTI_MATCH
+ if variant == 5:
+ return UnknownReason.TARGET_MISSING
+ if variant == 6:
+ return UnknownReason.OBSERVATION_UNAVAILABLE
+ if variant == 7:
+ return UnknownReason.STABILITY_UNPROVEN
+ raise InternalError("Raw enum value doesn't match any cases")
+
+ @staticmethod
+ def check_lower(value):
+ if value == UnknownReason.INVALID_PREDICATE:
+ return
+ if value == UnknownReason.UNSUPPORTED_PREDICATE:
+ return
+ if value == UnknownReason.UNTRUSTED_SOURCE:
+ return
+ if value == UnknownReason.MULTI_MATCH:
+ return
+ if value == UnknownReason.TARGET_MISSING:
+ return
+ if value == UnknownReason.OBSERVATION_UNAVAILABLE:
+ return
+ if value == UnknownReason.STABILITY_UNPROVEN:
+ return
+ raise ValueError(value)
+
+ @staticmethod
+ def write(value, buf):
+ if value == UnknownReason.INVALID_PREDICATE:
+ buf.write_i32(1)
+ if value == UnknownReason.UNSUPPORTED_PREDICATE:
+ buf.write_i32(2)
+ if value == UnknownReason.UNTRUSTED_SOURCE:
+ buf.write_i32(3)
+ if value == UnknownReason.MULTI_MATCH:
+ buf.write_i32(4)
+ if value == UnknownReason.TARGET_MISSING:
+ buf.write_i32(5)
+ if value == UnknownReason.OBSERVATION_UNAVAILABLE:
+ buf.write_i32(6)
+ if value == UnknownReason.STABILITY_UNPROVEN:
+ buf.write_i32(7)
+
+
+
+class _UniffiFfiConverterOptionalTypeUnknownReason(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeUnknownReason.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeUnknownReason.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeUnknownReason.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class PredicateOutcome:
+ def __init__(self, *, index:int, status:VerificationStatus, unknown_reason:typing.Optional[UnknownReason], observed_json:typing.Optional[str]):
+ self.index = index
+ self.status = status
+ self.unknown_reason = unknown_reason
+ self.observed_json = observed_json
+
+
+
+
+ def __str__(self):
+ return "PredicateOutcome(index={}, status={}, unknown_reason={}, observed_json={})".format(self.index, self.status, self.unknown_reason, self.observed_json)
+ def __eq__(self, other):
+ if self.index != other.index:
+ return False
+ if self.status != other.status:
+ return False
+ if self.unknown_reason != other.unknown_reason:
+ return False
+ if self.observed_json != other.observed_json:
+ return False
+ return True
+
+class _UniffiFfiConverterTypePredicateOutcome(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return PredicateOutcome(
+ index=_UniffiFfiConverterUInt64.read(buf),
+ status=_UniffiFfiConverterTypeVerificationStatus.read(buf),
+ unknown_reason=_UniffiFfiConverterOptionalTypeUnknownReason.read(buf),
+ observed_json=_UniffiFfiConverterOptionalString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterUInt64.check_lower(value.index)
+ _UniffiFfiConverterTypeVerificationStatus.check_lower(value.status)
+ _UniffiFfiConverterOptionalTypeUnknownReason.check_lower(value.unknown_reason)
+ _UniffiFfiConverterOptionalString.check_lower(value.observed_json)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterUInt64.write(value.index, buf)
+ _UniffiFfiConverterTypeVerificationStatus.write(value.status, buf)
+ _UniffiFfiConverterOptionalTypeUnknownReason.write(value.unknown_reason, buf)
+ _UniffiFfiConverterOptionalString.write(value.observed_json, buf)
+
@dataclass
class PressKeyInput:
def __init__(self, *, key:str, scope:DesktopScope, session:typing.Optional[str], modifiers:typing.Optional[typing.List[str]]):
@@ -2635,31 +3030,6 @@ class _UniffiFfiConverterTypeSetAgentCursorEnabledOutput(_UniffiConverterRustBuf
_UniffiFfiConverterString.write(value.session, buf)
_UniffiFfiConverterBoolean.write(value.enabled, buf)
-class _UniffiFfiConverterOptionalFloat64(_UniffiConverterRustBuffer):
- @classmethod
- def check_lower(cls, value):
- if value is not None:
- _UniffiFfiConverterFloat64.check_lower(value)
-
- @classmethod
- def write(cls, value, buf):
- if value is None:
- buf.write_u8(0)
- return
-
- buf.write_u8(1)
- _UniffiFfiConverterFloat64.write(value, buf)
-
- @classmethod
- def read(cls, buf):
- flag = buf.read_u8()
- if flag == 0:
- return None
- elif flag == 1:
- return _UniffiFfiConverterFloat64.read(buf)
- else:
- raise InternalError("Unexpected flag byte for optional type")
-
@dataclass
class SetAgentCursorMotionInput:
def __init__(self, *, session:str, start_handle:typing.Optional[float], end_handle:typing.Optional[float], arc_size:typing.Optional[float], arc_flow:typing.Optional[float], spring:typing.Optional[float], glide_duration_ms:typing.Optional[float], dwell_after_click_ms:typing.Optional[float], idle_hide_ms:typing.Optional[float], turn_radius:typing.Optional[float]):
@@ -2995,6 +3365,153 @@ class _UniffiFfiConverterTypeStartSessionOutput(_UniffiConverterRustBuffer):
_UniffiFfiConverterBoolean.write(value.active, buf)
_UniffiFfiConverterBoolean.write(value.revived, buf)
+class _UniffiFfiConverterOptionalTypeBoundsExpectation(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeBoundsExpectation.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeBoundsExpectation.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeBoundsExpectation.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class WindowPredicate:
+ def __init__(self, *, exists:typing.Optional[bool], bounds:typing.Optional[BoundsExpectation]):
+ self.exists = exists
+ self.bounds = bounds
+
+
+
+
+ def __str__(self):
+ return "WindowPredicate(exists={}, bounds={})".format(self.exists, self.bounds)
+ def __eq__(self, other):
+ if self.exists != other.exists:
+ return False
+ if self.bounds != other.bounds:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeWindowPredicate(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return WindowPredicate(
+ exists=_UniffiFfiConverterOptionalBoolean.read(buf),
+ bounds=_UniffiFfiConverterOptionalTypeBoundsExpectation.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalBoolean.check_lower(value.exists)
+ _UniffiFfiConverterOptionalTypeBoundsExpectation.check_lower(value.bounds)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalBoolean.write(value.exists, buf)
+ _UniffiFfiConverterOptionalTypeBoundsExpectation.write(value.bounds, buf)
+
+class _UniffiFfiConverterOptionalTypeWindowPredicate(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeWindowPredicate.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeWindowPredicate.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeWindowPredicate.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+class _UniffiFfiConverterOptionalTypeElementPredicate(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeElementPredicate.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeElementPredicate.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeElementPredicate.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
+@dataclass
+class StatePredicate:
+ def __init__(self, *, window:typing.Optional[WindowPredicate], element:typing.Optional[ElementPredicate]):
+ self.window = window
+ self.element = element
+
+
+
+
+ def __str__(self):
+ return "StatePredicate(window={}, element={})".format(self.window, self.element)
+ def __eq__(self, other):
+ if self.window != other.window:
+ return False
+ if self.element != other.element:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeStatePredicate(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return StatePredicate(
+ window=_UniffiFfiConverterOptionalTypeWindowPredicate.read(buf),
+ element=_UniffiFfiConverterOptionalTypeElementPredicate.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterOptionalTypeWindowPredicate.check_lower(value.window)
+ _UniffiFfiConverterOptionalTypeElementPredicate.check_lower(value.element)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterOptionalTypeWindowPredicate.write(value.window, buf)
+ _UniffiFfiConverterOptionalTypeElementPredicate.write(value.element, buf)
+
@dataclass
class TypeTextInput:
def __init__(self, *, text:str, scope:DesktopScope, session:typing.Optional[str]):
@@ -3037,6 +3554,185 @@ class _UniffiFfiConverterTypeTypeTextInput(_UniffiConverterRustBuffer):
_UniffiFfiConverterTypeDesktopScope.write(value.scope, buf)
_UniffiFfiConverterOptionalString.write(value.session, buf)
+class _UniffiFfiConverterInt64(_UniffiConverterPrimitiveInt):
+ CLASS_NAME = "i64"
+ VALUE_MIN = -2**63
+ VALUE_MAX = 2**63
+
+ @staticmethod
+ def read(buf):
+ return buf.read_i64()
+
+ @staticmethod
+ def write(value, buf):
+ buf.write_i64(value)
+
+class _UniffiFfiConverterSequenceTypeStatePredicate(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypeStatePredicate.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypeStatePredicate.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypeStatePredicate.read(buf) for i in range(count)
+ ]
+
+@dataclass
+class VerifyStateInput:
+ def __init__(self, *, pid:int, window_id:int, expect:typing.List[StatePredicate], session:typing.Optional[str], timeout_ms:typing.Optional[int], stable_samples:typing.Optional[int], include_screenshot:typing.Optional[bool]):
+ self.pid = pid
+ self.window_id = window_id
+ self.expect = expect
+ self.session = session
+ self.timeout_ms = timeout_ms
+ self.stable_samples = stable_samples
+ self.include_screenshot = include_screenshot
+
+
+
+
+ def __str__(self):
+ return "VerifyStateInput(pid={}, window_id={}, expect={}, session={}, timeout_ms={}, stable_samples={}, include_screenshot={})".format(self.pid, self.window_id, self.expect, self.session, self.timeout_ms, self.stable_samples, self.include_screenshot)
+ def __eq__(self, other):
+ if self.pid != other.pid:
+ return False
+ if self.window_id != other.window_id:
+ return False
+ if self.expect != other.expect:
+ return False
+ if self.session != other.session:
+ return False
+ if self.timeout_ms != other.timeout_ms:
+ return False
+ if self.stable_samples != other.stable_samples:
+ return False
+ if self.include_screenshot != other.include_screenshot:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeVerifyStateInput(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return VerifyStateInput(
+ pid=_UniffiFfiConverterInt64.read(buf),
+ window_id=_UniffiFfiConverterUInt64.read(buf),
+ expect=_UniffiFfiConverterSequenceTypeStatePredicate.read(buf),
+ session=_UniffiFfiConverterOptionalString.read(buf),
+ timeout_ms=_UniffiFfiConverterOptionalUInt64.read(buf),
+ stable_samples=_UniffiFfiConverterOptionalUInt64.read(buf),
+ include_screenshot=_UniffiFfiConverterOptionalBoolean.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterInt64.check_lower(value.pid)
+ _UniffiFfiConverterUInt64.check_lower(value.window_id)
+ _UniffiFfiConverterSequenceTypeStatePredicate.check_lower(value.expect)
+ _UniffiFfiConverterOptionalString.check_lower(value.session)
+ _UniffiFfiConverterOptionalUInt64.check_lower(value.timeout_ms)
+ _UniffiFfiConverterOptionalUInt64.check_lower(value.stable_samples)
+ _UniffiFfiConverterOptionalBoolean.check_lower(value.include_screenshot)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterInt64.write(value.pid, buf)
+ _UniffiFfiConverterUInt64.write(value.window_id, buf)
+ _UniffiFfiConverterSequenceTypeStatePredicate.write(value.expect, buf)
+ _UniffiFfiConverterOptionalString.write(value.session, buf)
+ _UniffiFfiConverterOptionalUInt64.write(value.timeout_ms, buf)
+ _UniffiFfiConverterOptionalUInt64.write(value.stable_samples, buf)
+ _UniffiFfiConverterOptionalBoolean.write(value.include_screenshot, buf)
+
+class _UniffiFfiConverterSequenceTypePredicateOutcome(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ for item in value:
+ _UniffiFfiConverterTypePredicateOutcome.check_lower(item)
+
+ @classmethod
+ def write(cls, value, buf):
+ items = len(value)
+ buf.write_i32(items)
+ for item in value:
+ _UniffiFfiConverterTypePredicateOutcome.write(item, buf)
+
+ @classmethod
+ def read(cls, buf):
+ count = buf.read_i32()
+ if count < 0:
+ raise InternalError("Unexpected negative sequence length")
+
+ return [
+ _UniffiFfiConverterTypePredicateOutcome.read(buf) for i in range(count)
+ ]
+
+@dataclass
+class VerifyStateOutput:
+ def __init__(self, *, status:VerificationStatus, stable:bool, elapsed_ms:int, samples:int, predicates:typing.List[PredicateOutcome]):
+ self.status = status
+ self.stable = stable
+ self.elapsed_ms = elapsed_ms
+ self.samples = samples
+ self.predicates = predicates
+
+
+
+
+ def __str__(self):
+ return "VerifyStateOutput(status={}, stable={}, elapsed_ms={}, samples={}, predicates={})".format(self.status, self.stable, self.elapsed_ms, self.samples, self.predicates)
+ def __eq__(self, other):
+ if self.status != other.status:
+ return False
+ if self.stable != other.stable:
+ return False
+ if self.elapsed_ms != other.elapsed_ms:
+ return False
+ if self.samples != other.samples:
+ return False
+ if self.predicates != other.predicates:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeVerifyStateOutput(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return VerifyStateOutput(
+ status=_UniffiFfiConverterTypeVerificationStatus.read(buf),
+ stable=_UniffiFfiConverterBoolean.read(buf),
+ elapsed_ms=_UniffiFfiConverterUInt64.read(buf),
+ samples=_UniffiFfiConverterUInt64.read(buf),
+ predicates=_UniffiFfiConverterSequenceTypePredicateOutcome.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterTypeVerificationStatus.check_lower(value.status)
+ _UniffiFfiConverterBoolean.check_lower(value.stable)
+ _UniffiFfiConverterUInt64.check_lower(value.elapsed_ms)
+ _UniffiFfiConverterUInt64.check_lower(value.samples)
+ _UniffiFfiConverterSequenceTypePredicateOutcome.check_lower(value.predicates)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterTypeVerificationStatus.write(value.status, buf)
+ _UniffiFfiConverterBoolean.write(value.stable, buf)
+ _UniffiFfiConverterUInt64.write(value.elapsed_ms, buf)
+ _UniffiFfiConverterUInt64.write(value.samples, buf)
+ _UniffiFfiConverterSequenceTypePredicateOutcome.write(value.predicates, buf)
+
@@ -3105,11 +3801,14 @@ __all__ = [
"CursorReducedMotion",
"CursorAction",
"EscalationReason",
+ "VerificationStatus",
+ "UnknownReason",
"ScrollDirection",
"ScrollBy",
"CaptureScope",
"EffectiveScope",
"Platform",
+ "BoundsExpectation",
"ClickInput",
"CursorMotionOutput",
"CursorPointOutput",
@@ -3117,6 +3816,8 @@ __all__ = [
"CursorThemeSelection",
"CursorVisualOutput",
"DragInput",
+ "ElementSelector",
+ "ElementPredicate",
"EndSessionInput",
"EndSessionOutput",
"EscalateSessionInput",
@@ -3128,6 +3829,7 @@ __all__ = [
"GetSessionStateInput",
"HotkeyInput",
"MoveCursorInput",
+ "PredicateOutcome",
"PressKeyInput",
"ScrollInput",
"SessionStateOutput",
@@ -3139,5 +3841,9 @@ __all__ = [
"SetAgentCursorThemeOutput",
"StartSessionInput",
"StartSessionOutput",
+ "WindowPredicate",
+ "StatePredicate",
"TypeTextInput",
+ "VerifyStateInput",
+ "VerifyStateOutput",
]
diff --git a/libs/cua-driver/python/tests/test_uniffi_loader.py b/libs/cua-driver/python/tests/test_uniffi_loader.py
index fcf905f504..1dd98bfa90 100644
--- a/libs/cua-driver/python/tests/test_uniffi_loader.py
+++ b/libs/cua-driver/python/tests/test_uniffi_loader.py
@@ -58,7 +58,7 @@ while True:
if request["method"] == "metadata":
result = {
"driver_version": "0.10.0",
- "contract_version": "0.2.0",
+ "contract_version": "0.3.0",
"tools_list_schema_version": "1",
"capability_version": "1",
"mcp_protocol_version": "2025-06-18",
@@ -106,8 +106,10 @@ except FileNotFoundError:
from cua_driver import (
CuaDriver,
EffectiveScope,
- GetDesktopStateInput,
+ StatePredicate,
StartSessionOutput,
+ VerifyStateInput,
+ WindowPredicate,
)
self.assertIsNotNone(EffectiveScope)
@@ -134,7 +136,7 @@ except FileNotFoundError:
if request["method"] == "metadata":
result = {
"driver_version": "0.12.6",
- "contract_version": "0.2.0",
+ "contract_version": "0.3.0",
"tools_list_schema_version": "1",
"capability_version": "1",
"mcp_protocol_version": "2025-06-18",
@@ -176,12 +178,24 @@ except FileNotFoundError:
"type_text",
"press_key",
"hotkey",
+ "verify_state",
}
self.assertTrue(all(hasattr(driver, name) for name in expected_methods))
result = asyncio.run(
- driver.get_desktop_state(
- GetDesktopStateInput(
- session="python-run", screenshot_out_file=None
+ driver.verify_state(
+ VerifyStateInput(
+ pid=123,
+ window_id=456,
+ expect=[
+ StatePredicate(
+ window=WindowPredicate(exists=True, bounds=None),
+ element=None,
+ )
+ ],
+ session="python-run",
+ timeout_ms=0,
+ stable_samples=1,
+ include_screenshot=True,
)
)
)
@@ -191,8 +205,19 @@ except FileNotFoundError:
self.assertEqual(result.text, "python ffi")
self.assertEqual(result.images[0].mime_type, "image/png")
self.assertTrue(result.verified)
- self.assertEqual(captured[0]["name"], "get_desktop_state")
- self.assertEqual(captured[0]["args"], {"session": "python-run"})
+ self.assertEqual(captured[0]["name"], "verify_state")
+ self.assertEqual(
+ captured[0]["args"],
+ {
+ "pid": 123,
+ "window_id": 456,
+ "expect": [{"window": {"exists": True}}],
+ "session": "python-run",
+ "timeout_ms": 0,
+ "stable_samples": 1,
+ "include_screenshot": True,
+ },
+ )
self.assertEqual(captured[0]["client_kind"], "python_sdk")
def test_generated_python_sdk_can_own_the_runtime_in_process(self) -> None:
diff --git a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
index 9f204ea41c..73094232da 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
@@ -151,6 +151,7 @@ cua-driver launch_app '{"bundle_id":"..."}'
# → {pid: 844, windows: [{window_id: 10725, ...}]}
cua-driver get_window_state '{"pid":844,"window_id":10725}'
cua-driver click '{"pid":844,"window_id":10725,"element_index":14}'
+cua-driver verify_state '{"pid":844,"window_id":10725,"expect":[{"element":{"selector":{"label_contains":"Saved"},"exists":true}}]}'
cua-driver stop
```
@@ -213,11 +214,14 @@ a certified host main-thread adapter returns a structured
successful cursor move. One-shot CLI adapters do not own an overlay
themselves.
-## The core invariant — snapshot before AND after every action
+## The core invariant — snapshot before and verify after every action
-**Every action MUST be bracketed by the state tool for the session's effective
-scope**: `get_window_state(pid, window_id)` in window scope, or
-`get_desktop_state(session)` in desktop scope.
+**Every action MUST be bracketed by observation for the session's effective
+scope.** Use `get_window_state(pid, window_id)` before a window action (or
+`get_desktop_state(session)` in desktop scope), then use `verify_state` for an
+expressible window-scoped postcondition. In effective desktop scope,
+`verify_state` is intentionally refused with `window_scope_disabled`; verify
+with a fresh `get_desktop_state` result and agent-owned visual/semantic reading.
- **Before** — the pre-action snapshot resolves the `element_index`
you're about to use. Indices from previous turns are stale; the
@@ -226,15 +230,24 @@ scope**: `get_window_state(pid, window_id)` in window scope, or
N+1, and indices from window A don't resolve against window B of
the same app. Skip this and element-indexed actions fail with
`No cached AX state`.
-- **After** — the post-action snapshot verifies the action actually
- landed. Without it you can't tell a silent no-op from a real
- effect. The accessibility-tree change (new value, new window,
- disappeared menu, disabled button, etc.) is your evidence that
- the action fired. If nothing changed, the action probably failed
- silently — say so, don't assume success.
-
-This applies to pixel clicks and desktop actions too — re-snapshot after to
-confirm the action landed on the intended target.
+- **After** — `verify_state(pid, window_id, expect)` checks a bounded,
+ deterministic postcondition. Results are `satisfied`, `unsatisfied`, or
+ `unknown`; `unknown` never means success. Set `include_screenshot:true` when
+ the outcome also needs visual reading. The driver returns that final image
+ without interpreting it. A multimodal agent harness reads the image and owns
+ the stop/retry/ladder decision.
+
+`unknown_reason` distinguishes invalid/unsupported predicates, untrusted web
+content, ambiguous matches, missing targets, unavailable observations, and
+`stability_unproven`. A positive final sample that was not observed for the
+requested consecutive sample count is `stability_unproven`, not success.
+Negative element existence is conservative: when an accessibility projection
+cannot prove its search domain exhaustive, absence remains `unknown`.
+
+Do not make the driver invent task meaning or retry actions automatically.
+For postconditions not expressible by `verify_state`, take a fresh state
+snapshot and let the agent judge the tree and/or image explicitly. This applies
+to pixel clicks and desktop actions too.
## Choose capture scope when the session starts
@@ -409,21 +422,30 @@ _dispatch rung_ on a real signal. Walk the rungs:
# Rung 1 — element ax action, backgrounded (the cheap default)
get_window_state(pid, window_id) # tree + screenshot, both, always
resp = click(pid, window_id, element_index) # or type_text / set_value / press_key
-get_window_state(pid, window_id) # re-snapshot — did the tree change?
+check = verify_state( # bounded structured read-back
+ pid, window_id,
+ expect=[...],
+ include_screenshot=true # optional evidence for multimodal harness
+)
-if resp.effect == "confirmed" and tree changed:
+if check.status == "satisfied":
done # driver-verified
+if check.status == "unknown" and check has an image:
+ harness reads the image # model-owned visual interpretation
+ if visual outcome is satisfied: done
+
# escalate only on a real signal
if resp.effect == "suspected_noop"
or resp.escalation.recommended == "px"
or get_window_state.degraded # empty tree → non-AX surface
+ or check.status != "satisfied"
or the tree looks wrong vs the screenshot: # e.g. an h:1 / off-viewport row
# Rung 2 — element px action off the SAME screenshot
pick the target pixel from the screenshot already in the response
click(pid, x, y) # background pixel — still no foreground
- get_window_state(pid, window_id) # re-snapshot, eyeball the result
+ verify_state(..., include_screenshot=true)
if it landed: done
# Rung 2b — exact browser page tools, when get_browser_state can bind this window
@@ -486,7 +508,7 @@ launch_app(target)
(or call list_windows(pid) separately)
→ get_window_state(pid, window_id)
→ [act] # every action also takes (pid, window_id) + your `session`
- → get_window_state(pid, window_id) → verify
+ → verify_state(pid, window_id, expect) # structured check; optional image
end_session(session) # when the run finishes
```
@@ -633,6 +655,7 @@ against a specific window.
| -------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| List an app's windows | `list_windows({pid})` | returns `window_id`, `title`, `bounds`, `z_index`, `is_on_screen`, `on_current_space`. Already included in `launch_app`'s response — only call this for long-lived pids |
| Snapshot a window | `get_window_state({pid, window_id})` | returns `tree_markdown` + `screenshot_*`; populates the `(pid, window_id)` element_index cache |
+| Verify a postcondition | `verify_state({pid, window_id, expect, include_screenshot?})` | polls bounded structured predicates; returns `satisfied`, `unsatisfied`, or `unknown`. Optional final image is interpreted by the agent harness, never by the driver |
| Left click | `click({pid, window_id, element_index})` | default `action: "press"`. Pixel form: `click({pid, x, y})` (window_id optional) — `modifier: ["cmd"\|"ctrl"]` |
| Double-click / open | `double_click({pid, window_id, element_index})` | Default action when the element advertises one (Open on Finder items / openable rows), else stamped pixel double-click at the element's center |
| Right click / context menu | `right_click({pid, window_id, element_index})` or `click({pid, window_id, element_index, action: "show_menu"})` | Browser page content should use the typed route where available; see `BROWSER.md` |
@@ -796,23 +819,28 @@ embedded webview for which exact browser binding is unavailable. The legacy
`page` tool remains a compatibility surface; do not use it as the starting
point for new browser workflows.
-## Re-snapshot and verify — mandatory
+## Verify after every action — mandatory
-**Always** call `get_window_state({pid, window_id})` after the
-action. This isn't optional verification — it's the second half of
-the snapshot invariant.
+**Always** verify after an action. Prefer
+`verify_state({pid, window_id, expect})` for structured state such as a
+window's existence/bounds or a semantic element's existence, value, enabled
+state, or selected state. Use its bounded poll and stable-sample requirement
+instead of hand-written sleeps. `unknown` means the driver could not establish
+the predicate; it is not success. Once a session has effective desktop scope,
+use a fresh `get_desktop_state(session)` result instead—window-scoped
+`verify_state` is denied by that capture policy.
-Check the tree diff: a changed value, a new element, a new window,
-or the disappearance of the thing you just clicked (menus collapse
-after selection, buttons may become disabled, etc.). The re-snapshot
-gives you both the tree and the screenshot, so you cross-check the tree
-diff against the pixels in one call — and when you're only confirming a
-tree change, `include_screenshot:false` skips the grab.
+Pass `include_screenshot:true` when visual evidence is useful. The same result
+then contains a fresh final window image. The driver still evaluates only the
+structured predicates; the multimodal agent harness reads the pixels and
+decides whether to stop, retry, or advance the ladder. For a postcondition not
+expressible by the tool, explicitly take a fresh `get_window_state` snapshot
+and have the harness judge its tree and image.
Switch to an **element px action** only on a real signal: the action
-response carried `effect:"suspected_noop"`, the re-snapshot came back
-`degraded` (empty tree → non-AX surface), the tree looks
-unchanged/unreadable or disagrees with the screenshot, or
+response carried `effect:"suspected_noop"`, verification returned
+`unsatisfied`/`unknown`, the snapshot came back `degraded` (empty tree →
+non-AX surface), the tree looks unchanged/unreadable or disagrees with the screenshot, or
`escalation.recommended` points you there (`px`). That's the
verify-then-escalate ladder in the behavior-matrix section. If the tree
is unchanged AND the screenshot confirms nothing moved, the action
diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs
index 1e0d41ad37..0538fa2517 100644
--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs
@@ -20,6 +20,7 @@ mod desktop;
mod inputs;
mod outputs;
mod session;
+mod verification;
pub use cursor::{
classify_cursor_semantics, CursorAction, CursorDelivery, CursorPlayback, CursorReducedMotion,
@@ -40,6 +41,11 @@ pub use outputs::{
SetAgentCursorEnabledOutput, SetAgentCursorMotionOutput, SetAgentCursorThemeOutput,
StartSessionOutput, ToolOutput,
};
+pub use verification::{
+ BoundsExpectation, ElementPredicate, ElementSelector, PredicateOutcome, StatePredicate,
+ UnknownReason, VerificationStatus, VerifyStateInput, VerifyStateOutput, WindowPredicate,
+ VERIFY_STATE_DEFAULT_TIMEOUT_MS,
+};
/// Shape version for the MCP `tools/list` result emitted by cua-driver.
pub const TOOLS_LIST_SCHEMA_VERSION: &str = "1";
@@ -48,7 +54,7 @@ pub const TOOLS_LIST_SCHEMA_VERSION: &str = "1";
pub const CAPABILITY_VERSION: &str = "1";
/// Shape version for the checked-in generated client contract.
-pub const CONTRACT_VERSION: &str = "0.2.0";
+pub const CONTRACT_VERSION: &str = "0.3.0";
/// MCP protocol version used by current cua-driver clients.
pub const MCP_PROTOCOL_VERSION: &str = "2025-06-18";
@@ -144,6 +150,7 @@ pub fn manifest() -> ContractManifest {
let mut tools = session::contracts();
tools.extend(desktop::contracts());
tools.extend(cursor_tools::contracts());
+ tools.extend(verification::contracts());
tools.sort_by(|left, right| left.name.cmp(&right.name));
ContractManifest {
generated_notice: "Generated by cua-contract-gen; do not edit by hand.".into(),
@@ -235,10 +242,31 @@ mod tests {
let mut sorted = names.clone();
sorted.sort_unstable();
assert_eq!(names, sorted);
- assert_eq!(manifest.contract_version, "0.2.0");
+ assert_eq!(manifest.contract_version, "0.3.0");
assert!(manifest.experimental);
}
+ #[test]
+ fn verify_state_is_a_portable_read_only_contract() {
+ let contract = tool_contract("verify_state").expect("verify_state contract");
+ assert_eq!(contract.schema_mode, SchemaMode::PortableSubset);
+ assert!(contract.annotations.read_only);
+ assert!(!contract.annotations.destructive);
+ assert!(contract
+ .capabilities
+ .iter()
+ .any(|capability| capability == "state.verify"));
+ assert_eq!(
+ contract.input_schema["required"],
+ serde_json::json!(["pid", "window_id", "expect"])
+ );
+ assert_eq!(
+ contract.input_schema["properties"]["expect"]["items"]["properties"]["element"]
+ ["properties"]["exists"]["enum"],
+ serde_json::json!([true])
+ );
+ }
+
#[test]
fn every_contract_has_success_schema_and_platforms() {
for tool in manifest().tools {
diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/verification.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/verification.rs
new file mode 100644
index 0000000000..bab727b38b
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/verification.rs
@@ -0,0 +1,335 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Cross-platform deterministic state-verification contract.
+//!
+//! The caller owns the task-level meaning of success. The driver only checks
+//! bounded predicates against one explicitly authorized window.
+
+use crate::{Platform, SchemaMode, ToolAnnotations, ToolContract, ToolInput, ToolOutput};
+use schemars::{json_schema, JsonSchema, Schema, SchemaGenerator};
+use serde::{Deserialize, Serialize};
+
+const ALL_PLATFORMS: [Platform; 3] = [Platform::Macos, Platform::Windows, Platform::Linux];
+
+pub const VERIFY_STATE_DEFAULT_TIMEOUT_MS: u64 = 5_000;
+
+fn timeout_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 10000,
+ "default": VERIFY_STATE_DEFAULT_TIMEOUT_MS
+ })
+}
+
+fn stable_samples_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({ "type": "integer", "minimum": 1, "maximum": 5, "default": 2 })
+}
+
+fn tolerance_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({ "type": "number", "minimum": 0, "maximum": 100 })
+}
+
+fn number_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({ "type": "number" })
+}
+
+fn integer_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({ "type": "integer" })
+}
+
+fn positive_integer_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({ "type": "integer", "minimum": 1 })
+}
+
+fn string_schema(generator: &mut SchemaGenerator) -> Schema {
+ String::json_schema(generator)
+}
+
+fn nonempty_string_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({ "type": "string", "minLength": 1 })
+}
+
+fn true_only_boolean_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({ "type": "boolean", "enum": [true] })
+}
+
+fn nullable_string_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({ "anyOf": [{ "type": "string" }, { "type": "null" }] })
+}
+
+fn nullable_unknown_reason_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "anyOf": [
+ {
+ "type": "string",
+ "enum": [
+ "invalid_predicate",
+ "unsupported_predicate",
+ "untrusted_source",
+ "multi_match",
+ "target_missing",
+ "observation_unavailable",
+ "stability_unproven"
+ ]
+ },
+ { "type": "null" }
+ ]
+ })
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, uniffi::Record)]
+#[serde(deny_unknown_fields)]
+pub struct BoundsExpectation {
+ #[schemars(schema_with = "number_schema")]
+ pub x: f64,
+ #[schemars(schema_with = "number_schema")]
+ pub y: f64,
+ #[schemars(schema_with = "number_schema")]
+ pub width: f64,
+ #[schemars(schema_with = "number_schema")]
+ pub height: f64,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "tolerance_schema")]
+ pub tolerance_px: Option<f64>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Record)]
+#[serde(deny_unknown_fields)]
+pub struct ElementSelector {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "nonempty_string_schema")]
+ pub role: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "nonempty_string_schema")]
+ pub label_contains: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, uniffi::Record)]
+#[serde(deny_unknown_fields)]
+pub struct WindowPredicate {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub exists: Option<bool>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub bounds: Option<BoundsExpectation>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Record)]
+#[serde(deny_unknown_fields)]
+pub struct ElementPredicate {
+ pub selector: ElementSelector,
+ /// Assert that at least one trusted element matches the selector.
+ ///
+ /// Element walks are not yet exhaustive on every platform, so absence
+ /// cannot be proven. `false` is rejected instead of returning an
+ /// indefinitely-unknown predicate.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "true_only_boolean_schema")]
+ pub exists: Option<bool>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub value_equals: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub enabled: Option<bool>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub selected: Option<bool>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, uniffi::Record)]
+#[serde(deny_unknown_fields)]
+pub struct StatePredicate {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub window: Option<WindowPredicate>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub element: Option<ElementPredicate>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, uniffi::Record)]
+#[serde(deny_unknown_fields)]
+pub struct VerifyStateInput {
+ /// Exact process whose window may be observed.
+ #[schemars(schema_with = "positive_integer_schema")]
+ pub pid: i64,
+ /// Exact native window identifier.
+ #[schemars(schema_with = "integer_schema")]
+ pub window_id: u64,
+ /// One to eight predicates, combined with logical AND.
+ #[schemars(length(min = 1, max = 8))]
+ pub expect: Vec<StatePredicate>,
+ /// Optional session id for capture-scope and authorization continuity.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "string_schema")]
+ pub session: Option<String>,
+ /// Bounded wait. Zero performs one sample.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "timeout_schema")]
+ pub timeout_ms: Option<u64>,
+ /// Consecutive satisfied samples required before returning success.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "stable_samples_schema")]
+ pub stable_samples: Option<u64>,
+ /// Return the final window screenshot as image content for a multimodal
+ /// caller. The driver does not interpret that image.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub include_screenshot: Option<bool>,
+}
+
+impl ToolInput for VerifyStateInput {
+ const TOOL_NAME: &'static str = "verify_state";
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Enum)]
+#[serde(rename_all = "snake_case")]
+pub enum VerificationStatus {
+ Satisfied,
+ Unsatisfied,
+ Unknown,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Enum)]
+#[serde(rename_all = "snake_case")]
+pub enum UnknownReason {
+ InvalidPredicate,
+ UnsupportedPredicate,
+ UntrustedSource,
+ MultiMatch,
+ TargetMissing,
+ ObservationUnavailable,
+ StabilityUnproven,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Record)]
+pub struct PredicateOutcome {
+ pub index: u64,
+ pub status: VerificationStatus,
+ #[schemars(required, schema_with = "nullable_unknown_reason_schema")]
+ pub unknown_reason: Option<UnknownReason>,
+ /// Normalized, bounded JSON projection of the matched state.
+ #[schemars(required, schema_with = "nullable_string_schema")]
+ pub observed_json: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Record)]
+pub struct VerifyStateOutput {
+ pub status: VerificationStatus,
+ pub stable: bool,
+ pub elapsed_ms: u64,
+ pub samples: u64,
+ pub predicates: Vec<PredicateOutcome>,
+}
+
+impl ToolOutput for VerifyStateOutput {}
+
+pub fn contracts() -> Vec<ToolContract> {
+ vec![ToolContract {
+ name: VerifyStateInput::TOOL_NAME.into(),
+ description: "Deterministically verify bounded predicates against one exact window. \
+ The driver evaluates structured window/accessibility state and may return the final \
+ screenshot as uninterpreted visual evidence for a multimodal caller. Predicate \
+ results are satisfied, unsatisfied, or unknown; unknown never implies success. \
+ Accessibility projections are conservative: absence remains unknown unless the \
+ observed search domain is proven exhaustive."
+ .into(),
+ platforms: ALL_PLATFORMS.to_vec(),
+ aliases: Vec::new(),
+ capabilities: vec![
+ "state.verify".into(),
+ "state.verify.window".into(),
+ "state.verify.element".into(),
+ "state.observe.visual_evidence".into(),
+ ],
+ annotations: ToolAnnotations {
+ read_only: true,
+ destructive: false,
+ idempotent: false,
+ open_world: false,
+ },
+ schema_mode: SchemaMode::PortableSubset,
+ cursor_semantics: None,
+ input_schema: VerifyStateInput::input_schema(),
+ success_output_schema: Some(VerifyStateOutput::output_schema()),
+ output_validator: crate::validate_typed_output::<VerifyStateOutput>,
+ }]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn schema_bounds_the_polling_contract() {
+ let schema = VerifyStateInput::input_schema();
+ assert_eq!(schema["properties"]["expect"]["minItems"], 1);
+ assert_eq!(schema["properties"]["expect"]["maxItems"], 8);
+ assert_eq!(
+ schema["properties"]["timeout_ms"]["default"],
+ VERIFY_STATE_DEFAULT_TIMEOUT_MS
+ );
+ assert_eq!(schema["properties"]["timeout_ms"]["maximum"], 10_000);
+ assert_eq!(schema["properties"]["stable_samples"]["maximum"], 5);
+ let selector = &schema["properties"]["expect"]["items"]["properties"]["element"]
+ ["properties"]["selector"];
+ assert_eq!(selector["properties"]["role"]["minLength"], 1);
+ assert_eq!(selector["properties"]["label_contains"]["minLength"], 1);
+ assert_eq!(schema["additionalProperties"], false);
+ }
+
+ #[test]
+ fn predicate_shape_is_flat_and_language_binding_friendly() {
+ let schema = VerifyStateInput::input_schema();
+ let item = &schema["properties"]["expect"]["items"];
+ assert!(item["properties"]["window"].is_object());
+ assert!(item["properties"]["element"].is_object());
+ assert!(item.get("oneOf").is_none());
+ }
+
+ #[test]
+ fn output_requires_tri_state_and_bounded_evidence_projection() {
+ let output = VerifyStateOutput {
+ status: VerificationStatus::Unknown,
+ stable: false,
+ elapsed_ms: 10,
+ samples: 1,
+ predicates: vec![PredicateOutcome {
+ index: 0,
+ status: VerificationStatus::Unknown,
+ unknown_reason: Some(UnknownReason::UntrustedSource),
+ observed_json: Some(json!({"role":"web_area"}).to_string()),
+ }],
+ };
+ assert!(output.validate().is_ok());
+ assert_eq!(
+ serde_json::to_value(output).unwrap()["status"],
+ json!("unknown")
+ );
+ let schema = VerifyStateOutput::output_schema();
+ let predicate = &schema["properties"]["predicates"]["items"];
+ for field in ["unknown_reason", "observed_json"] {
+ assert!(
+ predicate["properties"][field]["anyOf"]
+ .as_array()
+ .is_some_and(|variants| variants
+ .iter()
+ .any(|variant| variant["type"] == "null")),
+ "{field} must be required and nullable"
+ );
+ }
+ let satisfied = VerifyStateOutput {
+ status: VerificationStatus::Satisfied,
+ stable: true,
+ elapsed_ms: 1,
+ samples: 2,
+ predicates: vec![PredicateOutcome {
+ index: 0,
+ status: VerificationStatus::Satisfied,
+ unknown_reason: None,
+ observed_json: None,
+ }],
+ };
+ assert!(
+ satisfied.validate().is_ok(),
+ "published output schema must accept runtime null optionals"
+ );
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs
index aaadb0a577..bb10b41591 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs
@@ -212,6 +212,7 @@ const PRIVATE_OBSERVATION_OPERATIONS: &[&str] = &[
"get_desktop_state",
"get_accessibility_tree",
"get_window_state",
+ "verify_state",
"list_apps",
"list_windows",
"debug_window_info",
@@ -689,6 +690,7 @@ pub fn enforcement_adapters_for_call(
"get_desktop_state"
| "get_accessibility_tree"
| "get_window_state"
+ | "verify_state"
| "list_apps"
| "list_windows"
| "debug_window_info"
@@ -844,6 +846,7 @@ pub fn advertised_risk_for(tool: &str) -> RiskAssessment {
| "debug_window_info"
| "check_permissions"
| "get_accessibility_tree"
+ | "verify_state"
| "set_config"
| "escalate_session"
| "start_recording"
@@ -945,6 +948,11 @@ pub fn classify_tool_call(tool: &str, args: &Value) -> RiskAssessment {
enforcement: RiskEnforcement::Active,
operation_sensitive: true,
},
+ "verify_state" => RiskAssessment {
+ class: RiskClass::R2,
+ enforcement: RiskEnforcement::Active,
+ operation_sensitive: true,
+ },
"get_accessibility_tree"
| "list_apps"
| "list_windows"
@@ -1113,6 +1121,7 @@ fn enforce_hard_invariants(
| "bring_to_front"
| "get_accessibility_tree"
| "get_window_state"
+ | "verify_state"
| "page"
| "browser_prepare"
);
@@ -1480,6 +1489,19 @@ mod tests {
}
}
+ #[test]
+ fn verify_state_is_bounded_observation_not_file_egress() {
+ for args in [
+ serde_json::json!({}),
+ serde_json::json!({"include_screenshot": true}),
+ ] {
+ let observation = classify_tool_call("verify_state", &args);
+ assert_eq!(observation.class, RiskClass::R2);
+ assert_eq!(observation.enforcement, RiskEnforcement::Active);
+ }
+ assert_eq!(advertised_risk_for("verify_state").class, RiskClass::R2);
+ }
+
#[test]
fn os_permission_prompt_is_argument_sensitive() {
for args in [serde_json::json!({}), serde_json::json!({"prompt": false})] {
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs
index 27c2597146..4574758947 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/capture_scope.rs
@@ -187,6 +187,7 @@ fn tool_scope(tool_name: &str, args: &Value) -> ToolScope {
if matches!(
tool_name,
"get_window_state"
+ | "verify_state"
| "get_accessibility_tree"
| "get_app_state"
| "screenshot"
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/expectation.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/expectation.rs
new file mode 100644
index 0000000000..d107e328fe
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/expectation.rs
@@ -0,0 +1,1315 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Deterministic, bounded state verification.
+//!
+//! This module deliberately consumes the existing platform observation tools
+//! directly. It never re-enters `ToolRegistry::invoke`, so one outer
+//! `verify_state` admission owns authorization for the whole polling window.
+
+use async_trait::async_trait;
+use cua_driver_contract::{
+ ElementPredicate, PredicateOutcome, StatePredicate, ToolInput, UnknownReason,
+ VerificationStatus, VerifyStateInput, VerifyStateOutput, WindowPredicate,
+ VERIFY_STATE_DEFAULT_TIMEOUT_MS,
+};
+use serde_json::{json, Value};
+use std::{collections::HashMap, sync::Arc, time::Duration};
+
+use crate::{
+ protocol::{Content, ToolResult},
+ tool::{Tool, ToolDef},
+ tool_args::parse_typed_input,
+};
+
+const MAX_TIMEOUT_MS: u64 = 10_000;
+const DEFAULT_STABLE_SAMPLES: u64 = 2;
+const MAX_STABLE_SAMPLES: u64 = 5;
+const MAX_PREDICATES: usize = 8;
+const POLL_INTERVAL_MS: u64 = 100;
+
+#[derive(Debug, Clone, Default)]
+pub struct ObservationSnapshot {
+ pub window: Option<Value>,
+ pub elements: Option<Vec<Value>>,
+ pub element_source_trusted: bool,
+ /// True only when the platform proved that its structured element walk
+ /// completed without truncation. Negative element existence needs this.
+ pub elements_complete: bool,
+}
+
+#[derive(Debug, Default)]
+pub struct ObservationSample {
+ pub snapshot: ObservationSnapshot,
+ pub visual_evidence: Vec<Content>,
+}
+
+#[async_trait]
+pub trait ObservationProvider: Send + Sync {
+ async fn observe(
+ &self,
+ pid: i64,
+ window_id: u64,
+ include_elements: bool,
+ include_screenshot: bool,
+ ) -> Result<ObservationSample, String>;
+}
+
+/// Adapter over the already-registered platform observation implementations.
+///
+/// Platform registries construct this with fresh tool instances sharing the
+/// same platform state as their public `get_window_state` tool.
+pub struct ToolObservationProvider {
+ list_windows: Arc<dyn Tool>,
+ get_window_state: Arc<dyn Tool>,
+}
+
+impl ToolObservationProvider {
+ pub fn new(list_windows: Arc<dyn Tool>, get_window_state: Arc<dyn Tool>) -> Self {
+ Self {
+ list_windows,
+ get_window_state,
+ }
+ }
+}
+
+#[async_trait]
+impl ObservationProvider for ToolObservationProvider {
+ async fn observe(
+ &self,
+ pid: i64,
+ window_id: u64,
+ include_elements: bool,
+ include_screenshot: bool,
+ ) -> Result<ObservationSample, String> {
+ let listed = self
+ .list_windows
+ .invoke(json!({"pid": pid, "on_screen_only": false}))
+ .await;
+ if listed.is_error == Some(true) {
+ return Err(tool_error_text(&listed, "list_windows failed"));
+ }
+ let window = listed
+ .structured_content
+ .as_ref()
+ .and_then(|value| value.get("windows"))
+ .and_then(Value::as_array)
+ .and_then(|windows| {
+ windows
+ .iter()
+ .find(|window| {
+ window.get("window_id").and_then(Value::as_u64) == Some(window_id)
+ && window.get("pid").and_then(Value::as_i64) == Some(pid)
+ })
+ .cloned()
+ });
+ if window.is_none()
+ && listed
+ .structured_content
+ .as_ref()
+ .and_then(|value| value.get("windows"))
+ .and_then(Value::as_array)
+ .is_some_and(|windows| {
+ windows.iter().any(|candidate| {
+ candidate.get("window_id").and_then(Value::as_u64) == Some(window_id)
+ && candidate.get("pid").is_none_or(Value::is_null)
+ })
+ })
+ {
+ return Err(format!(
+ "window {window_id} was listed without a trustworthy owning pid"
+ ));
+ }
+
+ if window.is_none() || (!include_elements && !include_screenshot) {
+ return Ok(ObservationSample {
+ snapshot: ObservationSnapshot {
+ window,
+ elements: None,
+ element_source_trusted: false,
+ elements_complete: false,
+ },
+ visual_evidence: Vec::new(),
+ });
+ }
+
+ let state = self
+ .get_window_state
+ .invoke(json!({
+ "pid": pid,
+ "window_id": window_id,
+ "include_screenshot": include_screenshot,
+ // Internal direct-tool flag: verification must not refresh the
+ // shared action index/token cache.
+ // Registry ingress removes underscore-prefixed arguments before
+ // public dispatch. Direct platform-tool invocation is the
+ // trusted in-process channel for this non-mutating mode.
+ "_observation_only": true,
+ }))
+ .await;
+ if state.is_error == Some(true) {
+ return Err(tool_error_text(&state, "get_window_state failed"));
+ }
+ let structured = state.structured_content.as_ref();
+ let elements = structured
+ .and_then(|value| value.get("elements"))
+ .and_then(Value::as_array)
+ .cloned();
+ let trusted = structured
+ .and_then(|value| value.get("degraded"))
+ .and_then(Value::as_bool)
+ != Some(true);
+ let complete = structured
+ .and_then(|value| value.get("elements_complete"))
+ .and_then(Value::as_bool)
+ == Some(true);
+ let visual_evidence = state
+ .content
+ .into_iter()
+ .filter(|content| matches!(content, Content::Image { .. }))
+ .collect();
+
+ Ok(ObservationSample {
+ snapshot: ObservationSnapshot {
+ window,
+ elements,
+ element_source_trusted: trusted,
+ elements_complete: complete,
+ },
+ visual_evidence,
+ })
+ }
+}
+
+fn tool_error_text(result: &ToolResult, fallback: &str) -> String {
+ result
+ .content
+ .iter()
+ .find_map(|content| match content {
+ Content::Text { text, .. } => Some(text.clone()),
+ Content::Image { .. } => None,
+ })
+ .unwrap_or_else(|| fallback.to_owned())
+}
+
+pub struct VerifyStateTool {
+ provider: Arc<dyn ObservationProvider>,
+}
+
+impl VerifyStateTool {
+ pub fn new(provider: Arc<dyn ObservationProvider>) -> Self {
+ Self { provider }
+ }
+}
+
+static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();
+
+fn def() -> &'static ToolDef {
+ DEF.get_or_init(|| {
+ let contract = cua_driver_contract::tool_contract(VerifyStateInput::TOOL_NAME)
+ .expect("verify_state contract must be published");
+ ToolDef {
+ name: contract.name,
+ description: contract.description,
+ input_schema: contract.input_schema,
+ read_only: contract.annotations.read_only,
+ destructive: contract.annotations.destructive,
+ idempotent: contract.annotations.idempotent,
+ open_world: contract.annotations.open_world,
+ }
+ })
+}
+
+#[async_trait]
+impl Tool for VerifyStateTool {
+ fn def(&self) -> &ToolDef {
+ def()
+ }
+
+ async fn invoke(&self, args: Value) -> ToolResult {
+ let input: VerifyStateInput = match parse_typed_input("verify_state", args) {
+ Ok(input) => input,
+ Err(error) => return error,
+ };
+ if input.pid <= 0 {
+ return ToolResult::error("verify_state requires pid > 0");
+ }
+ if input.expect.is_empty() || input.expect.len() > MAX_PREDICATES {
+ return ToolResult::error("verify_state requires between 1 and 8 predicates");
+ }
+ if input.timeout_ms.is_some_and(|value| value > MAX_TIMEOUT_MS) {
+ return ToolResult::error("verify_state timeout_ms must be between 0 and 10000");
+ }
+ if input
+ .stable_samples
+ .is_some_and(|value| !(1..=MAX_STABLE_SAMPLES).contains(&value))
+ {
+ return ToolResult::error("verify_state stable_samples must be between 1 and 5");
+ }
+ let timeout_ms = input.timeout_ms.unwrap_or(VERIFY_STATE_DEFAULT_TIMEOUT_MS);
+ if timeout_ms == 0 && input.stable_samples.is_some_and(|samples| samples > 1) {
+ return ToolResult::error(
+ "verify_state timeout_ms=0 requires stable_samples=1 because only one sample is possible",
+ );
+ }
+ let stable_samples = if timeout_ms == 0 {
+ 1
+ } else {
+ input.stable_samples.unwrap_or(DEFAULT_STABLE_SAMPLES)
+ };
+ if let Some(error) = invalid_predicate_message(&input.expect) {
+ return ToolResult::error(error);
+ }
+ let include_elements = input
+ .expect
+ .iter()
+ .any(|predicate| predicate.element.is_some());
+ let started = tokio::time::Instant::now();
+ let deadline = started + Duration::from_millis(timeout_ms);
+ let mut samples = 0u64;
+ let mut consecutive_satisfied = 0u64;
+ let mut stable = false;
+
+ let mut last_outcomes = loop {
+ samples += 1;
+ let outcomes = match self
+ .provider
+ .observe(input.pid, input.window_id, include_elements, false)
+ .await
+ {
+ Ok(sample) => evaluate_predicates(&input.expect, &sample.snapshot),
+ Err(error) => unavailable_outcomes(&input.expect, &error),
+ };
+ let status = aggregate_status(&outcomes);
+ if status == VerificationStatus::Satisfied {
+ consecutive_satisfied += 1;
+ if consecutive_satisfied >= stable_samples {
+ stable = true;
+ break outcomes;
+ }
+ } else {
+ consecutive_satisfied = 0;
+ }
+ if timeout_ms == 0 || tokio::time::Instant::now() >= deadline {
+ break outcomes;
+ }
+ let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
+ tokio::time::sleep(remaining.min(Duration::from_millis(POLL_INTERVAL_MS))).await;
+ };
+
+ let last_status = aggregate_status(&last_outcomes);
+ if last_status == VerificationStatus::Satisfied && !stable {
+ for outcome in &mut last_outcomes {
+ if outcome.status == VerificationStatus::Satisfied {
+ outcome.status = VerificationStatus::Unknown;
+ outcome.unknown_reason = Some(UnknownReason::StabilityUnproven);
+ }
+ }
+ }
+ let status = aggregate_status(&last_outcomes);
+ let elapsed_ms = started.elapsed().as_millis().min(u128::from(u64::MAX)) as u64;
+ let output = VerifyStateOutput {
+ status,
+ stable,
+ elapsed_ms,
+ samples,
+ predicates: last_outcomes,
+ };
+ let mut result = ToolResult::text(format!(
+ "verify_state: {} after {} sample(s) in {} ms",
+ status_label(status),
+ samples,
+ elapsed_ms
+ ))
+ .with_structured(serde_json::to_value(&output).expect("VerifyStateOutput must serialize"));
+
+ if input.include_screenshot == Some(true) {
+ if let Ok(evidence) = self
+ .provider
+ .observe(input.pid, input.window_id, false, true)
+ .await
+ {
+ result.content.extend(evidence.visual_evidence);
+ }
+ }
+ result
+ }
+}
+
+fn invalid_predicate_message(expect: &[StatePredicate]) -> Option<String> {
+ for (index, predicate) in expect.iter().enumerate() {
+ if let Some(element) = predicate.element.as_ref() {
+ if element.exists == Some(false) {
+ return Some(format!(
+ "verify_state predicate {index} element.exists=false is unsupported because element snapshots are not exhaustive"
+ ));
+ }
+ for (name, value) in [
+ ("role", element.selector.role.as_deref()),
+ ("label_contains", element.selector.label_contains.as_deref()),
+ ] {
+ if value.is_some_and(|value| value.trim().is_empty()) {
+ return Some(format!(
+ "verify_state predicate {index} selector {name} must not be empty"
+ ));
+ }
+ }
+ }
+ }
+ None
+}
+
+fn status_label(status: VerificationStatus) -> &'static str {
+ match status {
+ VerificationStatus::Satisfied => "satisfied",
+ VerificationStatus::Unsatisfied => "unsatisfied",
+ VerificationStatus::Unknown => "unknown",
+ }
+}
+
+fn unavailable_outcomes(expect: &[StatePredicate], error: &str) -> Vec<PredicateOutcome> {
+ expect
+ .iter()
+ .enumerate()
+ .map(|(index, _)| PredicateOutcome {
+ index: index as u64,
+ status: VerificationStatus::Unknown,
+ unknown_reason: Some(UnknownReason::ObservationUnavailable),
+ observed_json: Some(bounded_json(&json!({"error": error}))),
+ })
+ .collect()
+}
+
+pub fn evaluate_predicates(
+ expect: &[StatePredicate],
+ snapshot: &ObservationSnapshot,
+) -> Vec<PredicateOutcome> {
+ expect
+ .iter()
+ .enumerate()
+ .map(|(index, predicate)| {
+ let (status, reason, observed) = match (&predicate.window, &predicate.element) {
+ (Some(window), None) => evaluate_window(window, snapshot.window.as_ref()),
+ (None, Some(element)) => evaluate_element(element, snapshot),
+ _ => (
+ VerificationStatus::Unknown,
+ Some(UnknownReason::InvalidPredicate),
+ None,
+ ),
+ };
+ PredicateOutcome {
+ index: index as u64,
+ status,
+ unknown_reason: reason,
+ observed_json: observed.map(|value| bounded_json(&value)),
+ }
+ })
+ .collect()
+}
+
+fn evaluate_window(
+ predicate: &WindowPredicate,
+ window: Option<&Value>,
+) -> (VerificationStatus, Option<UnknownReason>, Option<Value>) {
+ if predicate.exists.is_none() && predicate.bounds.is_none() {
+ return (
+ VerificationStatus::Unknown,
+ Some(UnknownReason::InvalidPredicate),
+ None,
+ );
+ }
+ let exists = window.is_some();
+ if let Some(expected_exists) = predicate.exists {
+ if exists != expected_exists {
+ return (
+ VerificationStatus::Unsatisfied,
+ None,
+ Some(json!({"exists": exists})),
+ );
+ }
+ }
+ let Some(window) = window else {
+ return if predicate.exists == Some(false) && predicate.bounds.is_none() {
+ (
+ VerificationStatus::Satisfied,
+ None,
+ Some(json!({"exists": false})),
+ )
+ } else {
+ (
+ VerificationStatus::Unknown,
+ Some(UnknownReason::TargetMissing),
+ Some(json!({"exists": false})),
+ )
+ };
+ };
+ if let Some(expected) = &predicate.bounds {
+ let Some(bounds) = window.get("bounds") else {
+ return (
+ VerificationStatus::Unknown,
+ Some(UnknownReason::UnsupportedPredicate),
+ Some(json!({"exists": true})),
+ );
+ };
+ let tolerance = expected.tolerance_px.unwrap_or(1.0);
+ let observed = [
+ bounds.get("x").and_then(Value::as_f64),
+ bounds.get("y").and_then(Value::as_f64),
+ bounds.get("width").and_then(Value::as_f64),
+ bounds.get("height").and_then(Value::as_f64),
+ ];
+ if observed.iter().any(Option::is_none) {
+ return (
+ VerificationStatus::Unknown,
+ Some(UnknownReason::UnsupportedPredicate),
+ Some(json!({"exists": true, "bounds": bounds})),
+ );
+ }
+ let observed = [
+ observed[0].unwrap(),
+ observed[1].unwrap(),
+ observed[2].unwrap(),
+ observed[3].unwrap(),
+ ];
+ let expected_values = [expected.x, expected.y, expected.width, expected.height];
+ if observed
+ .iter()
+ .zip(expected_values)
+ .any(|(actual, expected)| (actual - expected).abs() > tolerance)
+ {
+ return (
+ VerificationStatus::Unsatisfied,
+ None,
+ Some(json!({"exists": true, "bounds": bounds})),
+ );
+ }
+ }
+ (
+ VerificationStatus::Satisfied,
+ None,
+ Some(json!({"exists": true, "bounds": window.get("bounds")})),
+ )
+}
+
+fn evaluate_element(
+ predicate: &ElementPredicate,
+ snapshot: &ObservationSnapshot,
+) -> (VerificationStatus, Option<UnknownReason>, Option<Value>) {
+ if predicate.exists == Some(false) {
+ return (
+ VerificationStatus::Unknown,
+ Some(UnknownReason::InvalidPredicate),
+ None,
+ );
+ }
+ if (predicate.selector.role.is_none() && predicate.selector.label_contains.is_none())
+ || predicate
+ .selector
+ .role
+ .as_deref()
+ .is_some_and(|value| value.trim().is_empty())
+ || predicate
+ .selector
+ .label_contains
+ .as_deref()
+ .is_some_and(|value| value.trim().is_empty())
+ {
+ return (
+ VerificationStatus::Unknown,
+ Some(UnknownReason::InvalidPredicate),
+ None,
+ );
+ }
+ if snapshot.window.is_none() {
+ return (
+ VerificationStatus::Unknown,
+ Some(UnknownReason::TargetMissing),
+ Some(json!({"window_exists": false})),
+ );
+ }
+ if !snapshot.element_source_trusted {
+ return (
+ VerificationStatus::Unknown,
+ Some(UnknownReason::UntrustedSource),
+ None,
+ );
+ }
+ let Some(elements) = snapshot.elements.as_ref() else {
+ return (
+ VerificationStatus::Unknown,
+ Some(UnknownReason::ObservationUnavailable),
+ None,
+ );
+ };
+ let matches: Vec<&Value> = elements
+ .iter()
+ .filter(|element| selector_matches(&predicate.selector, element))
+ .collect();
+ if matches.is_empty() {
+ let contains_untrusted_region = elements.iter().any(|element| {
+ element.get("in_web_content").and_then(Value::as_bool) == Some(true)
+ || target_is_in_web_area(element, elements)
+ });
+ if !snapshot.elements_complete || contains_untrusted_region {
+ return (
+ VerificationStatus::Unknown,
+ Some(if contains_untrusted_region {
+ UnknownReason::UntrustedSource
+ } else {
+ UnknownReason::ObservationUnavailable
+ }),
+ Some(json!({
+ "matches": 0,
+ "elements_complete": snapshot.elements_complete,
+ "contains_untrusted_region": contains_untrusted_region
+ })),
+ );
+ }
+ return match predicate.exists {
+ Some(true) => (
+ VerificationStatus::Unsatisfied,
+ None,
+ Some(json!({"matches": 0})),
+ ),
+ _ => (
+ VerificationStatus::Unknown,
+ Some(UnknownReason::TargetMissing),
+ Some(json!({"matches": 0})),
+ ),
+ };
+ }
+ let trusted_matches: Vec<&Value> = matches
+ .iter()
+ .copied()
+ .filter(|element| !target_is_in_web_area(element, elements))
+ .collect();
+ if trusted_matches.is_empty() {
+ return (
+ VerificationStatus::Unknown,
+ Some(UnknownReason::UntrustedSource),
+ Some(json!({"matches": matches.len()})),
+ );
+ }
+ if trusted_matches.len() > 1
+ && (predicate.value_equals.is_some()
+ || predicate.enabled.is_some()
+ || predicate.selected.is_some())
+ {
+ return (
+ VerificationStatus::Unknown,
+ Some(UnknownReason::MultiMatch),
+ Some(json!({"matches": trusted_matches.len()})),
+ );
+ }
+ if trusted_matches.len() > 1 {
+ return (
+ VerificationStatus::Satisfied,
+ None,
+ Some(json!({"matches": trusted_matches.len()})),
+ );
+ }
+ let element = trusted_matches[0];
+ for (field, expected) in [
+ (
+ "value",
+ predicate
+ .value_equals
+ .as_ref()
+ .map(|value| Value::String(value.clone())),
+ ),
+ ("enabled", predicate.enabled.map(Value::Bool)),
+ ("selected", predicate.selected.map(Value::Bool)),
+ ] {
+ let Some(expected) = expected else {
+ continue;
+ };
+ let Some(actual) = element.get(field) else {
+ return (
+ VerificationStatus::Unknown,
+ Some(UnknownReason::UnsupportedPredicate),
+ Some(project_element(element)),
+ );
+ };
+ if actual != &expected {
+ return (
+ VerificationStatus::Unsatisfied,
+ None,
+ Some(project_element(element)),
+ );
+ }
+ }
+ (
+ VerificationStatus::Satisfied,
+ None,
+ Some(project_element(element)),
+ )
+}
+
+fn selector_matches(selector: &cua_driver_contract::ElementSelector, element: &Value) -> bool {
+ if let Some(role) = selector.role.as_deref() {
+ if !element
+ .get("role")
+ .and_then(Value::as_str)
+ .is_some_and(|actual| normalized_role(actual) == normalized_role(role))
+ {
+ return false;
+ }
+ }
+ if let Some(label) = selector.label_contains.as_deref() {
+ let needle = label.to_lowercase();
+ if !element
+ .get("label")
+ .and_then(Value::as_str)
+ .is_some_and(|actual| actual.to_lowercase().contains(&needle))
+ {
+ return false;
+ }
+ }
+ true
+}
+
+fn normalized_role(role: &str) -> String {
+ let normalized: String = role
+ .chars()
+ .filter(|character| character.is_ascii_alphanumeric())
+ .flat_map(char::to_lowercase)
+ .collect();
+ let normalized = normalized
+ .strip_prefix("ax")
+ .unwrap_or(&normalized)
+ .to_owned();
+ match normalized.as_str() {
+ "pushbutton" => "button".to_owned(),
+ "pagetab" | "tabitem" => "tab".to_owned(),
+ _ => normalized,
+ }
+}
+
+fn target_is_in_web_area(target: &Value, elements: &[Value]) -> bool {
+ let by_index: HashMap<u64, &Value> = elements
+ .iter()
+ .filter_map(|element| {
+ element
+ .get("element_index")
+ .and_then(Value::as_u64)
+ .map(|index| (index, element))
+ })
+ .collect();
+ let mut current = Some(target);
+ for _ in 0..32 {
+ let Some(element) = current else {
+ break;
+ };
+ if element.get("in_web_content").and_then(Value::as_bool) == Some(true) {
+ return true;
+ }
+ if element
+ .get("role")
+ .and_then(Value::as_str)
+ .is_some_and(|role| {
+ let normalized = role.to_ascii_lowercase().replace(['_', ' '], "");
+ normalized.contains("webarea")
+ || normalized.contains("document")
+ || normalized == "embedded"
+ })
+ {
+ return true;
+ }
+ current = element
+ .get("parent_index")
+ .and_then(Value::as_u64)
+ .and_then(|index| by_index.get(&index).copied());
+ }
+ false
+}
+
+fn project_element(element: &Value) -> Value {
+ let mut projection = serde_json::Map::new();
+ for key in [
+ "element_index",
+ "role",
+ "label",
+ "value",
+ "enabled",
+ "selected",
+ "frame",
+ ] {
+ if let Some(value) = element.get(key) {
+ projection.insert(key.to_owned(), value.clone());
+ }
+ }
+ Value::Object(projection)
+}
+
+fn bounded_json(value: &Value) -> String {
+ let mut encoded = serde_json::to_string(value).unwrap_or_else(|_| "{}".to_owned());
+ if encoded.len() > 2_000 {
+ let mut boundary = 1_997;
+ while !encoded.is_char_boundary(boundary) {
+ boundary -= 1;
+ }
+ encoded.truncate(boundary);
+ encoded.push_str("...");
+ }
+ encoded
+}
+
+fn aggregate_status(outcomes: &[PredicateOutcome]) -> VerificationStatus {
+ if outcomes
+ .iter()
+ .any(|outcome| outcome.status == VerificationStatus::Unsatisfied)
+ {
+ VerificationStatus::Unsatisfied
+ } else if outcomes
+ .iter()
+ .any(|outcome| outcome.status == VerificationStatus::Unknown)
+ {
+ VerificationStatus::Unknown
+ } else {
+ VerificationStatus::Satisfied
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cua_driver_contract::{
+ BoundsExpectation, ElementSelector, VerificationStatus, WindowPredicate,
+ };
+
+ fn window() -> Value {
+ json!({
+ "window_id": 7,
+ "pid": 42,
+ "bounds": {"x": 10.0, "y": 20.0, "width": 300.0, "height": 400.0}
+ })
+ }
+
+ fn element_predicate(label: &str) -> StatePredicate {
+ StatePredicate {
+ window: None,
+ element: Some(ElementPredicate {
+ selector: ElementSelector {
+ role: Some("checkbox".into()),
+ label_contains: Some(label.into()),
+ },
+ exists: Some(true),
+ value_equals: Some("1".into()),
+ enabled: None,
+ selected: None,
+ }),
+ }
+ }
+
+ #[test]
+ fn evaluates_window_bounds_with_tolerance() {
+ let predicates = vec![StatePredicate {
+ window: Some(WindowPredicate {
+ exists: Some(true),
+ bounds: Some(BoundsExpectation {
+ x: 10.5,
+ y: 20.0,
+ width: 300.0,
+ height: 400.0,
+ tolerance_px: Some(1.0),
+ }),
+ }),
+ element: None,
+ }];
+ let outcomes = evaluate_predicates(
+ &predicates,
+ &ObservationSnapshot {
+ window: Some(window()),
+ elements: None,
+ element_source_trusted: false,
+ elements_complete: false,
+ },
+ );
+ assert_eq!(outcomes[0].status, VerificationStatus::Satisfied);
+ }
+
+ #[test]
+ fn unique_element_value_is_satisfied() {
+ let outcomes = evaluate_predicates(
+ &[element_predicate("updates")],
+ &ObservationSnapshot {
+ window: Some(window()),
+ elements: Some(vec![json!({
+ "element_index": 3,
+ "role": "checkbox",
+ "label": "Automatically check for updates",
+ "value": "1"
+ })]),
+ element_source_trusted: true,
+ elements_complete: true,
+ },
+ );
+ assert_eq!(outcomes[0].status, VerificationStatus::Satisfied);
+ }
+
+ #[test]
+ fn duplicate_property_target_is_unknown_not_first_match_wins() {
+ let element = json!({
+ "element_index": 3,
+ "role": "checkbox",
+ "label": "Updates",
+ "value": "1"
+ });
+ let outcomes = evaluate_predicates(
+ &[element_predicate("updates")],
+ &ObservationSnapshot {
+ window: Some(window()),
+ elements: Some(vec![element.clone(), element]),
+ element_source_trusted: true,
+ elements_complete: true,
+ },
+ );
+ assert_eq!(outcomes[0].status, VerificationStatus::Unknown);
+ assert_eq!(outcomes[0].unknown_reason, Some(UnknownReason::MultiMatch));
+ }
+
+ #[test]
+ fn web_area_readback_is_unknown() {
+ let outcomes = evaluate_predicates(
+ &[element_predicate("updates")],
+ &ObservationSnapshot {
+ window: Some(window()),
+ elements: Some(vec![
+ json!({
+ "element_index": 1,
+ "role": "AXWebArea",
+ "label": "Page"
+ }),
+ json!({
+ "element_index": 3,
+ "parent_index": 1,
+ "role": "checkbox",
+ "label": "Updates",
+ "value": "1"
+ }),
+ ]),
+ element_source_trusted: true,
+ elements_complete: true,
+ },
+ );
+ assert_eq!(outcomes[0].status, VerificationStatus::Unknown);
+ assert_eq!(
+ outcomes[0].unknown_reason,
+ Some(UnknownReason::UntrustedSource)
+ );
+ }
+
+ #[test]
+ fn web_area_existence_is_unknown_even_with_multiple_matches() {
+ let mut predicate = element_predicate("updates");
+ predicate.element.as_mut().unwrap().value_equals = None;
+ let outcomes = evaluate_predicates(
+ &[predicate],
+ &ObservationSnapshot {
+ window: Some(window()),
+ elements: Some(vec![
+ json!({"element_index": 1, "role": "WebArea", "label": "Page"}),
+ json!({
+ "element_index": 2,
+ "parent_index": 1,
+ "role": "checkbox",
+ "label": "Updates"
+ }),
+ json!({
+ "element_index": 3,
+ "parent_index": 1,
+ "role": "checkbox",
+ "label": "Updates"
+ }),
+ ]),
+ element_source_trusted: true,
+ elements_complete: true,
+ },
+ );
+ assert_eq!(outcomes[0].status, VerificationStatus::Unknown);
+ assert_eq!(
+ outcomes[0].unknown_reason,
+ Some(UnknownReason::UntrustedSource)
+ );
+ }
+
+ #[test]
+ fn normalizes_native_roles_across_platforms() {
+ for native_role in ["AXCheckBox", "CheckBox", "check box"] {
+ let outcomes = evaluate_predicates(
+ &[element_predicate("updates")],
+ &ObservationSnapshot {
+ window: Some(window()),
+ elements: Some(vec![json!({
+ "element_index": 3,
+ "role": native_role,
+ "label": "Updates",
+ "value": "1"
+ })]),
+ element_source_trusted: true,
+ elements_complete: true,
+ },
+ );
+ assert_eq!(
+ outcomes[0].status,
+ VerificationStatus::Satisfied,
+ "native role {native_role} should normalize to checkbox"
+ );
+ }
+ assert_eq!(normalized_role("AXButton"), normalized_role("push button"));
+ assert_eq!(normalized_role("TabItem"), normalized_role("page tab"));
+ }
+
+ #[test]
+ fn explicit_windows_and_linux_web_markers_are_untrusted() {
+ for native_role in ["Document", "document web"] {
+ let outcomes = evaluate_predicates(
+ &[element_predicate("updates")],
+ &ObservationSnapshot {
+ window: Some(window()),
+ elements: Some(vec![json!({
+ "element_index": 3,
+ "role": native_role,
+ "label": "Updates",
+ "value": "1",
+ "in_web_content": true
+ })]),
+ element_source_trusted: true,
+ elements_complete: true,
+ },
+ );
+ assert_eq!(outcomes[0].status, VerificationStatus::Unknown);
+ assert_eq!(
+ outcomes[0].unknown_reason,
+ Some(UnknownReason::UntrustedSource)
+ );
+ }
+ }
+
+ #[test]
+ fn negative_element_existence_is_invalid_even_for_incomplete_walks() {
+ let predicate = StatePredicate {
+ window: None,
+ element: Some(ElementPredicate {
+ selector: ElementSelector {
+ role: Some("button".into()),
+ label_contains: Some("Missing".into()),
+ },
+ exists: Some(false),
+ value_equals: None,
+ enabled: None,
+ selected: None,
+ }),
+ };
+ let outcomes = evaluate_predicates(
+ &[predicate],
+ &ObservationSnapshot {
+ window: Some(window()),
+ elements: Some(vec![]),
+ element_source_trusted: true,
+ elements_complete: false,
+ },
+ );
+ assert_eq!(outcomes[0].status, VerificationStatus::Unknown);
+ assert_eq!(
+ outcomes[0].unknown_reason,
+ Some(UnknownReason::InvalidPredicate)
+ );
+ }
+
+ #[test]
+ fn empty_selector_value_is_invalid() {
+ let mut predicate = element_predicate("");
+ predicate.element.as_mut().unwrap().selector.role = Some(" ".into());
+ let outcomes = evaluate_predicates(
+ &[predicate],
+ &ObservationSnapshot {
+ window: Some(window()),
+ elements: Some(vec![]),
+ element_source_trusted: true,
+ elements_complete: true,
+ },
+ );
+ assert_eq!(outcomes[0].status, VerificationStatus::Unknown);
+ assert_eq!(
+ outcomes[0].unknown_reason,
+ Some(UnknownReason::InvalidPredicate)
+ );
+ }
+
+ #[test]
+ fn missing_optional_property_is_unknown_not_false() {
+ let mut predicate = element_predicate("updates");
+ let element = predicate.element.as_mut().unwrap();
+ element.value_equals = None;
+ element.enabled = Some(true);
+ let outcomes = evaluate_predicates(
+ &[predicate],
+ &ObservationSnapshot {
+ window: Some(window()),
+ elements: Some(vec![json!({
+ "element_index": 3,
+ "role": "checkbox",
+ "label": "Updates"
+ })]),
+ element_source_trusted: true,
+ elements_complete: true,
+ },
+ );
+ assert_eq!(outcomes[0].status, VerificationStatus::Unknown);
+ assert_eq!(
+ outcomes[0].unknown_reason,
+ Some(UnknownReason::UnsupportedPredicate)
+ );
+ }
+
+ struct FakeProvider {
+ calls: std::sync::atomic::AtomicUsize,
+ snapshot: ObservationSnapshot,
+ }
+
+ #[async_trait]
+ impl ObservationProvider for FakeProvider {
+ async fn observe(
+ &self,
+ _pid: i64,
+ _window_id: u64,
+ _include_elements: bool,
+ include_screenshot: bool,
+ ) -> Result<ObservationSample, String> {
+ self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ Ok(ObservationSample {
+ snapshot: self.snapshot.clone(),
+ visual_evidence: include_screenshot
+ .then(|| Content::image_png("cG5n".into()))
+ .into_iter()
+ .collect(),
+ })
+ }
+ }
+
+ #[tokio::test]
+ async fn verify_tool_waits_for_stability_and_returns_visual_evidence() {
+ let provider = Arc::new(FakeProvider {
+ calls: std::sync::atomic::AtomicUsize::new(0),
+ snapshot: ObservationSnapshot {
+ window: Some(window()),
+ elements: None,
+ element_source_trusted: false,
+ elements_complete: false,
+ },
+ });
+ let tool = VerifyStateTool::new(provider.clone());
+ let result = tool
+ .invoke(json!({
+ "pid": 42,
+ "window_id": 7,
+ "expect": [{
+ "window": {
+ "exists": true,
+ "bounds": {
+ "x": 10,
+ "y": 20,
+ "width": 300,
+ "height": 400,
+ "tolerance_px": 0
+ }
+ }
+ }],
+ "timeout_ms": 500,
+ "stable_samples": 2,
+ "include_screenshot": true
+ }))
+ .await;
+ assert_ne!(result.is_error, Some(true));
+ assert_eq!(
+ result.structured_content.as_ref().unwrap()["status"],
+ json!("satisfied")
+ );
+ assert_eq!(
+ result.structured_content.as_ref().unwrap()["samples"],
+ json!(2)
+ );
+ assert_eq!(
+ provider.calls.load(std::sync::atomic::Ordering::SeqCst),
+ 3,
+ "two verification samples plus one final visual-evidence capture"
+ );
+ assert!(result
+ .content
+ .iter()
+ .any(|content| matches!(content, Content::Image { .. })));
+ }
+
+ #[tokio::test]
+ async fn verify_tool_ignores_trusted_transport_metadata() {
+ let provider = Arc::new(FakeProvider {
+ calls: std::sync::atomic::AtomicUsize::new(0),
+ snapshot: ObservationSnapshot {
+ window: Some(window()),
+ elements: None,
+ element_source_trusted: false,
+ elements_complete: false,
+ },
+ });
+ let result = VerifyStateTool::new(provider)
+ .invoke(json!({
+ "pid": 42,
+ "window_id": 7,
+ "expect": [{"window": {"exists": true}}],
+ "timeout_ms": 0,
+ "stable_samples": 1,
+ "_session_id": "injected-by-daemon",
+ "_transport_session_id": "injected-by-daemon"
+ }))
+ .await;
+ assert_ne!(result.is_error, Some(true));
+ assert_eq!(
+ result.structured_content.as_ref().unwrap()["status"],
+ json!("satisfied")
+ );
+ }
+
+ #[tokio::test]
+ async fn verify_tool_rejects_out_of_contract_polling_bounds() {
+ let provider = Arc::new(FakeProvider {
+ calls: std::sync::atomic::AtomicUsize::new(0),
+ snapshot: ObservationSnapshot::default(),
+ });
+ let tool = VerifyStateTool::new(provider.clone());
+ for invalid in [
+ json!({
+ "pid": 42, "window_id": 7,
+ "expect": [{"window": {"exists": true}}],
+ "timeout_ms": 10_001
+ }),
+ json!({
+ "pid": 42, "window_id": 7,
+ "expect": [{"window": {"exists": true}}],
+ "stable_samples": 0
+ }),
+ json!({
+ "pid": 42, "window_id": 7,
+ "expect": [{"window": {"exists": true}}],
+ "timeout_ms": 0,
+ "stable_samples": 2
+ }),
+ json!({
+ "pid": 42, "window_id": 7,
+ "expect": [{"element": {
+ "selector": {"label_contains": ""}
+ }}]
+ }),
+ json!({
+ "pid": 42, "window_id": 7,
+ "expect": [{"element": {
+ "selector": {"role": "button"},
+ "exists": false
+ }}]
+ }),
+ ] {
+ assert_eq!(tool.invoke(invalid).await.is_error, Some(true));
+ }
+ assert_eq!(provider.calls.load(std::sync::atomic::Ordering::SeqCst), 0);
+ }
+
+ #[tokio::test]
+ async fn satisfied_last_sample_is_not_success_without_required_stability() {
+ let provider = Arc::new(FakeProvider {
+ calls: std::sync::atomic::AtomicUsize::new(0),
+ snapshot: ObservationSnapshot {
+ window: Some(window()),
+ elements: None,
+ element_source_trusted: false,
+ elements_complete: false,
+ },
+ });
+ let result = VerifyStateTool::new(provider)
+ .invoke(json!({
+ "pid": 42,
+ "window_id": 7,
+ "expect": [{"window": {"exists": true}}],
+ "timeout_ms": 1,
+ "stable_samples": 5
+ }))
+ .await;
+ assert_eq!(
+ result.structured_content.as_ref().unwrap()["status"],
+ json!("unknown")
+ );
+ assert_eq!(
+ result.structured_content.as_ref().unwrap()["stable"],
+ json!(false)
+ );
+ assert_eq!(
+ result.structured_content.as_ref().unwrap()["predicates"][0]["status"],
+ json!("unknown")
+ );
+ assert_eq!(
+ result.structured_content.as_ref().unwrap()["predicates"][0]["unknown_reason"],
+ json!("stability_unproven")
+ );
+ }
+
+ struct TransientProvider {
+ calls: std::sync::atomic::AtomicUsize,
+ }
+
+ #[async_trait]
+ impl ObservationProvider for TransientProvider {
+ async fn observe(
+ &self,
+ _pid: i64,
+ _window_id: u64,
+ _include_elements: bool,
+ _include_screenshot: bool,
+ ) -> Result<ObservationSample, String> {
+ let call = self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ if call == 0 {
+ Err("transient observation failure".into())
+ } else {
+ Ok(ObservationSample {
+ snapshot: ObservationSnapshot {
+ window: Some(window()),
+ elements: None,
+ element_source_trusted: false,
+ elements_complete: false,
+ },
+ visual_evidence: vec![],
+ })
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn transient_observation_failure_is_retried_until_stable() {
+ let provider = Arc::new(TransientProvider {
+ calls: std::sync::atomic::AtomicUsize::new(0),
+ });
+ let result = VerifyStateTool::new(provider.clone())
+ .invoke(json!({
+ "pid": 42,
+ "window_id": 7,
+ "expect": [{"window": {"exists": true}}],
+ "timeout_ms": 500,
+ "stable_samples": 2
+ }))
+ .await;
+ assert_eq!(
+ result.structured_content.as_ref().unwrap()["status"],
+ json!("satisfied")
+ );
+ assert_eq!(
+ provider.calls.load(std::sync::atomic::Ordering::SeqCst),
+ 3,
+ "one transient error plus two stable samples"
+ );
+ }
+
+ #[test]
+ fn observed_json_utf8_truncation_is_bounded_and_valid() {
+ let encoded = bounded_json(&json!({"label": "é".repeat(2_000)}));
+ assert!(encoded.len() <= 2_000);
+ assert!(encoded.ends_with("..."));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
index f98663ed3a..1e77be9656 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
@@ -56,6 +56,7 @@ pub mod cursor_sampler;
pub mod daemon;
pub mod element_cache;
pub mod element_token;
+pub mod expectation;
pub mod ffmpeg_install;
pub mod health_report;
pub mod image_utils;
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs
index 4badd6ecab..94a1211cfb 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs
@@ -356,17 +356,16 @@ fn agent_instructions() -> String {
format!(
r#"cua-driver: cross-platform background computer-use automation.
-Tools let you interact with any app without stealing keyboard focus or moving the visible cursor. Prefer element_index ({tree_kind}) paths over pixel coordinates — they work on backgrounded/hidden windows.
+Tools operate apps without stealing focus or moving the real pointer. Prefer `element_index` ({tree_kind}) over pixels; it works on backgrounded or hidden windows.
Workflow per turn:
-0. start_session(session) once at the start of a run → declares THIS run's identity (a stable id you choose, e.g. "research-1"). Pass that same `session` on every action below. It owns your agent cursor (a distinct color per id) and follows the run across apps/windows. End with end_session(session) when done. Concurrent runs/subagents each use their OWN `session`. (Omitting `session` still works, just with no cursor.)
-1. launch_app → idempotent, returns pid + windows array in one call. Pass creates_new_application_instance:true if another run may touch the same app, so you get your own window.
-2. (skip list_windows when launch_app already returned a single window)
-3. get_window_state(pid, window_id) → refresh the {tree_kind} snapshot, get element indices
-4. click/type_text/press_key using element_index from step 3 (+ your `session`)
-5. get_window_state(pid, window_id) again → verify the action landed
+0. `start_session(session)` once per run; reuse that id on actions. Concurrent runs use distinct ids. End it when done.
+1. `launch_app` returns pid and windows. Use `creates_new_application_instance:true` when another run may touch the app.
+2. `get_window_state(pid, window_id)` refreshes the tree and element indices.
+3. Act with the fresh index.
+4. `verify_state(pid, window_id, expect)` checks bounded structured postconditions. `unknown` is not success. Set `include_screenshot:true` when the multimodal agent should also read visual evidence and decide whether to stop, retry, or advance the ladder.
-Agent cursor: a per-SESSION overlay cursor visualises where a run is acting without moving the real pointer. It is shown only for a DECLARED session (pass `session`), is color-coded by the session id, and is removed by end_session or the idle-TTL. The same id over MCP, the CLI, or the raw socket drives the same cursor. set_agent_cursor_* tools hide/show/customise it. Note: a pure accessibility-action (element_index) click snaps the cursor with a brief pulse on its first action rather than a long glide, so it can be easy to miss — issue a pixel click or move_cursor first for a visibly gliding demo/recording.
+A declared session owns a colored agent-cursor overlay; it never moves the real pointer. Pure accessibility actions show only a brief first pulse. Use `move_cursor` or a pixel action first when a recording needs a visible glide.
If a `cua-driver` skill is loaded in your harness (Claude Code / Codex / OpenClaw / OpenCode dirs), prefer its detailed workflow — SKILL.md plus {platform_skill_pointer}. Install with `cua-driver skills install` if not yet present."#
)
@@ -418,6 +417,23 @@ mod image_mime_type_tests {
}
}
+#[cfg(test)]
+mod agent_instruction_tests {
+ use super::agent_instructions;
+
+ #[test]
+ fn instructions_route_structured_and_visual_verification_to_the_right_owner() {
+ let instructions = agent_instructions();
+ assert!(instructions.contains("verify_state"));
+ assert!(instructions.contains("`unknown` is not success"));
+ assert!(instructions.contains("multimodal agent"));
+ assert!(
+ instructions.split_whitespace().count() <= 200,
+ "initialize instructions should stay within the documented context budget"
+ );
+ }
+}
+
#[cfg(test)]
mod initialize_metadata_tests {
use super::*;
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session_manifest.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session_manifest.rs
index f6a5b3ff0c..2c80907f61 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session_manifest.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session_manifest.rs
@@ -828,6 +828,7 @@ pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {
"parallel_mouse_drag",
"get_accessibility_tree",
"get_window_state",
+ "verify_state",
"get_desktop_state",
];
if let Some(tool) = ORIGIN_BYPASS_TOOLS
@@ -1693,8 +1694,9 @@ allow:
assert!(loaded.is_idle_expired());
assert!(loaded.authorize_dispatch().is_err());
- assert!(manifest(
- r#"
+ for bypass_tool in ["page", "verify_state"] {
+ let policy = format!(
+ r#"
version: 1
mode: bounded
expires_after: 1h
@@ -1703,11 +1705,16 @@ resources:
browser:
origins: [https://app.example.com]
allow:
- tools: [browser_navigate, page]
-"#,
- )
- .unwrap_err()
- .contains("bypasses the typed browser origin adapter"));
+ tools: [browser_navigate, {bypass_tool}]
+"#
+ );
+ assert!(
+ manifest(&policy)
+ .unwrap_err()
+ .contains("bypasses the typed browser origin adapter"),
+ "{bypass_tool} must not bypass origin-scoped browser policy"
+ );
+ }
}
#[cfg(feature = "yaml")]
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool_args.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool_args.rs
index 4282bb54fb..289447aeaf 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool_args.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool_args.rs
@@ -98,6 +98,7 @@ mod reserved_args_tests {
let mut args = json!({
"pid": 42,
"_session_id": "forged",
+ "_observation_only": true,
"_cua_browser_prepare_mcp_host_approved": true,
"profile": {"mode": "isolated_new", "_future_public_field": "retained"}
});
diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs
index e17362051f..a95719e408 100644
--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs
@@ -11,6 +11,7 @@ use cua_driver_contract::{
GetSessionStateInput, HotkeyInput, MoveCursorInput, PressKeyInput, ScrollInput,
SessionStateOutput, SetAgentCursorEnabledInput, SetAgentCursorMotionInput,
SetAgentCursorThemeInput, StartSessionInput, StartSessionOutput, ToolInput, TypeTextInput,
+ VerifyStateInput,
};
use cua_driver_core::daemon::{
is_daemon_listening, request_daemon_metadata, send_request, socket_path_for_namespace,
@@ -552,6 +553,7 @@ macro_rules! desktop_tool_methods {
get_desktop_state: GetDesktopStateInput,
get_screen_size: GetScreenSizeInput,
get_cursor_position: GetCursorPositionInput,
+ verify_state: VerifyStateInput,
move_cursor: MoveCursorInput,
click: ClickInput,
drag: DragInput,
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs
index eaf0ba9409..4c195f6b57 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs
@@ -685,6 +685,76 @@ fn harness_gtk3_ax_tree() {
);
}
+#[test]
+#[ignore]
+fn harness_gtk3_verify_state() {
+ run_case(
+ native_readonly_case(
+ "gtk3",
+ "verify_state",
+ Targeting::Ax,
+ DriverRoute::AxRead,
+ vec![OracleKind::AxState],
+ ),
+ |pid, window_id, driver| {
+ let verified = driver.call(
+ "verify_state",
+ serde_json::json!({
+ "pid": pid as i64,
+ "window_id": window_id,
+ "expect": [
+ {"window": {"exists": true}},
+ {"element": {
+ "selector": {"label_contains": "btn-increment"},
+ "exists": true,
+ "enabled": true
+ }},
+ {"element": {
+ "selector": {"label_contains": "chk-agree"},
+ "exists": true,
+ "selected": false
+ }}
+ ],
+ "timeout_ms": 10_000,
+ "stable_samples": 2,
+ "include_screenshot": true
+ }),
+ );
+ assert!(
+ !verified.is_error(),
+ "GTK3 verify_state failed: {}",
+ verified.text()
+ );
+ assert_eq!(
+ verified.structured()["status"],
+ "satisfied",
+ "verify_state outcome: {}",
+ verified.structured()
+ );
+ assert_eq!(
+ verified.structured()["stable"],
+ true,
+ "verify_state outcome: {}",
+ verified.structured()
+ );
+ assert!(
+ verified.structured()["samples"].as_u64().unwrap_or(0) >= 2,
+ "verify_state did not enforce consecutive stable samples: {}",
+ verified.structured()
+ );
+ assert!(
+ verified.raw["result"]["content"]
+ .as_array()
+ .is_some_and(|content| content.iter().any(|item| {
+ item["type"] == "image" && item["mimeType"] == "image/png"
+ })),
+ "verify_state did not return final visual evidence"
+ );
+ Observation::delivered(vec![OracleKind::AxState], Evidence::default())
+ },
+ );
+}
+
macro_rules! catalog_test {
($name:ident, $row:expr) => {
#[test]
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_swiftui_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/harness_swiftui_test.rs
index 5df102bdcd..3ef0fa7438 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/harness_swiftui_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/harness_swiftui_test.rs
@@ -180,6 +180,76 @@ fn harness_swiftui_smoke() {
);
}
+#[test]
+#[ignore]
+fn harness_swiftui_verify_state() {
+ run_case(
+ native_readonly_case(
+ "swiftui",
+ "verify_state",
+ Targeting::Ax,
+ DriverRoute::AxRead,
+ vec![OracleKind::AxState],
+ ),
+ |pid, wid, driver| {
+ let verified = driver.call(
+ "verify_state",
+ serde_json::json!({
+ "pid": pid as i64,
+ "window_id": wid,
+ "expect": [
+ {"window": {"exists": true}},
+ {"element": {
+ "selector": {"label_contains": "Increment"},
+ "exists": true,
+ "enabled": true
+ }},
+ {"element": {
+ "selector": {"label_contains": "I agree"},
+ "exists": true,
+ "selected": false
+ }}
+ ],
+ "timeout_ms": 10_000,
+ "stable_samples": 2,
+ "include_screenshot": true
+ }),
+ );
+ assert!(
+ !verified.is_error(),
+ "SwiftUI verify_state failed: {}",
+ verified.text()
+ );
+ assert_eq!(
+ verified.structured()["status"],
+ "satisfied",
+ "verify_state outcome: {}",
+ verified.structured()
+ );
+ assert_eq!(
+ verified.structured()["stable"],
+ true,
+ "verify_state outcome: {}",
+ verified.structured()
+ );
+ assert!(
+ verified.structured()["samples"].as_u64().unwrap_or(0) >= 2,
+ "verify_state did not enforce consecutive stable samples: {}",
+ verified.structured()
+ );
+ assert!(
+ verified.raw["result"]["content"]
+ .as_array()
+ .is_some_and(|content| content.iter().any(|item| {
+ item["type"] == "image" && item["mimeType"] == "image/png"
+ })),
+ "verify_state did not return final visual evidence"
+ );
+ Observation::delivered(vec![OracleKind::AxState], Evidence::default())
+ },
+ );
+}
+
#[test]
#[ignore]
fn harness_swiftui_counter_background() {
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_winui3_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/harness_winui3_test.rs
index 29c6b66c03..88d152bfbc 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/harness_winui3_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/harness_winui3_test.rs
@@ -176,6 +176,76 @@ fn harness_winui3_smoke() {
);
}
+#[test]
+#[ignore]
+fn harness_winui3_verify_state() {
+ run_case(
+ native_readonly_case(
+ "winui3",
+ "verify_state",
+ Targeting::Ax,
+ DriverRoute::AxRead,
+ vec![OracleKind::AxState],
+ ),
+ |pid, wid, driver| {
+ let verified = driver.call(
+ "verify_state",
+ serde_json::json!({
+ "pid": pid as i64,
+ "window_id": wid,
+ "expect": [
+ {"window": {"exists": true}},
+ {"element": {
+ "selector": {"label_contains": "Increment"},
+ "exists": true,
+ "enabled": true
+ }},
+ {"element": {
+ "selector": {"label_contains": "I agree"},
+ "exists": true,
+ "selected": false
+ }}
+ ],
+ "timeout_ms": 10_000,
+ "stable_samples": 2,
+ "include_screenshot": true
+ }),
+ );
+ assert!(
+ !verified.is_error(),
+ "WinUI3 verify_state failed: {}",
+ verified.text()
+ );
+ assert_eq!(
+ verified.structured()["status"],
+ "satisfied",
+ "verify_state outcome: {}",
+ verified.structured()
+ );
+ assert_eq!(
+ verified.structured()["stable"],
+ true,
+ "verify_state outcome: {}",
+ verified.structured()
+ );
+ assert!(
+ verified.structured()["samples"].as_u64().unwrap_or(0) >= 2,
+ "verify_state did not enforce consecutive stable samples: {}",
+ verified.structured()
+ );
+ assert!(
+ verified.raw["result"]["content"]
+ .as_array()
+ .is_some_and(|content| content.iter().any(|item| {
+ item["type"] == "image" && item["mimeType"] == "image/png"
+ })),
+ "verify_state did not return final visual evidence"
+ );
+ Observation::delivered(vec![OracleKind::AxState], Evidence::default())
+ },
+ );
+}
+
#[test]
#[ignore]
fn harness_winui3_type_text() {
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs
index 9ef2bd029f..5336a8dc2b 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/atspi/mod.rs
@@ -24,6 +24,10 @@ pub struct AtspiNode {
pub value: Option<String>,
/// Checked state when the accessibility backend exposes one for a toggle.
pub checked: Option<bool>,
+ /// Enabled state when the accessibility backend returned a state set.
+ pub enabled: Option<bool>,
+ /// Toggle/selection state for selectable controls.
+ pub selected: Option<bool>,
pub description: Option<String>,
pub actions: Vec<String>,
/// For AT-SPI: element_key = element_index as u64.
@@ -44,6 +48,9 @@ pub struct AtspiTreeResult {
pub tree_markdown: String,
pub nodes: Vec<AtspiNode>,
pub bounds: Vec<(usize, i32, i32, u32, u32)>,
+ /// True only for a native AT-SPI walk. The X11 property fallback is a
+ /// partial discovery aid and must not prove verification predicates.
+ pub trusted: bool,
}
/// Walk the AT-SPI tree for a window identified by (pid, xid).
@@ -71,6 +78,7 @@ pub(crate) fn walk_tree_for_recording(
tree_markdown,
nodes,
bounds,
+ trusted: true,
};
}
}
@@ -114,6 +122,7 @@ pub fn walk_tree_bounded(
tree_markdown: md,
nodes,
bounds,
+ trusted: true,
};
}
}
@@ -231,6 +240,7 @@ fn walk_via_x11_properties(xid: u64, query: Option<&str>) -> AtspiTreeResult {
tree_markdown: String::new(),
nodes: vec![],
bounds: vec![],
+ trusted: false,
}
}
};
@@ -256,6 +266,8 @@ fn walk_via_x11_properties(xid: u64, query: Option<&str>) -> AtspiTreeResult {
},
value: None,
checked: None,
+ enabled: None,
+ selected: None,
description: if wm_class.is_empty() {
None
} else {
@@ -284,6 +296,7 @@ fn walk_via_x11_properties(xid: u64, query: Option<&str>) -> AtspiTreeResult {
tree_markdown,
nodes,
bounds: vec![],
+ trusted: false,
}
}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs b/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs
index 3d0aaeb400..915af05240 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs
@@ -129,6 +129,8 @@ struct Visited<'a> {
name: String,
value: Option<String>,
checked: Option<bool>,
+ enabled: Option<bool>,
+ selected: Option<bool>,
actions: Vec<String>,
has_editable: bool,
has_value: bool,
@@ -488,7 +490,8 @@ async fn collect_visited_bounded<'a>(
_ => String::new(),
};
let focused = matches!(state_r.as_ref(), Some(Ok(s)) if s.contains(State::Focused));
- let checked = if role.to_ascii_lowercase().contains("check") {
+ let role_lower = role.to_ascii_lowercase();
+ let checked = if role_lower.contains("check") {
state_r
.as_ref()
.and_then(|state| state.as_ref().ok())
@@ -496,6 +499,24 @@ async fn collect_visited_bounded<'a>(
} else {
None
};
+ let enabled = state_r
+ .as_ref()
+ .and_then(|state| state.as_ref().ok())
+ .map(|state| state.contains(State::Enabled) && state.contains(State::Sensitive));
+ let selected = if role_lower.contains("check") {
+ checked
+ } else if role_lower.contains("radio")
+ || role_lower.contains("list item")
+ || role_lower.contains("menu item")
+ || matches!(role_lower.as_str(), "tab" | "page tab" | "tab item")
+ {
+ state_r
+ .as_ref()
+ .and_then(|state| state.as_ref().ok())
+ .map(|state| state.contains(State::Selected) || state.contains(State::Checked))
+ } else {
+ None
+ };
// Collect action names, numeric value, and (crucially) Text-interface
// content. Only touch `proxies` when an interface is actually present,
@@ -580,6 +601,8 @@ async fn collect_visited_bounded<'a>(
name,
value,
checked,
+ enabled,
+ selected,
actions,
has_editable,
has_value,
@@ -645,6 +668,8 @@ fn render(visited: &[Visited<'_>]) -> (String, Vec<AtspiNode>) {
},
value: v.value.clone().filter(|s| !s.is_empty()),
checked: v.checked,
+ enabled: v.enabled,
+ selected: v.selected,
description: None,
actions: v.actions.clone(),
element_key: idx as u64,
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/browser_consent_ui.rs b/libs/cua-driver/rust/crates/platform-linux/src/browser_consent_ui.rs
index c0b76d2327..100862b4ab 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/browser_consent_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/browser_consent_ui.rs
@@ -317,6 +317,8 @@ mod tests {
name: Some(name.to_owned()),
value: None,
checked: None,
+ enabled: None,
+ selected: None,
description: None,
actions: actions.iter().map(|value| (*value).to_owned()).collect(),
element_key: 0,
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs b/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs
index 77f7d81e14..171240b152 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/browser_setup_ui.rs
@@ -522,6 +522,8 @@ mod tests {
name: Some(name.to_owned()),
value: value.map(str::to_owned),
checked: None,
+ enabled: None,
+ selected: None,
description: None,
actions: actions.iter().map(|value| (*value).to_owned()).collect(),
element_key: 0,
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
index df57376b3c..84db5fe35e 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
@@ -519,7 +519,8 @@ impl Tool for GetWindowStateTool {
with [element_index N] in the markdown and as `element_index` in \
the structured array.\n\n\
PREFERRED CONSUMERS read `structuredContent.elements` (one entry \
- per indexed row with `element_index`, `role`, `label`, \
+ per indexed row with `element_index`, `role`, `label`, `value`, \
+ `enabled`, `selected`, \
`frame: {x,y,w,h}` when AT-SPI reports usable bounds, \
`parent_index`, `depth`). The markdown `tree_markdown` stays \
available and unchanged in shape for existing text-parsing \
@@ -607,6 +608,10 @@ impl Tool for GetWindowStateTool {
// explicit `include_screenshot:false` opt-out (with no screenshot_out_file)
// skips the grab to return tree only.
let should_capture = include_screenshot != Some(false) || screenshot_out_file.is_some();
+ let observation_only = args
+ .get("_observation_only")
+ .and_then(|value| value.as_bool())
+ == Some(true);
let state = self.state.clone();
let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
@@ -666,6 +671,7 @@ impl Tool for GetWindowStateTool {
let mut structured = json!({ "window_id": xid, "pid": pid });
if let Some(tr) = tree_opt {
+ let source_trusted = tr.trusted;
let count = tr
.nodes
.iter()
@@ -675,8 +681,13 @@ impl Tool for GetWindowStateTool {
content.push(cua_driver_core::protocol::Content::text(
header + &tr.tree_markdown,
));
- state.element_cache.update(pid, xid, &tr.nodes);
+ if !observation_only {
+ state.element_cache.update(pid, xid, &tr.nodes);
+ }
structured["element_count"] = json!(count);
+ // AT-SPI's current bounded walker does not surface an
+ // exhaustive-walk proof. Keep negative existence unknown.
+ structured["elements_complete"] = json!(false);
structured["tree_markdown"] = json!(tr.tree_markdown);
// Surface 6: register a snapshot in the global token
@@ -684,8 +695,10 @@ impl Tool for GetWindowStateTool {
// by an opaque per-snapshot `element_token` alongside
// its existing integer `element_index`. The integer
// surface stays unchanged — the token is additive.
- let snapshot_id = cua_driver_core::element_token::global()
- .register_snapshot(pid as i32, xid as u32, count);
+ let snapshot_id = (!observation_only).then(|| {
+ cua_driver_core::element_token::global()
+ .register_snapshot(pid as i32, xid as u32, count)
+ });
// Structured `elements` array: one entry per actionable node.
// Shape: `{element_index, element_token, role, label,
@@ -707,19 +720,24 @@ impl Tool for GetWindowStateTool {
// `label` mirrors what a human reading the markdown row
// would call this element: name first, then value,
// then description.
- let label = n.name.clone()
+ let label = n
+ .name
+ .clone()
.or_else(|| n.value.clone())
.or_else(|| n.description.clone());
let mut entry = json!({
"element_index": idx,
- // Surface 6: opaque token paired to the
- // integer index. See cua-driver-core's
- // `element_token` module for the format
- // and validity contract.
- "element_token": cua_driver_core::element_token::token_for(snapshot_id, idx),
"role": n.role,
"depth": n.depth,
});
+ if let Some(snapshot_id) = snapshot_id {
+ entry["element_token"] = json!(
+ cua_driver_core::element_token::token_for(snapshot_id, idx)
+ );
+ }
+ if n.in_web_content {
+ entry["in_web_content"] = json!(true);
+ }
if let Some(label) = label {
entry["label"] = json!(label);
}
@@ -732,6 +750,12 @@ impl Tool for GetWindowStateTool {
if let Some(value) = n.value.clone().filter(|v| !v.is_empty()) {
entry["value"] = json!(value);
}
+ if let Some(enabled) = n.enabled {
+ entry["enabled"] = json!(enabled);
+ }
+ if let Some(selected) = n.selected {
+ entry["selected"] = json!(selected);
+ }
if let Some(parent) = n.parent_element_index {
entry["parent_index"] = json!(parent);
}
@@ -743,10 +767,12 @@ impl Tool for GetWindowStateTool {
.collect();
structured["elements"] = json!(elements);
// Surface 6: snapshot id mirror for debug correlation.
- structured["snapshot_id"] =
- json!(cua_driver_core::element_token::token_for(snapshot_id, 0)
- .trim_end_matches(":0")
- .to_string());
+ if let Some(snapshot_id) = snapshot_id {
+ structured["snapshot_id"] =
+ json!(cua_driver_core::element_token::token_for(snapshot_id, 0)
+ .trim_end_matches(":0")
+ .to_string());
+ }
structured["_note"] = json!(
"Prefer `elements` — `tree_markdown` will continue to work \
but new fields will only be added to the structured side. \
@@ -760,7 +786,14 @@ impl Tool for GetWindowStateTool {
// daemon isn't on the desktop session bus so the registry is
// empty), or it's a non-AX surface (canvas/WebGL). Mark it
// degraded so callers don't read `elements: []` as authoritative.
- if count == 0 {
+ if !source_trusted {
+ structured["degraded"] = json!(true);
+ structured["degraded_reason"] = json!(
+ "x11_property_fallback_partial: AT-SPI was unavailable and \
+ Cua Driver only recovered window metadata. Treat it as \
+ discovery evidence; it cannot prove checked state."
+ );
+ } else if count == 0 {
structured["degraded"] = json!(true);
structured["degraded_reason"] = json!(
"atspi_tree_empty: the AT-SPI walk returned no actionable \
@@ -782,12 +815,14 @@ impl Tool for GetWindowStateTool {
}
if let Some((b64_opt, file_path, w, h, orig_w)) = shot_opt {
- if let Some(ow) = orig_w {
- if w > 0 {
- state.resize_registry.set_ratio(pid, ow as f64 / w as f64);
+ if !observation_only {
+ if let Some(ow) = orig_w {
+ if w > 0 {
+ state.resize_registry.set_ratio(pid, ow as f64 / w as f64);
+ }
+ } else {
+ state.resize_registry.clear_ratio(pid);
}
- } else {
- state.resize_registry.clear_ratio(pid);
}
// ax mode + screenshot_out_file writes the PNG to disk and
// returns b64=None — never embed the image bytes in that case.
@@ -7022,6 +7057,16 @@ pub fn build_registry_with_provider(
r.register(Box::new(GetWindowStateTool {
state: state.clone(),
}));
+ r.register(Box::new(
+ cua_driver_core::expectation::VerifyStateTool::new(std::sync::Arc::new(
+ cua_driver_core::expectation::ToolObservationProvider::new(
+ std::sync::Arc::new(ListWindowsTool),
+ std::sync::Arc::new(GetWindowStateTool {
+ state: state.clone(),
+ }),
+ ),
+ )),
+ ));
r.register(Box::new(LaunchAppTool));
r.register(Box::new(KillAppTool));
r.register(Box::new(BringToFrontTool));
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs
index 8cb57d6173..2a780d1cf9 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs
@@ -307,6 +307,14 @@ pub fn build_registry() -> cua_driver_core::tool::ToolRegistry {
r.register(Box::new(ListAppsTool));
r.register(Box::new(ListWindowsTool));
r.register(Box::new(GetWindowStateTool));
+ r.register(Box::new(
+ cua_driver_core::expectation::VerifyStateTool::new(std::sync::Arc::new(
+ cua_driver_core::expectation::ToolObservationProvider::new(
+ std::sync::Arc::new(ListWindowsTool),
+ std::sync::Arc::new(GetWindowStateTool),
+ ),
+ )),
+ ));
r.register(Box::new(LaunchAppTool));
r.register(Box::new(KillAppTool));
r.register(Box::new(ClickTool));
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/cache.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/cache.rs
index e6a7a36eff..15aa754169 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/ax/cache.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/cache.rs
@@ -168,6 +168,7 @@ mod tests {
max_value: None,
enabled: None,
selected: None,
+ in_web_content: false,
}
}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs b/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs
index 60a238a4fe..eb1c50cf44 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/tree.rs
@@ -105,6 +105,10 @@ pub struct AXNode {
pub enabled: Option<bool>,
/// AXSelected. `None` when the app doesn't report the attribute.
pub selected: Option<bool>,
+ /// True when this node is an AX web-document root or descends from one.
+ /// This trust marker is independent of actionable ancestry because
+ /// AXWebArea is commonly non-actionable and therefore has no element index.
+ pub in_web_content: bool,
}
#[derive(Default)]
@@ -298,6 +302,7 @@ pub fn walk_tree_bounded(
child,
0,
None,
+ false,
&mut nodes,
&mut lines,
&mut index_counter,
@@ -346,6 +351,7 @@ unsafe fn walk_element(
element: AXUIElementRef,
depth: usize,
parent_index: Option<usize>,
+ in_web_content: bool,
nodes: &mut Vec<AXNode>,
lines: &mut Vec<(usize, String)>,
counter: &mut usize,
@@ -371,6 +377,8 @@ unsafe fn walk_element(
let role = copy_string_attr(element, "AXRole").unwrap_or_else(|| "AXUnknown".into());
+ let in_web_content = in_web_content || is_web_content_role(&role);
+
// Skip pure layout containers that have no interesting content.
if role == "AXScrollArea" || role == "AXGroup" {
// Still recurse — children may be interesting. Layout containers
@@ -382,6 +390,7 @@ unsafe fn walk_element(
child,
depth,
parent_index,
+ in_web_content,
nodes,
lines,
counter,
@@ -431,6 +440,7 @@ unsafe fn walk_element(
child,
depth + 1,
parent_index,
+ in_web_content,
nodes,
lines,
counter,
@@ -500,6 +510,7 @@ unsafe fn walk_element(
max_value: control_state.max_value,
enabled: control_state.enabled,
selected: control_state.selected,
+ in_web_content,
}
} else {
AXNode {
@@ -533,6 +544,7 @@ unsafe fn walk_element(
max_value: control_state.max_value,
enabled: control_state.enabled,
selected: control_state.selected,
+ in_web_content,
}
};
@@ -551,6 +563,7 @@ unsafe fn walk_element(
child,
depth + 1,
next_parent,
+ in_web_content,
nodes,
lines,
counter,
@@ -563,6 +576,30 @@ unsafe fn walk_element(
}
}
+fn is_web_content_role(role: &str) -> bool {
+ let normalized = role
+ .chars()
+ .filter(|character| character.is_ascii_alphanumeric())
+ .flat_map(char::to_lowercase)
+ .collect::<String>();
+ normalized.contains("webarea") || normalized.contains("documentweb") || normalized == "document"
+}
+
+#[cfg(test)]
+mod web_content_role_tests {
+ use super::is_web_content_role;
+
+ #[test]
+ fn recognizes_native_web_document_roles_without_marking_app_chrome() {
+ for role in ["AXWebArea", "AXDocumentWeb", "document"] {
+ assert!(is_web_content_role(role), "{role} must start web trust");
+ }
+ for role in ["AXWindow", "AXButton", "AXToolbar"] {
+ assert!(!is_web_content_role(role), "{role} stays native");
+ }
+ }
+}
+
fn format_node_line(node: &AXNode) -> String {
let mut parts = String::new();
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/browser/consent_ui.rs b/libs/cua-driver/rust/crates/platform-macos/src/browser/consent_ui.rs
index 52703cbd76..beb3b1c258 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/browser/consent_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/browser/consent_ui.rs
@@ -273,6 +273,7 @@ mod tests {
max_value: None,
enabled: None,
selected: None,
+ in_web_content: false,
}
}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/browser/setup_ui.rs b/libs/cua-driver/rust/crates/platform-macos/src/browser/setup_ui.rs
index 2f50d420be..2cacc0850f 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/browser/setup_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/browser/setup_ui.rs
@@ -1708,6 +1708,7 @@ mod tests {
max_value: None,
enabled: None,
selected: None,
+ in_web_content: false,
}
}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs
index 212290f954..8036a271c7 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs
@@ -209,6 +209,13 @@ impl Tool for GetWindowStateTool {
// still forces a capture (an explicit "write the frame to disk").
let include_screenshot = args.get("include_screenshot").and_then(|v| v.as_bool());
let should_capture = include_screenshot != Some(false) || screenshot_out_file.is_some();
+ // Internal direct-tool mode used by verify_state. Registry ingress
+ // strips underscore-prefixed arguments before public dispatch; only
+ // a trusted direct in-process invocation can enable this mode.
+ let observation_only = args
+ .get("_observation_only")
+ .and_then(|value| value.as_bool())
+ == Some(true);
// Optional caps — when omitted, fall back to the defaults baked into
// the AX walker (#22865). minimum:1 keyed in the schema, but defend
// against 0 here as well so a misbehaving client can't disable the
@@ -275,11 +282,13 @@ impl Tool for GetWindowStateTool {
// click(element_index=N) picked whatever the walk happened to return.
// For an unresolved scope, replace any prior entry with an empty
// snapshot so a stale index map cannot be clicked through either.
- if let Some(ref r) = tree_result {
- if scope_matched {
- self.state.element_cache.update(pid, window_id, &r.nodes);
- } else {
- self.state.element_cache.update(pid, window_id, &[]);
+ if !observation_only {
+ if let Some(ref r) = tree_result {
+ if scope_matched {
+ self.state.element_cache.update(pid, window_id, &r.nodes);
+ } else {
+ self.state.element_cache.update(pid, window_id, &[]);
+ }
}
}
@@ -373,16 +382,18 @@ impl Tool for GetWindowStateTool {
// different ratios (only the large one downscales), and a
// pid-only key leaked one window's ratio into the other's
// pixel clicks.
- if let Some(ow) = orig_w {
- if w > 0 {
- self.state.resize_registry.set_ratio(
- pid,
- window_id,
- ow as f64 / w as f64,
- );
+ if !observation_only {
+ if let Some(ow) = orig_w {
+ if w > 0 {
+ self.state.resize_registry.set_ratio(
+ pid,
+ window_id,
+ ow as f64 / w as f64,
+ );
+ }
+ } else {
+ self.state.resize_registry.clear_ratio(pid, window_id);
}
- } else {
- self.state.resize_registry.clear_ratio(pid, window_id);
}
Some((b64, file_path, w, h, bounds, scale))
}
@@ -390,7 +401,9 @@ impl Tool for GetWindowStateTool {
tracing::warn!(
"Screenshot frame could not be verified for window {window_id}: {e:?}"
);
- self.state.resize_registry.clear_ratio(pid, window_id);
+ if !observation_only {
+ self.state.resize_registry.clear_ratio(pid, window_id);
+ }
screenshot_frame_error = Some(e);
None
}
@@ -421,7 +434,10 @@ impl Tool for GetWindowStateTool {
}
// Summary text line (matching Swift reference format).
- let element_count = self.state.element_cache.element_count(pid, window_id);
+ let element_count = tree_result
+ .as_ref()
+ .map(|r| r.nodes.iter().filter(|n| n.element_index.is_some()).count())
+ .unwrap_or(0);
let summary = if let Some(ref r) = tree_result {
format!(
"window_id={window_id} pid={pid} size={}x{} elements={element_count}\n\n{}",
@@ -432,7 +448,7 @@ impl Tool for GetWindowStateTool {
};
content.push(Content::text(summary));
} else if let Some(ref r) = tree_result {
- let element_count = self.state.element_cache.element_count(pid, window_id);
+ let element_count = r.nodes.iter().filter(|n| n.element_index.is_some()).count();
content.push(Content::text(format!(
"window_id={window_id} pid={pid} elements={element_count}\n\n{}",
r.tree_markdown
@@ -445,7 +461,10 @@ impl Tool for GetWindowStateTool {
);
}
- let element_count = self.state.element_cache.element_count(pid, window_id);
+ let element_count = tree_result
+ .as_ref()
+ .map(|r| r.nodes.iter().filter(|n| n.element_index.is_some()).count())
+ .unwrap_or(0);
let tree_md = tree_result
.as_ref()
.map(|r| r.tree_markdown.clone())
@@ -466,7 +485,7 @@ impl Tool for GetWindowStateTool {
.as_ref()
.map(|r| r.nodes.iter().filter(|n| n.element_index.is_some()).count())
.unwrap_or(0);
- let snapshot_id = if scope_matched {
+ let snapshot_id = if scope_matched && !observation_only {
Some(cua_driver_core::element_token::global().register_snapshot(
pid,
window_id,
@@ -484,13 +503,20 @@ impl Tool for GetWindowStateTool {
// preferred-for-back-compat-only via the `_note` field below.
let elements_json: Vec<serde_json::Value> = match (snapshot_id, tree_result.as_ref()) {
(Some(sid), Some(r)) => build_elements_array_with_token(&r.nodes, sid),
+ (None, Some(r)) if scope_matched => build_elements_array(&r.nodes),
_ => Vec::new(),
};
+ // The structured array intentionally contains only actionable nodes,
+ // and AX child reads can fail independently of the element/depth caps.
+ // Until the walker exposes a proof over the projected search domain,
+ // absence must remain unknown rather than being claimed complete.
+ let elements_complete = false;
let mut structured = serde_json::json!({
"window_id": window_id,
"pid": pid,
"element_count": element_count,
+ "elements_complete": elements_complete,
"tree_markdown": tree_md,
"elements": elements_json,
"_note": "Prefer `elements` — `tree_markdown` will continue to work \
@@ -771,9 +797,24 @@ pub(crate) fn build_elements_array_with_token(
if let Some(enabled) = node.enabled {
entry["enabled"] = serde_json::Value::Bool(enabled);
}
- if let Some(selected) = node.selected {
+ let selected = node.selected.or_else(|| {
+ let role = node.role.to_ascii_lowercase();
+ if role.contains("checkbox") || role.contains("radiobutton") {
+ node.value_state.as_deref().and_then(|value| match value {
+ "1" | "true" | "on" => Some(true),
+ "0" | "false" | "off" => Some(false),
+ _ => None,
+ })
+ } else {
+ None
+ }
+ });
+ if let Some(selected) = selected {
entry["selected"] = serde_json::Value::Bool(selected);
}
+ if node.in_web_content {
+ entry["in_web_content"] = serde_json::Value::Bool(true);
+ }
if let Some(frame) = frame {
entry["frame"] = frame;
}
@@ -954,6 +995,7 @@ mod tests {
max_value: None,
enabled: None,
selected: None,
+ in_web_content: false,
}
}
@@ -1080,6 +1122,29 @@ mod tests {
assert_eq!(entry["selected"], false);
}
+ #[test]
+ fn elements_surface_inherited_web_content_trust_marker() {
+ let mut nodes = vec![node(
+ Some(0),
+ "AXButton",
+ Some("Renderer button"),
+ 2,
+ None,
+ None,
+ )];
+ nodes[0].in_web_content = true;
+ let entry = &build_elements_array(&nodes)[0];
+ assert_eq!(entry["in_web_content"], true);
+ }
+
+ #[test]
+ fn checkbox_value_state_normalizes_to_selected() {
+ let mut nodes = vec![node(Some(0), "AXCheckBox", Some("I agree"), 0, None, None)];
+ nodes[0].value_state = Some("0".into());
+ let entry = &build_elements_array(&nodes)[0];
+ assert_eq!(entry["selected"], false);
+ }
+
#[test]
fn elements_control_state_fields_omitted_when_absent() {
// Stock behaviour is unchanged for elements without control state.
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
index f5c5ca2277..b3ff1c2421 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
@@ -639,6 +639,14 @@ pub fn register_all(
registry.register(Box::new(get_window_state::GetWindowStateTool::new(
state.clone(),
)));
+ registry.register(Box::new(
+ cua_driver_core::expectation::VerifyStateTool::new(Arc::new(
+ cua_driver_core::expectation::ToolObservationProvider::new(
+ Arc::new(list_windows::ListWindowsTool),
+ Arc::new(get_window_state::GetWindowStateTool::new(state.clone())),
+ ),
+ )),
+ ));
registry.register(Box::new(launch_app::LaunchAppTool));
registry.register(Box::new(kill_app::KillAppTool));
registry.register(Box::new(bring_to_front::BringToFrontTool));
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/browser_consent_ui.rs b/libs/cua-driver/rust/crates/platform-windows/src/browser_consent_ui.rs
index e30e607cf9..a12808e80f 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/browser_consent_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/browser_consent_ui.rs
@@ -200,6 +200,8 @@ mod tests {
automation_id: None,
help_text: None,
actions: actions.iter().map(|value| (*value).to_owned()).collect(),
+ enabled: None,
+ selected: None,
element_ptr: 7,
center_x: 0,
center_y: 0,
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/browser_setup_ui.rs b/libs/cua-driver/rust/crates/platform-windows/src/browser_setup_ui.rs
index 9f9f4d9a2b..ce1eb41dcc 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/browser_setup_ui.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/browser_setup_ui.rs
@@ -614,6 +614,8 @@ mod tests {
automation_id: None,
help_text: None,
actions: actions.iter().map(|value| (*value).to_owned()).collect(),
+ enabled: None,
+ selected: None,
element_ptr: 7,
center_x: 0,
center_y: 0,
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/msaa.rs b/libs/cua-driver/rust/crates/platform-windows/src/msaa.rs
index 6caa5046e3..a1ed48da86 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/msaa.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/msaa.rs
@@ -192,6 +192,8 @@ unsafe fn walk(
automation_id: None,
help_text: None,
actions: actions.clone(),
+ enabled: None,
+ selected: None,
element_ptr: ptr,
center_x,
center_y,
@@ -210,6 +212,8 @@ unsafe fn walk(
automation_id: None,
help_text: None,
actions: Vec::new(),
+ enabled: None,
+ selected: None,
element_ptr: ptr,
center_x: 0,
center_y: 0,
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
index 6265c3b83c..6902e5d912 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
@@ -839,8 +839,9 @@ impl Tool for GetWindowStateTool {
any element-indexed action against that window. The index map is replaced by \
the next snapshot of the same (pid, window_id).\n\n\
PREFERRED CONSUMERS read `structuredContent.elements` (one entry per \
- indexed row with `element_index`, `role`, `label`, `frame: {x,y,w,h}`, \
- `parent_index`, `depth`). The markdown `tree_markdown` stays available \
+ indexed row with `element_index`, `role`, `label`, `value`, `enabled`, \
+ `selected`, `frame: {x,y,w,h}`, `parent_index`, `depth`). The markdown \
+ `tree_markdown` stays available \
and unchanged in shape for existing text-parsing callers — but new \
fields will only be added to the structured side.\n\n\
The UIA tree walked is the window's tree (HWND-scoped); the screenshot and \
@@ -962,6 +963,10 @@ impl Tool for GetWindowStateTool {
// `screenshot_out_file` the bytes go to disk and the path is surfaced
// instead of embedding base64; otherwise the base64 PNG is embedded.
let include_screenshot = args.get("include_screenshot").and_then(|v| v.as_bool());
+ let observation_only = args
+ .get("_observation_only")
+ .and_then(|value| value.as_bool())
+ == Some(true);
let do_tree = true;
let do_shot = include_screenshot != Some(false) || screenshot_out_file.is_some();
@@ -1045,6 +1050,7 @@ impl Tool for GetWindowStateTool {
let mut structured = json!({ "window_id": hwnd, "pid": pid });
if let Some(tr) = tree_opt {
+ let is_msaa = tr.nodes.iter().any(|n| n.msaa_role.is_some());
let count = tr
.nodes
.iter()
@@ -1058,13 +1064,18 @@ impl Tool for GetWindowStateTool {
// node whose msaa_role is Some came from the MSAA
// walker, so the entire snapshot must Drop via
// IAccessible and click must dispatch through MSAA.
- let is_msaa = tr.nodes.iter().any(|n| n.msaa_role.is_some());
- if is_msaa {
- state.element_cache.update_msaa(pid, hwnd, &tr.nodes);
- } else {
- state.element_cache.update(pid, hwnd, &tr.nodes);
+ if !observation_only {
+ if is_msaa {
+ state.element_cache.update_msaa(pid, hwnd, &tr.nodes);
+ } else {
+ state.element_cache.update(pid, hwnd, &tr.nodes);
+ }
}
structured["element_count"] = json!(count);
+ // UIA currently does not expose whether a bounded walk
+ // exhausted every subtree. Keep negative existence
+ // conservative until that proof is available.
+ structured["elements_complete"] = json!(false);
structured["tree_markdown"] = json!(tr.tree_markdown);
// Surface 6: register a snapshot in the global token
@@ -1072,11 +1083,13 @@ impl Tool for GetWindowStateTool {
// stores u32 — truncate (HWND fits in 32-bit on
// every supported edition; the upper 32 bits are
// zero in user-space).
- let snapshot_id = cua_driver_core::element_token::global().register_snapshot(
- pid as i32,
- hwnd as u32,
- count,
- );
+ let snapshot_id = (!observation_only).then(|| {
+ cua_driver_core::element_token::global().register_snapshot(
+ pid as i32,
+ hwnd as u32,
+ count,
+ )
+ });
// Structured `elements` array — preferred consumption
// path. Shape matches the cross-platform spec:
@@ -1089,20 +1102,25 @@ impl Tool for GetWindowStateTool {
.filter_map(|n| {
let idx = n.element_index?;
// `label`: name → value → automation_id → help_text.
- let label = n.name.clone()
+ let label = n
+ .name
+ .clone()
.or_else(|| n.value.clone())
.or_else(|| n.automation_id.clone())
.or_else(|| n.help_text.clone());
let mut entry = json!({
"element_index": idx,
- // Surface 6: opaque token paired to the
- // integer index. See cua-driver-core's
- // `element_token` module for the format
- // and validity contract.
- "element_token": cua_driver_core::element_token::token_for(snapshot_id, idx),
"role": n.control_type,
"depth": n.depth,
});
+ if let Some(snapshot_id) = snapshot_id {
+ entry["element_token"] = json!(
+ cua_driver_core::element_token::token_for(snapshot_id, idx)
+ );
+ }
+ if n.in_web_content {
+ entry["in_web_content"] = json!(true);
+ }
if let Some(label) = label {
entry["label"] = json!(label);
}
@@ -1115,6 +1133,12 @@ impl Tool for GetWindowStateTool {
if let Some(value) = n.value.clone().filter(|v| !v.is_empty()) {
entry["value"] = json!(value);
}
+ if let Some(enabled) = n.enabled {
+ entry["enabled"] = json!(enabled);
+ }
+ if let Some(selected) = n.selected {
+ entry["selected"] = json!(selected);
+ }
if let Some(parent) = n.parent_element_index {
entry["parent_index"] = json!(parent);
}
@@ -1131,10 +1155,12 @@ impl Tool for GetWindowStateTool {
.collect();
structured["elements"] = json!(elements);
// Surface 6: snapshot id mirror for debug correlation.
- structured["snapshot_id"] =
- json!(cua_driver_core::element_token::token_for(snapshot_id, 0)
- .trim_end_matches(":0")
- .to_string());
+ if let Some(snapshot_id) = snapshot_id {
+ structured["snapshot_id"] =
+ json!(cua_driver_core::element_token::token_for(snapshot_id, 0)
+ .trim_end_matches(":0")
+ .to_string());
+ }
structured["_note"] = json!(
"Prefer `elements` — `tree_markdown` will continue to work \
but new fields will only be added to the structured side. \
@@ -1150,7 +1176,14 @@ impl Tool for GetWindowStateTool {
// UIA tree means element_index has nothing to bind to, so the
// deliberate move is an element px action — read the screenshot
// already in this response and click by pixel (x,y).
- if count == 0 {
+ if is_msaa {
+ structured["degraded"] = json!(true);
+ structured["degraded_reason"] = json!(
+ "msaa_fallback_partial: the UIA provider was unavailable and \
+ Cua Driver used a partial MSAA tree. Treat it as discovery \
+ evidence only; it cannot prove checked state."
+ );
+ } else if count == 0 {
structured["degraded"] = json!(true);
structured["degraded_reason"] = json!(
"ax_tree_empty: the UIA walk returned no actionable elements. \
@@ -1169,12 +1202,14 @@ impl Tool for GetWindowStateTool {
}
if let Some((b64_opt, file_path, w, h, orig_w)) = screenshot_opt {
- if let Some(ow) = orig_w {
- if w > 0 {
- state.resize_registry.set_ratio(pid, ow as f64 / w as f64);
+ if !observation_only {
+ if let Some(ow) = orig_w {
+ if w > 0 {
+ state.resize_registry.set_ratio(pid, ow as f64 / w as f64);
+ }
+ } else {
+ state.resize_registry.clear_ratio(pid);
}
- } else {
- state.resize_registry.clear_ratio(pid);
}
// base64 is embedded only when no out_file was given (vision
// path). With `screenshot_out_file` the bytes went to disk and
@@ -8549,6 +8584,16 @@ pub fn build_registry_with_provider(
r.register(Box::new(GetWindowStateTool {
state: state.clone(),
}));
+ r.register(Box::new(
+ cua_driver_core::expectation::VerifyStateTool::new(std::sync::Arc::new(
+ cua_driver_core::expectation::ToolObservationProvider::new(
+ std::sync::Arc::new(ListWindowsTool),
+ std::sync::Arc::new(GetWindowStateTool {
+ state: state.clone(),
+ }),
+ ),
+ )),
+ ));
r.register(Box::new(LaunchAppTool));
r.register(Box::new(KillAppTool));
r.register(Box::new(BringToFrontTool));
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs
index a540c10854..d81eb02971 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs
@@ -299,6 +299,14 @@ pub fn build_registry() -> cua_driver_core::tool::ToolRegistry {
r.register(Box::new(ListAppsTool));
r.register(Box::new(ListWindowsTool));
r.register(Box::new(GetWindowStateTool));
+ r.register(Box::new(
+ cua_driver_core::expectation::VerifyStateTool::new(std::sync::Arc::new(
+ cua_driver_core::expectation::ToolObservationProvider::new(
+ std::sync::Arc::new(ListWindowsTool),
+ std::sync::Arc::new(GetWindowStateTool),
+ ),
+ )),
+ ));
r.register(Box::new(LaunchAppTool));
r.register(Box::new(KillAppTool));
r.register(Box::new(ClickTool));
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/uia/mod.rs b/libs/cua-driver/rust/crates/platform-windows/src/uia/mod.rs
index e47db06a2d..2eb71bcb06 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/uia/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/uia/mod.rs
@@ -15,12 +15,14 @@ use windows::Win32::System::Com::{
};
use windows::Win32::UI::Accessibility::{
CUIAutomation, IUIAutomation, IUIAutomationCacheRequest, IUIAutomationElement,
+ IUIAutomationSelectionItemPattern, IUIAutomationTogglePattern, ToggleState_Off, ToggleState_On,
TreeScope_Children, TreeScope_Subtree, UIA_AutomationIdPropertyId,
UIA_BoundingRectanglePropertyId, UIA_ControlTypePropertyId, UIA_ExpandCollapsePatternId,
UIA_HelpTextPropertyId, UIA_InvokePatternId, UIA_IsEnabledPropertyId,
UIA_IsOffscreenPropertyId, UIA_NamePropertyId, UIA_ProcessIdPropertyId,
- UIA_RangeValuePatternId, UIA_ScrollPatternId, UIA_SelectionItemPatternId, UIA_TextPatternId,
- UIA_TogglePatternId, UIA_ValuePatternId, UIA_ValueValuePropertyId,
+ UIA_RangeValuePatternId, UIA_ScrollPatternId, UIA_SelectionItemIsSelectedPropertyId,
+ UIA_SelectionItemPatternId, UIA_TextPatternId, UIA_TogglePatternId,
+ UIA_ToggleToggleStatePropertyId, UIA_ValuePatternId, UIA_ValueValuePropertyId,
};
pub mod cache;
@@ -57,6 +59,11 @@ pub struct UiaNode {
pub automation_id: Option<String>,
pub help_text: Option<String>,
pub actions: Vec<String>,
+ /// Enabled state reported by UIA. `None` is reserved for fallback
+ /// backends that cannot establish it.
+ pub enabled: Option<bool>,
+ /// Toggle/selection state when the element exposes one of those patterns.
+ pub selected: Option<bool>,
/// Raw COM pointer (IUIAutomationElement for UIA path, IAccessible for
/// MSAA path) as usize. Retained — `ElementCache` Drop releases it via
/// the `kind`-appropriate vtable.
@@ -148,6 +155,8 @@ unsafe fn walk_tree_unsafe(
UIA_IsEnabledPropertyId,
UIA_IsOffscreenPropertyId,
UIA_BoundingRectanglePropertyId,
+ UIA_ToggleToggleStatePropertyId,
+ UIA_SelectionItemIsSelectedPropertyId,
] {
let _ = cache_req.AddProperty(*prop);
}
@@ -535,7 +544,11 @@ unsafe fn walk_cached_bounded(
let value = read_cached_bstr_value(element);
let automation_id = read_cached_bstr(element, UIA_AutomationIdPropertyId);
let help_text = read_cached_bstr(element, UIA_HelpTextPropertyId);
- let is_enabled = read_cached_bool(element, UIA_IsEnabledPropertyId).unwrap_or(true);
+ let enabled = read_cached_bool(element, UIA_IsEnabledPropertyId);
+ // Missing UIA state must remain unknown on the structured observation
+ // surface. Action discovery keeps its historical best-effort assumption.
+ let is_enabled = enabled.unwrap_or(true);
+ let selected = read_cached_selected(element);
let actions = detect_cached_actions(element, &control_type, is_enabled);
let is_actionable = !actions.is_empty() && is_enabled;
let has_content = name
@@ -566,6 +579,8 @@ unsafe fn walk_cached_bounded(
automation_id: automation_id.clone(),
help_text: help_text.clone(),
actions: actions.clone(),
+ enabled,
+ selected,
element_ptr: ptr,
center_x,
center_y,
@@ -584,6 +599,8 @@ unsafe fn walk_cached_bounded(
automation_id: automation_id.clone(),
help_text: help_text.clone(),
actions: vec![],
+ enabled,
+ selected,
element_ptr: ptr,
center_x: 0,
center_y: 0,
@@ -752,6 +769,29 @@ fn detect_cached_actions(
actions
}
+fn read_cached_selected(element: &IUIAutomationElement) -> Option<bool> {
+ unsafe {
+ if let Ok(pattern) = element.GetCachedPattern(UIA_TogglePatternId) {
+ if let Ok(toggle) = pattern.cast::<IUIAutomationTogglePattern>() {
+ return match toggle.CachedToggleState() {
+ Ok(state) if state == ToggleState_On => Some(true),
+ Ok(state) if state == ToggleState_Off => Some(false),
+ _ => None,
+ };
+ }
+ }
+ if let Ok(pattern) = element.GetCachedPattern(UIA_SelectionItemPatternId) {
+ if let Ok(selection) = pattern.cast::<IUIAutomationSelectionItemPattern>() {
+ return selection
+ .CachedIsSelected()
+ .ok()
+ .map(|selected| selected.as_bool());
+ }
+ }
+ }
+ None
+}
+
fn control_type_name(id: i32) -> String {
match id {
50000 => "Button",
diff --git a/libs/cua-driver/typescript/src/native/cua_driver_contract.ts b/libs/cua-driver/typescript/src/native/cua_driver_contract.ts
index a7406a931c..370ab35361 100644
--- a/libs/cua-driver/typescript/src/native/cua_driver_contract.ts
+++ b/libs/cua-driver/typescript/src/native/cua_driver_contract.ts
@@ -6,7 +6,7 @@
import nativeModule from "./cua_driver_contract-ffi.js";
import { type UniffiRustFutureContinuationCallback, type UniffiForeignFutureDroppedCallback, type UniffiForeignFutureDroppedCallbackStruct,
} from "./cua_driver_contract-ffi.js";
-import { type UniffiByteArray, AbstractFfiConverterByteArray, FfiConverterArray, FfiConverterBool, FfiConverterFloat64, FfiConverterInt32, FfiConverterOptional, FfiConverterUInt32, FfiConverterUInt64, FfiConverterUInt8, RustBuffer, UniffiEnum, UniffiInternalError, UniffiRustCaller, uniffiCreateFfiConverterString, uniffiCreateRecord,
+import { type UniffiByteArray, AbstractFfiConverterByteArray, FfiConverterArray, FfiConverterBool, FfiConverterFloat64, FfiConverterInt32, FfiConverterInt64, FfiConverterOptional, FfiConverterUInt32, FfiConverterUInt64, FfiConverterUInt8, RustBuffer, UniffiEnum, UniffiInternalError, UniffiRustCaller, uniffiCreateFfiConverterString, uniffiCreateRecord,
} from "@ubjs/core";
const uniffiCaller = new UniffiRustCaller(() => ({ code: 0 }));
@@ -19,6 +19,61 @@ const uniffiIsDebug =
// Public interface members begin here.
+export type BoundsExpectation = {
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+ tolerancePx?: number
+}
+
+/**
+ * Generated factory for {@link BoundsExpectation} record objects.
+ */
+export const BoundsExpectation = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<BoundsExpectation, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<BoundsExpectation>,
+ });
+})();
+
+const FfiConverterTypeBoundsExpectation = (() => {
+ type TypeName = BoundsExpectation;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ x: FfiConverterFloat64.read(from),
+ y: FfiConverterFloat64.read(from),
+ width: FfiConverterFloat64.read(from),
+ height: FfiConverterFloat64.read(from),
+ tolerancePx: FfiConverterOptionalFloat64.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterFloat64.write(value.x, into);
+ FfiConverterFloat64.write(value.y, into);
+ FfiConverterFloat64.write(value.width, into);
+ FfiConverterFloat64.write(value.height, into);
+ FfiConverterOptionalFloat64.write(value.tolerancePx, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterFloat64.allocationSize(value.x) +
+ FfiConverterFloat64.allocationSize(value.y) +
+ FfiConverterFloat64.allocationSize(value.width) +
+ FfiConverterFloat64.allocationSize(value.height) +
+ FfiConverterOptionalFloat64.allocationSize(value.tolerancePx);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export enum DesktopScope {
Desktop
}
@@ -600,6 +655,111 @@ const FfiConverterTypeDragInput = (() => {
return new FFIConverter();
})();
+export type ElementSelector = {
+ role?: string,
+ labelContains?: string
+}
+
+/**
+ * Generated factory for {@link ElementSelector} record objects.
+ */
+export const ElementSelector = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<ElementSelector, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<ElementSelector>,
+ });
+})();
+
+const FfiConverterTypeElementSelector = (() => {
+ type TypeName = ElementSelector;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ role: FfiConverterOptionalString.read(from),
+ labelContains: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterOptionalString.write(value.role, into);
+ FfiConverterOptionalString.write(value.labelContains, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterOptionalString.allocationSize(value.role) +
+ FfiConverterOptionalString.allocationSize(value.labelContains);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type ElementPredicate = {
+ selector: ElementSelector,
+ /**
+ * Assert that at least one trusted element matches the selector.
+ *
+ * Element walks are not yet exhaustive on every platform, so absence
+ * cannot be proven. `false` is rejected instead of returning an
+ * indefinitely-unknown predicate.
+ */
+ exists?: boolean,
+ valueEquals?: string,
+ enabled?: boolean,
+ selected?: boolean
+}
+
+/**
+ * Generated factory for {@link ElementPredicate} record objects.
+ */
+export const ElementPredicate = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<ElementPredicate, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<ElementPredicate>,
+ });
+})();
+
+const FfiConverterTypeElementPredicate = (() => {
+ type TypeName = ElementPredicate;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ selector: FfiConverterTypeElementSelector.read(from),
+ exists: FfiConverterOptionalBoolean.read(from),
+ valueEquals: FfiConverterOptionalString.read(from),
+ enabled: FfiConverterOptionalBoolean.read(from),
+ selected: FfiConverterOptionalBoolean.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterTypeElementSelector.write(value.selector, into);
+ FfiConverterOptionalBoolean.write(value.exists, into);
+ FfiConverterOptionalString.write(value.valueEquals, into);
+ FfiConverterOptionalBoolean.write(value.enabled, into);
+ FfiConverterOptionalBoolean.write(value.selected, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterTypeElementSelector.allocationSize(value.selector) +
+ FfiConverterOptionalBoolean.allocationSize(value.exists) +
+ FfiConverterOptionalString.allocationSize(value.valueEquals) +
+ FfiConverterOptionalBoolean.allocationSize(value.enabled) +
+ FfiConverterOptionalBoolean.allocationSize(value.selected);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export type EndSessionInput = {
/**
* The session id to end.
@@ -1150,6 +1310,136 @@ const FfiConverterTypeMoveCursorInput = (() => {
return new FFIConverter();
})();
+export enum VerificationStatus {
+ Satisfied,
+ Unsatisfied,
+ Unknown
+}
+
+const FfiConverterTypeVerificationStatus = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = VerificationStatus;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return VerificationStatus.Satisfied;
+ case 2: return VerificationStatus.Unsatisfied;
+ case 3: return VerificationStatus.Unknown;
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value) {
+ case VerificationStatus.Satisfied: return ordinalConverter.write(1, into);
+ case VerificationStatus.Unsatisfied: return ordinalConverter.write(2, into);
+ case VerificationStatus.Unknown: return ordinalConverter.write(3, into);
+ }
+ }
+ allocationSize(value: TypeName): number {
+ return ordinalConverter.allocationSize(0);
+ }
+ }
+ return new FFIConverter();
+})();
+
+export enum UnknownReason {
+ InvalidPredicate,
+ UnsupportedPredicate,
+ UntrustedSource,
+ MultiMatch,
+ TargetMissing,
+ ObservationUnavailable,
+ StabilityUnproven
+}
+
+const FfiConverterTypeUnknownReason = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = UnknownReason;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return UnknownReason.InvalidPredicate;
+ case 2: return UnknownReason.UnsupportedPredicate;
+ case 3: return UnknownReason.UntrustedSource;
+ case 4: return UnknownReason.MultiMatch;
+ case 5: return UnknownReason.TargetMissing;
+ case 6: return UnknownReason.ObservationUnavailable;
+ case 7: return UnknownReason.StabilityUnproven;
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value) {
+ case UnknownReason.InvalidPredicate: return ordinalConverter.write(1, into);
+ case UnknownReason.UnsupportedPredicate: return ordinalConverter.write(2, into);
+ case UnknownReason.UntrustedSource: return ordinalConverter.write(3, into);
+ case UnknownReason.MultiMatch: return ordinalConverter.write(4, into);
+ case UnknownReason.TargetMissing: return ordinalConverter.write(5, into);
+ case UnknownReason.ObservationUnavailable: return ordinalConverter.write(6, into);
+ case UnknownReason.StabilityUnproven: return ordinalConverter.write(7, into);
+ }
+ }
+ allocationSize(value: TypeName): number {
+ return ordinalConverter.allocationSize(0);
+ }
+ }
+ return new FFIConverter();
+})();
+
+export type PredicateOutcome = {
+ index: bigint,
+ status: VerificationStatus,
+ unknownReason?: UnknownReason,
+ /**
+ * Normalized, bounded JSON projection of the matched state.
+ */
+ observedJson?: string
+}
+
+/**
+ * Generated factory for {@link PredicateOutcome} record objects.
+ */
+export const PredicateOutcome = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<PredicateOutcome, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<PredicateOutcome>,
+ });
+})();
+
+const FfiConverterTypePredicateOutcome = (() => {
+ type TypeName = PredicateOutcome;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ index: FfiConverterUInt64.read(from),
+ status: FfiConverterTypeVerificationStatus.read(from),
+ unknownReason: FfiConverterOptionalTypeUnknownReason.read(from),
+ observedJson: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterUInt64.write(value.index, into);
+ FfiConverterTypeVerificationStatus.write(value.status, into);
+ FfiConverterOptionalTypeUnknownReason.write(value.unknownReason, into);
+ FfiConverterOptionalString.write(value.observedJson, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterUInt64.allocationSize(value.index) +
+ FfiConverterTypeVerificationStatus.allocationSize(value.status) +
+ FfiConverterOptionalTypeUnknownReason.allocationSize(value.unknownReason) +
+ FfiConverterOptionalString.allocationSize(value.observedJson);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export type PressKeyInput = {
key: string,
scope: DesktopScope,
@@ -1858,6 +2148,92 @@ const FfiConverterTypeStartSessionOutput = (() => {
return new FFIConverter();
})();
+export type WindowPredicate = {
+ exists?: boolean,
+ bounds?: BoundsExpectation
+}
+
+/**
+ * Generated factory for {@link WindowPredicate} record objects.
+ */
+export const WindowPredicate = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<WindowPredicate, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<WindowPredicate>,
+ });
+})();
+
+const FfiConverterTypeWindowPredicate = (() => {
+ type TypeName = WindowPredicate;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ exists: FfiConverterOptionalBoolean.read(from),
+ bounds: FfiConverterOptionalTypeBoundsExpectation.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterOptionalBoolean.write(value.exists, into);
+ FfiConverterOptionalTypeBoundsExpectation.write(value.bounds, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterOptionalBoolean.allocationSize(value.exists) +
+ FfiConverterOptionalTypeBoundsExpectation.allocationSize(value.bounds);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type StatePredicate = {
+ window?: WindowPredicate,
+ element?: ElementPredicate
+}
+
+/**
+ * Generated factory for {@link StatePredicate} record objects.
+ */
+export const StatePredicate = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<StatePredicate, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<StatePredicate>,
+ });
+})();
+
+const FfiConverterTypeStatePredicate = (() => {
+ type TypeName = StatePredicate;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ window: FfiConverterOptionalTypeWindowPredicate.read(from),
+ element: FfiConverterOptionalTypeElementPredicate.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterOptionalTypeWindowPredicate.write(value.window, into);
+ FfiConverterOptionalTypeElementPredicate.write(value.element, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterOptionalTypeWindowPredicate.allocationSize(value.window) +
+ FfiConverterOptionalTypeElementPredicate.allocationSize(value.element);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export type TypeTextInput = {
text: string,
scope: DesktopScope,
@@ -1908,6 +2284,146 @@ const FfiConverterTypeTypeTextInput = (() => {
return new FFIConverter();
})();
+export type VerifyStateInput = {
+ /**
+ * Exact process whose window may be observed.
+ */
+ pid: bigint,
+ /**
+ * Exact native window identifier.
+ */
+ windowId: bigint,
+ /**
+ * One to eight predicates, combined with logical AND.
+ */
+ expect: Array<StatePredicate>,
+ /**
+ * Optional session id for capture-scope and authorization continuity.
+ */
+ session?: string,
+ /**
+ * Bounded wait. Zero performs one sample.
+ */
+ timeoutMs?: bigint,
+ /**
+ * Consecutive satisfied samples required before returning success.
+ */
+ stableSamples?: bigint,
+ /**
+ * Return the final window screenshot as image content for a multimodal
+ * caller. The driver does not interpret that image.
+ */
+ includeScreenshot?: boolean
+}
+
+/**
+ * Generated factory for {@link VerifyStateInput} record objects.
+ */
+export const VerifyStateInput = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<VerifyStateInput, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<VerifyStateInput>,
+ });
+})();
+
+const FfiConverterTypeVerifyStateInput = (() => {
+ type TypeName = VerifyStateInput;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ pid: FfiConverterInt64.read(from),
+ windowId: FfiConverterUInt64.read(from),
+ expect: FfiConverterSequenceTypeStatePredicate.read(from),
+ session: FfiConverterOptionalString.read(from),
+ timeoutMs: FfiConverterOptionalUInt64.read(from),
+ stableSamples: FfiConverterOptionalUInt64.read(from),
+ includeScreenshot: FfiConverterOptionalBoolean.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterInt64.write(value.pid, into);
+ FfiConverterUInt64.write(value.windowId, into);
+ FfiConverterSequenceTypeStatePredicate.write(value.expect, into);
+ FfiConverterOptionalString.write(value.session, into);
+ FfiConverterOptionalUInt64.write(value.timeoutMs, into);
+ FfiConverterOptionalUInt64.write(value.stableSamples, into);
+ FfiConverterOptionalBoolean.write(value.includeScreenshot, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterInt64.allocationSize(value.pid) +
+ FfiConverterUInt64.allocationSize(value.windowId) +
+ FfiConverterSequenceTypeStatePredicate.allocationSize(value.expect) +
+ FfiConverterOptionalString.allocationSize(value.session) +
+ FfiConverterOptionalUInt64.allocationSize(value.timeoutMs) +
+ FfiConverterOptionalUInt64.allocationSize(value.stableSamples) +
+ FfiConverterOptionalBoolean.allocationSize(value.includeScreenshot);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type VerifyStateOutput = {
+ status: VerificationStatus,
+ stable: boolean,
+ elapsedMs: bigint,
+ samples: bigint,
+ predicates: Array<PredicateOutcome>
+}
+
+/**
+ * Generated factory for {@link VerifyStateOutput} record objects.
+ */
+export const VerifyStateOutput = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<VerifyStateOutput, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<VerifyStateOutput>,
+ });
+})();
+
+const FfiConverterTypeVerifyStateOutput = (() => {
+ type TypeName = VerifyStateOutput;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ status: FfiConverterTypeVerificationStatus.read(from),
+ stable: FfiConverterBool.read(from),
+ elapsedMs: FfiConverterUInt64.read(from),
+ samples: FfiConverterUInt64.read(from),
+ predicates: FfiConverterSequenceTypePredicateOutcome.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterTypeVerificationStatus.write(value.status, into);
+ FfiConverterBool.write(value.stable, into);
+ FfiConverterUInt64.write(value.elapsedMs, into);
+ FfiConverterUInt64.write(value.samples, into);
+ FfiConverterSequenceTypePredicateOutcome.write(value.predicates, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterTypeVerificationStatus.allocationSize(value.status) +
+ FfiConverterBool.allocationSize(value.stable) +
+ FfiConverterUInt64.allocationSize(value.elapsedMs) +
+ FfiConverterUInt64.allocationSize(value.samples) +
+ FfiConverterSequenceTypePredicateOutcome.allocationSize(value.predicates);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export enum Platform {
Macos,
Windows,
@@ -1940,6 +2456,9 @@ const FfiConverterTypePlatform = (() => {
return new FFIConverter();
})();
+// FfiConverter for number | undefined
+const FfiConverterOptionalFloat64 = new FfiConverterOptional(FfiConverterFloat64);
+
// FfiConverter for string | undefined
const FfiConverterOptionalString = new FfiConverterOptional(FfiConverterString);
@@ -1958,24 +2477,42 @@ const FfiConverterOptionalUInt64 = new FfiConverterOptional(FfiConverterUInt64);
// FfiConverter for Array<string> | undefined
const FfiConverterOptionalSequenceString = new FfiConverterOptional(FfiConverterSequenceString);
+// FfiConverter for boolean | undefined
+const FfiConverterOptionalBoolean = new FfiConverterOptional(FfiConverterBool);
+
// FfiConverter for CursorPointOutput | undefined
const FfiConverterOptionalTypeCursorPointOutput = new FfiConverterOptional(FfiConverterTypeCursorPointOutput);
+// FfiConverter for UnknownReason | undefined
+const FfiConverterOptionalTypeUnknownReason = new FfiConverterOptional(FfiConverterTypeUnknownReason);
+
// FfiConverter for ScrollBy | undefined
const FfiConverterOptionalTypeScrollBy = new FfiConverterOptional(FfiConverterTypeScrollBy);
// FfiConverter for EscalationReason | undefined
const FfiConverterOptionalTypeEscalationReason = new FfiConverterOptional(FfiConverterTypeEscalationReason);
-// FfiConverter for number | undefined
-const FfiConverterOptionalFloat64 = new FfiConverterOptional(FfiConverterFloat64);
-
// FfiConverter for CaptureScope | undefined
const FfiConverterOptionalTypeCaptureScope = new FfiConverterOptional(FfiConverterTypeCaptureScope);
// FfiConverter for CursorThemeSelection | undefined
const FfiConverterOptionalTypeCursorThemeSelection = new FfiConverterOptional(FfiConverterTypeCursorThemeSelection);
+// FfiConverter for BoundsExpectation | undefined
+const FfiConverterOptionalTypeBoundsExpectation = new FfiConverterOptional(FfiConverterTypeBoundsExpectation);
+
+// FfiConverter for WindowPredicate | undefined
+const FfiConverterOptionalTypeWindowPredicate = new FfiConverterOptional(FfiConverterTypeWindowPredicate);
+
+// FfiConverter for ElementPredicate | undefined
+const FfiConverterOptionalTypeElementPredicate = new FfiConverterOptional(FfiConverterTypeElementPredicate);
+
+// FfiConverter for Array<StatePredicate>
+const FfiConverterSequenceTypeStatePredicate = new FfiConverterArray(FfiConverterTypeStatePredicate);
+
+// FfiConverter for Array<PredicateOutcome>
+const FfiConverterSequenceTypePredicateOutcome = new FfiConverterArray(FfiConverterTypePredicateOutcome);
+
/**
* This should be called before anything else.
@@ -2001,6 +2538,7 @@ function uniffiEnsureInitialized() {
export default Object.freeze({
initialize: uniffiEnsureInitialized,
converters: {
+ FfiConverterTypeBoundsExpectation,
FfiConverterTypeCaptureScope,
FfiConverterTypeClickButton,
FfiConverterTypeClickInput,
@@ -2014,6 +2552,8 @@ export default Object.freeze({
FfiConverterTypeDesktopScope,
FfiConverterTypeDragInput,
FfiConverterTypeEffectiveScope,
+ FfiConverterTypeElementPredicate,
+ FfiConverterTypeElementSelector,
FfiConverterTypeEndSessionInput,
FfiConverterTypeEndSessionOutput,
FfiConverterTypeEscalateSessionInput,
@@ -2027,6 +2567,7 @@ export default Object.freeze({
FfiConverterTypeHotkeyInput,
FfiConverterTypeMoveCursorInput,
FfiConverterTypePlatform,
+ FfiConverterTypePredicateOutcome,
FfiConverterTypePressKeyInput,
FfiConverterTypeScrollBy,
FfiConverterTypeScrollDirection,
@@ -2040,6 +2581,12 @@ export default Object.freeze({
FfiConverterTypeSetAgentCursorThemeOutput,
FfiConverterTypeStartSessionInput,
FfiConverterTypeStartSessionOutput,
+ FfiConverterTypeStatePredicate,
FfiConverterTypeTypeTextInput,
+ FfiConverterTypeUnknownReason,
+ FfiConverterTypeVerificationStatus,
+ FfiConverterTypeVerifyStateInput,
+ FfiConverterTypeVerifyStateOutput,
+ FfiConverterTypeWindowPredicate,
}
});
diff --git a/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts b/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts
index 8b9e3cfe93..93a117eda9 100644
--- a/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts
+++ b/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts
@@ -543,6 +543,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_fn_method_cuadriver_verify_state": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_fn_method_cuadriversession_call_tool": {
args: [FfiType.Handle, FfiType.RustBuffer, FfiType.RustBuffer],
ret: FfiType.Handle,
@@ -643,6 +648,11 @@ const DEFINITIONS = {
ret: FfiType.Handle,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_verify_state": {
+ args: [FfiType.Handle, FfiType.RustBuffer],
+ ret: FfiType.Handle,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_fn_method_driveractivityobserver_on_activity": {
args: [FfiType.Handle, FfiType.RustBuffer],
ret: FfiType.Void,
@@ -918,6 +928,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_method_cuadriver_verify_state": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_checksum_method_cuadriversession_call_tool": {
args: [],
ret: FfiType.UInt16,
@@ -1018,6 +1033,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_verify_state": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_driver_sdk_checksum_method_driveractivityobserver_on_activity": {
args: [],
ret: FfiType.UInt16,
@@ -1245,6 +1265,7 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_fn_method_cuadriver_socket_path(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_driver_sdk_fn_method_cuadriver_start_session(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriver_type_text(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriver_verify_state(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriversession_call_tool(uniffiSelf: bigint, name: Uint8Array, argumentsJson: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriversession_click(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriversession_close(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): void;
@@ -1265,6 +1286,7 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_fn_method_cuadriversession_set_agent_cursor_theme(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriversession_start_session(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_cuadriversession_type_text(uniffiSelf: bigint, input: Uint8Array): bigint;
+ uniffi_cua_driver_sdk_fn_method_cuadriversession_verify_state(uniffiSelf: bigint, input: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_method_driveractivityobserver_on_activity(uniffiSelf: bigint, event: Uint8Array, uniffi_out_err: UniffiRustCallStatus): void;
uniffi_cua_driver_sdk_fn_method_driverauthorizationhost_authorize(uniffiSelf: bigint, request: Uint8Array): bigint;
uniffi_cua_driver_sdk_fn_constructor_embeddedcuadriverhost_new(binaryPath: Uint8Array, hostBundleId: Uint8Array, uniffi_out_err: UniffiRustCallStatus): bigint;
@@ -1320,6 +1342,7 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_checksum_method_cuadriver_socket_path(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_start_session(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriver_type_text(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriver_verify_state(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriversession_call_tool(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriversession_click(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriversession_close(): number;
@@ -1340,6 +1363,7 @@ interface NativeModuleInterface {
uniffi_cua_driver_sdk_checksum_method_cuadriversession_set_agent_cursor_theme(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriversession_start_session(): number;
uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text(): number;
+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_verify_state(): number;
uniffi_cua_driver_sdk_checksum_method_driveractivityobserver_on_activity(): number;
uniffi_cua_driver_sdk_checksum_method_driverauthorizationhost_authorize(): number;
uniffi_cua_driver_sdk_checksum_constructor_embeddedcuadriverhost_new(): number;
diff --git a/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts b/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
index 75a6556910..77ca84c133 100644
--- a/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
+++ b/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts
@@ -6,12 +6,12 @@
import nativeModule from "./cua_driver_sdk-ffi.js";
import { type UniffiRustFutureContinuationCallback, type UniffiForeignFutureDroppedCallback, type UniffiForeignFutureDroppedCallbackStruct, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverActivityObserver, type UniffiForeignFutureResultRustBuffer, type UniffiForeignFutureCompleterustBuffer, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost,
} from "./cua_driver_sdk-ffi.js";
-import { type ClickInput, type DragInput, type EndSessionInput, type EndSessionOutput, type EscalateSessionInput, type GetAgentCursorStateInput, type GetCursorPositionInput, type GetDesktopStateInput, type GetScreenSizeInput, type GetSessionStateInput, type HotkeyInput, type MoveCursorInput, type PressKeyInput, type ScrollInput, type SessionStateOutput, type SetAgentCursorEnabledInput, type SetAgentCursorMotionInput, type SetAgentCursorThemeInput, type StartSessionInput, type StartSessionOutput, type TypeTextInput,
+import { type ClickInput, type DragInput, type EndSessionInput, type EndSessionOutput, type EscalateSessionInput, type GetAgentCursorStateInput, type GetCursorPositionInput, type GetDesktopStateInput, type GetScreenSizeInput, type GetSessionStateInput, type HotkeyInput, type MoveCursorInput, type PressKeyInput, type ScrollInput, type SessionStateOutput, type SetAgentCursorEnabledInput, type SetAgentCursorMotionInput, type SetAgentCursorThemeInput, type StartSessionInput, type StartSessionOutput, type TypeTextInput, type VerifyStateInput,
} from "./cua_driver_contract.js";
import { type FfiConverter, type UniffiByteArray, type UniffiGcObject, type UniffiHandle, type UniffiObjectFactory, type UniffiReferenceHolder, type UniffiRustCallStatus, AbstractFfiConverterByteArray, FfiConverterArray, FfiConverterBool, FfiConverterInt32, FfiConverterObject, FfiConverterObjectWithCallbacks, FfiConverterOptional, FfiConverterUInt32, FfiConverterUInt64, FfiConverterUInt8, RustBuffer, UniffiAbstractObject, UniffiEnum, UniffiError, UniffiInternalError, UniffiResult, UniffiRustCaller, destructorGuardSymbol, pointerLiteralSymbol, uniffiCreateFfiConverterString, uniffiCreateRecord, uniffiRustCallAsync, uniffiTraitInterfaceCall, uniffiTraitInterfaceCallAsyncWithError, uniffiTypeNameSymbol, variantOrdinalSymbol,
} from "@ubjs/core";
import uniffiCuaDriverContractModule from "./cua_driver_contract.js";
-const { FfiConverterTypeClickInput, FfiConverterTypeDragInput, FfiConverterTypeEndSessionInput, FfiConverterTypeEndSessionOutput, FfiConverterTypeEscalateSessionInput, FfiConverterTypeGetAgentCursorStateInput, FfiConverterTypeGetCursorPositionInput, FfiConverterTypeGetDesktopStateInput, FfiConverterTypeGetScreenSizeInput, FfiConverterTypeGetSessionStateInput, FfiConverterTypeHotkeyInput, FfiConverterTypeMoveCursorInput, FfiConverterTypePressKeyInput, FfiConverterTypeScrollInput, FfiConverterTypeSessionStateOutput, FfiConverterTypeSetAgentCursorEnabledInput, FfiConverterTypeSetAgentCursorMotionInput, FfiConverterTypeSetAgentCursorThemeInput, FfiConverterTypeStartSessionInput, FfiConverterTypeStartSessionOutput, FfiConverterTypeTypeTextInput } = uniffiCuaDriverContractModule.converters;
+const { FfiConverterTypeClickInput, FfiConverterTypeDragInput, FfiConverterTypeEndSessionInput, FfiConverterTypeEndSessionOutput, FfiConverterTypeEscalateSessionInput, FfiConverterTypeGetAgentCursorStateInput, FfiConverterTypeGetCursorPositionInput, FfiConverterTypeGetDesktopStateInput, FfiConverterTypeGetScreenSizeInput, FfiConverterTypeGetSessionStateInput, FfiConverterTypeHotkeyInput, FfiConverterTypeMoveCursorInput, FfiConverterTypePressKeyInput, FfiConverterTypeScrollInput, FfiConverterTypeSessionStateOutput, FfiConverterTypeSetAgentCursorEnabledInput, FfiConverterTypeSetAgentCursorMotionInput, FfiConverterTypeSetAgentCursorThemeInput, FfiConverterTypeStartSessionInput, FfiConverterTypeStartSessionOutput, FfiConverterTypeTypeTextInput, FfiConverterTypeVerifyStateInput } = uniffiCuaDriverContractModule.converters;
const uniffiCaller = new UniffiRustCaller(() => ({ code: 0 }));
const uniffiIsDebug =
@@ -2568,6 +2568,7 @@ export interface CuaDriverLike {
socketPath(): string;
startSession(input: StartSessionInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<StartSessionOutput>;
typeText(input: TypeTextInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+ verifyState(input: VerifyStateInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
}
/**
* @deprecated Use `CuaDriverLike` instead.
@@ -3610,6 +3611,38 @@ private constructor(pointer: UniffiHandle) {
}
}
+ async verifyState(input: VerifyStateInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_verify_state(
+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeVerifyStateInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeToolResult.lift.bind(FfiConverterTypeToolResult),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
uniffiDestroy(): void {
const ptr = (this as any)[destructorGuardSymbol];
@@ -3718,6 +3751,7 @@ export interface CuaDriverSessionLike {
setAgentCursorTheme(input: SetAgentCursorThemeInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
startSession(input: StartSessionInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<StartSessionOutput>;
typeText(input: TypeTextInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
+ verifyState(input: VerifyStateInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;
}
/**
* @deprecated Use `CuaDriverSessionLike` instead.
@@ -4363,6 +4397,38 @@ private constructor(pointer: UniffiHandle) {
}
}
+ async verifyState(input: VerifyStateInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {
+ const __stack = uniffiIsDebug ? new Error().stack : undefined;
+ try {
+ return await uniffiRustCallAsync(
+ /*rustCaller:*/ uniffiCaller,
+ /*rustFutureFunc:*/ () => {
+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_verify_state(
+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeVerifyStateInput.lower(input, nativeModule().rustbuffer_alloc)
+ );
+ },
+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,
+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,
+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,
+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,
+ // Async returns always go through the JS-side converter: the
+ // FFI symbol returns the future handle (u64), and the user-level
+ // RustBuffer comes back via the shared `rust_future_complete_*`
+ // export. The bytes the runtime hands back must be deserialized
+ // here using the per-callable return-type converter.
+ /*liftFunc:*/ FfiConverterTypeToolResult.lift.bind(FfiConverterTypeToolResult),
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ /*asyncOpts:*/ asyncOpts_,
+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)
+ );
+ } catch (__error: any) {
+ if (uniffiIsDebug && __error instanceof Error) {
+ __error.stack = __stack;
+ }
+ throw __error;
+ }
+ }
+
uniffiDestroy(): void {
const ptr = (this as any)[destructorGuardSymbol];
@@ -5298,6 +5364,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_type_text() !== 25156) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_type_text");
}
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_verify_state() !== 26193) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_verify_state");
+ }
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_call_tool() !== 52859) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_call_tool");
}
@@ -5358,6 +5427,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text() !== 63241) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_type_text");
}
+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_verify_state() !== 36472) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_verify_state");
+ }
if (nativeModule().uniffi_cua_driver_sdk_checksum_method_driveractivityobserver_on_activity() !== 9786) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_driveractivityobserver_on_activity");
}
diff --git a/libs/cua-driver/typescript/test/electron-main-fixture.mjs b/libs/cua-driver/typescript/test/electron-main-fixture.mjs
index 11864495b3..577daa01c4 100644
--- a/libs/cua-driver/typescript/test/electron-main-fixture.mjs
+++ b/libs/cua-driver/typescript/test/electron-main-fixture.mjs
@@ -27,7 +27,7 @@ const server = net.createServer(socket => {
const request = JSON.parse(buffer.split("\\n", 1)[0]);
const result = request.method === "metadata" ? {
driver_version: ${JSON.stringify(packageVersion)},
- contract_version: hostBundleId.endsWith(".failure") ? "incompatible" : "0.2.0",
+ contract_version: hostBundleId.endsWith(".failure") ? "incompatible" : "0.3.0",
tools_list_schema_version: "1",
capability_version: "1",
mcp_protocol_version: "2025-06-18",
diff --git a/libs/cua-driver/typescript/test/native-daemon-fixture.mjs b/libs/cua-driver/typescript/test/native-daemon-fixture.mjs
index 8d1c591e50..bd95385e28 100644
--- a/libs/cua-driver/typescript/test/native-daemon-fixture.mjs
+++ b/libs/cua-driver/typescript/test/native-daemon-fixture.mjs
@@ -17,7 +17,7 @@ const server = net.createServer((connection) => {
ok: true,
result: {
driver_version: "0.12.6",
- contract_version: "0.2.0",
+ contract_version: "0.3.0",
tools_list_schema_version: "1",
capability_version: "1",
mcp_protocol_version: "2025-06-18",
diff --git a/libs/cua-driver/typescript/test/native-loader.test.mjs b/libs/cua-driver/typescript/test/native-loader.test.mjs
index 7032e64349..80326e6913 100644
--- a/libs/cua-driver/typescript/test/native-loader.test.mjs
+++ b/libs/cua-driver/typescript/test/native-loader.test.mjs
@@ -53,7 +53,7 @@ const server = net.createServer(socket => {
const request = JSON.parse(buffer.split("\\n", 1)[0]);
const result = request.method === "metadata" ? {
driver_version: "0.10.0",
- contract_version: "0.2.0",
+ contract_version: "0.3.0",
tools_list_schema_version: "1",
capability_version: "1",
mcp_protocol_version: "2025-06-18",
@@ -121,7 +121,7 @@ test(
await readyPromise
assert.equal(existsSync(socketPath), true)
const sdk = await import("@trycua/cua-driver")
- const { CuaDriver, GetDesktopStateInput } = sdk
+ const { CuaDriver, StatePredicate, VerifyStateInput, WindowPredicate } = sdk
assert.equal("StdioMcpTransport" in sdk, false)
await assert.rejects(
import("@trycua/cua-driver/sdk"),
@@ -147,13 +147,26 @@ test(
"typeText",
"pressKey",
"hotkey",
+ "verifyState",
]
assert.equal(
expectedMethods.every((name) => typeof driver[name] === "function"),
true,
)
- const result = await driver.getDesktopState(
- GetDesktopStateInput.new({ session: "node-run" }),
+ const result = await driver.verifyState(
+ VerifyStateInput.new({
+ pid: 123n,
+ windowId: 456n,
+ expect: [
+ StatePredicate.new({
+ window: WindowPredicate.new({ exists: true }),
+ }),
+ ],
+ session: "node-run",
+ timeoutMs: 0n,
+ stableSamples: 1n,
+ includeScreenshot: true,
+ }),
)
const request = await requestPromise
driver.uniffiDestroy()
@@ -161,8 +174,16 @@ test(
assert.equal(result.text, "node ffi")
assert.equal(result.images[0].mimeType, "image/png")
assert.equal(result.verified, true)
- assert.equal(request.name, "get_desktop_state")
- assert.deepEqual(request.args, { session: "node-run" })
+ assert.equal(request.name, "verify_state")
+ assert.deepEqual(request.args, {
+ pid: 123,
+ window_id: 456,
+ expect: [{ window: { exists: true } }],
+ session: "node-run",
+ timeout_ms: 0,
+ stable_samples: 1,
+ include_screenshot: true,
+ })
assert.equal(request.client_kind, "typescript_sdk")
} finally {
fixture.kill()
diff --git a/scripts/ci/macos/run-rust-e2e.sh b/scripts/ci/macos/run-rust-e2e.sh
index 886b3667cb..9e4164f42e 100755
--- a/scripts/ci/macos/run-rust-e2e.sh
+++ b/scripts/ci/macos/run-rust-e2e.sh
@@ -337,7 +337,8 @@ if [[ "${SUITE}" == native || "${SUITE}" == all ]]; then
harness_swiftui_smoke \
harness_swiftui_counter_background \
harness_swiftui_set_value_background \
- harness_swiftui_popover_foreground; do
+ harness_swiftui_popover_foreground \
+ harness_swiftui_verify_state; do
run_test "swiftui-${swiftui_test}" cargo test -p cua-driver --test harness_swiftui_test -- \
--ignored --exact "${swiftui_test}" --nocapture --test-threads=1
done
diff --git a/scripts/docs-generators/cua-driver.ts b/scripts/docs-generators/cua-driver.ts
index 813a2f67c4..d921e52530 100644
--- a/scripts/docs-generators/cua-driver.ts
+++ b/scripts/docs-generators/cua-driver.ts
@@ -73,11 +73,15 @@ export interface MCPInputSchema {
}
export interface MCPPropertyDoc {
- type: string;
+ type: string | string[];
description: string;
items?: { type: string };
enum?: string[];
minItems?: number;
+ maxItems?: number;
+ minimum?: number;
+ maximum?: number;
+ default?: unknown;
}
export interface MCPDocumentation {
@@ -718,7 +722,16 @@ export function generateMCPToolDoc(tool: MCPToolDoc): string[] {
const requiredLabel = isRequired ? 'required' : 'optional';
const typeLabel = formatPropertyType(prop);
const description = escapeMdxText(prop.description ?? '');
- const suffix = description ? `: ${description}` : '';
+ const details: string[] = [];
+ if (prop.default !== undefined) details.push(`default: \`${JSON.stringify(prop.default)}\``);
+ if (prop.minimum !== undefined || prop.maximum !== undefined) {
+ details.push(`range: ${prop.minimum ?? 'unbounded'}–${prop.maximum ?? 'unbounded'}`);
+ }
+ if (prop.minItems !== undefined || prop.maxItems !== undefined) {
+ details.push(`items: ${prop.minItems ?? 0}–${prop.maxItems ?? 'unbounded'}`);
+ }
+ const prose = [description, details.join('; ')].filter(Boolean).join(' ');
+ const suffix = prose ? `: ${prose}` : '';
lines.push(`- \`${propName}\` (${typeLabel}, ${requiredLabel})${suffix}`);
}
lines.push('');
@@ -771,7 +784,7 @@ function formatPropertyType(prop: MCPPropertyDoc): string {
const itemType = prop.items?.type ?? 'unknown';
return `array of ${itemType}`;
}
- return prop.type;
+ return Array.isArray(prop.type) ? prop.type.join(' or ') : prop.type;
}
function syntheticExampleValue(name: string, prop: MCPPropertyDoc): unknown {
@@ -799,6 +812,7 @@ function syntheticExampleValue(name: string, prop: MCPPropertyDoc): unknown {
case 'array':
if (name === 'keys') return ['cmd', 'c'];
if (name === 'modifiers') return ['cmd'];
+ if (name === 'expect') return [{ window: { exists: true } }];
if (name === 'files' || (prop.minItems ?? 0) > 0) return ['example'];
return [];
case 'string':