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 run_actions batch tool (CUA-1194) (#4737)

Francesco Bonaccia03d05b5f3c6
diff --git a/.github/scripts/cua-driver-mcp-compat/expected-tools.json b/.github/scripts/cua-driver-mcp-compat/expected-tools.json
index dc795bed82..d6840deb33 100644
--- a/.github/scripts/cua-driver-mcp-compat/expected-tools.json
+++ b/.github/scripts/cua-driver-mcp-compat/expected-tools.json
@@ -51,6 +51,7 @@
"press_key",
"replay_trajectory",
"right_click",
+ "run_actions",
"scroll",
"set_agent_cursor_enabled",
"set_agent_cursor_motion",
diff --git a/.github/scripts/tests/test_cua_driver_release_wiring.py b/.github/scripts/tests/test_cua_driver_release_wiring.py
index e446fde8bd..17fdec3ce4 100644
--- a/.github/scripts/tests/test_cua_driver_release_wiring.py
+++ b/.github/scripts/tests/test_cua_driver_release_wiring.py
@@ -1042,7 +1042,7 @@ fi
self.assertEqual(
len(expected["baseTools"]), len(set(expected["baseTools"]))
)
- self.assertEqual(len(expected["baseTools"]), 58)
+ self.assertEqual(len(expected["baseTools"]), 59)
self.assertEqual(
expected["outputSchemaCountByPlatform"],
{"darwin": 35, "linux": 39, "win32": 35},
diff --git a/docs/content/docs/cua-driver/reference/index.mdx b/docs/content/docs/cua-driver/reference/index.mdx
index ecd13c5abe..af25779160 100644
--- a/docs/content/docs/cua-driver/reference/index.mdx
+++ b/docs/content/docs/cua-driver/reference/index.mdx
@@ -38,6 +38,7 @@ description: "Every cua-driver command and every MCP tool on macOS, Linux and Wi
| [Typing tools](/cua-driver/reference/mcp-tools/keyboard) | Type text into a field or window. 1 tools. |
| [Key and shortcut tools](/cua-driver/reference/mcp-tools/keys-and-shortcuts) | Press keys and keyboard shortcuts. 2 tools. |
| [Value and clipboard tools](/cua-driver/reference/mcp-tools/values-and-clipboard) | Set element values and read or write the clipboard. 3 tools. |
+| [Batch tool](/cua-driver/reference/mcp-tools/batch) | Run several action tools in one call. 1 tools. |
| [Page tools](/cua-driver/reference/mcp-tools/page) | Read and act on web pages, and prepare and navigate browsers. 4 tools. |
| [Browser input tools](/cua-driver/reference/mcp-tools/browser-input) | Exact browser input over CDP: clicks, typing, pointer, dialogs, files and downloads. 6 tools. |
| [Session tools](/cua-driver/reference/mcp-tools/sessions) | Start, escalate, inspect and end lifecycle sessions. 6 tools. |
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/batch.mdx b/docs/content/docs/cua-driver/reference/mcp-tools/batch.mdx
new file mode 100644
index 0000000000..7fa9a6f530
--- /dev/null
+++ b/docs/content/docs/cua-driver/reference/mcp-tools/batch.mdx
@@ -0,0 +1,34 @@
+---
+title: "Batch tool"
+description: "Run several action tools in one call."
+---
+
+{/*
+ AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
+ Generated by: pnpm --dir docs docs:generate:cua-driver
+ Source: cua-driver dump-docs --type mcp (macOS, Linux and Windows registries)
+ Version: 0.34.0
+*/}
+
+Served by `cua-driver mcp`; see [MCP tools](/cua-driver/reference/mcp-tools) for every tool.
+
+## `run_actions`
+
+Run several action tools in ONE call, in order, and stop at the first failure. Use it when you already know the next few actions and do not need to look at the app between them (fill three fields, click, then read the result). Each step is `{tool, args}` where `tool` is one of click, double_click, right_click, set_value, type_text, press_key, hotkey, scroll, drag and `args` are exactly that tool's arguments. Every step goes through the same session, permission and approval checks as a direct call; a batch grants nothing extra. All steps are validated before the first one runs, so a malformed step 4 changes nothing. Element tokens and element_index values come from a get_window_state read before the batch; a step that changes the UI can invalidate later element targets, so put element-targeted actions before the actions that reshuffle the window, or use pixel targets after them.
+
+Returns per-step status (`ok` or the error message) and, when `observe` is given, ONE bounded get_window_state read after the last executed step. Without `observe` nothing is read. The batch uses one session: steps may omit `session` or repeat the batch's. `delay_ms` pauses between steps (max 2000). At most 32 steps.
+
+Effect: destructive. Platforms: macOS, Linux, Windows.
+
+| Parameter | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="run_actions--delay_ms"></span>`delay_ms` | `integer` | | Pause between steps in milliseconds (not after the last). Default 0. Range: 0 to 2000. |
+| <span id="run_actions--observe"></span>`observe` | `object` | | Optional end-of-batch observation: arguments for ONE get_window_state call. `pid` and `window_id` default to those of the last step that names both. Defaults to include_screenshot=false and max_elements=200 to stay cheap; pass include_screenshot=true or a larger max_elements to widen it. Omit to read nothing. |
+| <span id="run_actions--session"></span>`session` | `string` | | For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session. |
+| <span id="run_actions--steps"></span>`steps` | `object[]` | required | Ordered actions. Execution stops at the first failing step. Items: 1 to 32. |
+
+**Example arguments**
+
+```json
+{"steps":[{"tool":"click"}]}
+```
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/index.mdx b/docs/content/docs/cua-driver/reference/mcp-tools/index.mdx
index f1f9436acc..7b350adb01 100644
--- a/docs/content/docs/cua-driver/reference/mcp-tools/index.mdx
+++ b/docs/content/docs/cua-driver/reference/mcp-tools/index.mdx
@@ -143,6 +143,14 @@ Set element values and read or write the clipboard. [Reference](/cua-driver/refe
| <span id="clipboard_read"></span>[`clipboard_read`](/cua-driver/reference/mcp-tools/values-and-clipboard#clipboard_read) | List available system clipboard types and optionally return privacy-sensitive plain text. | macOS, Linux, Windows |
| <span id="clipboard_write"></span>[`clipboard_write`](/cua-driver/reference/mcp-tools/values-and-clipboard#clipboard_write) | Replace the system clipboard with exactly one value: plain text, an image from an absolute local path, or a file URL from an absolute local path. | macOS, Linux, Windows |
+## Batch tool
+
+Run several action tools in one call. [Reference](/cua-driver/reference/mcp-tools/batch).
+
+| Tool | Description | Platforms |
+| --- | --- | --- |
+| <span id="run_actions"></span>[`run_actions`](/cua-driver/reference/mcp-tools/batch#run_actions) | Run several action tools in ONE call, in order, and stop at the first failure. | macOS, Linux, Windows |
+
## Page tools
Read and act on web pages, and prepare and navigate browsers. [Reference](/cua-driver/reference/mcp-tools/page).
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/meta.json b/docs/content/docs/cua-driver/reference/mcp-tools/meta.json
index 3b30c56812..0a8e56fbbf 100644
--- a/docs/content/docs/cua-driver/reference/mcp-tools/meta.json
+++ b/docs/content/docs/cua-driver/reference/mcp-tools/meta.json
@@ -11,6 +11,7 @@
"keyboard",
"keys-and-shortcuts",
"values-and-clipboard",
+ "batch",
"page",
"browser-input",
"sessions",
diff --git a/libs/cua-driver/rust/CHANGELOG.md b/libs/cua-driver/rust/CHANGELOG.md
index bb529c4e5f..bd74743f2d 100644
--- a/libs/cua-driver/rust/CHANGELOG.md
+++ b/libs/cua-driver/rust/CHANGELOG.md
@@ -5,6 +5,7 @@
### Features
* **cua-driver:** `get_window_state` returns one tree representation by default (compact markdown; `tree_format` selects `elements` or `both`), walks at most 250 nodes unless `max_elements` says otherwise and says when it truncated, and omits `_note` / `background_input` unless `verbose:true`. `full_output:true` restores the previous full response. New `since:<snapshot_id>` returns only added, changed and removed rows (CUA-1192, CUA-1193). The typed SDKs keep the full response unless a shape is requested.
+* **cua-driver:** `run_actions` runs an ordered list of action tools (click, double_click, right_click, set_value, type_text, press_key, hotkey, scroll, drag) in one call, stops at the first failure, and returns per-step status plus one optional bounded `get_window_state` observation. Every step passes the same session, permission and approval checks as a direct call (CUA-1194).
### Bug Fixes
diff --git a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
index 4b78f68900..f48a9e0ab9 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
@@ -40,7 +40,7 @@ The MCP server instructions carry the same rules, so they apply even when this f
1. Start with a targeted read: `get_window_state({pid, window_id, query:"Save"})` returns about 2K chars where a full snapshot is about 42K. Bound large trees with `max_elements` / `max_depth`, and pass `include_screenshot:false` when the tree is enough. Widen only if the target is missing.
2. Act by `element_token`. A narrowed read keeps the full snapshot actionable, so you can act on a match without re-reading. Use pixels only for surfaces missing from the tree.
3. Verify at checkpoints (after a meaningful state change, before finishing), not after every action. One `verify_state` or one targeted `get_window_state` is usually enough.
-4. Batch known steps in one call once the batch tool exists (CUA-1194, not yet available).
+4. Batch known steps in one `run_actions` call (stops at the first failure, one optional bounded read at the end); see [Workflow](WORKFLOW.md#batch-known-actions).
## Act
@@ -50,6 +50,7 @@ The MCP server instructions carry the same rules, so they apply even when this f
| Find or open the requested app | `list_apps`, `list_windows`, `launch_app` | Current platform guide below |
| Observe one window | `get_window_state({pid, window_id, query})` | [Workflow](WORKFLOW.md) |
| Act on a control | `click` / `type_text` with a fresh `element_token` and exact window target | [Workflow](WORKFLOW.md) |
+| Run several decided actions in one call | `run_actions({steps:[{tool,args},...], observe?})`; stops at the first failure | [Workflow](WORKFLOW.md#batch-known-actions) |
| Use pixels when semantics cannot reach it | Fresh target screenshot, then `x,y` on the same target | [Workflow](WORKFLOW.md) |
| Verify the outcome | `verify_state({pid, window_id, expect})` or a fresh snapshot read by the agent | [Workflow](WORKFLOW.md) |
| Operate the authorized desktop | `get_desktop_state` → input with `target:{kind:"desktop",display_id:"primary"}` → `get_desktop_state` | [Workflow](WORKFLOW.md), [Linux](LINUX.md) on Wayland |
diff --git a/libs/cua-driver/rust/Skills/cua-driver/WORKFLOW.md b/libs/cua-driver/rust/Skills/cua-driver/WORKFLOW.md
index 0086d3e6f7..7b540b5f35 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/WORKFLOW.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/WORKFLOW.md
@@ -76,6 +76,25 @@ If a text action returns `unverifiable`, take a fresh snapshot before retrying.
Keep `delivery_mode:"background"` as the default for window input. The route may use accessibility hit-testing even when addressed by pixels: pixel coordinates do not promise physical pointer delivery. Read the returned `route` instead of inferring it from the tool name.
+## Batch known actions
+
+When the next several actions are already decided and nothing between them needs a look, send them as one `run_actions` call instead of one call per action. The batch runs the same tools in order, stops at the first failure, and returns per-step status plus at most one bounded observation. Typical fit: fill several fields, then press a button, then read the result. Do not batch across a point where the answer decides the next step, or when a step reshuffles the window and invalidates element tokens used by later steps (use pixel targets after it, or split the batch there).
+
+```bash
+cua-driver run_actions '{"session":"run-1","steps":[
+ {"tool":"set_value","args":{"pid":844,"element_token":"s0000002a:14","value":"Ada"}},
+ {"tool":"set_value","args":{"pid":844,"element_token":"s0000002a:15","value":"Lovelace"}},
+ {"tool":"click","args":{"target":{"kind":"window","pid":844,"window_id":10725},"element_token":"s0000002a:21"}},
+ {"tool":"press_key","args":{"pid":844,"key":"return"}}
+ ],"delay_ms":100,"observe":{"max_elements":120}}'
+```
+
+- `tool` is one of `click`, `double_click`, `right_click`, `set_value`, `type_text`, `press_key`, `hotkey`, `scroll`, `drag`; `args` are exactly that tool's arguments. Run `describe run_actions` and `describe <tool>` for schemas. Up to 32 steps.
+- Every step is validated before the first runs, so a malformed step changes nothing. Each step then passes the same session, permission, capability-manifest and approval checks as a direct call; a batch grants nothing a single call lacks, and a refused step ends the batch like any other failure.
+- A batch has one session. Set `session` on `run_actions`; a step may repeat it but not name another.
+- `observe` is optional and reads once, after the last executed step (also after a failure): `get_window_state` arguments, `pid`/`window_id` taken from the last step that names both, `include_screenshot:false` and `max_elements:200` unless you override. Omit `observe` to read nothing.
+- Read `steps[].ok` and `failed_step`. Steps before a failure did run and are not rolled back; steps after it did not. Observe before repairing, as for a single `unverifiable` action.
+
## Pixel coordinates
Ground window actions on the PNG from that exact `get_window_state`; ground desktop actions on `get_desktop_state`. Origins are top-left, increasing downward. The driver handles its own window capture scaling; do not add window offsets to window-local input.
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 b0902a0605..6007d49ae9 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
@@ -892,6 +892,7 @@ pub fn advertised_risk_for(tool: &str) -> RiskAssessment {
| "press_key"
| "hotkey"
| "set_value"
+ | "run_actions"
| "invoke_menu"
| "launch_app"
| "bring_to_front"
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools.rs
new file mode 100644
index 0000000000..315d086cf3
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools.rs
@@ -0,0 +1,490 @@
+//! `run_actions`: run an ordered list of existing action tools in one call.
+//!
+//! The tool owns no input logic. Every step is dispatched through the same
+//! [`ToolRegistry`] entry point a direct call uses, inside the batch's own
+//! authorization scope. Policy, permission mode, capability manifest,
+//! session capture scope, protected-resource consent, desktop coordination
+//! and recording therefore run once per step exactly as for a single call,
+//! and a batch cannot reach any tool or argument that a single call could
+//! not. The batch itself is only a thin ordered loop plus up-front validation.
+
+use std::sync::OnceLock;
+use std::time::Duration;
+
+use async_trait::async_trait;
+use serde_json::{json, Map, Value};
+
+use crate::{
+ protocol::{Content, ToolResult},
+ recording_tools::ReplayRegistrySlot,
+ tool::{Tool, ToolDef, ToolRegistry},
+};
+
+/// Public name of the batch tool.
+pub const RUN_ACTIONS_TOOL: &str = "run_actions";
+
+/// Action tools a batch may run. Observation tools are deliberately absent:
+/// the batch has exactly one optional observation, at the end.
+pub const BATCHABLE_TOOLS: &[&str] = &[
+ "click",
+ "double_click",
+ "right_click",
+ "set_value",
+ "type_text",
+ "press_key",
+ "hotkey",
+ "scroll",
+ "drag",
+];
+
+/// Most steps one call may carry. Keeps a batch inside client call timeouts.
+pub const MAX_STEPS: usize = 32;
+/// Longest pause between two steps.
+pub const MAX_DELAY_MS: u64 = 2_000;
+/// Default `max_elements` for the end-of-batch observation.
+const DEFAULT_OBSERVE_MAX_ELEMENTS: u64 = 200;
+const MESSAGE_LIMIT: usize = 300;
+const OBSERVE_TOOL: &str = "get_window_state";
+
+pub struct RunActionsTool {
+ registry: ReplayRegistrySlot,
+}
+
+impl RunActionsTool {
+ pub fn new(registry: ReplayRegistrySlot) -> Self {
+ Self { registry }
+ }
+}
+
+static DEF: OnceLock<ToolDef> = OnceLock::new();
+
+#[async_trait]
+impl Tool for RunActionsTool {
+ fn def(&self) -> &ToolDef {
+ DEF.get_or_init(|| ToolDef {
+ name: RUN_ACTIONS_TOOL.into(),
+ description: "Run several action tools in ONE call, in order, and stop at the first \
+ failure. Use it when you already know the next few actions and do not need to \
+ look at the app between them (fill three fields, click, then read the result). \
+ Each step is `{tool, args}` where `tool` is one of click, double_click, \
+ right_click, set_value, type_text, press_key, hotkey, scroll, drag and `args` \
+ are exactly that tool's arguments. Every step goes through the same session, \
+ permission and approval checks as a direct call; a batch grants nothing extra. \
+ All steps are validated before the first one runs, so a malformed step 4 \
+ changes nothing. Element tokens and element_index values come from a \
+ get_window_state read before the batch; a step that changes the UI can \
+ invalidate later element targets, so put element-targeted actions before the \
+ actions that reshuffle the window, or use pixel targets after them.\n\n\
+ Returns per-step status (`ok` or the error message) and, when `observe` is \
+ given, ONE bounded get_window_state read after the last executed step. \
+ Without `observe` nothing is read. The batch uses one session: steps may \
+ omit `session` or repeat the batch's. `delay_ms` pauses between steps (max \
+ 2000). At most 32 steps."
+ .into(),
+ input_schema: json!({
+ "type": "object",
+ "required": ["steps"],
+ "properties": {
+ "steps": {
+ "type": "array",
+ "minItems": 1,
+ "maxItems": MAX_STEPS,
+ "description": "Ordered actions. Execution stops at the first failing step.",
+ "items": {
+ "type": "object",
+ "required": ["tool"],
+ "properties": {
+ "tool": { "type": "string", "enum": BATCHABLE_TOOLS, "description": "Action tool to run." },
+ "args": { "type": "object", "description": "Arguments for that tool, as in a direct call." }
+ },
+ "additionalProperties": false
+ }
+ },
+ "delay_ms": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": MAX_DELAY_MS,
+ "description": "Pause between steps in milliseconds (not after the last). Default 0."
+ },
+ "observe": {
+ "type": "object",
+ "description": "Optional end-of-batch observation: arguments for ONE get_window_state call. `pid` and `window_id` default to those of the last step that names both. Defaults to include_screenshot=false and max_elements=200 to stay cheap; pass include_screenshot=true or a larger max_elements to widen it. Omit to read nothing."
+ }
+ },
+ "additionalProperties": false
+ }),
+ read_only: false,
+ destructive: true,
+ idempotent: false,
+ open_world: true,
+ })
+ }
+
+ async fn invoke(&self, args: Value) -> ToolResult {
+ let registry = match self.registry.lock().unwrap().upgrade() {
+ Some(registry) => registry,
+ None => {
+ return ToolResult::error(
+ "run_actions is not available: registry not initialised yet.",
+ )
+ }
+ };
+ let plan = match Plan::parse(&registry, &args) {
+ Ok(plan) => plan,
+ Err(error) => return error.into_result(),
+ };
+ plan.run(&registry).await
+ }
+}
+
+struct Step {
+ tool: &'static str,
+ args: Value,
+}
+
+struct Plan {
+ steps: Vec<Step>,
+ delay: Duration,
+ observe: Option<Value>,
+}
+
+struct PlanError {
+ step: Option<usize>,
+ message: String,
+}
+
+impl PlanError {
+ fn batch(message: impl Into<String>) -> Self {
+ Self {
+ step: None,
+ message: message.into(),
+ }
+ }
+
+ fn step(index: usize, message: impl Into<String>) -> Self {
+ Self {
+ step: Some(index),
+ message: message.into(),
+ }
+ }
+
+ fn into_result(self) -> ToolResult {
+ let location = match self.step {
+ Some(index) => format!("step {} of the batch: ", index + 1),
+ None => String::new(),
+ };
+ ToolResult::error(format!(
+ "run_actions rejected before running anything: {location}{}",
+ self.message
+ ))
+ .with_structured(json!({
+ "ok": false,
+ "code": "invalid_batch",
+ "executed": 0,
+ "failed_step": self.step,
+ "detail": self.message,
+ }))
+ }
+}
+
+impl Plan {
+ fn parse(registry: &ToolRegistry, args: &Value) -> Result<Self, PlanError> {
+ let object = args
+ .as_object()
+ .ok_or_else(|| PlanError::batch("arguments must be a JSON object"))?;
+ let raw_steps = object
+ .get("steps")
+ .and_then(Value::as_array)
+ .ok_or_else(|| PlanError::batch("`steps` must be a non-empty array"))?;
+ if raw_steps.is_empty() || raw_steps.len() > MAX_STEPS {
+ return Err(PlanError::batch(format!(
+ "`steps` must hold 1 to {MAX_STEPS} items, got {}",
+ raw_steps.len()
+ )));
+ }
+ let delay_ms = match object.get("delay_ms") {
+ None | Some(Value::Null) => 0,
+ Some(value) => value
+ .as_u64()
+ .filter(|ms| *ms <= MAX_DELAY_MS)
+ .ok_or_else(|| {
+ PlanError::batch(format!("`delay_ms` must be an integer 0 to {MAX_DELAY_MS}"))
+ })?,
+ };
+ // The trusted label the dispatcher recorded for this call's public
+ // session. Every step runs in that one session.
+ let session = object
+ .get("_public_session_label")
+ .and_then(Value::as_str)
+ .map(str::to_owned);
+
+ let mut steps = Vec::with_capacity(raw_steps.len());
+ for (index, raw) in raw_steps.iter().enumerate() {
+ steps.push(parse_step(registry, index, raw, session.as_deref())?);
+ }
+
+ let observe = match object.get("observe") {
+ None | Some(Value::Null) => None,
+ Some(value) => Some(parse_observe(registry, value, &steps, session.as_deref())?),
+ };
+ Ok(Self {
+ steps,
+ delay: Duration::from_millis(delay_ms),
+ observe,
+ })
+ }
+
+ async fn run(self, registry: &ToolRegistry) -> ToolResult {
+ let total = self.steps.len();
+ let mut reports = Vec::with_capacity(total);
+ let mut lines = Vec::with_capacity(total + 2);
+ let mut failed_step = None;
+
+ for (index, step) in self.steps.into_iter().enumerate() {
+ if index > 0 && !self.delay.is_zero() {
+ tokio::time::sleep(self.delay).await;
+ }
+ let result = registry.invoke(step.tool, step.args).await;
+ let ok = result.is_error != Some(true);
+ let message = bounded_message(&result);
+ lines.push(format!(
+ "{}. {} {}{}",
+ index + 1,
+ step.tool,
+ if ok { "ok" } else { "ERROR" },
+ if message.is_empty() {
+ String::new()
+ } else {
+ format!(": {message}")
+ }
+ ));
+ let mut report = json!({
+ "index": index,
+ "tool": step.tool,
+ "ok": ok,
+ "message": message,
+ });
+ if !ok {
+ if let Some(code) = result
+ .structured_content
+ .as_ref()
+ .and_then(|value| value.get("code"))
+ .and_then(Value::as_str)
+ {
+ report["code"] = Value::String(code.to_owned());
+ }
+ }
+ reports.push(report);
+ if !ok {
+ failed_step = Some(index);
+ break;
+ }
+ }
+
+ let executed = reports.len();
+ let mut structured = json!({
+ "ok": failed_step.is_none(),
+ "total": total,
+ "executed": executed,
+ "failed_step": failed_step,
+ "steps": reports,
+ });
+ let header = match failed_step {
+ None => format!("run_actions: {total}/{total} steps ok"),
+ Some(index) => format!(
+ "run_actions: step {} of {total} failed; {} step(s) ran before it, {} not run",
+ index + 1,
+ index,
+ total - executed
+ ),
+ };
+ lines.insert(0, header);
+
+ // One observation at the end, also after a failure so the caller can
+ // see where the app was left.
+ let mut observation_content = Vec::new();
+ if let Some(args) = self.observe {
+ let result = registry.invoke(OBSERVE_TOOL, args).await;
+ let ok = result.is_error != Some(true);
+ let mut report = json!({ "ok": ok, "tool": OBSERVE_TOOL });
+ if ok {
+ if let Some(state) = result.structured_content.clone() {
+ report["state"] = state;
+ }
+ observation_content = result.content;
+ lines.push("observation: get_window_state ok (below)".to_owned());
+ } else {
+ let message = bounded_message(&result);
+ lines.push(format!("observation: get_window_state ERROR: {message}"));
+ report["message"] = Value::String(message);
+ }
+ structured["observation"] = report;
+ }
+
+ let mut content = vec![Content::text(lines.join("\n"))];
+ content.append(&mut observation_content);
+ ToolResult {
+ content,
+ is_error: failed_step.map(|_| true),
+ structured_content: Some(structured),
+ ..Default::default()
+ }
+ }
+}
+
+fn parse_step(
+ registry: &ToolRegistry,
+ index: usize,
+ raw: &Value,
+ session: Option<&str>,
+) -> Result<Step, PlanError> {
+ let object = raw
+ .as_object()
+ .ok_or_else(|| PlanError::step(index, "must be an object {tool, args}"))?;
+ if let Some(extra) = object
+ .keys()
+ .find(|key| !matches!(key.as_str(), "tool" | "args"))
+ {
+ return Err(PlanError::step(
+ index,
+ format!("unknown field `{extra}`; a step has only `tool` and `args`"),
+ ));
+ }
+ let name = object
+ .get("tool")
+ .and_then(Value::as_str)
+ .ok_or_else(|| PlanError::step(index, "`tool` must be a string"))?;
+ let tool = BATCHABLE_TOOLS
+ .iter()
+ .copied()
+ .find(|candidate| *candidate == name)
+ .ok_or_else(|| {
+ PlanError::step(
+ index,
+ format!(
+ "`{name}` cannot run in a batch; allowed tools: {}",
+ BATCHABLE_TOOLS.join(", ")
+ ),
+ )
+ })?;
+ let mut args = match object.get("args") {
+ None | Some(Value::Null) => Value::Object(Map::new()),
+ Some(value @ Value::Object(_)) => value.clone(),
+ Some(_) => return Err(PlanError::step(index, "`args` must be an object")),
+ };
+ prepare_args(&mut args, session).map_err(|message| PlanError::step(index, message))?;
+ validate_against_schema(registry, tool, &args)
+ .map_err(|message| PlanError::step(index, format!("{tool}: {message}")))?;
+ Ok(Step { tool, args })
+}
+
+fn parse_observe(
+ registry: &ToolRegistry,
+ value: &Value,
+ steps: &[Step],
+ session: Option<&str>,
+) -> Result<Value, PlanError> {
+ let mut args = value
+ .as_object()
+ .cloned()
+ .map(Value::Object)
+ .ok_or_else(|| {
+ PlanError::batch("`observe` must be an object of get_window_state arguments")
+ })?;
+ prepare_args(&mut args, session)
+ .map_err(|message| PlanError::batch(format!("observe: {message}")))?;
+ let object = args.as_object_mut().expect("object");
+ // Inherit the window from the last step that names one, so the common
+ // "act, then look at the same window" case needs no repetition.
+ let inherited = steps.iter().rev().find_map(|step| {
+ let pid = step.args.get("pid").and_then(Value::as_i64)?;
+ let window_id = step.args.get("window_id").and_then(Value::as_i64)?;
+ Some((pid, window_id))
+ });
+ if let Some((pid, window_id)) = inherited {
+ object.entry("pid").or_insert_with(|| json!(pid));
+ object
+ .entry("window_id")
+ .or_insert_with(|| json!(window_id));
+ }
+ if !object.contains_key("pid") || !object.contains_key("window_id") {
+ return Err(PlanError::batch(
+ "observe: `pid` and `window_id` are required (no step names both to inherit from)",
+ ));
+ }
+ object
+ .entry("include_screenshot")
+ .or_insert(Value::Bool(false));
+ object
+ .entry("max_elements")
+ .or_insert_with(|| json!(DEFAULT_OBSERVE_MAX_ELEMENTS));
+ validate_against_schema(registry, OBSERVE_TOOL, &args)
+ .map_err(|message| PlanError::batch(format!("observe: {message}")))?;
+ Ok(args)
+}
+
+/// Reject runtime-private fields and pin the step to the batch's session.
+fn prepare_args(args: &mut Value, session: Option<&str>) -> Result<(), String> {
+ let object = args.as_object_mut().expect("object");
+ if let Some(key) = object.keys().find(|key| key.starts_with('_')) {
+ return Err(format!("`{key}` is reserved and cannot be set"));
+ }
+ let own = object
+ .get("session")
+ .and_then(Value::as_str)
+ .filter(|s| !s.is_empty());
+ match (own, session) {
+ (Some(own), Some(batch)) if own != batch => Err(format!(
+ "session `{own}` differs from the batch's session `{batch}`; a batch runs in one session"
+ )),
+ (Some(own), None) if own != "default" => Err(format!(
+ "session `{own}` differs from the batch's session; set `session` on run_actions itself"
+ )),
+ (_, Some(batch)) => {
+ object.insert("session".to_owned(), Value::String(batch.to_owned()));
+ Ok(())
+ }
+ _ => Ok(()),
+ }
+}
+
+fn validate_against_schema(
+ registry: &ToolRegistry,
+ tool: &str,
+ args: &Value,
+) -> Result<(), String> {
+ let def = registry
+ .get_def(tool)
+ .ok_or_else(|| format!("tool `{tool}` is not available on this platform"))?;
+ let schema = crate::tool::advertised_runtime_input_schema(&def.name, &def.input_schema);
+ let validator = jsonschema::validator_for(&schema)
+ .map_err(|error| format!("input schema is unusable: {error}"))?;
+ validator.validate(args).map_err(|error| {
+ let path = error.instance_path().to_string();
+ if path.is_empty() {
+ format!("invalid arguments: {error}")
+ } else {
+ format!("invalid arguments at {path}: {error}")
+ }
+ })
+}
+
+fn bounded_message(result: &ToolResult) -> String {
+ let text = result
+ .content
+ .iter()
+ .find_map(|content| match content {
+ Content::Text { text, .. } => Some(text.trim()),
+ _ => None,
+ })
+ .unwrap_or("");
+ let first_line = text.lines().next().unwrap_or("");
+ let mut message: String = first_line.chars().take(MESSAGE_LIMIT).collect();
+ if first_line.chars().count() > MESSAGE_LIMIT {
+ message.push_str("...");
+ }
+ message
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/tests.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/tests.rs
new file mode 100644
index 0000000000..e80c6a01ea
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/tests.rs
@@ -0,0 +1,396 @@
+use std::io::Write;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use async_trait::async_trait;
+use serde_json::{json, Value};
+
+use crate::{
+ authorization::PermissionMode,
+ protocol::ToolResult,
+ session_authorization::{
+ EffectiveAuthorizationContext, SessionAuthorizationRegistry, SessionModeCeiling,
+ },
+ tool::{Tool, ToolDef, ToolRegistry},
+};
+
+/// A stand-in platform tool that records every call it receives and fails
+/// when asked to (`{"fail": true}`).
+struct Probe {
+ def: ToolDef,
+ calls: Arc<Mutex<Vec<Value>>>,
+}
+
+#[async_trait]
+impl Tool for Probe {
+ fn def(&self) -> &ToolDef {
+ &self.def
+ }
+
+ async fn invoke(&self, args: Value) -> ToolResult {
+ self.calls.lock().unwrap().push(args.clone());
+ if args["fail"] == true {
+ ToolResult::error(format!("{} refused: probe asked to fail", self.def.name))
+ } else {
+ ToolResult::text(format!("{} done", self.def.name))
+ }
+ }
+}
+
+struct Harness {
+ registry: Arc<ToolRegistry>,
+ calls: std::collections::HashMap<&'static str, Arc<Mutex<Vec<Value>>>>,
+}
+
+impl Harness {
+ fn new() -> Self {
+ let mut registry = ToolRegistry::new();
+ let mut calls = std::collections::HashMap::new();
+ for name in super::BATCHABLE_TOOLS
+ .iter()
+ .copied()
+ .chain(["get_window_state"])
+ {
+ let log = Arc::new(Mutex::new(Vec::new()));
+ calls.insert(name, log.clone());
+ registry.register(Box::new(Probe {
+ def: ToolDef {
+ name: name.into(),
+ description: "probe".into(),
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "pid": {"type": "integer"},
+ "window_id": {"type": "integer"},
+ "text": {"type": "string"},
+ "fail": {"type": "boolean"},
+ "include_screenshot": {"type": "boolean"},
+ "max_elements": {"type": "integer", "minimum": 1}
+ },
+ "additionalProperties": false
+ }),
+ read_only: name == "get_window_state",
+ destructive: false,
+ idempotent: false,
+ open_world: false,
+ },
+ calls: log,
+ }));
+ }
+ registry.register_session_tools();
+ let registry = Arc::new(registry);
+ registry.init_self_weak();
+ Self { registry, calls }
+ }
+
+ fn hits(&self, tool: &str) -> usize {
+ self.calls[tool].lock().unwrap().len()
+ }
+
+ fn last(&self, tool: &str) -> Value {
+ self.calls[tool]
+ .lock()
+ .unwrap()
+ .last()
+ .cloned()
+ .expect("tool was called")
+ }
+
+ async fn run(&self, args: Value) -> ToolResult {
+ self.registry
+ .invoke_with_context(super::RUN_ACTIONS_TOOL, args, context(None))
+ .await
+ }
+}
+
+fn context(manifest: Option<&str>) -> Arc<EffectiveAuthorizationContext> {
+ let mode = if manifest.is_some() {
+ PermissionMode::Bounded
+ } else {
+ PermissionMode::Unrestricted
+ };
+ let ceiling = SessionModeCeiling::for_trusted_sessions(
+ [mode],
+ mode == PermissionMode::Unrestricted,
+ Duration::from_secs(60),
+ Duration::from_secs(30),
+ )
+ .unwrap();
+ let manifest = manifest.map(|source| {
+ let mut file = tempfile::NamedTempFile::new().unwrap();
+ file.write_all(source.as_bytes()).unwrap();
+ Arc::new(crate::session_manifest::load_manifest(file.path()).expect("manifest loads"))
+ });
+ SessionAuthorizationRegistry::with_ceiling(ceiling)
+ .compatibility_context(mode, manifest)
+ .unwrap()
+}
+
+fn text(result: &ToolResult) -> String {
+ result
+ .content
+ .iter()
+ .filter_map(|content| match content {
+ crate::protocol::Content::Text { text, .. } => Some(text.as_str()),
+ _ => None,
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+#[tokio::test]
+async fn runs_steps_in_order_and_reports_each() {
+ let harness = Harness::new();
+ let result = harness
+ .run(json!({"steps": [
+ {"tool": "set_value", "args": {"pid": 42, "window_id": 7, "text": "a"}},
+ {"tool": "type_text", "args": {"pid": 42, "text": "b"}},
+ {"tool": "press_key", "args": {"pid": 42}},
+ ]}))
+ .await;
+ assert_ne!(result.is_error, Some(true), "{}", text(&result));
+ let structured = result.structured_content.unwrap();
+ assert_eq!(structured["ok"], true);
+ assert_eq!(structured["executed"], 3);
+ let tools: Vec<_> = structured["steps"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|step| step["tool"].as_str().unwrap().to_owned())
+ .collect();
+ assert_eq!(tools, ["set_value", "type_text", "press_key"]);
+ assert_eq!(structured.get("observation"), None);
+ assert_eq!(harness.hits("get_window_state"), 0, "no observe, no read");
+}
+
+#[tokio::test]
+async fn stops_at_the_first_failure_and_still_observes() {
+ let harness = Harness::new();
+ let result = harness
+ .run(json!({
+ "steps": [
+ {"tool": "click", "args": {"pid": 42, "window_id": 7}},
+ {"tool": "set_value", "args": {"pid": 42, "window_id": 7, "fail": true}},
+ {"tool": "press_key", "args": {"pid": 42}},
+ ],
+ "observe": {}
+ }))
+ .await;
+ assert_eq!(result.is_error, Some(true));
+ let structured = result.structured_content.clone().unwrap();
+ assert_eq!(structured["failed_step"], 1);
+ assert_eq!(structured["executed"], 2);
+ assert_eq!(structured["steps"][1]["ok"], false);
+ assert!(structured["steps"][1]["message"]
+ .as_str()
+ .unwrap()
+ .contains("probe asked to fail"));
+ assert_eq!(
+ harness.hits("press_key"),
+ 0,
+ "steps after the failure must not run"
+ );
+ assert!(text(&result).contains("step 2 of 3 failed"));
+ assert_eq!(harness.hits("get_window_state"), 1);
+ assert_eq!(structured["observation"]["ok"], true);
+}
+
+#[tokio::test]
+async fn validates_every_step_before_running_any() {
+ let harness = Harness::new();
+ let cases = [
+ (
+ json!({"tool": "get_window_state", "args": {}}),
+ "cannot run in a batch",
+ ),
+ (
+ json!({"tool": "run_actions", "args": {}}),
+ "cannot run in a batch",
+ ),
+ (
+ json!({"tool": "click", "args": {"pid": "forty-two"}}),
+ "invalid arguments",
+ ),
+ (
+ json!({"tool": "click", "args": {"bogus": 1}}),
+ "invalid arguments",
+ ),
+ (
+ json!({"tool": "click", "args": {"_session_id": "x"}}),
+ "reserved",
+ ),
+ (
+ json!({"tool": "click", "args": {"session": "other"}}),
+ "differs from the batch",
+ ),
+ (json!({"tool": "click", "extra": 1}), "unknown field"),
+ (json!({"tool": "click", "args": 5}), "must be an object"),
+ ];
+ for (bad, expected) in cases {
+ let result = harness
+ .run(json!({"steps": [
+ {"tool": "click", "args": {"pid": 42}},
+ {"tool": "press_key", "args": {"pid": 42}},
+ bad.clone(),
+ ]}))
+ .await;
+ assert_eq!(result.is_error, Some(true), "{bad}");
+ let message = text(&result);
+ assert!(message.contains("step 3"), "{bad}: {message}");
+ assert!(message.contains(expected), "{bad}: {message}");
+ assert_eq!(result.structured_content.unwrap()["code"], "invalid_batch");
+ }
+ assert_eq!(
+ harness.hits("click"),
+ 0,
+ "a rejected batch must execute nothing"
+ );
+ assert_eq!(harness.hits("press_key"), 0);
+}
+
+#[tokio::test]
+async fn rejects_bad_batch_shapes() {
+ let harness = Harness::new();
+ for args in [
+ json!({"steps": []}),
+ json!({"steps": "click"}),
+ json!({"steps": [{"tool": "click"}], "delay_ms": 5000}),
+ json!({"steps": vec![json!({"tool": "click"}); super::MAX_STEPS + 1]}),
+ json!({"steps": [{"tool": "click"}], "observe": {"pid": 1}}),
+ json!({"steps": [{"tool": "click"}], "observe": {}}),
+ json!({"steps": [{"tool": "click", "args": {"pid": 1, "window_id": 2}}], "observe": {"max_elements": 0}}),
+ ] {
+ let result = harness.run(args.clone()).await;
+ assert_eq!(result.is_error, Some(true), "{args}");
+ }
+ assert_eq!(harness.hits("click"), 0);
+}
+
+#[tokio::test]
+async fn observation_inherits_the_window_and_stays_bounded() {
+ let harness = Harness::new();
+ let result = harness
+ .run(json!({
+ "steps": [
+ {"tool": "click", "args": {"pid": 42, "window_id": 7}},
+ {"tool": "type_text", "args": {"pid": 42, "text": "x"}},
+ ],
+ "observe": {}
+ }))
+ .await;
+ assert_ne!(result.is_error, Some(true), "{}", text(&result));
+ let observed = harness.last("get_window_state");
+ assert_eq!(observed["pid"], 42);
+ assert_eq!(observed["window_id"], 7);
+ assert_eq!(observed["include_screenshot"], false);
+ assert_eq!(observed["max_elements"], 200);
+
+ harness
+ .run(json!({
+ "steps": [{"tool": "click", "args": {"pid": 42, "window_id": 7}}],
+ "observe": {"pid": 1, "window_id": 2, "include_screenshot": true, "max_elements": 10}
+ }))
+ .await;
+ let observed = harness.last("get_window_state");
+ assert_eq!(observed["pid"], 1);
+ assert_eq!(observed["include_screenshot"], true);
+ assert_eq!(observed["max_elements"], 10);
+ assert_eq!(
+ harness.hits("get_window_state"),
+ 2,
+ "exactly one read per batch"
+ );
+}
+
+#[tokio::test]
+async fn pauses_between_steps_but_not_after_the_last() {
+ let harness = Harness::new();
+ let started = std::time::Instant::now();
+ harness
+ .run(json!({"delay_ms": 120, "steps": [
+ {"tool": "click", "args": {"pid": 42}},
+ {"tool": "click", "args": {"pid": 42}},
+ ]}))
+ .await;
+ let elapsed = started.elapsed();
+ assert!(elapsed >= Duration::from_millis(120), "{elapsed:?}");
+ assert!(elapsed < Duration::from_millis(240), "{elapsed:?}");
+}
+
+#[tokio::test]
+async fn every_step_runs_in_the_batch_session() {
+ let harness = Harness::new();
+ let result = harness
+ .run(json!({"session": "batch-s1", "steps": [
+ {"tool": "click", "args": {"pid": 42}},
+ {"tool": "press_key", "args": {"pid": 42, "session": "batch-s1"}},
+ ]}))
+ .await;
+ assert_ne!(result.is_error, Some(true), "{}", text(&result));
+ for tool in ["click", "press_key"] {
+ let session = harness.last(tool)["session"].as_str().unwrap().to_owned();
+ assert!(session.ends_with("batch-s1"), "{tool}: {session}");
+ }
+}
+
+#[tokio::test]
+async fn each_step_is_held_to_the_capability_manifest() {
+ let harness = Harness::new();
+ let manifest = "version: 2\nmode: bounded\nexpires_after: 1h\nidle_timeout: 30m\nallow:\n tools: [run_actions, click]\n";
+ let result = harness
+ .registry
+ .invoke_with_context(
+ super::RUN_ACTIONS_TOOL,
+ json!({"steps": [
+ {"tool": "click", "args": {"pid": 42}},
+ {"tool": "set_value", "args": {"pid": 42, "text": "secret"}},
+ {"tool": "click", "args": {"pid": 42}},
+ ]}),
+ context(Some(manifest)),
+ )
+ .await;
+ assert_eq!(result.is_error, Some(true));
+ let message = text(&result);
+ let structured = result.structured_content.unwrap();
+ // The manifest scopes pid-targeted input to declared applications, and
+ // none is declared: the very first step is refused by the same gate a
+ // direct call meets, so nothing reaches any tool.
+ assert_eq!(structured["failed_step"], 0, "{message}");
+ assert!(message.contains("capability manifest"), "{message}");
+ assert_eq!(harness.hits("click"), 0);
+ assert_eq!(harness.hits("set_value"), 0, "later steps never run");
+}
+
+#[tokio::test]
+async fn the_batch_itself_needs_the_manifest_to_allow_it() {
+ let harness = Harness::new();
+ let manifest = "version: 2\nmode: bounded\nexpires_after: 1h\nidle_timeout: 30m\nallow:\n tools: [click]\n";
+ let result = harness
+ .registry
+ .invoke_with_context(
+ super::RUN_ACTIONS_TOOL,
+ json!({"steps": [{"tool": "click", "args": {"pid": 42}}]}),
+ context(Some(manifest)),
+ )
+ .await;
+ assert_eq!(result.is_error, Some(true));
+ assert_eq!(harness.hits("click"), 0);
+}
+
+#[tokio::test]
+async fn the_batch_is_advertised_with_its_schema() {
+ let harness = Harness::new();
+ let def = harness
+ .registry
+ .get_def(super::RUN_ACTIONS_TOOL)
+ .expect("registered");
+ assert_eq!(def.input_schema["required"], json!(["steps"]));
+ let listed: Vec<_> = def.input_schema["properties"]["steps"]["items"]["properties"]["tool"]
+ ["enum"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|value| value.as_str().unwrap())
+ .collect();
+ assert_eq!(listed, super::BATCHABLE_TOOLS);
+}
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 09d691965e..eabf86392b 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
@@ -53,6 +53,7 @@ pub mod action_target;
pub mod agent_cursor;
pub mod authorization;
pub mod background_input;
+pub mod batch_tools;
pub mod browser;
pub mod build_info;
pub mod capture_mode;
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 6cc446d128..315711a4af 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
@@ -378,8 +378,6 @@ fn agent_instructions() -> String {
)
};
- // TODO(CUA-1194): when the batch tool lands, add a loop step: send several
- // known steps in one batch call instead of one call per action.
format!(
r#"cua-driver: background GUI automation. No shell: for non-GUI outcomes use an app API/SDK, CLI or filesystem and read the result back there.
@@ -388,6 +386,7 @@ Efficient loop:
2. Read narrowly: `get_window_state` with `query:"Save"` (or `max_elements`) returns ~2K chars vs ~42K for a full snapshot. Widen only if the target is missing; `include_screenshot:false` when the tree suffices.
3. Act by `element_token` ({tree_kind}) from the latest snapshot; pixel `x,y` only for surfaces missing from the tree. A new snapshot stales older tokens.
4. Verify at checkpoints, not after every action: `verify_state(pid, window_id, expect)` or one targeted read. `unknown` and `effect:"unverifiable"` are not success.
+5. Batch known steps: `run_actions({{steps:[{{tool,args}}]}})` stops at the first failure.
Use the narrowest semantic route first: `set_window_frame` plus `list_windows` for geometry, typed browser tools for pages, clipboard tools for the clipboard. Stay in the background; `delivery_mode:"foreground"` only if refused or unverifiable.
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 1d3b4c7994..3f799da033 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
@@ -985,6 +985,7 @@ pub fn load_manifest(path: &Path) -> Result<SessionManifest, String> {
"press_key",
"hotkey",
"set_value",
+ "run_actions",
"mouse_button_down",
"mouse_button_up",
"mouse_drag",
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
index 2d60e6775e..e2c60174a3 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
@@ -209,7 +209,7 @@ fn unknown_argument(def: &ToolDef, args: &Value) -> Option<String> {
.cloned()
}
-fn advertised_runtime_input_schema(tool_name: &str, schema: &Value) -> Value {
+pub(crate) fn advertised_runtime_input_schema(tool_name: &str, schema: &Value) -> Value {
let mut schema = schema.clone();
let closed = schema["additionalProperties"] == false;
let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) else {
@@ -403,6 +403,7 @@ pub fn default_capabilities_for(tool_name: &str) -> Vec<String> {
"stop_recording" => &["recording.stop"],
"get_recording_state" => &["recording.state"],
"replay_trajectory" => &["recording.replay"],
+ "run_actions" => &["input.batch"],
"install_ffmpeg" => &["recording.install_dependency"],
"install_extension" => &["extension.install"],
@@ -932,6 +933,17 @@ impl ToolRegistry {
self.register(Box::new(ListSessionsTool));
self.register(Box::new(GetSessionStateTool));
self.register(Box::new(EndSessionTool));
+ self.register_batch_tools();
+ }
+
+ /// Register `run_actions`, which re-enters this registry for every step.
+ /// Called from [`Self::register_session_tools`] so every platform that
+ /// registers sessions gets it; [`Self::init_self_weak`] supplies the
+ /// registry handle, as for `replay_trajectory`.
+ fn register_batch_tools(&mut self) {
+ self.register(Box::new(crate::batch_tools::RunActionsTool::new(
+ self.replay_registry.clone(),
+ )));
}
pub fn register_perception_tool(
@@ -1723,6 +1735,7 @@ impl ToolRegistry {
| "stop_recording"
| "get_recording_state"
| "replay_trajectory"
+ | "run_actions"
| "start_session"
| "end_session"
);
diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_handshake_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_handshake_test.rs
index 55efaa93e5..f18b9a50d7 100644
--- a/libs/cua-driver/rust/crates/cua-driver/tests/protocol_handshake_test.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/tests/protocol_handshake_test.rs
@@ -60,6 +60,7 @@ fn all_expected_tools_registered() {
"stop_recording",
"get_recording_state",
"replay_trajectory",
+ "run_actions",
"page",
];
for name in expected {
diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json
index 53d48a7aa1..7200493d69 100644
--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json
+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json
@@ -3466,6 +3466,70 @@
"name": "end_session",
"read_only": false
},
+ {
+ "description": "Run several action tools in ONE call, in order, and stop at the first failure. Use it when you already know the next few actions and do not need to look at the app between them (fill three fields, click, then read the result). Each step is `{tool, args}` where `tool` is one of click, double_click, right_click, set_value, type_text, press_key, hotkey, scroll, drag and `args` are exactly that tool's arguments. Every step goes through the same session, permission and approval checks as a direct call; a batch grants nothing extra. All steps are validated before the first one runs, so a malformed step 4 changes nothing. Element tokens and element_index values come from a get_window_state read before the batch; a step that changes the UI can invalidate later element targets, so put element-targeted actions before the actions that reshuffle the window, or use pixel targets after them.\n\nReturns per-step status (`ok` or the error message) and, when `observe` is given, ONE bounded get_window_state read after the last executed step. Without `observe` nothing is read. The batch uses one session: steps may omit `session` or repeat the batch's. `delay_ms` pauses between steps (max 2000). At most 32 steps.",
+ "destructive": true,
+ "idempotent": false,
+ "input_schema": {
+ "additionalProperties": false,
+ "properties": {
+ "delay_ms": {
+ "description": "Pause between steps in milliseconds (not after the last). Default 0.",
+ "maximum": 2000,
+ "minimum": 0,
+ "type": "integer"
+ },
+ "observe": {
+ "description": "Optional end-of-batch observation: arguments for ONE get_window_state call. `pid` and `window_id` default to those of the last step that names both. Defaults to include_screenshot=false and max_elements=200 to stay cheap; pass include_screenshot=true or a larger max_elements to widen it. Omit to read nothing.",
+ "type": "object"
+ },
+ "session": {
+ "description": "For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.",
+ "type": "string"
+ },
+ "steps": {
+ "description": "Ordered actions. Execution stops at the first failing step.",
+ "items": {
+ "additionalProperties": false,
+ "properties": {
+ "args": {
+ "description": "Arguments for that tool, as in a direct call.",
+ "type": "object"
+ },
+ "tool": {
+ "description": "Action tool to run.",
+ "enum": [
+ "click",
+ "double_click",
+ "right_click",
+ "set_value",
+ "type_text",
+ "press_key",
+ "hotkey",
+ "scroll",
+ "drag"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "tool"
+ ],
+ "type": "object"
+ },
+ "maxItems": 32,
+ "minItems": 1,
+ "type": "array"
+ }
+ },
+ "required": [
+ "steps"
+ ],
+ "type": "object"
+ },
+ "name": "run_actions",
+ "read_only": false
+ },
{
"description": "Check the saved stable/nightly Cua Driver channel for a release on GitHub. Returns current and selected channels, current and latest versions, an `update_available` boolean, the install one-liner, and the release notes URL. Read-only — never installs. Pacman-owned Linux executables return package-manager guidance without checking GitHub. Mirror of `cua-driver check-update --json`.",
"destructive": false,
diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json
index e19656720a..c8947f4d6c 100644
--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json
+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json
@@ -3102,6 +3102,70 @@
"name": "end_session",
"read_only": false
},
+ {
+ "description": "Run several action tools in ONE call, in order, and stop at the first failure. Use it when you already know the next few actions and do not need to look at the app between them (fill three fields, click, then read the result). Each step is `{tool, args}` where `tool` is one of click, double_click, right_click, set_value, type_text, press_key, hotkey, scroll, drag and `args` are exactly that tool's arguments. Every step goes through the same session, permission and approval checks as a direct call; a batch grants nothing extra. All steps are validated before the first one runs, so a malformed step 4 changes nothing. Element tokens and element_index values come from a get_window_state read before the batch; a step that changes the UI can invalidate later element targets, so put element-targeted actions before the actions that reshuffle the window, or use pixel targets after them.\n\nReturns per-step status (`ok` or the error message) and, when `observe` is given, ONE bounded get_window_state read after the last executed step. Without `observe` nothing is read. The batch uses one session: steps may omit `session` or repeat the batch's. `delay_ms` pauses between steps (max 2000). At most 32 steps.",
+ "destructive": true,
+ "idempotent": false,
+ "input_schema": {
+ "additionalProperties": false,
+ "properties": {
+ "delay_ms": {
+ "description": "Pause between steps in milliseconds (not after the last). Default 0.",
+ "maximum": 2000,
+ "minimum": 0,
+ "type": "integer"
+ },
+ "observe": {
+ "description": "Optional end-of-batch observation: arguments for ONE get_window_state call. `pid` and `window_id` default to those of the last step that names both. Defaults to include_screenshot=false and max_elements=200 to stay cheap; pass include_screenshot=true or a larger max_elements to widen it. Omit to read nothing.",
+ "type": "object"
+ },
+ "session": {
+ "description": "For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.",
+ "type": "string"
+ },
+ "steps": {
+ "description": "Ordered actions. Execution stops at the first failing step.",
+ "items": {
+ "additionalProperties": false,
+ "properties": {
+ "args": {
+ "description": "Arguments for that tool, as in a direct call.",
+ "type": "object"
+ },
+ "tool": {
+ "description": "Action tool to run.",
+ "enum": [
+ "click",
+ "double_click",
+ "right_click",
+ "set_value",
+ "type_text",
+ "press_key",
+ "hotkey",
+ "scroll",
+ "drag"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "tool"
+ ],
+ "type": "object"
+ },
+ "maxItems": 32,
+ "minItems": 1,
+ "type": "array"
+ }
+ },
+ "required": [
+ "steps"
+ ],
+ "type": "object"
+ },
+ "name": "run_actions",
+ "read_only": false
+ },
{
"description": "Check the saved stable/nightly Cua Driver channel for a release on GitHub. Returns current and selected channels, current and latest versions, an `update_available` boolean, the install one-liner, and the release notes URL. Read-only — never installs. Pacman-owned Linux executables return package-manager guidance without checking GitHub. Mirror of `cua-driver check-update --json`.",
"destructive": false,
diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json
index c49a8a33de..6cf59e8d36 100644
--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json
+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json
@@ -3158,6 +3158,70 @@
"name": "end_session",
"read_only": false
},
+ {
+ "description": "Run several action tools in ONE call, in order, and stop at the first failure. Use it when you already know the next few actions and do not need to look at the app between them (fill three fields, click, then read the result). Each step is `{tool, args}` where `tool` is one of click, double_click, right_click, set_value, type_text, press_key, hotkey, scroll, drag and `args` are exactly that tool's arguments. Every step goes through the same session, permission and approval checks as a direct call; a batch grants nothing extra. All steps are validated before the first one runs, so a malformed step 4 changes nothing. Element tokens and element_index values come from a get_window_state read before the batch; a step that changes the UI can invalidate later element targets, so put element-targeted actions before the actions that reshuffle the window, or use pixel targets after them.\n\nReturns per-step status (`ok` or the error message) and, when `observe` is given, ONE bounded get_window_state read after the last executed step. Without `observe` nothing is read. The batch uses one session: steps may omit `session` or repeat the batch's. `delay_ms` pauses between steps (max 2000). At most 32 steps.",
+ "destructive": true,
+ "idempotent": false,
+ "input_schema": {
+ "additionalProperties": false,
+ "properties": {
+ "delay_ms": {
+ "description": "Pause between steps in milliseconds (not after the last). Default 0.",
+ "maximum": 2000,
+ "minimum": 0,
+ "type": "integer"
+ },
+ "observe": {
+ "description": "Optional end-of-batch observation: arguments for ONE get_window_state call. `pid` and `window_id` default to those of the last step that names both. Defaults to include_screenshot=false and max_elements=200 to stay cheap; pass include_screenshot=true or a larger max_elements to widen it. Omit to read nothing.",
+ "type": "object"
+ },
+ "session": {
+ "description": "For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session.",
+ "type": "string"
+ },
+ "steps": {
+ "description": "Ordered actions. Execution stops at the first failing step.",
+ "items": {
+ "additionalProperties": false,
+ "properties": {
+ "args": {
+ "description": "Arguments for that tool, as in a direct call.",
+ "type": "object"
+ },
+ "tool": {
+ "description": "Action tool to run.",
+ "enum": [
+ "click",
+ "double_click",
+ "right_click",
+ "set_value",
+ "type_text",
+ "press_key",
+ "hotkey",
+ "scroll",
+ "drag"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "tool"
+ ],
+ "type": "object"
+ },
+ "maxItems": 32,
+ "minItems": 1,
+ "type": "array"
+ }
+ },
+ "required": [
+ "steps"
+ ],
+ "type": "object"
+ },
+ "name": "run_actions",
+ "read_only": false
+ },
{
"description": "Check the saved stable/nightly Cua Driver channel for a release on GitHub. Returns current and selected channels, current and latest versions, an `update_available` boolean, the install one-liner, and the release notes URL. Read-only — never installs. Pacman-owned Linux executables return package-manager guidance without checking GitHub. Mirror of `cua-driver check-update --json`.",
"destructive": false,
diff --git a/scripts/docs-generators/cua-driver.ts b/scripts/docs-generators/cua-driver.ts
index db40087878..6b4965ec39 100644
--- a/scripts/docs-generators/cua-driver.ts
+++ b/scripts/docs-generators/cua-driver.ts
@@ -296,6 +296,12 @@ export const MCP_CATEGORIES: Array<McpCategory & { tools: string[] }> = [
summary: 'Set element values and read or write the clipboard',
tools: ['set_value', 'clipboard_read', 'clipboard_write'],
},
+ {
+ slug: 'batch',
+ title: 'Batch tool',
+ summary: 'Run several action tools in one call',
+ tools: ['run_actions'],
+ },
{
slug: 'page',
title: 'Page tools',