Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(computer): preserve driver failures and parent cleanup (#2510)

Max7f7dd6a13609
diff --git a/core/computer_server.py b/core/computer_server.py
index 99138732a..cd511eb19 100644
--- a/core/computer_server.py
+++ b/core/computer_server.py
@@ -13,6 +13,7 @@ from copy import deepcopy
from dataclasses import dataclass, field
import hashlib
import json
+import logging
import os
from pathlib import Path
import sys
@@ -29,6 +30,7 @@ if __package__ in {None, ""}:
sys.path.insert(0, str(_PACKAGE_ROOT))
from config.atomic_io import write_atomic
+from core.agent_core.ai.errors import redact_provider_text
from core.computer_use import (
COMPUTER_USE_LEASE_FILE,
COMPUTER_USE_LEASE_LOCK_FILE,
@@ -48,6 +50,9 @@ _UPSTREAM_RESPONSE_LIMIT = 128 * 1024 * 1024
# transport deadline above that documented bound while still preventing a dead
# reader from holding the desktop lease forever.
_UPSTREAM_REQUEST_TIMEOUT_SECONDS = 180.0
+_UPSTREAM_DETAIL_LIMIT = 2048
+_UPSTREAM_DIAGNOSTIC_SCAN_LIMIT = 8192
+_UPSTREAM_DIAGNOSTIC_LOG_LIMIT = 20
_ADMISSION_RETRY_LIMIT = 1
_PROXY_PROCESS_ENV_KEYS = (
"HOME",
@@ -78,6 +83,8 @@ _ALLOWED_TARGET_KEYS = frozenset({"kind", "pid", "window_id"})
_COMMAND_MODIFIERS = frozenset({"cmd", "command", "meta"})
_SHIFT_MODIFIERS = frozenset({"shift"})
+logger = logging.getLogger(__name__)
+
class ComputerServerError(RuntimeError):
"""A request cannot be forwarded safely."""
@@ -485,6 +492,7 @@ class JsonRpcUpstream:
stdout = self._process.stdout
assert stdout is not None
error: BaseException = UpstreamUnavailable("computer-use upstream exited")
+ malformed_lines = 0
try:
while True:
line = await stdout.readline()
@@ -492,7 +500,19 @@ class JsonRpcUpstream:
break
try:
message = json.loads(line)
- except json.JSONDecodeError:
+ except json.JSONDecodeError as exc:
+ detail = _bounded_diagnostic(line)
+ malformed_lines += 1
+ if malformed_lines <= _UPSTREAM_DIAGNOSTIC_LOG_LIMIT:
+ logger.warning(
+ "computer-use upstream returned malformed JSON: %s",
+ detail or _bounded_diagnostic(str(exc)),
+ )
+ elif malformed_lines == _UPSTREAM_DIAGNOSTIC_LOG_LIMIT + 1:
+ logger.warning(
+ "computer-use upstream malformed JSON log limit reached; "
+ "further lines suppressed"
+ )
continue
request_id = message.get("id")
if isinstance(request_id, int):
@@ -501,8 +521,17 @@ class JsonRpcUpstream:
future.set_result(message)
except asyncio.CancelledError:
raise
- except BaseException:
- error = UpstreamUnavailable("computer-use upstream reader failed")
+ except BaseException as exc:
+ detail = _bounded_diagnostic(str(exc))
+ logger.warning(
+ "computer-use upstream reader failed (%s): %s",
+ type(exc).__name__,
+ detail or type(exc).__name__,
+ )
+ error = UpstreamUnavailable(
+ "computer-use upstream reader failed"
+ + (f": {detail}" if detail else "")
+ )
finally:
for future in tuple(self._pending.values()):
if not future.done():
@@ -511,8 +540,30 @@ class JsonRpcUpstream:
async def _stderr_loop(self) -> None:
stderr = self._process.stderr
assert stderr is not None
- while await stderr.readline():
- pass
+ logged_lines = 0
+ try:
+ while True:
+ line = await stderr.readline()
+ if not line:
+ return
+ detail = _bounded_diagnostic(line)
+ if detail and logged_lines < _UPSTREAM_DIAGNOSTIC_LOG_LIMIT:
+ logger.warning("computer-use upstream stderr: %s", detail)
+ logged_lines += 1
+ elif detail and logged_lines == _UPSTREAM_DIAGNOSTIC_LOG_LIMIT:
+ logger.warning(
+ "computer-use upstream stderr log limit reached; "
+ "further lines suppressed"
+ )
+ logged_lines += 1
+ except asyncio.CancelledError:
+ raise
+ except BaseException as exc:
+ detail = _bounded_diagnostic(str(exc))
+ logger.warning(
+ "computer-use upstream stderr reader failed: %s",
+ detail or type(exc).__name__,
+ )
async def close(self) -> None:
stdin = self._process.stdin
@@ -599,8 +650,92 @@ def _load_snapshot(state_path: Path) -> tuple[list[dict[str, Any]], set[str]]:
return advertised, accepted_session
-def _error_result(code: str, message: str | None = None, **params: Any) -> dict[str, Any]:
- payload = {"code": code, "params": params}
+def _bounded_diagnostic(value: Any) -> str | None:
+ """Return a single-line diagnostic without carrying arbitrary payloads."""
+
+ if isinstance(value, bytes):
+ text = value[:_UPSTREAM_DIAGNOSTIC_SCAN_LIMIT].decode(
+ "utf-8",
+ errors="replace",
+ )
+ elif isinstance(value, str):
+ text = value[:_UPSTREAM_DIAGNOSTIC_SCAN_LIMIT]
+ else:
+ return None
+ text = "".join(
+ character
+ if character in "\r\n" or character >= " " and character != "\x7f"
+ else " "
+ for character in text
+ )
+ text = redact_provider_text(text)
+ text = " ".join(text.split())
+ if not text:
+ return None
+ if len(text) > _UPSTREAM_DETAIL_LIMIT:
+ return text[: _UPSTREAM_DETAIL_LIMIT - 3].rstrip() + "..."
+ return text
+
+
+def _diagnostic_candidate(value: Any) -> str | bytes | None:
+ if isinstance(value, (str, bytes)) and value.strip():
+ return value
+ return None
+
+
+def _diagnostic_from_mapping(value: Any) -> str | bytes | None:
+ if not isinstance(value, Mapping):
+ return None
+ for key in ("message", "reason", "detail", "error"):
+ detail = _diagnostic_candidate(value.get(key))
+ if detail:
+ return detail
+ return None
+
+
+def _diagnostic_from_content(value: Any) -> str | bytes | None:
+ if not isinstance(value, list):
+ return None
+ for item in value:
+ if not isinstance(item, Mapping) or item.get("type") != "text":
+ continue
+ detail = _diagnostic_candidate(item.get("text"))
+ if detail:
+ return detail
+ return None
+
+
+def _driver_error_params(value: Mapping[str, Any]) -> dict[str, Any]:
+ structured_params = value.get("params")
+ params = dict(structured_params) if isinstance(structured_params, dict) else {}
+ for key in ("message", "reason", "detail", "error"):
+ if key not in params:
+ continue
+ diagnostic = _bounded_diagnostic(params[key])
+ if diagnostic is None:
+ params.pop(key)
+ else:
+ params[key] = diagnostic
+ exit_code = value.get("exit_code")
+ if isinstance(exit_code, int) and not isinstance(exit_code, bool):
+ params.setdefault("exit_code", exit_code)
+ return params
+
+
+def _error_result(
+ code: str,
+ message: str | None = None,
+ *,
+ detail: str | bytes | None = None,
+ result_params: Mapping[str, Any] | None = None,
+ **params: Any,
+) -> dict[str, Any]:
+ payload_params = dict(result_params) if result_params is not None else {}
+ payload_params.update(params)
+ payload = {"code": code, "params": payload_params}
+ bounded_detail = _bounded_diagnostic(detail)
+ if bounded_detail:
+ payload["detail"] = bounded_detail
return {
"content": [
{
@@ -618,18 +753,41 @@ def _fold_tool_result(
tool_name: str | None = None,
) -> dict[str, Any]:
if "error" in message:
- return _error_result("upstream_error")
+ upstream_error = message.get("error")
+ detail = _diagnostic_from_mapping(upstream_error)
+ params: dict[str, Any] = {}
+ if isinstance(upstream_error, Mapping):
+ rpc_code = upstream_error.get("code")
+ if isinstance(rpc_code, (int, str)) and not isinstance(rpc_code, bool):
+ params["rpc_code"] = rpc_code
+ if detail is None:
+ detail = _diagnostic_from_mapping(upstream_error.get("data"))
+ return _error_result(
+ "upstream_error",
+ detail=detail,
+ result_params=params,
+ )
result = deepcopy(message.get("result"))
if not isinstance(result, dict):
return _error_result("upstream_protocol_error")
structured = result.pop("structuredContent", None)
if result.get("isError") is True:
if isinstance(structured, dict) and isinstance(structured.get("code"), str):
- structured_params = structured.get("params")
- if isinstance(structured_params, dict):
- return _error_result(structured["code"], **structured_params)
- return _error_result(structured["code"])
- return _error_result("upstream_tool_error", tool=tool_name or "")
+ detail = (
+ _diagnostic_from_mapping(structured)
+ or _diagnostic_from_mapping(structured.get("params"))
+ or _diagnostic_from_content(result.get("content"))
+ )
+ return _error_result(
+ structured["code"],
+ detail=detail,
+ result_params=_driver_error_params(structured),
+ )
+ return _error_result(
+ "upstream_tool_error",
+ detail=_diagnostic_from_content(result.get("content")),
+ tool=tool_name or "",
+ )
if structured is not None:
content = result.get("content")
if not isinstance(content, list):
@@ -1185,7 +1343,7 @@ class ComputerUseServer:
acquisition.lease,
)
raise
- except UpstreamUnavailable:
+ except UpstreamUnavailable as exc:
if upstream is not None:
await self._discard_upstream(upstream)
if (
@@ -1197,9 +1355,16 @@ class ComputerUseServer:
self._lease_manager.release,
acquisition.lease,
)
+ detail = _bounded_diagnostic(str(exc))
+ logger.warning(
+ "computer-use upstream unavailable during %s: %s",
+ name,
+ detail or type(exc).__name__,
+ )
return _error_result(
"upstream_unavailable",
"The computer-use proxy exited. Observe again before retrying.",
+ detail=detail,
)
except Exception as exc:
if (
@@ -1211,8 +1376,16 @@ class ComputerUseServer:
self._lease_manager.release,
acquisition.lease,
)
+ detail = _bounded_diagnostic(str(exc))
+ logger.warning(
+ "computer-use call failed during %s (%s): %s",
+ name,
+ type(exc).__name__,
+ detail or type(exc).__name__,
+ )
return _error_result(
"computer_use_error",
+ detail=detail,
error_type=type(exc).__name__,
)
finally:
diff --git a/core/computer_use.py b/core/computer_use.py
index bf09e88a1..8ba87bbd6 100644
--- a/core/computer_use.py
+++ b/core/computer_use.py
@@ -36,7 +36,7 @@ COMPUTER_USE_LOCK_FILE = "computer-use.lock"
COMPUTER_USE_LEASE_FILE = "computer-lease.json"
COMPUTER_USE_LEASE_LOCK_FILE = "computer-lease.lock"
COMPUTER_USE_TOOL_SNAPSHOT_SHA256 = (
- "4257e598f5a6ad7e632b48e96c03257d7c5ed618a93b72820b2d4fef0f196acf"
+ "4c6a9c351f9ead8dac182ee8b9e4bb2ec5b9f66f35e4d36373643792e97a8d67"
)
COMPUTER_USE_TOOL_NAMES = (
diff --git a/desktop/cua-driver/PATCHES.md b/desktop/cua-driver/PATCHES.md
index 84f941071..bb9270557 100644
--- a/desktop/cua-driver/PATCHES.md
+++ b/desktop/cua-driver/PATCHES.md
@@ -27,6 +27,14 @@ native `mouseDown`/`mouseUp` delivery, so the acceptance can prove one raw
mouse pair and unchanged default behavior without relying on the tool result
alone.
+For embedded serve mode, the patch also makes parent-liveness shutdown
+terminal: stdin EOF removes only the socket bound by that process, removes its
+PID file, aborts accepted connection tasks, and drops the Tokio runtime without
+waiting for non-cancellable platform work. The terminal path leaves process
+globals intact because abandoned tasks may still reference them until process
+exit. Explicit daemon shutdown keeps the existing graceful drain and global
+teardown.
+
The upstream investigation found no consumable maintainer-accepted contract
with these semantics. The relevant discussions are:
@@ -42,11 +50,12 @@ contract, and upgrade plan are duplicated in `sources.json`. The release
provenance uses schema 2 and includes those hashes plus the prepared binary
hash and post-signing packaged hash.
-When upstream exposes an opt-in raw `count=1` macOS click selector with the
-same default-compatible contract, remove this patch and pin the upstream
-release. Otherwise, rebase the patch onto the next pinned source commit,
-rerun the fixture acceptance, refresh the source and snapshot hashes, and
-review the Avibe forwarding admission again.
+When upstream exposes both an opt-in raw `count=1` macOS click selector with
+the same default-compatible contract and terminal embedded parent-liveness
+cleanup, remove this patch and pin the upstream release. Otherwise, rebase the
+patch onto the next pinned source commit, rerun the fixture and lifecycle
+acceptance, refresh the source and snapshot hashes, and review the Avibe
+forwarding admission again.
The bounded foreground mode remains deferred. It requires separate evidence
for apps that reject both AX actions and background synthetic events; it is
diff --git a/desktop/cua-driver/patches/0001-macos-raw-single-click.patch b/desktop/cua-driver/patches/0001-macos-raw-single-click.patch
index a0d636d25..bad40b002 100644
--- a/desktop/cua-driver/patches/0001-macos-raw-single-click.patch
+++ b/desktop/cua-driver/patches/0001-macos-raw-single-click.patch
@@ -404,3 +404,258 @@ index 4621a4627..f8f0125ce 100644
// Opt-in windows for the persistent exact-window activation certification.
// Ordinary harness launches remain byte-for-byte and behaviorally unchanged.
final class BringToFrontMatrixWindows {
+diff --git a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+index b9637489..51b62d4c 100644
+--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
++++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+@@ -931,2 +931,8 @@ mod peer_authentication_tests {
+ /// This is `async` and must be called from a tokio runtime.
++#[derive(Clone, Copy, Debug, PartialEq, Eq)]
++pub enum ServeShutdown {
++ Requested,
++ ParentLiveness,
++}
++
+ #[cfg(unix)]
+@@ -936,3 +942,3 @@ pub async fn run_serve(
+ pid_file_path: Option<&str>,
+-) -> anyhow::Result<()> {
++) -> anyhow::Result<ServeShutdown> {
+ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+@@ -996,3 +1002,2 @@ pub async fn run_serve(
+-
+- loop {
++ let shutdown = loop {
+ tokio::select! {
+@@ -1381,3 +1387,3 @@ pub async fn run_serve(
+ eprintln!("Cua Driver daemon shutting down.");
+- break;
++ break ServeShutdown::Requested;
+ }
+@@ -1385,5 +1391,18 @@ pub async fn run_serve(
+ eprintln!("Cua Driver embedded host closed its lifetime pipe; shutting down.");
+- break;
++ break ServeShutdown::ParentLiveness;
+ }
+ }
++ };
++
++ if shutdown == ServeShutdown::ParentLiveness {
++ // The owning shell is gone, so no accepted request may keep this
++ // embedded helper alive. Remove only the endpoint this listener bound,
++ // then abandon in-flight work without waiting for platform calls or
++ // blocking-pool tasks that cannot be cancelled.
++ remove_owned_socket(socket_path, bound_socket);
++ if let Some(pid_path) = pid_file_path {
++ let _ = std::fs::remove_file(pid_path);
++ }
++ connection_tasks.abort_all();
++ return Ok(shutdown);
+ }
+@@ -1404,3 +1423,2 @@ pub async fn run_serve(
+-
+- Ok(())
++ Ok(shutdown)
+ }
+@@ -1663,3 +1682,3 @@ pub async fn run_serve(
+ pid_file_path: Option<&str>,
+-) -> anyhow::Result<()> {
++) -> anyhow::Result<ServeShutdown> {
+ use std::os::windows::io::AsRawHandle as _;
+@@ -2175,3 +2194,3 @@ pub async fn run_serve(
+ Some(error) => Err(error),
+- None => Ok(()),
++ None => Ok(ServeShutdown::Requested),
+ }
+@@ -2221,3 +2240,3 @@ pub async fn run_serve(
+ _pid_file_path: Option<&str>,
+-) -> anyhow::Result<()> {
++) -> anyhow::Result<ServeShutdown> {
+ anyhow::bail!("cua-driver serve is not supported on this platform");
+@@ -2285,5 +2304,12 @@ pub fn run_serve_cmd(
+ let result = rt.block_on(run_serve(sdk, &socket_path, pid_file_path.as_deref()));
+- rt.shutdown_timeout(std::time::Duration::from_secs(30));
+- cua_driver_core::session_authorization::release_configured_registry_for_shutdown();
+- cua_driver_core::session::release_process_state_for_shutdown();
++ if matches!(result.as_ref(), Ok(&ServeShutdown::ParentLiveness)) {
++ // Accepted tasks and blocking-pool work may still reference process
++ // globals. The owning host is gone, so abandon the runtime and let
++ // process exit reclaim those globals instead of clearing them first.
++ rt.shutdown_background();
++ } else {
++ rt.shutdown_timeout(std::time::Duration::from_secs(30));
++ cua_driver_core::session_authorization::release_configured_registry_for_shutdown();
++ cua_driver_core::session::release_process_state_for_shutdown();
++ }
+ if let Err(e) = result {
+@@ -2571,2 +2595,169 @@ mod socket_tests {
+-
++#[cfg(all(test, unix))]
++mod parent_liveness_tests {
++ use super::{run_serve_cmd, send_request, DaemonRequest};
++ use async_trait::async_trait;
++ use cua_driver_core::protocol::ToolResult;
++ use cua_driver_core::tool::{Tool, ToolDef, ToolRegistry};
++ use serde_json::Value;
++ use std::process::{Command, Stdio};
++ use std::sync::OnceLock;
++ use std::time::{Duration, Instant};
++
++ const CHILD_ENV: &str = "CUA_DRIVER_PARENT_LIVENESS_TEST_CHILD";
++ const SOCKET_ENV: &str = "CUA_DRIVER_PARENT_LIVENESS_TEST_SOCKET";
++ const PID_FILE_ENV: &str = "CUA_DRIVER_PARENT_LIVENESS_TEST_PID_FILE";
++ const STARTED_ENV: &str = "CUA_DRIVER_PARENT_LIVENESS_TEST_STARTED";
++
++ struct BlockingTool;
++
++ static BLOCKING_TOOL_DEF: OnceLock<ToolDef> = OnceLock::new();
++
++ #[async_trait]
++ impl Tool for BlockingTool {
++ fn def(&self) -> &ToolDef {
++ BLOCKING_TOOL_DEF.get_or_init(|| ToolDef {
++ name: "health_report".into(),
++ description: "test-only non-cancellable platform call".into(),
++ input_schema: serde_json::json!({"type": "object"}),
++ read_only: true,
++ destructive: false,
++ idempotent: true,
++ open_world: false,
++ })
++ }
++
++ async fn invoke(&self, _args: Value) -> ToolResult {
++ std::fs::write(
++ std::env::var(STARTED_ENV).expect("started marker path"),
++ "started\n",
++ )
++ .expect("write started marker");
++ std::thread::sleep(Duration::from_secs(60));
++ ToolResult::text("finished")
++ }
++ }
++
++ fn register_blocking_tool(registry: &mut ToolRegistry) {
++ registry.register(Box::new(BlockingTool));
++ }
++
++ fn wait_for_path(path: &std::path::Path, timeout: Duration) {
++ let deadline = Instant::now() + timeout;
++ while Instant::now() < deadline {
++ if path.exists() {
++ return;
++ }
++ std::thread::sleep(Duration::from_millis(20));
++ }
++ panic!("timed out waiting for {}", path.display());
++ }
++
++ #[test]
++ fn parent_liveness_child() {
++ if std::env::var_os(CHILD_ENV).is_none() {
++ return;
++ }
++ let driver =
++ cua_driver_sdk::CuaDriver::create_for_host(cua_driver_sdk::DriverHostOptions {
++ cursor: cursor_overlay::CursorConfig {
++ enabled: false,
++ ..cursor_overlay::CursorConfig::default()
++ },
++ host_owns_permission_ux: true,
++ host_bundle_id: Some("com.trycua.parent-liveness-test".into()),
++ claude_code_compatibility: false,
++ prepare_desktop_environment: false,
++ register_host_tools: Some(register_blocking_tool),
++ authorization_host: None,
++ activity_observer: None,
++ });
++ let socket = std::env::var(SOCKET_ENV).expect("socket path");
++ let pid_file = std::env::var(PID_FILE_ENV).expect("pid file path");
++ run_serve_cmd(driver, &socket, Some(&pid_file));
++ }
++
++ #[test]
++ fn parent_liveness_exits_without_waiting_for_blocked_calls_and_unlinks_only_its_socket() {
++ let directory = tempfile::tempdir().expect("temporary directory");
++ let socket = directory.path().join("driver.sock");
++ let pid_file = directory.path().join("driver.pid");
++ let started = directory.path().join("call-started");
++ let unrelated_socket = directory.path().join("unrelated.sock");
++ let unrelated_state = directory.path().join("unrelated-state");
++ let _unrelated_listener =
++ std::os::unix::net::UnixListener::bind(&unrelated_socket).expect("unrelated socket");
++ std::fs::write(&unrelated_state, "preserve\n").expect("unrelated state");
++
++ let home = directory.path().join("home");
++ std::fs::create_dir_all(&home).expect("test home");
++ let mut child = Command::new(std::env::current_exe().expect("test executable"))
++ .args([
++ "--exact",
++ "serve::parent_liveness_tests::parent_liveness_child",
++ "--nocapture",
++ ])
++ .env(CHILD_ENV, "1")
++ .env(SOCKET_ENV, &socket)
++ .env(PID_FILE_ENV, &pid_file)
++ .env(STARTED_ENV, &started)
++ .env("HOME", &home)
++ .env("XDG_CACHE_HOME", home.join(".cache"))
++ .env("XDG_CONFIG_HOME", home.join(".config"))
++ .env("XDG_DATA_HOME", home.join(".local/share"))
++ .env(cua_driver_core::EMBEDDED_ENV, "1")
++ .env(cua_driver_core::PARENT_LIVENESS_STDIN_ENV, "1")
++ .env("CUA_DRIVER_RS_TELEMETRY_ENABLED", "0")
++ .env("CUA_DRIVER_RS_UPDATE_CHECK", "0")
++ .stdin(Stdio::piped())
++ .stdout(Stdio::null())
++ .stderr(Stdio::inherit())
++ .spawn()
++ .expect("spawn test daemon");
++
++ wait_for_path(&socket, Duration::from_secs(10));
++ wait_for_path(&pid_file, Duration::from_secs(10));
++
++ let socket_for_call = socket.to_string_lossy().into_owned();
++ let call = std::thread::spawn(move || {
++ send_request(
++ &socket_for_call,
++ &DaemonRequest {
++ method: "call".into(),
++ name: Some("health_report".into()),
++ args: Some(serde_json::json!({})),
++ session_id: None,
++ observation_origin: None,
++ client_kind: None,
++ },
++ )
++ });
++ wait_for_path(&started, Duration::from_secs(10));
++
++ drop(child.stdin.take());
++ let deadline = Instant::now() + Duration::from_secs(5);
++ let status = loop {
++ if let Some(status) = child.try_wait().expect("poll test daemon") {
++ break status;
++ }
++ if Instant::now() >= deadline {
++ let _ = child.kill();
++ let _ = child.wait();
++ let _ = call.join();
++ panic!("embedded daemon stayed alive after its parent-liveness pipe closed");
++ }
++ std::thread::sleep(Duration::from_millis(20));
++ };
++ let _ = call.join();
++
++ assert!(status.success(), "child test failed: {status}");
++ assert!(!socket.exists(), "owned socket survived parent cleanup");
++ assert!(!pid_file.exists(), "owned pid file survived parent cleanup");
++ assert!(unrelated_socket.exists(), "unrelated socket was removed");
++ assert_eq!(
++ std::fs::read_to_string(unrelated_state).expect("unrelated state"),
++ "preserve\n"
++ );
++ }
++}
++
+ #[cfg(all(test, unix))]
diff --git a/desktop/cua-driver/sources.json b/desktop/cua-driver/sources.json
index b2a643629..0093429ea 100644
--- a/desktop/cua-driver/sources.json
+++ b/desktop/cua-driver/sources.json
@@ -4,7 +4,7 @@
"version": "0.31.0",
"tag": "cua-driver-rs-v0.31.0",
"source_commit": "5272e492d61b96caf08e3bf434d91126c1f3dccc",
- "tool_snapshot_sha256": "4257e598f5a6ad7e632b48e96c03257d7c5ed618a93b72820b2d4fef0f196acf",
+ "tool_snapshot_sha256": "4c6a9c351f9ead8dac182ee8b9e4bb2ec5b9f66f35e4d36373643792e97a8d67",
"license": "MIT",
"release_base_url": "https://github.com/trycua/cua/releases/download/cua-driver-rs-v0.31.0",
"release_checksums_asset": "checksums.txt",
@@ -22,8 +22,8 @@
"patch": {
"variant": "avibe-raw-single-click-v1",
"file": "patches/0001-macos-raw-single-click.patch",
- "sha256": "45c28ca5fc737649b85ddebbb57ef837490b6349ecc1e0ac04782bfee58bdbe8",
- "contract": "click.click_mode=raw",
+ "sha256": "b720fb0e80a5fcc7796de175c905d73208ce8a53716a517074087f50d09ed584",
+ "contract": "click.click_mode=raw; embedded parent-liveness cleanup",
"upstream_refs": [
"https://github.com/trycua/cua/pull/3922",
"https://github.com/trycua/cua/pull/3539",
@@ -32,7 +32,7 @@
"https://github.com/trycua/cua/issues/4350",
"https://github.com/trycua/cua/issues/2874"
],
- "upgrade_plan": "Drop this patch when an upstream release exposes an opt-in raw count=1 macOS click selector with the same default-compatible contract; otherwise rebase it onto the next pinned source commit and rerun the hit-test-only acceptance."
+ "upgrade_plan": "Drop this patch when an upstream release exposes both an opt-in raw count=1 macOS click selector with the same default-compatible contract and terminal embedded parent-liveness cleanup; otherwise rebase it onto the next pinned source commit and rerun the hit-test and lifecycle acceptance."
}
},
"managed_policy": "policy.yaml",
diff --git a/desktop/cua-driver/tools-v0.31.0.json b/desktop/cua-driver/tools-v0.31.0.json
index 1cd48e132..c1e81b505 100644
--- a/desktop/cua-driver/tools-v0.31.0.json
+++ b/desktop/cua-driver/tools-v0.31.0.json
@@ -1 +1 @@
-{"driver_version":"0.31.0","patch_sha256":"45c28ca5fc737649b85ddebbb57ef837490b6349ecc1e0ac04782bfee58bdbe8","schema_version":1,"source_commit":"5272e492d61b96caf08e3bf434d91126c1f3dccc","source_tag":"cua-driver-rs-v0.31.0","source_variant":"avibe-raw-single-click-v1","tools":[{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":["app.list"],"description":"List macOS apps — both currently running and installed-but-not-running — with per-app state flags:\n\n- running: is a process for this app live? (pid is 0 when false)\n- active: is it the system-frontmost app? (implies running)\n- launch_path: filesystem path to the `.app` bundle, when known. Pass this to `launch_app` to start the app cold.\n- kind: `\"desktop\"` for `.app` bundles on macOS.\n- last_used: RFC3339 timestamp from the bundle's filesystem mtime, when readable; otherwise null.\n\nStandalone running entries include only apps with NSApplicationActivationPolicyRegular — background helpers and system UI agents are filtered out. Installed apps resolve their running/pid state against all live processes by bundle identifier, so an installed app whose process runs as an accessory (LSUIElement / menu-bar apps, e.g. Cua Driver itself) still reports its live pid. Installed apps come from scanning /Applications, /Applications/Utilities, ~/Applications, /System/Applications, and /System/Applications/Utilities.\n\nUse this for \"is X installed?\" as well as \"is X running?\". For per-window state — on-screen, on-current-Space, minimized, window titles — call list_windows instead. For just opening an app — running or not — call launch_app({bundle_id: ...}) directly; list_apps is not a prerequisite.","inputSchema":{"additionalProperties":false,"properties":{"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"}},"type":"object"},"name":"list_apps","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"apps":{"items":{"properties":{"active":{"type":"boolean"},"bundle_id":{"type":["string","null"]},"kind":{"type":["string","null"]},"last_used":{"type":["string","null"]},"launch_path":{"type":["string","null"]},"name":{"type":"string"},"pid":{"minimum":0,"type":"integer"},"running":{"type":"boolean"}},"required":["pid","name","running","active"],"type":"object"},"type":"array"}},"required":["apps"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r2","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":["window.list"],"description":"List all layer-0 top-level windows currently known to WindowServer. Includes off-screen windows (minimized, on another Space, hidden-launched). Use this to find a window_id before calling get_window_state.\n\nPer-record fields: window_id, pid, app_name, title, bounds (x/y/width/height, top-left origin), z_index (integer or null; higher values are closer to the front; null means stacking order is unavailable and callers must not infer one), is_on_screen, space_ids, current_space_id (the active Space on that window's display), and on_current_space. The top-level current_space_id is WindowServer's main/global active Space and can differ from a record's current_space_id when displays use independent Spaces. To select a frontmost candidate, take the maximum integer z_index; if every value is null, use an explicit fallback instead of relying on array order.","inputSchema":{"additionalProperties":false,"properties":{"on_screen_only":{"description":"When true, drop windows not on the current Space. Default false.","type":"boolean"},"pid":{"description":"Optional pid filter. When set, only this pid's windows are returned.","type":"integer"},"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"}},"type":"object"},"name":"list_windows","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"current_space_id":{"minimum":0,"type":["integer","null"]},"windows":{"items":{"properties":{"app_name":{"type":"string"},"bounds":{"properties":{"height":{"type":"number"},"width":{"type":"number"},"x":{"type":"number"},"y":{"type":"number"}},"required":["x","y","width","height"],"type":"object"},"current_space_id":{"minimum":0,"type":["integer","null"]},"is_on_screen":{"type":"boolean"},"layer":{"format":"int32","type":["integer","null"]},"minimized":{"type":["boolean","null"]},"on_current_space":{"type":["boolean","null"]},"pid":{"maximum":4294967295,"minimum":0,"type":["integer","null"]},"space_ids":{"items":{"minimum":0,"type":"integer"},"type":["array","null"]},"title":{"type":"string"},"window_id":{"minimum":0,"type":"integer"},"z_index":{"description":"Higher values are closer to the front. Null means the provider cannot observe stacking order; callers must not infer an order from array position or treat null as zero.","type":["integer","null"]}},"required":["window_id","pid","app_name","title","bounds","is_on_screen","z_index"],"type":"object"},"type":"array"}},"required":["windows"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r2","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":true},"capabilities":["accessibility.window_state","accessibility.tree","accessibility.tree.structured","accessibility.tree.bounded","accessibility.element_tokens","screen.capture","screen.capture.window"],"description":"Walk a running app's AX tree and return BOTH a structured `elements` array (preferred) AND a Markdown rendering of the same tree (back-compat). Every actionable element is tagged with [element_index N] in the markdown and as `element_index` in the structured array; pass each element's `element_token` to click, type_text, press_key, etc.\n\nINVARIANT: call get_window_state once per turn per (pid, window_id) before any element action. The next snapshot of the window replaces this one, stales its element tokens, and lists the replaced ids in `invalidated_snapshot_ids`.\n\nPREFERRED CONSUMERS read `structuredContent.elements` (one entry per indexed row with `element_index`, `role`, `label`, `value` (the element's text/AXValue when present — use it to verify what a field holds), `actions` (names of AX actions exposed by the element, omitted when empty), `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\nAlways returns BOTH the element tree AND a screenshot — ground on both and cross-check (the tree lies on some surfaces: Electron echo-confirms, Catalyst null values, virtualized off-viewport rows with `h:1` frames). You choose the modality at ACTION time, not here: an element ax action (pass `element_token` → the accessibility rung) or an element px action (pass `x`,`y` → the pixel rung, read straight off this screenshot). `capture_mode` is deprecated and ignored. Pass `include_screenshot:false` to skip the grab and get the tree only — the cheap path when you're just re-indexing before an element ax action.\n\nThe mirror image: pass `include_accessibility_tree:false` to SKIP the AX walk entirely (the expensive part, bounded by timeout_ms) and return just the screenshot plus window metadata — `window_bounds`, `screenshot_scale`, `screenshot_width`/`screenshot_height`, `app_name`, and `window_title` — the capture-only path for rendering a live window preview / picture-in-picture without paying for perception. Setting BOTH `include_accessibility_tree:false` and `include_screenshot:false` is an error (nothing to return). Optional `max_image_dimension` overrides the configured screenshot long-edge limit for this call; use 0 for native resolution. The legacy `max_dimension` remains a tighter cap for compatibility.\n\nThe snapshot is SCOPED to `window_id`: a window_id that no longer exists is refused with `window_id_not_found`, and one owned by another process is refused with `window_owner_pid_mismatch` naming the real `owner_pid` to retry with (macOS hosts a sandboxed app's Open/Save panel out-of-process, so its window belongs to the panel service, not the app). If the window is live under this pid but its accessibility surface can't be resolved, the tree comes back EMPTY with `degraded_reason: ax_window_unresolved` and the screenshot of the requested window; background input is refused until it resolves, so re-snapshot or act with `delivery_mode:\"foreground\"`. When that pid is an app still launching (its window exists before it answers accessibility), the walk first waits up to `timeout_ms` for it; if it never answers, the tree comes back EMPTY with `degraded_reason: ax_app_launching`, `truncated: true` and `truncation_reason: app_lookup_timeout`. A window on another Space still resolves by its exact CGWindowID. This tool never returns another surface's elements under your window_id. Before exposing a screenshot, its raw dimensions are validated as a coherent 1x/2x representation of the requested WindowServer bounds. `px_frame_mismatch` or `px_capture_unavailable` omits an unprovable screenshot/pixel frame instead of guessing a transform; the truthful AX payload remains available.\n\nOptional `query` projects both tree_markdown and structured `elements` to matching lines plus their ancestor chain (case-insensitive substring). The element_index values are unchanged, the complete snapshot remains actionable, and `element_count` continues to report its total size; `filtered_element_count` reports the projected response size.\n\nOptional `max_elements` / `max_depth` bound the AX walk to mitigate context-window blow-up on Electron / Obsidian / large web apps that produce 10k+ element trees. When applied, BOTH the markdown and the structured elements are truncated identically. Omit both for current default behaviour (≤2 000 elements, depth ≤25).","inputSchema":{"additionalProperties":false,"properties":{"capture_mode":{"description":"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_token) or an element px action (x,y). Any value (including the old \"som\"/\"screenshot\" aliases) is accepted but has no effect.","enum":["ax","vision"],"type":"string"},"include_accessibility_tree":{"description":"Default true — walk the AX tree and return `elements` + `tree_markdown` alongside the screenshot. Set false to SKIP the AX walk entirely (the expensive part, bounded by timeout_ms) and return just the screenshot plus window metadata (bounds, scale, app_name, window_title) — the capture-only path for rendering a live window preview / picture-in-picture. Mirrors include_screenshot. Setting BOTH include_accessibility_tree:false AND include_screenshot:false is an error (nothing to return).","type":"boolean"},"include_screenshot":{"description":"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.","type":"boolean"},"max_depth":{"description":"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.","minimum":1,"type":"integer"},"max_dimension":{"description":"Optional cap on the returned screenshot's long edge, in pixels (aspect ratio preserved) — the cheap path for a small preview / thumbnail. Applied on top of the session/global max_image_dimension ceiling; the tighter of the two wins. Omit for the configured default.","minimum":1,"type":"integer"},"max_elements":{"description":"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.","minimum":1,"type":"integer"},"max_image_dimension":{"description":"Per-call override for the returned screenshot's long edge in pixels. An explicit value wins over the session/global setting; 0 returns native resolution. Omit to preserve configured behavior.","minimum":0,"type":"integer"},"pid":{"description":"Target process ID.","type":"integer"},"query":{"description":"Case-insensitive filter for tree_markdown and structured elements. Returns matching actionable rows plus their actionable ancestors without renumbering element_index values.","type":"string"},"screenshot_out_file":{"description":"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.","type":"string"},"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"},"timeout_ms":{"default":1000,"description":"Wall-clock budget in milliseconds for the accessibility-tree walk (default 1000, min 100, max 120000). Bounds the WHOLE walk. When the budget runs out the tool returns the PARTIAL tree it has, flagged with `truncated: true`, `truncation_reason`, `nodes_visited`, `nodes_pending` and `elements_complete: false`; retry with a larger value (e.g. 5000) or narrow with `query` / `max_depth`.","maximum":120000,"minimum":100,"type":"integer"},"window_id":{"description":"Target window ID from list_windows.","type":"integer"}},"required":["pid","window_id"],"type":"object"},"name":"get_window_state","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"app_name":{"type":["string","null"]},"degraded":{"type":["boolean","null"]},"degraded_reason":{"type":["string","null"]},"element_count":{"minimum":0,"type":["integer","null"]},"elements":{"items":{"properties":{"actions":{"items":{"type":"string"},"type":["array","null"]},"depth":{"minimum":0,"type":"integer"},"element_index":{"minimum":0,"type":"integer"},"element_token":{"type":["string","null"]},"enabled":{"type":["boolean","null"]},"frame":{"properties":{"h":{"type":"number"},"w":{"type":"number"},"x":{"type":"number"},"y":{"type":"number"}},"required":["x","y","w","h"],"type":["object","null"]},"in_web_content":{"type":["boolean","null"]},"label":{"type":["string","null"]},"max":{"type":["number","null"]},"min":{"type":["number","null"]},"parent_index":{"minimum":0,"type":["integer","null"]},"role":{"type":"string"},"selected":{"type":["boolean","null"]},"value":{"type":["string","null"]},"value_description":{"type":["string","null"]}},"required":["element_index","role","depth"],"type":"object"},"type":["array","null"]},"elements_complete":{"type":["boolean","null"]},"filtered_element_count":{"minimum":0,"type":["integer","null"]},"pid":{"minimum":0,"type":"integer"},"returned_element_count":{"minimum":0,"type":["integer","null"]},"screenshot_file_path":{"type":["string","null"]},"screenshot_frame_valid":{"type":["boolean","null"]},"screenshot_height":{"minimum":0,"type":["integer","null"]},"screenshot_mime_type":{"type":["string","null"]},"screenshot_scale":{"type":["number","null"]},"screenshot_width":{"minimum":0,"type":["integer","null"]},"snapshot_id":{"type":["string","null"]},"total_element_count":{"minimum":0,"type":["integer","null"]},"tree_markdown":{"type":["string","null"]},"truncated":{"type":["boolean","null"]},"truncation_reason":{"type":["string","null"]},"window_bounds":{"properties":{"height":{"type":"number"},"width":{"type":"number"},"x":{"type":"number"},"y":{"type":"number"}},"required":["x","y","width","height"],"type":["object","null"]},"window_id":{"minimum":0,"type":"integer"},"window_title":{"type":["string","null"]}},"required":["pid","window_id"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r3","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":true},"capabilities":["state.verify","state.verify.window","state.verify.element","state.observe.visual_evidence"],"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.","inputSchema":{"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.","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":"For multi-call work, prefer a short public session label and repeat it on every call that\naccepts it. Omit it to use the authenticated transport's implicit lifecycle session. This\nfield never selects capture modality or authorization.","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"},"name":"verify_state","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"elapsed_ms":{"minimum":0,"type":"integer"},"predicates":{"items":{"properties":{"index":{"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":{"minimum":0,"type":"integer"},"stable":{"type":"boolean"},"status":{"enum":["satisfied","unsatisfied","unknown"],"type":"string"}},"required":["status","stable","elapsed_ms","samples","predicates"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r2","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"capabilities":["app.launch"],"description":"Launch a macOS app in the background — the target does NOT come to the foreground.\n\nProvide either `bundle_id` (preferred — unambiguous, e.g. `com.apple.calculator`) or `name` (e.g. \"Calculator\"). If both are given, bundle_id wins.\n\nOptional `urls` are handed to the app as open targets — for Finder, pass a folder path to open a backgrounded Finder window there.\n\nBrowser DevTools setup belongs to `browser_prepare`, which can prove that a separate isolated profile is driver-owned before enabling CDP.\n\nOptional `webkit_inspector_port`: opens a WebKit inspector server on the specified port (sets WEBKIT_INSPECTOR_SERVER=127.0.0.1:N + TAURI_WEBVIEW_AUTOMATION=1). Use this for Tauri/WebKit-based apps.\n\nOptional `creates_new_application_instance`: when true, forces a new app instance even if one is already running (passes -n to open). Reach for this when another agent or session may drive the SAME app concurrently — it returns a fresh pid + window so each session acts on its own isolated window instead of clobbering one shared instance. Without it, single-instance apps (Calculator, many utilities) hand every caller the same window, so two sessions fight over it.\n\nOptional `additional_arguments`: extra argv strings appended after --args.\n\nReturns the launched app's pid, bundle_id, name, and a `windows` array (same shape as `list_windows`) so callers can skip an extra round-trip before `get_window_state(pid, window_id)`. `launch_state` distinguishes whether the request was sent, the process is running, and a window is ready. When the focus-steal belt-and-braces demotion check ran (target pid ≠ prior frontmost), the response also includes `self_activation_suppressed: bool` — true if focus stayed with the prior frontmost, false if the launched app held focus despite the re-demote attempt.","inputSchema":{"additionalProperties":false,"properties":{"additional_arguments":{"description":"Extra arguments appended after --args when launching.","items":{"type":"string"},"type":"array"},"bundle_id":{"description":"App bundle identifier, e.g. com.apple.calculator. Preferred over name.","type":"string"},"creates_new_application_instance":{"description":"When true, force a new app instance even if already running (open -n). Use for concurrent multi-agent/multi-session work so each session gets an isolated instance + window instead of sharing one — on single-instance apps (e.g. Calculator) every caller otherwise gets the same window and the sessions clobber each other.","type":"boolean"},"name":{"description":"App display name. Used only when bundle_id is absent.","type":"string"},"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"},"urls":{"description":"Optional file paths or URLs to open with the app (e.g. a folder path for Finder).","items":{"type":"string"},"type":"array"},"webkit_inspector_port":{"description":"Open a WebKit inspector server on this port (sets WEBKIT_INSPECTOR_SERVER env var).","type":"integer"}},"type":"object"},"name":"launch_app","risk":{"class":"r1","enforcement":"metadata_only","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"capabilities":["app.kill"],"description":"Force-terminate a process by pid (kill -9 equivalent on macOS / Linux; taskkill /F equivalent on Windows). Use as escalation when the cooperative close path (hotkey cmd+q on macOS, click-the-X on Windows) failed to make the process exit. Unsaved state is lost — prefer the cooperative path first.","inputSchema":{"additionalProperties":false,"properties":{"pid":{"description":"PID of the process to terminate.","type":"integer"},"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"}},"required":["pid"],"type":"object"},"name":"kill_app","risk":{"class":"r3","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"capabilities":["window.frame.set"],"description":"Set one exact top-level window's frame in the desktop-coordinate space reported by list_windows and verify the resulting geometry through an independent readback.","inputSchema":{"additionalProperties":false,"properties":{"height":{"minimum":1,"type":"number"},"pid":{"minimum":1,"type":"integer"},"session":{"description":"For multi-call work, prefer a short public session label and repeat it on every call that\naccepts it. Omit it to use the authenticated transport's implicit lifecycle session.","type":"string"},"width":{"minimum":1,"type":"number"},"window_id":{"minimum":1,"type":"integer"},"x":{"type":"number"},"y":{"type":"number"}},"required":["pid","window_id","x","y","width","height"],"type":"object"},"name":"set_window_frame","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.pointer.click","input.pointer.click.left","accessibility.element_tokens","input.delivery_mode"],"description":"Click against a target pid. **Prefer `element_token` over pixel coordinates** — the token works on backgrounded / minimized / hidden / off-Space windows, identifies one exact snapshot element, and tells you what you're clicking via the cached element's role + label. Reach for `x, y` only when the target is a canvas / video / WebGL / custom-drawn surface that doesn't appear in the AX tree.\n\nTwo addressing modes:\n\n- element_token (from get_window_state): AX action path. Works on backgrounded/hidden windows. No cursor move, no focus steal. The snapshot cache is scoped per (pid, window_id) and is replaced by the next snapshot of the same window — re-snapshot every turn before clicking.\n\n- x, y (window-local screenshot pixels, top-left origin of the PNG returned by get_window_state): CGEvent path. Synthesizes mouse events and posts to pid. Use modifier for cmd/shift/option/ctrl. Needs a visible on-screen window to anchor the conversion.\n\nbutton: \"left\" (default), \"right\", or \"middle\". Defaults to left so the field is fully back-compat — omit it and you get the legacy left-click behaviour. Pixel path: routes through the CGEvent left/right/middle mouse-button primitives. AX path: \"right\" maps to AXShowMenu (same surface as the dedicated `right_click` tool); \"middle\" has no AX equivalent and falls back to a pixel middle-click at the element's center. For a window-addressed background pixel left-click, click_mode:\"raw\" bypasses the AX hit-test optimization and posts exactly one routed mouse down/up pair. Keep the default click_mode:\"auto\" unless AXPress was observed to return a hollow success.\naction: press (default), show_menu, pick, confirm, cancel, open.\nfrom_zoom: set true after a zoom call to auto-translate zoom-image pixel coordinates to full-window space.","inputSchema":{"additionalProperties":false,"properties":{"action":{"description":"AX action: press, show_menu, pick, confirm, cancel, open.","type":"string"},"button":{"description":"Mouse button. Default: \"left\" — omit for legacy left-click behaviour. Pixel path uses the matching CGEvent primitive; AX path maps \"right\" to AXShowMenu and falls back to a pixel middle-click at the element's center for \"middle\".","enum":["left","right","middle"],"type":"string"},"capture_id":{"description":"Optional immutable source capture ID returned by get_window_state or get_desktop_state. With x,y, Driver atomically admits and consumes that exact capture before dispatch; stale, mismatched, or out-of-bounds captures are refused without fallback.","type":"string"},"click_mode":{"description":"Pixel single-click delivery selector. Default \"auto\" preserves the AX-first background optimization. \"raw\" is opt-in and valid only for an exact pid + window_id background left-click with x/y, count=1, and no modifiers; it bypasses AX hit-testing and uses the existing routed CGEvent path.","enum":["auto","raw"],"type":"string"},"count":{"description":"Click count (pixel path only). Default 1.","type":"integer"},"debug_image_out":{"description":"Optional file path. When set on a pixel-addressed click, captures a fresh screenshot, draws a red crosshair at (x, y), and writes the PNG. Use to verify coordinate spaces. Requires window_id; incompatible with from_zoom.","type":"string"},"delivery_mode":{"description":"Best-effort-background ladder rung (default \"background\"). \"background\": perform the AX action or post the CGEvent without fronting. \"foreground\": briefly front the window, act, let transient UI settle, then restore the prior frontmost app. Requires window_id. Modified clicks require \"foreground\" so macOS observes physical modifier-key state. A generic click has no independent postcondition read-back, except selection of list-like AX rows whose AXSelected state can be confirmed; otherwise confirm the effect from a fresh state snapshot. Use the agent loop: background AX (element_token) → snapshot → background pixel (x/y) → snapshot → delivery_mode:\"foreground\".","enum":["background","foreground"],"type":"string"},"element_token":{"description":"Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.","type":"string"},"from_zoom":{"description":"When true, x and y are in the last zoom image for this pid; driver translates back to full-window coordinates.","type":"boolean"},"modifier":{"description":"Modifier keys: cmd, shift, option/alt, ctrl.","items":{"type":"string"},"type":"array"},"pid":{"description":"Target process ID.","type":"integer"},"scope":{"description":"Coordinate frame for a windowless screen-absolute click (default \"window\"). Pass \"desktop\" when sending x,y with NO pid/window_id — the coordinates are then true screen pixels (read from get_desktop_state with scope=\"desktop\"). Per-call; not a setting.","enum":["window","desktop"],"type":"string"},"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"},"target":{"description":"Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.","oneOf":[{"additionalProperties":true,"properties":{"kind":{"const":"window","type":"string"},"pid":{"minimum":0,"type":"integer"},"window_id":{"minimum":0,"type":"integer"}},"required":["kind","pid","window_id"],"type":"object"},{"additionalProperties":true,"properties":{"display_id":{"type":"string"},"kind":{"const":"desktop","type":"string"}},"required":["kind","display_id"],"type":"object"}]},"window_id":{"description":"Target window ID. Omit when element_token is supplied (the token carries it).","type":"integer"},"x":{"description":"X in screenshot pixels. A window target uses the get_window_state PNG; a desktop target uses the native get_desktop_state PNG. The driver reverses Retina backing scale and any window-image downscale.","type":"number"},"y":{"description":"Y in screenshot pixels from the image selected by target.","type":"number"}},"required":[],"type":"object"},"name":"click","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.pointer.click","input.pointer.click.left","input.pointer.click.double","accessibility.element_tokens","input.delivery_mode"],"description":"Double-click at (x, y) or on an AX element identified by element_token.\n\nAX path (element_token provided): performs `AXOpen` when the element advertises it (Finder items, openable list rows/cells); otherwise resolves the element's on-screen center and falls back to a pixel double-click there.\n\nPixel path (x, y provided): two down/up pairs ~80 ms apart at the given coordinates.","inputSchema":{"additionalProperties":false,"properties":{"delivery_mode":{"description":"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.","enum":["background","foreground"],"type":"string"},"element_token":{"description":"Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.","type":"string"},"pid":{"type":"integer"},"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"},"window_id":{"description":"CGWindowID. Omit when element_token is supplied (the token carries it).","type":"integer"},"x":{"description":"Screen X coordinate (pixel path).","type":"number"},"y":{"description":"Screen Y coordinate (pixel path).","type":"number"}},"required":["pid"],"type":"object"},"name":"double_click","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.pointer.click","input.pointer.click.right","accessibility.element_tokens","input.delivery_mode"],"description":"Right-click against a target pid. Two addressing modes:\n\n- `element_token` (from the last `get_window_state` snapshot) — performs `AXShowMenu` on the cached element. Pure AX RPC, works on backgrounded / hidden windows, no cursor move or focus steal. Requires a prior `get_window_state(pid, window_id)` in this turn.\n\n- `x`, `y` — synthesizes `rightMouseDown` / `rightMouseUp` CGEvent pair posted to the pid. Driver converts image-pixel → screen-point internally. `modifier` forces the CGEvent path (AX actions don't propagate modifier keys).\n\nExactly one of `element_token` or (`x` AND `y`) must be provided. `pid` always required.","inputSchema":{"additionalProperties":false,"properties":{"delivery_mode":{"description":"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.","enum":["background","foreground"],"type":"string"},"element_token":{"description":"Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.","type":"string"},"modifier":{"description":"Modifier keys held during the right-click: cmd/shift/option/ctrl. Pixel path only.","items":{"type":"string"},"type":"array"},"pid":{"description":"Target process ID.","type":"integer"},"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"},"window_id":{"description":"CGWindowID. Omit when element_token is supplied (the token carries it).","type":"integer"},"x":{"description":"X in window-local screenshot pixels. Must be provided together with y.","type":"number"},"y":{"description":"Y in window-local screenshot pixels. Must be provided together with x.","type":"number"}},"required":["pid"],"type":"object"},"name":"right_click","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.pointer.drag","input.delivery_mode"],"description":"Press-drag-release gesture from (from_x, from_y) to (to_x, to_y) in window-local screenshot pixels — the same space get_window_state returns. Top-left origin of the target's window.\n\nUse for: marquee/lasso selection, drag-and-drop, resizing via a handle, scrubbing a slider, repositioning a panel.\n\n`duration_ms` (default 500) is the wall-clock budget for the path between mouse-down and mouse-up; `steps` (default 20) is the number of intermediate mouseDragged events linearly interpolated along the path. Increase both for slower, more human drags; decrease for snap gestures.\n\n`modifier` keys (cmd/shift/option/ctrl) are held across the entire gesture.\n\nWhen `from_zoom` is true, coordinates are in the last zoom image for this pid; the driver maps them back to window coordinates before dispatching.","inputSchema":{"additionalProperties":false,"properties":{"button":{"description":"Mouse button used for the drag. Default: left.","enum":["left","right","middle"],"type":"string"},"delivery_mode":{"description":"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.","enum":["background","foreground"],"type":"string"},"duration_ms":{"description":"Wall-clock duration of the drag path between mouseDown and mouseUp. Default: 500.","maximum":10000,"minimum":0,"type":"integer"},"from_x":{"description":"Drag-start X in window-local screenshot pixels. Top-left origin.","type":"number"},"from_y":{"description":"Drag-start Y in window-local screenshot pixels. Top-left origin.","type":"number"},"from_zoom":{"description":"When true, coordinates are in the last zoom image for this pid; driver maps back to window coordinates.","type":"boolean"},"modifier":{"description":"Modifier keys held across the entire gesture: cmd/shift/option/ctrl.","items":{"type":"string"},"type":"array"},"pid":{"description":"Target process ID.","type":"integer"},"scope":{"default":"window","description":"Use desktop with no pid/window_id for native get_desktop_state screenshot coordinates.","enum":["window","desktop"],"type":"string"},"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":"Number of intermediate mouseDragged events linearly interpolated along the path. Default: 20.","maximum":200,"minimum":1,"type":"integer"},"target":{"anyOf":[{"description":"Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.","oneOf":[{"additionalProperties":true,"properties":{"kind":{"const":"window","type":"string"},"pid":{"minimum":0,"type":"integer"},"window_id":{"minimum":0,"type":"integer"}},"required":["kind","pid","window_id"],"type":"object"},{"additionalProperties":true,"properties":{"display_id":{"type":"string"},"kind":{"const":"desktop","type":"string"}},"required":["kind","display_id"],"type":"object"}]},{"type":"null"}]},"to_x":{"description":"Drag-end X in window-local screenshot pixels.","type":"number"},"to_y":{"description":"Drag-end Y in window-local screenshot pixels.","type":"number"},"window_id":{"description":"CGWindowID for the window the pixel coordinates were measured against. Optional only when pid owns exactly one eligible top-level window; otherwise the action refuses with ambiguous_window_target.","type":"integer"}},"required":["from_x","from_y","to_x","to_y"],"type":"object"},"name":"drag","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.keyboard.type","input.keyboard.type.terminal_safe","accessibility.element_tokens","input.delivery_mode"],"description":"Insert text into the target pid via `AXSetAttribute(kAXSelectedText)`. Works for standard Cocoa text fields and text views. No keystrokes are synthesized — special keys (Return / Escape / arrows) go through `press_key` / `hotkey`. For Chromium / Electron inputs that don't implement `kAXSelectedText`, the tool falls back to CGEvent character synthesis automatically when the estimated route stays within the daemon transport budget. Longer synthesized routes are refused before character events and return a safe chunk size; one-call AX insertion remains uncapped.\n\nOptional `element_token` (from the last `get_window_state` snapshot) directs the write to a specific field. Without `element_token`, the write goes to the pid's currently focused element.\n\nWEB CONTENT (Chromium/WebKit/Electron — browser tabs, Slack, VS Code, X's compose box): AXValue is not independent proof that the renderer/DOM observed an AX write or synthesized keystrokes. The driver detects this at the element level (an AXWebArea ancestor) and refuses to trust AXValue-only read-back there. Electron AX targets that are web content or cannot be proven native refuse background delivery before mutation because the AX route cannot establish exact renderer focus; use the px form or explicit foreground delivery. Other web-content paths return effect:\"unverifiable\" + escalation, never a false \"confirmed\" (a browser's own native address bar/toolbar stays trusted). For a browser TAB the reliable path is the `page` tool (drives the DOM via CDP); for an embedded web view use this tool's px form: pass x,y (no element_token) to pixel-click the field then type, in one call. NOTE: a px focus-click won't reliably open+focus a CLOSED control; AX-press to open/activate it first (works in the background), then px-type. Always confirm via the screenshot; if px-background still drops, escalate to delivery_mode:\"foreground\".","inputSchema":{"additionalProperties":false,"properties":{"delay_ms":{"description":"Milliseconds between characters in the CGEvent fallback path. Default 30. Ignored when the AX path succeeds.","maximum":200,"minimum":0,"type":"integer"},"delivery_mode":{"description":"Best-effort-background ladder rung (default \"background\"). \"background\": AX insert, then CGEvent keystrokes if needed — no focus steal; native controls can be confirmed via AXValue read-back, while web-content writes remain effect:\"unverifiable\". \"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 remains unverifiable and a fresh snapshot shows the text did not appear.","enum":["background","foreground"],"type":"string"},"element_token":{"description":"Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.","type":"string"},"pid":{"description":"Target process ID.","type":"integer"},"scope":{"default":"window","description":"Use desktop with no pid/window_id to type into the frontmost application.","enum":["window","desktop"],"type":"string"},"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"},"target":{"anyOf":[{"description":"Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.","oneOf":[{"additionalProperties":true,"properties":{"kind":{"const":"window","type":"string"},"pid":{"minimum":0,"type":"integer"},"window_id":{"minimum":0,"type":"integer"}},"required":["kind","pid","window_id"],"type":"object"},{"additionalProperties":true,"properties":{"display_id":{"type":"string"},"kind":{"const":"desktop","type":"string"}},"required":["kind","display_id"],"type":"object"}]},{"type":"null"}]},"text":{"description":"Text to insert at the target's cursor.","type":"string"},"window_id":{"description":"CGWindowID. Omit when element_token is supplied (the token carries it).","type":"integer"},"x":{"description":"Screenshot-pixel X of the field to type into — the element px action form. Pass x,y (no element_token) and the tool pixel-clicks there to establish real renderer focus, then types. Use for Chromium/Electron inputs the AX path can't reach. Read straight off the get_window_state PNG, same convention as click.","type":"number"},"y":{"description":"Screenshot-pixel Y of the field (see x).","type":"number"}},"required":["text"],"type":"object"},"name":"type_text","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.keyboard.press","accessibility.element_tokens","input.delivery_mode"],"description":"Press and release a single key. Follows the same `delivery_mode` ladder as click/type_text — it does NOT raise the window by default:\n• `background` (default): post to the pid WITHOUT fronting/raising — the auth-message path (Chromium-safe). With element_token it focuses that AX element first. `window_id` only targets; it does not raise.\n• `foreground`: guard and briefly front the exact window, focus an addressed AX element when supplied, send a genuine HID key transition so Chromium content, inline editors, and native menu equivalents receive it, then restore prior frontmost. Requires window_id.\n\nA key press is confirmed only when a bounded native AX value/selection read-back changes on the same control. Otherwise a successfully attempted post remains effect:\"unverifiable\" without implying delivery failure or recommending foreground. Key names: return, tab, escape, up/down/left/right, space, delete, home, end, pageup, pagedown, f1-f12, plus any letter or digit. Modifiers array: cmd, shift, option/alt, ctrl, fn.","inputSchema":{"additionalProperties":false,"properties":{"delivery_mode":{"description":"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.","enum":["background","foreground"],"type":"string"},"element_token":{"description":"Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.","type":"string"},"key":{"description":"Key name: return, tab, escape, up, down, etc.","type":"string"},"modifiers":{"description":"Modifier keys: cmd, shift, option/alt, ctrl, fn.","items":{"type":"string"},"type":"array"},"pid":{"type":"integer"},"scope":{"default":"window","description":"Use desktop with no pid/window_id to send the key to the frontmost application.","enum":["window","desktop"],"type":"string"},"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"},"target":{"anyOf":[{"description":"Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.","oneOf":[{"additionalProperties":true,"properties":{"kind":{"const":"window","type":"string"},"pid":{"minimum":0,"type":"integer"},"window_id":{"minimum":0,"type":"integer"}},"required":["kind","pid","window_id"],"type":"object"},{"additionalProperties":true,"properties":{"display_id":{"type":"string"},"kind":{"const":"desktop","type":"string"}},"required":["kind","display_id"],"type":"object"}]},{"type":"null"}]},"window_id":{"description":"Target window. Required for delivery_mode:\"foreground\". Does NOT itself raise the window — raising is gated on delivery_mode.","type":"integer"},"x":{"description":"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_token.","type":"number"},"y":{"description":"Screenshot-pixel Y (see x).","type":"number"}},"required":["key"],"type":"object"},"name":"press_key","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.keyboard.hotkey","input.delivery_mode"],"description":"Press a key combination — e.g. `[\"cmd\", \"c\"]` for Copy, `[\"cmd\", \"shift\", \"4\"]` for screenshot selection. Follows the same `delivery_mode` ladder as click/type_text — it does NOT raise the window by default:\n• `background` (default): post the combo to the target pid WITHOUT fronting or raising it — uses the macOS 14+ auth-message envelope so Chromium/Electron accept it as trusted live input. With an AX target, focus that exact element first. No top-level focus steal. `window_id` here only targets the combo; it does not raise.\n• `foreground`: briefly front the window (NSMenu path, < 1 ms via SLPSSetFrontProcessWithOptions) so native menu key-equivalents (Cmd+Z, Cmd+W) dispatch, then restore the prior frontmost — the explicit escalation for menu-bar shortcuts on non-Chromium apps that ignore a background combo. With an AX target or x,y, the focused field receives the chord through the foreground HID queue (needed by native Chromium fields such as the omnibox). Requires window_id.\n\nA combo is never driver-verifiable (no read-back) → effect:\"unverifiable\"; confirm via screenshot. NOTE: a keyboard combo does NOT focus a text field — to type into a backgrounded Electron input, establish real renderer focus with a PIXEL click first, then `type_text`. If an app only accepts paste, call `clipboard_write`, then `clipboard_read` and verify its types (and text when applicable) before selecting or replacing editor content; only then send Cmd+V.\n\nRecognized modifiers: cmd/command, shift, option/alt, ctrl/control, fn. Non-modifier keys use the same vocabulary as `press_key`. Order: modifiers first, one non-modifier last.","inputSchema":{"additionalProperties":false,"properties":{"delivery_mode":{"description":"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.","enum":["background","foreground"],"type":"string"},"element_token":{"description":"Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.","type":"string"},"keys":{"description":"Modifier(s) and one non-modifier key, e.g. [\"cmd\", \"c\"].","items":{"type":"string"},"minItems":2,"type":"array"},"pid":{"description":"Target process ID.","type":"integer"},"scope":{"default":"window","description":"Use desktop with no pid/window_id to send the chord to the frontmost application.","enum":["window","desktop"],"type":"string"},"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"},"target":{"anyOf":[{"description":"Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.","oneOf":[{"additionalProperties":true,"properties":{"kind":{"const":"window","type":"string"},"pid":{"minimum":0,"type":"integer"},"window_id":{"minimum":0,"type":"integer"}},"required":["kind","pid","window_id"],"type":"object"},{"additionalProperties":true,"properties":{"display_id":{"type":"string"},"kind":{"const":"desktop","type":"string"}},"required":["kind","display_id"],"type":"object"}]},{"type":"null"}]},"window_id":{"description":"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.","type":"integer"},"x":{"description":"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.","type":"number"},"y":{"description":"Screenshot-pixel Y (see x).","type":"number"}},"required":["keys"],"type":"object"},"name":"hotkey","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.keyboard.type","accessibility.element_tokens"],"description":"Set a value on a UI element. Two modes depending on element role:\n\n- **AXPopUpButton / select dropdown**: finds the child option whose title or value matches `value` (case-insensitive) and AXPresses it directly — the native macOS popup menu is never opened, so focus is never stolen. Use this for HTML <select> elements in Safari or any native NSPopUpButton.\n\n- **All other elements**: writes AXValue directly (sliders, steppers, date pickers, native text fields that expose settable AXValue).\n\nFor free-form text entry into web inputs, prefer `type_text_chars` which synthesises key events — AXValue writes are ignored by WebKit.","inputSchema":{"additionalProperties":false,"properties":{"element_token":{"description":"Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.","type":"string"},"pid":{"type":"integer"},"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"},"value":{"description":"New value. AX will coerce to the element's native type.","type":"string"},"window_id":{"description":"CGWindowID. Omit when element_token is supplied (the token carries it).","type":"integer"}},"required":["pid","value"],"type":"object"},"name":"set_value","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.pointer.scroll","accessibility.element_tokens","input.delivery_mode"],"description":"Scroll the target pid. Two paths, picked by how you address the scroll:\n\n• **Targeted wheel path** — when you pass a target, either `element_token` (preferred) or window-local `x, y` pixels: the driver synthesizes a real mouse-wheel event (CGEventCreateScrollWheelEvent, at that screen point. The renderer hit-tests the wheel at the cursor, so the scroll lands on whatever element is under the point — exactly like physically rolling the wheel over it. This is the ONLY way to scroll a nested `overflow:auto` region (e.g. a scrollable <div> with no tabindex): such regions never take keyboard focus, so the keystroke path below no-ops on them. Use this for inner/nested scrollers in web views.\n\n• **Keystroke path (focused region)** — when you pass NO target (just pid + direction): synthesizes PageDown/PageUp (by='page') or Down/Up arrows (by='line'); horizontal uses Left/Right arrows. Drives the focused / page scroller only.\n\nMapping: by='page' → larger step; by='line' → smaller step; amount = number of wheel notches (targeted path) or keystroke repetitions (keystroke path).","inputSchema":{"additionalProperties":false,"properties":{"amount":{"description":"Pixel-wheel path: number of wheel notches. Keystroke path: number of keystroke repetitions. Larger requests are clamped to the maximum. Default: 3.","maximum":50,"minimum":1,"type":"integer"},"by":{"description":"Scroll granularity. Default: line.","enum":["line","page"],"type":"string"},"delivery_mode":{"description":"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.","enum":["background","foreground"],"type":"string"},"direction":{"description":"Scroll direction.","enum":["up","down","left","right"],"type":"string"},"element_token":{"description":"Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.","type":"string"},"pid":{"type":"integer"},"scope":{"default":"window","description":"Use desktop with x,y and no pid/window_id for native get_desktop_state screenshot coordinates.","enum":["window","desktop"],"type":"string"},"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"},"target":{"anyOf":[{"description":"Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.","oneOf":[{"additionalProperties":true,"properties":{"kind":{"const":"window","type":"string"},"pid":{"minimum":0,"type":"integer"},"window_id":{"minimum":0,"type":"integer"}},"required":["kind","pid","window_id"],"type":"object"},{"additionalProperties":true,"properties":{"display_id":{"type":"string"},"kind":{"const":"desktop","type":"string"}},"required":["kind","display_id"],"type":"object"}]},{"type":"null"}]},"window_id":{"type":"integer"},"x":{"description":"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.","type":"number"},"y":{"description":"Window-local screenshot Y. See `x`.","type":"number"}},"required":["direction"],"type":"object"},"name":"scroll","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":true},"capabilities":["clipboard.read","clipboard.types"],"description":"List available system clipboard types and optionally return privacy-sensitive plain text. Clipboard content is never retained in telemetry.","inputSchema":{"additionalProperties":false,"properties":{"include_text":{"default":false,"description":"Return plain-text clipboard content in addition to the available types.\nClipboard content is privacy-sensitive and is never retained in telemetry.","type":"boolean"},"session":{"description":"For multi-call work, prefer a short public session label and repeat it on every call that\naccepts it. Omit it to use the authenticated transport's implicit lifecycle session.","type":"string"}},"required":[],"type":"object"},"name":"clipboard_read","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"content_redacted_from_telemetry":{"type":"boolean"},"privacy_sensitive":{"type":"boolean"},"supported":{"type":"boolean"},"text":{"anyOf":[{"type":"string"},{"type":"null"}]},"types":{"items":{"type":"string"},"type":"array"}},"required":["supported","types","text","privacy_sensitive","content_redacted_from_telemetry"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r2","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"capabilities":["clipboard.write","clipboard.write.text","clipboard.write.image","clipboard.write.file_url","clipboard.types"],"description":"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. Returns the available types for read-back before paste.","inputSchema":{"additionalProperties":false,"properties":{"file_path":{"description":"Absolute path to a local file to place on the clipboard as a file URL.","type":"string"},"image_path":{"description":"Absolute path to a local image to place on the clipboard.","type":"string"},"session":{"description":"For multi-call work, prefer a short public session label and repeat it on every call that\naccepts it. Omit it to use the authenticated transport's implicit lifecycle session.","type":"string"},"text":{"description":"Plain text to place on the clipboard.","type":"string"}},"required":[],"type":"object"},"name":"clipboard_write","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"content_redacted_from_telemetry":{"type":"boolean"},"privacy_sensitive":{"type":"boolean"},"supported":{"type":"boolean"},"types":{"items":{"type":"string"},"type":"array"},"written_type":{"type":"string"}},"required":["supported","written_type","types","privacy_sensitive","content_redacted_from_telemetry"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":["screen.dimensions"],"description":"Return the logical size of the main display in points plus its backing scale factor. Agents click in points; Retina displays have scale_factor 2.0. Requires no TCC permissions.","inputSchema":{"additionalProperties":false,"properties":{"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"}},"type":"object"},"name":"get_screen_size","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"height":{"type":"number"},"scale_factor":{"type":"number"},"width":{"type":"number"}},"required":["width","height","scale_factor"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r0","enforcement":"metadata_only","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":true},"capabilities":["screen.capture","screen.dimensions"],"description":"Capture the full display in true screen pixels, full size unless `max_image_dimension` caps it. Use its PNG as the coordinate source for actions whose target is {kind:\"desktop\",display_id:\"primary\"}. Returns the true screen size and backing scale factor. Vision-only: no AX tree walk.","inputSchema":{"additionalProperties":false,"properties":{"max_image_dimension":{"description":"Optional long-edge cap for the returned PNG, in pixels (aspect ratio preserved). Omitted or 0 returns the full-size capture. When the cap downsizes the image, the response reports `screenshot_original_width/height`, and x/y read off it for this session's later scope:\"desktop\" actions (or passed with its `capture_id`) are mapped back to the full-size frame automatically.","minimum":0,"type":"integer"},"screenshot_out_file":{"description":"Write PNG here instead of base64.","type":"string"},"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"}},"type":"object"},"name":"get_desktop_state","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"agent_overlay_capture":{"additionalProperties":false,"properties":{"method":{"type":["string","null"]},"reason":{"type":["string","null"]},"status":{"oneOf":[{"const":"excluded","type":"string"},{"const":"not_present","type":"string"},{"const":"not_excluded","type":"string"}]}},"required":["status"],"type":["object","null"]},"display":{"type":"string"},"platform":{"enum":["macos","linux","windows"],"type":"string"},"scale_factor":{"type":"number"},"screen_height":{"type":"integer"},"screen_width":{"type":"integer"},"screenshot_file_path":{"type":"string"},"screenshot_height":{"type":"integer"},"screenshot_mime_type":{"const":"image/png"},"screenshot_width":{"type":"integer"}},"required":["platform","display","screenshot_width","screenshot_height","screen_width","screen_height","scale_factor","screenshot_mime_type"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r3","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":["screen.cursor.position"],"description":"Return the current mouse cursor position in screen points (origin top-left).","inputSchema":{"additionalProperties":false,"properties":{"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"}},"type":"object"},"name":"get_cursor_position","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"available":{"type":"boolean"},"source":{"type":"string"},"x":{"type":"number"},"y":{"type":"number"}},"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r0","enforcement":"metadata_only","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":[],"description":"Single-call end-to-end driver diagnostics. Designed to let downstream consumers ship one stable call instead of stitching together check_permissions, doctor, version, bundle attribution, and platform capability status. On macOS, prompt-capable direct capture is deliberately skipped; use `cua-driver permissions grant` to verify it explicitly. cua-driver owns the health model; consumers stay thin.\n\nInput — all optional:\n {\n \"include\": [\"<check_name>\", ...], // run only these\n \"skip\": [\"<check_name>\", ...] // skip these\n }\nIf both are given, `include` wins.\n\nCanonical check names:\n macOS : binary_version, platform_supported, session_active,\n bundle_identity, tcc_accessibility, tcc_screen_recording,\n ax_capability, screen_capture_capability\n Windows: binary_version, platform_supported, session_active,\n ax_capability (via UIA), screen_capture_capability (via DXGI)\n Linux : binary_version, platform_supported, session_active,\n ax_capability (via AT-SPI), screen_capture_capability (via X11)\n\nOutput — stable contract, schema_version=\"1\":\n {\n \"schema_version\": \"1\",\n \"platform\": \"darwin\" | \"win32\" | \"linux\",\n \"driver_version\": \"<semver>\",\n \"overall\": \"ok\" | \"degraded\" | \"failed\",\n \"checks\": [\n {\n \"name\": \"<one of the canonical names above>\",\n \"status\": \"pass\" | \"fail\" | \"skip\",\n \"message\": \"<one-line summary, always present>\",\n \"hint\": \"<remediation step, present when status=fail>\",\n \"data\": { /* check-specific structured fields */ }\n },\n ...\n ]\n }\n\n`overall` rules:\n - `ok` — every non-skipped check passes\n - `degraded` — at least one non-core check fails (binary is still usable)\n - `failed` — any core check fails (binary_version, platform_supported, session_active)\n\nStability: schema_version=\"1\" is the contract. Future breaking changes will be `\"2\"`. Adding new check names under the same schema_version is non-breaking; consumers must tolerate unknown check names.","inputSchema":{"additionalProperties":false,"properties":{"include":{"description":"Only run these checks (canonical names). Wins over `skip`.","items":{"type":"string"},"type":"array"},"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"},"skip":{"description":"Skip these checks (canonical names). Ignored when `include` is set.","items":{"type":"string"},"type":"array"}},"type":"object"},"name":"health_report","risk":{"class":"r0","enforcement":"metadata_only","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":["accessibility.tree","accessibility.tree.structured"],"description":"Return a lightweight snapshot of the desktop: running regular apps and on-screen visible windows with their bounds, z-order, and owner pid.\n\nFor the full AX subtree of a single window (with interactive element indices you can click by), use `get_window_state` instead — that's the heavy per-window tool. This one is a fast discovery read that needs no TCC grants.","inputSchema":{"additionalProperties":false,"properties":{"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"}},"type":"object"},"name":"get_accessibility_tree","risk":{"class":"r2","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":["screen.capture","screen.capture.window","screen.capture.region"],"description":"Capture a cropped JPEG of a window region (x1,y1)–(x2,y2) in screenshot pixel coordinates, with 20% padding added on each side. The output image is at most 500 px wide.\n\nAfter a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordinates back to full-window space. Coordinate actions return `screenshot_context_missing` when no current snapshot contains a screenshot owned by this session. `from_zoom` actions return `zoom_context_missing` when the zoom was never created or was replaced; call `get_window_state`, then `zoom`, again on the same connection.","inputSchema":{"additionalProperties":false,"properties":{"pid":{"description":"Optional target pid. When omitted, the driver resolves the unique current snapshot for this session and window.","type":"integer"},"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"},"window_id":{"description":"CGWindowID from list_windows.","type":"integer"},"x1":{"description":"Left edge of region in screenshot pixels.","type":"number"},"x2":{"description":"Right edge of region in screenshot pixels.","type":"number"},"y1":{"description":"Top edge of region in screenshot pixels.","type":"number"},"y2":{"description":"Bottom edge of region in screenshot pixels.","type":"number"}},"required":["window_id","x1","y1","x2","y2"],"type":"object"},"name":"zoom","risk":{"class":"r2","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"capabilities":["session.lifecycle.start","session.capture_scope"],"description":"Optionally create or return a lifecycle session before acting. For multi-call work, prefer a short public `session` label and repeat it on every call that accepts it; an omitted value uses the authenticated transport lease's implicit session instead. This tool is optional because an ordinary action can create or reuse a named run directly. Use it to set the initial cursor theme before acting or to revive a public name after it has ended; ordinary actions never revive ended names. `capture_scope` is deprecated compatibility input; new callers select window or desktop modality per action. Idempotent.","inputSchema":{"additionalProperties":true,"properties":{"capture_scope":{"description":"Deprecated compatibility policy. New callers select window or desktop\nmodality on each action instead of storing it on the session.","enum":["auto","window","desktop"],"type":"string"},"cursor_theme":{"description":"Optional initial cursor theme. The host applies it before the cursor is\nfirst made visible, avoiding a flash of the default theme.","properties":{"reduced_motion":{"default":"auto","enum":["auto","on","off"],"type":"string"},"theme_id":{"type":"string"}},"required":["theme_id"],"type":["object","null"]},"session":{"description":"Optional stable public label for this run (e.g. \"research-run-1\").\nWhen omitted, the authenticated transport lease's implicit session is\ncreated or returned.","type":"string"}},"required":[],"type":"object"},"name":"start_session","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"active":{"type":"boolean"},"capture_scope":{"enum":["auto","window","desktop"],"type":"string"},"desktop_capture_authorized":{"type":"boolean"},"desktop_unlocked":{"type":"boolean"},"effective_scope":{"enum":["window","desktop"],"type":"string"},"escalation_detail":{"anyOf":[{"type":"string"},{"type":"null"}]},"escalation_reason":{"anyOf":[{"enum":["ax_tree_pixel_mismatch","background_delivery_failed","foreground_ineffective","no_window_target","other"],"type":"string"},{"type":"null"}]},"revived":{"type":"boolean"},"session":{"type":"string"}},"required":["session","capture_scope","effective_scope","desktop_capture_authorized","desktop_unlocked","escalation_reason","escalation_detail","active","revived"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"metadata_only","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":["session.lifecycle.read"],"description":"Read content-free lifecycle, cursor, recording, and idle status for one session visible to this authenticated transport. Omit `session` to inspect its implicit session.","inputSchema":{"additionalProperties":true,"properties":{"session":{"description":"Optional public label. When omitted, inspect the caller's attached\nimplicit session.","type":"string"}},"required":[],"type":"object"},"name":"get_session","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"client_kind":{"enum":["cli","direct","mcp","python_sdk","typescript_sdk"],"type":"string"},"cursor_visible":{"type":"boolean"},"expires_in_seconds":{"minimum":0,"type":"integer"},"idle_seconds":{"minimum":0,"type":"integer"},"implicit":{"type":"boolean"},"recording_active":{"type":"boolean"},"session":{"anyOf":[{"type":"string"},{"type":"null"}]},"state":{"enum":["active","ending"],"type":"string"},"transport":{"enum":["cli","daemon","mcp_stdio","mcp_http"],"type":"string"}},"required":["session","implicit","state","client_kind","transport","cursor_visible","recording_active","idle_seconds","expires_in_seconds"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r0","enforcement":"metadata_only","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":["session.lifecycle.list"],"description":"List content-free lifecycle summaries attached to this authenticated transport lease. It does not enumerate other callers' sessions.","inputSchema":{"additionalProperties":true,"properties":{"cursor":{"description":"Opaque continuation cursor returned by a previous call.","type":"string"},"limit":{"description":"Maximum number of content-free summaries to return (default 50, max\n100). Ordinary agent transports are scoped to their own lease.","minimum":0,"type":["integer","null"]}},"required":[],"type":"object"},"name":"list_sessions","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"next_cursor":{"anyOf":[{"type":"string"},{"type":"null"}]},"sessions":{"items":{"properties":{"client_kind":{"enum":["cli","direct","mcp","python_sdk","typescript_sdk"],"type":"string"},"cursor_visible":{"type":"boolean"},"expires_in_seconds":{"minimum":0,"type":"integer"},"idle_seconds":{"minimum":0,"type":"integer"},"implicit":{"type":"boolean"},"recording_active":{"type":"boolean"},"session":{"anyOf":[{"type":"string"},{"type":"null"}]},"state":{"enum":["active","ending"],"type":"string"},"transport":{"enum":["cli","daemon","mcp_stdio","mcp_http"],"type":"string"}},"required":["session","implicit","state","client_kind","transport","cursor_visible","recording_active","idle_seconds","expires_in_seconds"],"type":"object"},"type":"array"}},"required":["sessions","next_cursor"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r0","enforcement":"metadata_only","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"capabilities":["session.lifecycle.end"],"description":"End one visible lifecycle session and run its cursor, recording, configuration, and other cleanup hooks exactly once. Omit `session` to end the authenticated transport's implicit session. Idempotent.","inputSchema":{"additionalProperties":true,"properties":{"session":{"description":"Optional public label to end. When omitted, end the caller's attached\nimplicit session.","type":"string"}},"required":[],"type":"object"},"name":"end_session","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"active":{"const":false},"session":{"type":"string"}},"required":["session","active"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"metadata_only","operation_sensitive":false,"version":"1"}}]}
+{"driver_version":"0.31.0","patch_sha256":"b720fb0e80a5fcc7796de175c905d73208ce8a53716a517074087f50d09ed584","schema_version":1,"source_commit":"5272e492d61b96caf08e3bf434d91126c1f3dccc","source_tag":"cua-driver-rs-v0.31.0","source_variant":"avibe-raw-single-click-v1","tools":[{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":["app.list"],"description":"List macOS apps — both currently running and installed-but-not-running — with per-app state flags:\n\n- running: is a process for this app live? (pid is 0 when false)\n- active: is it the system-frontmost app? (implies running)\n- launch_path: filesystem path to the `.app` bundle, when known. Pass this to `launch_app` to start the app cold.\n- kind: `\"desktop\"` for `.app` bundles on macOS.\n- last_used: RFC3339 timestamp from the bundle's filesystem mtime, when readable; otherwise null.\n\nStandalone running entries include only apps with NSApplicationActivationPolicyRegular — background helpers and system UI agents are filtered out. Installed apps resolve their running/pid state against all live processes by bundle identifier, so an installed app whose process runs as an accessory (LSUIElement / menu-bar apps, e.g. Cua Driver itself) still reports its live pid. Installed apps come from scanning /Applications, /Applications/Utilities, ~/Applications, /System/Applications, and /System/Applications/Utilities.\n\nUse this for \"is X installed?\" as well as \"is X running?\". For per-window state — on-screen, on-current-Space, minimized, window titles — call list_windows instead. For just opening an app — running or not — call launch_app({bundle_id: ...}) directly; list_apps is not a prerequisite.","inputSchema":{"additionalProperties":false,"properties":{"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"}},"type":"object"},"name":"list_apps","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"apps":{"items":{"properties":{"active":{"type":"boolean"},"bundle_id":{"type":["string","null"]},"kind":{"type":["string","null"]},"last_used":{"type":["string","null"]},"launch_path":{"type":["string","null"]},"name":{"type":"string"},"pid":{"minimum":0,"type":"integer"},"running":{"type":"boolean"}},"required":["pid","name","running","active"],"type":"object"},"type":"array"}},"required":["apps"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r2","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":["window.list"],"description":"List all layer-0 top-level windows currently known to WindowServer. Includes off-screen windows (minimized, on another Space, hidden-launched). Use this to find a window_id before calling get_window_state.\n\nPer-record fields: window_id, pid, app_name, title, bounds (x/y/width/height, top-left origin), z_index (integer or null; higher values are closer to the front; null means stacking order is unavailable and callers must not infer one), is_on_screen, space_ids, current_space_id (the active Space on that window's display), and on_current_space. The top-level current_space_id is WindowServer's main/global active Space and can differ from a record's current_space_id when displays use independent Spaces. To select a frontmost candidate, take the maximum integer z_index; if every value is null, use an explicit fallback instead of relying on array order.","inputSchema":{"additionalProperties":false,"properties":{"on_screen_only":{"description":"When true, drop windows not on the current Space. Default false.","type":"boolean"},"pid":{"description":"Optional pid filter. When set, only this pid's windows are returned.","type":"integer"},"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"}},"type":"object"},"name":"list_windows","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"current_space_id":{"minimum":0,"type":["integer","null"]},"windows":{"items":{"properties":{"app_name":{"type":"string"},"bounds":{"properties":{"height":{"type":"number"},"width":{"type":"number"},"x":{"type":"number"},"y":{"type":"number"}},"required":["x","y","width","height"],"type":"object"},"current_space_id":{"minimum":0,"type":["integer","null"]},"is_on_screen":{"type":"boolean"},"layer":{"format":"int32","type":["integer","null"]},"minimized":{"type":["boolean","null"]},"on_current_space":{"type":["boolean","null"]},"pid":{"maximum":4294967295,"minimum":0,"type":["integer","null"]},"space_ids":{"items":{"minimum":0,"type":"integer"},"type":["array","null"]},"title":{"type":"string"},"window_id":{"minimum":0,"type":"integer"},"z_index":{"description":"Higher values are closer to the front. Null means the provider cannot observe stacking order; callers must not infer an order from array position or treat null as zero.","type":["integer","null"]}},"required":["window_id","pid","app_name","title","bounds","is_on_screen","z_index"],"type":"object"},"type":"array"}},"required":["windows"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r2","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":true},"capabilities":["accessibility.window_state","accessibility.tree","accessibility.tree.structured","accessibility.tree.bounded","accessibility.element_tokens","screen.capture","screen.capture.window"],"description":"Walk a running app's AX tree and return BOTH a structured `elements` array (preferred) AND a Markdown rendering of the same tree (back-compat). Every actionable element is tagged with [element_index N] in the markdown and as `element_index` in the structured array; pass each element's `element_token` to click, type_text, press_key, etc.\n\nINVARIANT: call get_window_state once per turn per (pid, window_id) before any element action. The next snapshot of the window replaces this one, stales its element tokens, and lists the replaced ids in `invalidated_snapshot_ids`.\n\nPREFERRED CONSUMERS read `structuredContent.elements` (one entry per indexed row with `element_index`, `role`, `label`, `value` (the element's text/AXValue when present — use it to verify what a field holds), `actions` (names of AX actions exposed by the element, omitted when empty), `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\nAlways returns BOTH the element tree AND a screenshot — ground on both and cross-check (the tree lies on some surfaces: Electron echo-confirms, Catalyst null values, virtualized off-viewport rows with `h:1` frames). You choose the modality at ACTION time, not here: an element ax action (pass `element_token` → the accessibility rung) or an element px action (pass `x`,`y` → the pixel rung, read straight off this screenshot). `capture_mode` is deprecated and ignored. Pass `include_screenshot:false` to skip the grab and get the tree only — the cheap path when you're just re-indexing before an element ax action.\n\nThe mirror image: pass `include_accessibility_tree:false` to SKIP the AX walk entirely (the expensive part, bounded by timeout_ms) and return just the screenshot plus window metadata — `window_bounds`, `screenshot_scale`, `screenshot_width`/`screenshot_height`, `app_name`, and `window_title` — the capture-only path for rendering a live window preview / picture-in-picture without paying for perception. Setting BOTH `include_accessibility_tree:false` and `include_screenshot:false` is an error (nothing to return). Optional `max_image_dimension` overrides the configured screenshot long-edge limit for this call; use 0 for native resolution. The legacy `max_dimension` remains a tighter cap for compatibility.\n\nThe snapshot is SCOPED to `window_id`: a window_id that no longer exists is refused with `window_id_not_found`, and one owned by another process is refused with `window_owner_pid_mismatch` naming the real `owner_pid` to retry with (macOS hosts a sandboxed app's Open/Save panel out-of-process, so its window belongs to the panel service, not the app). If the window is live under this pid but its accessibility surface can't be resolved, the tree comes back EMPTY with `degraded_reason: ax_window_unresolved` and the screenshot of the requested window; background input is refused until it resolves, so re-snapshot or act with `delivery_mode:\"foreground\"`. When that pid is an app still launching (its window exists before it answers accessibility), the walk first waits up to `timeout_ms` for it; if it never answers, the tree comes back EMPTY with `degraded_reason: ax_app_launching`, `truncated: true` and `truncation_reason: app_lookup_timeout`. A window on another Space still resolves by its exact CGWindowID. This tool never returns another surface's elements under your window_id. Before exposing a screenshot, its raw dimensions are validated as a coherent 1x/2x representation of the requested WindowServer bounds. `px_frame_mismatch` or `px_capture_unavailable` omits an unprovable screenshot/pixel frame instead of guessing a transform; the truthful AX payload remains available.\n\nOptional `query` projects both tree_markdown and structured `elements` to matching lines plus their ancestor chain (case-insensitive substring). The element_index values are unchanged, the complete snapshot remains actionable, and `element_count` continues to report its total size; `filtered_element_count` reports the projected response size.\n\nOptional `max_elements` / `max_depth` bound the AX walk to mitigate context-window blow-up on Electron / Obsidian / large web apps that produce 10k+ element trees. When applied, BOTH the markdown and the structured elements are truncated identically. Omit both for current default behaviour (≤2 000 elements, depth ≤25).","inputSchema":{"additionalProperties":false,"properties":{"capture_mode":{"description":"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_token) or an element px action (x,y). Any value (including the old \"som\"/\"screenshot\" aliases) is accepted but has no effect.","enum":["ax","vision"],"type":"string"},"include_accessibility_tree":{"description":"Default true — walk the AX tree and return `elements` + `tree_markdown` alongside the screenshot. Set false to SKIP the AX walk entirely (the expensive part, bounded by timeout_ms) and return just the screenshot plus window metadata (bounds, scale, app_name, window_title) — the capture-only path for rendering a live window preview / picture-in-picture. Mirrors include_screenshot. Setting BOTH include_accessibility_tree:false AND include_screenshot:false is an error (nothing to return).","type":"boolean"},"include_screenshot":{"description":"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.","type":"boolean"},"max_depth":{"description":"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.","minimum":1,"type":"integer"},"max_dimension":{"description":"Optional cap on the returned screenshot's long edge, in pixels (aspect ratio preserved) — the cheap path for a small preview / thumbnail. Applied on top of the session/global max_image_dimension ceiling; the tighter of the two wins. Omit for the configured default.","minimum":1,"type":"integer"},"max_elements":{"description":"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.","minimum":1,"type":"integer"},"max_image_dimension":{"description":"Per-call override for the returned screenshot's long edge in pixels. An explicit value wins over the session/global setting; 0 returns native resolution. Omit to preserve configured behavior.","minimum":0,"type":"integer"},"pid":{"description":"Target process ID.","type":"integer"},"query":{"description":"Case-insensitive filter for tree_markdown and structured elements. Returns matching actionable rows plus their actionable ancestors without renumbering element_index values.","type":"string"},"screenshot_out_file":{"description":"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.","type":"string"},"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"},"timeout_ms":{"default":1000,"description":"Wall-clock budget in milliseconds for the accessibility-tree walk (default 1000, min 100, max 120000). Bounds the WHOLE walk. When the budget runs out the tool returns the PARTIAL tree it has, flagged with `truncated: true`, `truncation_reason`, `nodes_visited`, `nodes_pending` and `elements_complete: false`; retry with a larger value (e.g. 5000) or narrow with `query` / `max_depth`.","maximum":120000,"minimum":100,"type":"integer"},"window_id":{"description":"Target window ID from list_windows.","type":"integer"}},"required":["pid","window_id"],"type":"object"},"name":"get_window_state","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"app_name":{"type":["string","null"]},"degraded":{"type":["boolean","null"]},"degraded_reason":{"type":["string","null"]},"element_count":{"minimum":0,"type":["integer","null"]},"elements":{"items":{"properties":{"actions":{"items":{"type":"string"},"type":["array","null"]},"depth":{"minimum":0,"type":"integer"},"element_index":{"minimum":0,"type":"integer"},"element_token":{"type":["string","null"]},"enabled":{"type":["boolean","null"]},"frame":{"properties":{"h":{"type":"number"},"w":{"type":"number"},"x":{"type":"number"},"y":{"type":"number"}},"required":["x","y","w","h"],"type":["object","null"]},"in_web_content":{"type":["boolean","null"]},"label":{"type":["string","null"]},"max":{"type":["number","null"]},"min":{"type":["number","null"]},"parent_index":{"minimum":0,"type":["integer","null"]},"role":{"type":"string"},"selected":{"type":["boolean","null"]},"value":{"type":["string","null"]},"value_description":{"type":["string","null"]}},"required":["element_index","role","depth"],"type":"object"},"type":["array","null"]},"elements_complete":{"type":["boolean","null"]},"filtered_element_count":{"minimum":0,"type":["integer","null"]},"pid":{"minimum":0,"type":"integer"},"returned_element_count":{"minimum":0,"type":["integer","null"]},"screenshot_file_path":{"type":["string","null"]},"screenshot_frame_valid":{"type":["boolean","null"]},"screenshot_height":{"minimum":0,"type":["integer","null"]},"screenshot_mime_type":{"type":["string","null"]},"screenshot_scale":{"type":["number","null"]},"screenshot_width":{"minimum":0,"type":["integer","null"]},"snapshot_id":{"type":["string","null"]},"total_element_count":{"minimum":0,"type":["integer","null"]},"tree_markdown":{"type":["string","null"]},"truncated":{"type":["boolean","null"]},"truncation_reason":{"type":["string","null"]},"window_bounds":{"properties":{"height":{"type":"number"},"width":{"type":"number"},"x":{"type":"number"},"y":{"type":"number"}},"required":["x","y","width","height"],"type":["object","null"]},"window_id":{"minimum":0,"type":"integer"},"window_title":{"type":["string","null"]}},"required":["pid","window_id"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r3","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":true},"capabilities":["state.verify","state.verify.window","state.verify.element","state.observe.visual_evidence"],"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.","inputSchema":{"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.","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":"For multi-call work, prefer a short public session label and repeat it on every call that\naccepts it. Omit it to use the authenticated transport's implicit lifecycle session. This\nfield never selects capture modality or authorization.","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"},"name":"verify_state","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"elapsed_ms":{"minimum":0,"type":"integer"},"predicates":{"items":{"properties":{"index":{"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":{"minimum":0,"type":"integer"},"stable":{"type":"boolean"},"status":{"enum":["satisfied","unsatisfied","unknown"],"type":"string"}},"required":["status","stable","elapsed_ms","samples","predicates"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r2","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"capabilities":["app.launch"],"description":"Launch a macOS app in the background — the target does NOT come to the foreground.\n\nProvide either `bundle_id` (preferred — unambiguous, e.g. `com.apple.calculator`) or `name` (e.g. \"Calculator\"). If both are given, bundle_id wins.\n\nOptional `urls` are handed to the app as open targets — for Finder, pass a folder path to open a backgrounded Finder window there.\n\nBrowser DevTools setup belongs to `browser_prepare`, which can prove that a separate isolated profile is driver-owned before enabling CDP.\n\nOptional `webkit_inspector_port`: opens a WebKit inspector server on the specified port (sets WEBKIT_INSPECTOR_SERVER=127.0.0.1:N + TAURI_WEBVIEW_AUTOMATION=1). Use this for Tauri/WebKit-based apps.\n\nOptional `creates_new_application_instance`: when true, forces a new app instance even if one is already running (passes -n to open). Reach for this when another agent or session may drive the SAME app concurrently — it returns a fresh pid + window so each session acts on its own isolated window instead of clobbering one shared instance. Without it, single-instance apps (Calculator, many utilities) hand every caller the same window, so two sessions fight over it.\n\nOptional `additional_arguments`: extra argv strings appended after --args.\n\nReturns the launched app's pid, bundle_id, name, and a `windows` array (same shape as `list_windows`) so callers can skip an extra round-trip before `get_window_state(pid, window_id)`. `launch_state` distinguishes whether the request was sent, the process is running, and a window is ready. When the focus-steal belt-and-braces demotion check ran (target pid ≠ prior frontmost), the response also includes `self_activation_suppressed: bool` — true if focus stayed with the prior frontmost, false if the launched app held focus despite the re-demote attempt.","inputSchema":{"additionalProperties":false,"properties":{"additional_arguments":{"description":"Extra arguments appended after --args when launching.","items":{"type":"string"},"type":"array"},"bundle_id":{"description":"App bundle identifier, e.g. com.apple.calculator. Preferred over name.","type":"string"},"creates_new_application_instance":{"description":"When true, force a new app instance even if already running (open -n). Use for concurrent multi-agent/multi-session work so each session gets an isolated instance + window instead of sharing one — on single-instance apps (e.g. Calculator) every caller otherwise gets the same window and the sessions clobber each other.","type":"boolean"},"name":{"description":"App display name. Used only when bundle_id is absent.","type":"string"},"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"},"urls":{"description":"Optional file paths or URLs to open with the app (e.g. a folder path for Finder).","items":{"type":"string"},"type":"array"},"webkit_inspector_port":{"description":"Open a WebKit inspector server on this port (sets WEBKIT_INSPECTOR_SERVER env var).","type":"integer"}},"type":"object"},"name":"launch_app","risk":{"class":"r1","enforcement":"metadata_only","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"capabilities":["app.kill"],"description":"Force-terminate a process by pid (kill -9 equivalent on macOS / Linux; taskkill /F equivalent on Windows). Use as escalation when the cooperative close path (hotkey cmd+q on macOS, click-the-X on Windows) failed to make the process exit. Unsaved state is lost — prefer the cooperative path first.","inputSchema":{"additionalProperties":false,"properties":{"pid":{"description":"PID of the process to terminate.","type":"integer"},"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"}},"required":["pid"],"type":"object"},"name":"kill_app","risk":{"class":"r3","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"capabilities":["window.frame.set"],"description":"Set one exact top-level window's frame in the desktop-coordinate space reported by list_windows and verify the resulting geometry through an independent readback.","inputSchema":{"additionalProperties":false,"properties":{"height":{"minimum":1,"type":"number"},"pid":{"minimum":1,"type":"integer"},"session":{"description":"For multi-call work, prefer a short public session label and repeat it on every call that\naccepts it. Omit it to use the authenticated transport's implicit lifecycle session.","type":"string"},"width":{"minimum":1,"type":"number"},"window_id":{"minimum":1,"type":"integer"},"x":{"type":"number"},"y":{"type":"number"}},"required":["pid","window_id","x","y","width","height"],"type":"object"},"name":"set_window_frame","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.pointer.click","input.pointer.click.left","accessibility.element_tokens","input.delivery_mode"],"description":"Click against a target pid. **Prefer `element_token` over pixel coordinates** — the token works on backgrounded / minimized / hidden / off-Space windows, identifies one exact snapshot element, and tells you what you're clicking via the cached element's role + label. Reach for `x, y` only when the target is a canvas / video / WebGL / custom-drawn surface that doesn't appear in the AX tree.\n\nTwo addressing modes:\n\n- element_token (from get_window_state): AX action path. Works on backgrounded/hidden windows. No cursor move, no focus steal. The snapshot cache is scoped per (pid, window_id) and is replaced by the next snapshot of the same window — re-snapshot every turn before clicking.\n\n- x, y (window-local screenshot pixels, top-left origin of the PNG returned by get_window_state): CGEvent path. Synthesizes mouse events and posts to pid. Use modifier for cmd/shift/option/ctrl. Needs a visible on-screen window to anchor the conversion.\n\nbutton: \"left\" (default), \"right\", or \"middle\". Defaults to left so the field is fully back-compat — omit it and you get the legacy left-click behaviour. Pixel path: routes through the CGEvent left/right/middle mouse-button primitives. AX path: \"right\" maps to AXShowMenu (same surface as the dedicated `right_click` tool); \"middle\" has no AX equivalent and falls back to a pixel middle-click at the element's center. For a window-addressed background pixel left-click, click_mode:\"raw\" bypasses the AX hit-test optimization and posts exactly one routed mouse down/up pair. Keep the default click_mode:\"auto\" unless AXPress was observed to return a hollow success.\naction: press (default), show_menu, pick, confirm, cancel, open.\nfrom_zoom: set true after a zoom call to auto-translate zoom-image pixel coordinates to full-window space.","inputSchema":{"additionalProperties":false,"properties":{"action":{"description":"AX action: press, show_menu, pick, confirm, cancel, open.","type":"string"},"button":{"description":"Mouse button. Default: \"left\" — omit for legacy left-click behaviour. Pixel path uses the matching CGEvent primitive; AX path maps \"right\" to AXShowMenu and falls back to a pixel middle-click at the element's center for \"middle\".","enum":["left","right","middle"],"type":"string"},"capture_id":{"description":"Optional immutable source capture ID returned by get_window_state or get_desktop_state. With x,y, Driver atomically admits and consumes that exact capture before dispatch; stale, mismatched, or out-of-bounds captures are refused without fallback.","type":"string"},"click_mode":{"description":"Pixel single-click delivery selector. Default \"auto\" preserves the AX-first background optimization. \"raw\" is opt-in and valid only for an exact pid + window_id background left-click with x/y, count=1, and no modifiers; it bypasses AX hit-testing and uses the existing routed CGEvent path.","enum":["auto","raw"],"type":"string"},"count":{"description":"Click count (pixel path only). Default 1.","type":"integer"},"debug_image_out":{"description":"Optional file path. When set on a pixel-addressed click, captures a fresh screenshot, draws a red crosshair at (x, y), and writes the PNG. Use to verify coordinate spaces. Requires window_id; incompatible with from_zoom.","type":"string"},"delivery_mode":{"description":"Best-effort-background ladder rung (default \"background\"). \"background\": perform the AX action or post the CGEvent without fronting. \"foreground\": briefly front the window, act, let transient UI settle, then restore the prior frontmost app. Requires window_id. Modified clicks require \"foreground\" so macOS observes physical modifier-key state. A generic click has no independent postcondition read-back, except selection of list-like AX rows whose AXSelected state can be confirmed; otherwise confirm the effect from a fresh state snapshot. Use the agent loop: background AX (element_token) → snapshot → background pixel (x/y) → snapshot → delivery_mode:\"foreground\".","enum":["background","foreground"],"type":"string"},"element_token":{"description":"Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.","type":"string"},"from_zoom":{"description":"When true, x and y are in the last zoom image for this pid; driver translates back to full-window coordinates.","type":"boolean"},"modifier":{"description":"Modifier keys: cmd, shift, option/alt, ctrl.","items":{"type":"string"},"type":"array"},"pid":{"description":"Target process ID.","type":"integer"},"scope":{"description":"Coordinate frame for a windowless screen-absolute click (default \"window\"). Pass \"desktop\" when sending x,y with NO pid/window_id — the coordinates are then true screen pixels (read from get_desktop_state with scope=\"desktop\"). Per-call; not a setting.","enum":["window","desktop"],"type":"string"},"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"},"target":{"description":"Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.","oneOf":[{"additionalProperties":true,"properties":{"kind":{"const":"window","type":"string"},"pid":{"minimum":0,"type":"integer"},"window_id":{"minimum":0,"type":"integer"}},"required":["kind","pid","window_id"],"type":"object"},{"additionalProperties":true,"properties":{"display_id":{"type":"string"},"kind":{"const":"desktop","type":"string"}},"required":["kind","display_id"],"type":"object"}]},"window_id":{"description":"Target window ID. Omit when element_token is supplied (the token carries it).","type":"integer"},"x":{"description":"X in screenshot pixels. A window target uses the get_window_state PNG; a desktop target uses the native get_desktop_state PNG. The driver reverses Retina backing scale and any window-image downscale.","type":"number"},"y":{"description":"Y in screenshot pixels from the image selected by target.","type":"number"}},"required":[],"type":"object"},"name":"click","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.pointer.click","input.pointer.click.left","input.pointer.click.double","accessibility.element_tokens","input.delivery_mode"],"description":"Double-click at (x, y) or on an AX element identified by element_token.\n\nAX path (element_token provided): performs `AXOpen` when the element advertises it (Finder items, openable list rows/cells); otherwise resolves the element's on-screen center and falls back to a pixel double-click there.\n\nPixel path (x, y provided): two down/up pairs ~80 ms apart at the given coordinates.","inputSchema":{"additionalProperties":false,"properties":{"delivery_mode":{"description":"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.","enum":["background","foreground"],"type":"string"},"element_token":{"description":"Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.","type":"string"},"pid":{"type":"integer"},"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"},"window_id":{"description":"CGWindowID. Omit when element_token is supplied (the token carries it).","type":"integer"},"x":{"description":"Screen X coordinate (pixel path).","type":"number"},"y":{"description":"Screen Y coordinate (pixel path).","type":"number"}},"required":["pid"],"type":"object"},"name":"double_click","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.pointer.click","input.pointer.click.right","accessibility.element_tokens","input.delivery_mode"],"description":"Right-click against a target pid. Two addressing modes:\n\n- `element_token` (from the last `get_window_state` snapshot) — performs `AXShowMenu` on the cached element. Pure AX RPC, works on backgrounded / hidden windows, no cursor move or focus steal. Requires a prior `get_window_state(pid, window_id)` in this turn.\n\n- `x`, `y` — synthesizes `rightMouseDown` / `rightMouseUp` CGEvent pair posted to the pid. Driver converts image-pixel → screen-point internally. `modifier` forces the CGEvent path (AX actions don't propagate modifier keys).\n\nExactly one of `element_token` or (`x` AND `y`) must be provided. `pid` always required.","inputSchema":{"additionalProperties":false,"properties":{"delivery_mode":{"description":"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.","enum":["background","foreground"],"type":"string"},"element_token":{"description":"Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.","type":"string"},"modifier":{"description":"Modifier keys held during the right-click: cmd/shift/option/ctrl. Pixel path only.","items":{"type":"string"},"type":"array"},"pid":{"description":"Target process ID.","type":"integer"},"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"},"window_id":{"description":"CGWindowID. Omit when element_token is supplied (the token carries it).","type":"integer"},"x":{"description":"X in window-local screenshot pixels. Must be provided together with y.","type":"number"},"y":{"description":"Y in window-local screenshot pixels. Must be provided together with x.","type":"number"}},"required":["pid"],"type":"object"},"name":"right_click","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.pointer.drag","input.delivery_mode"],"description":"Press-drag-release gesture from (from_x, from_y) to (to_x, to_y) in window-local screenshot pixels — the same space get_window_state returns. Top-left origin of the target's window.\n\nUse for: marquee/lasso selection, drag-and-drop, resizing via a handle, scrubbing a slider, repositioning a panel.\n\n`duration_ms` (default 500) is the wall-clock budget for the path between mouse-down and mouse-up; `steps` (default 20) is the number of intermediate mouseDragged events linearly interpolated along the path. Increase both for slower, more human drags; decrease for snap gestures.\n\n`modifier` keys (cmd/shift/option/ctrl) are held across the entire gesture.\n\nWhen `from_zoom` is true, coordinates are in the last zoom image for this pid; the driver maps them back to window coordinates before dispatching.","inputSchema":{"additionalProperties":false,"properties":{"button":{"description":"Mouse button used for the drag. Default: left.","enum":["left","right","middle"],"type":"string"},"delivery_mode":{"description":"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.","enum":["background","foreground"],"type":"string"},"duration_ms":{"description":"Wall-clock duration of the drag path between mouseDown and mouseUp. Default: 500.","maximum":10000,"minimum":0,"type":"integer"},"from_x":{"description":"Drag-start X in window-local screenshot pixels. Top-left origin.","type":"number"},"from_y":{"description":"Drag-start Y in window-local screenshot pixels. Top-left origin.","type":"number"},"from_zoom":{"description":"When true, coordinates are in the last zoom image for this pid; driver maps back to window coordinates.","type":"boolean"},"modifier":{"description":"Modifier keys held across the entire gesture: cmd/shift/option/ctrl.","items":{"type":"string"},"type":"array"},"pid":{"description":"Target process ID.","type":"integer"},"scope":{"default":"window","description":"Use desktop with no pid/window_id for native get_desktop_state screenshot coordinates.","enum":["window","desktop"],"type":"string"},"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":"Number of intermediate mouseDragged events linearly interpolated along the path. Default: 20.","maximum":200,"minimum":1,"type":"integer"},"target":{"anyOf":[{"description":"Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.","oneOf":[{"additionalProperties":true,"properties":{"kind":{"const":"window","type":"string"},"pid":{"minimum":0,"type":"integer"},"window_id":{"minimum":0,"type":"integer"}},"required":["kind","pid","window_id"],"type":"object"},{"additionalProperties":true,"properties":{"display_id":{"type":"string"},"kind":{"const":"desktop","type":"string"}},"required":["kind","display_id"],"type":"object"}]},{"type":"null"}]},"to_x":{"description":"Drag-end X in window-local screenshot pixels.","type":"number"},"to_y":{"description":"Drag-end Y in window-local screenshot pixels.","type":"number"},"window_id":{"description":"CGWindowID for the window the pixel coordinates were measured against. Optional only when pid owns exactly one eligible top-level window; otherwise the action refuses with ambiguous_window_target.","type":"integer"}},"required":["from_x","from_y","to_x","to_y"],"type":"object"},"name":"drag","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.keyboard.type","input.keyboard.type.terminal_safe","accessibility.element_tokens","input.delivery_mode"],"description":"Insert text into the target pid via `AXSetAttribute(kAXSelectedText)`. Works for standard Cocoa text fields and text views. No keystrokes are synthesized — special keys (Return / Escape / arrows) go through `press_key` / `hotkey`. For Chromium / Electron inputs that don't implement `kAXSelectedText`, the tool falls back to CGEvent character synthesis automatically when the estimated route stays within the daemon transport budget. Longer synthesized routes are refused before character events and return a safe chunk size; one-call AX insertion remains uncapped.\n\nOptional `element_token` (from the last `get_window_state` snapshot) directs the write to a specific field. Without `element_token`, the write goes to the pid's currently focused element.\n\nWEB CONTENT (Chromium/WebKit/Electron — browser tabs, Slack, VS Code, X's compose box): AXValue is not independent proof that the renderer/DOM observed an AX write or synthesized keystrokes. The driver detects this at the element level (an AXWebArea ancestor) and refuses to trust AXValue-only read-back there. Electron AX targets that are web content or cannot be proven native refuse background delivery before mutation because the AX route cannot establish exact renderer focus; use the px form or explicit foreground delivery. Other web-content paths return effect:\"unverifiable\" + escalation, never a false \"confirmed\" (a browser's own native address bar/toolbar stays trusted). For a browser TAB the reliable path is the `page` tool (drives the DOM via CDP); for an embedded web view use this tool's px form: pass x,y (no element_token) to pixel-click the field then type, in one call. NOTE: a px focus-click won't reliably open+focus a CLOSED control; AX-press to open/activate it first (works in the background), then px-type. Always confirm via the screenshot; if px-background still drops, escalate to delivery_mode:\"foreground\".","inputSchema":{"additionalProperties":false,"properties":{"delay_ms":{"description":"Milliseconds between characters in the CGEvent fallback path. Default 30. Ignored when the AX path succeeds.","maximum":200,"minimum":0,"type":"integer"},"delivery_mode":{"description":"Best-effort-background ladder rung (default \"background\"). \"background\": AX insert, then CGEvent keystrokes if needed — no focus steal; native controls can be confirmed via AXValue read-back, while web-content writes remain effect:\"unverifiable\". \"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 remains unverifiable and a fresh snapshot shows the text did not appear.","enum":["background","foreground"],"type":"string"},"element_token":{"description":"Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.","type":"string"},"pid":{"description":"Target process ID.","type":"integer"},"scope":{"default":"window","description":"Use desktop with no pid/window_id to type into the frontmost application.","enum":["window","desktop"],"type":"string"},"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"},"target":{"anyOf":[{"description":"Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.","oneOf":[{"additionalProperties":true,"properties":{"kind":{"const":"window","type":"string"},"pid":{"minimum":0,"type":"integer"},"window_id":{"minimum":0,"type":"integer"}},"required":["kind","pid","window_id"],"type":"object"},{"additionalProperties":true,"properties":{"display_id":{"type":"string"},"kind":{"const":"desktop","type":"string"}},"required":["kind","display_id"],"type":"object"}]},{"type":"null"}]},"text":{"description":"Text to insert at the target's cursor.","type":"string"},"window_id":{"description":"CGWindowID. Omit when element_token is supplied (the token carries it).","type":"integer"},"x":{"description":"Screenshot-pixel X of the field to type into — the element px action form. Pass x,y (no element_token) and the tool pixel-clicks there to establish real renderer focus, then types. Use for Chromium/Electron inputs the AX path can't reach. Read straight off the get_window_state PNG, same convention as click.","type":"number"},"y":{"description":"Screenshot-pixel Y of the field (see x).","type":"number"}},"required":["text"],"type":"object"},"name":"type_text","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.keyboard.press","accessibility.element_tokens","input.delivery_mode"],"description":"Press and release a single key. Follows the same `delivery_mode` ladder as click/type_text — it does NOT raise the window by default:\n• `background` (default): post to the pid WITHOUT fronting/raising — the auth-message path (Chromium-safe). With element_token it focuses that AX element first. `window_id` only targets; it does not raise.\n• `foreground`: guard and briefly front the exact window, focus an addressed AX element when supplied, send a genuine HID key transition so Chromium content, inline editors, and native menu equivalents receive it, then restore prior frontmost. Requires window_id.\n\nA key press is confirmed only when a bounded native AX value/selection read-back changes on the same control. Otherwise a successfully attempted post remains effect:\"unverifiable\" without implying delivery failure or recommending foreground. Key names: return, tab, escape, up/down/left/right, space, delete, home, end, pageup, pagedown, f1-f12, plus any letter or digit. Modifiers array: cmd, shift, option/alt, ctrl, fn.","inputSchema":{"additionalProperties":false,"properties":{"delivery_mode":{"description":"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.","enum":["background","foreground"],"type":"string"},"element_token":{"description":"Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.","type":"string"},"key":{"description":"Key name: return, tab, escape, up, down, etc.","type":"string"},"modifiers":{"description":"Modifier keys: cmd, shift, option/alt, ctrl, fn.","items":{"type":"string"},"type":"array"},"pid":{"type":"integer"},"scope":{"default":"window","description":"Use desktop with no pid/window_id to send the key to the frontmost application.","enum":["window","desktop"],"type":"string"},"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"},"target":{"anyOf":[{"description":"Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.","oneOf":[{"additionalProperties":true,"properties":{"kind":{"const":"window","type":"string"},"pid":{"minimum":0,"type":"integer"},"window_id":{"minimum":0,"type":"integer"}},"required":["kind","pid","window_id"],"type":"object"},{"additionalProperties":true,"properties":{"display_id":{"type":"string"},"kind":{"const":"desktop","type":"string"}},"required":["kind","display_id"],"type":"object"}]},{"type":"null"}]},"window_id":{"description":"Target window. Required for delivery_mode:\"foreground\". Does NOT itself raise the window — raising is gated on delivery_mode.","type":"integer"},"x":{"description":"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_token.","type":"number"},"y":{"description":"Screenshot-pixel Y (see x).","type":"number"}},"required":["key"],"type":"object"},"name":"press_key","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.keyboard.hotkey","input.delivery_mode"],"description":"Press a key combination — e.g. `[\"cmd\", \"c\"]` for Copy, `[\"cmd\", \"shift\", \"4\"]` for screenshot selection. Follows the same `delivery_mode` ladder as click/type_text — it does NOT raise the window by default:\n• `background` (default): post the combo to the target pid WITHOUT fronting or raising it — uses the macOS 14+ auth-message envelope so Chromium/Electron accept it as trusted live input. With an AX target, focus that exact element first. No top-level focus steal. `window_id` here only targets the combo; it does not raise.\n• `foreground`: briefly front the window (NSMenu path, < 1 ms via SLPSSetFrontProcessWithOptions) so native menu key-equivalents (Cmd+Z, Cmd+W) dispatch, then restore the prior frontmost — the explicit escalation for menu-bar shortcuts on non-Chromium apps that ignore a background combo. With an AX target or x,y, the focused field receives the chord through the foreground HID queue (needed by native Chromium fields such as the omnibox). Requires window_id.\n\nA combo is never driver-verifiable (no read-back) → effect:\"unverifiable\"; confirm via screenshot. NOTE: a keyboard combo does NOT focus a text field — to type into a backgrounded Electron input, establish real renderer focus with a PIXEL click first, then `type_text`. If an app only accepts paste, call `clipboard_write`, then `clipboard_read` and verify its types (and text when applicable) before selecting or replacing editor content; only then send Cmd+V.\n\nRecognized modifiers: cmd/command, shift, option/alt, ctrl/control, fn. Non-modifier keys use the same vocabulary as `press_key`. Order: modifiers first, one non-modifier last.","inputSchema":{"additionalProperties":false,"properties":{"delivery_mode":{"description":"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.","enum":["background","foreground"],"type":"string"},"element_token":{"description":"Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.","type":"string"},"keys":{"description":"Modifier(s) and one non-modifier key, e.g. [\"cmd\", \"c\"].","items":{"type":"string"},"minItems":2,"type":"array"},"pid":{"description":"Target process ID.","type":"integer"},"scope":{"default":"window","description":"Use desktop with no pid/window_id to send the chord to the frontmost application.","enum":["window","desktop"],"type":"string"},"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"},"target":{"anyOf":[{"description":"Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.","oneOf":[{"additionalProperties":true,"properties":{"kind":{"const":"window","type":"string"},"pid":{"minimum":0,"type":"integer"},"window_id":{"minimum":0,"type":"integer"}},"required":["kind","pid","window_id"],"type":"object"},{"additionalProperties":true,"properties":{"display_id":{"type":"string"},"kind":{"const":"desktop","type":"string"}},"required":["kind","display_id"],"type":"object"}]},{"type":"null"}]},"window_id":{"description":"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.","type":"integer"},"x":{"description":"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.","type":"number"},"y":{"description":"Screenshot-pixel Y (see x).","type":"number"}},"required":["keys"],"type":"object"},"name":"hotkey","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.keyboard.type","accessibility.element_tokens"],"description":"Set a value on a UI element. Two modes depending on element role:\n\n- **AXPopUpButton / select dropdown**: finds the child option whose title or value matches `value` (case-insensitive) and AXPresses it directly — the native macOS popup menu is never opened, so focus is never stolen. Use this for HTML <select> elements in Safari or any native NSPopUpButton.\n\n- **All other elements**: writes AXValue directly (sliders, steppers, date pickers, native text fields that expose settable AXValue).\n\nFor free-form text entry into web inputs, prefer `type_text_chars` which synthesises key events — AXValue writes are ignored by WebKit.","inputSchema":{"additionalProperties":false,"properties":{"element_token":{"description":"Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.","type":"string"},"pid":{"type":"integer"},"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"},"value":{"description":"New value. AX will coerce to the element's native type.","type":"string"},"window_id":{"description":"CGWindowID. Omit when element_token is supplied (the token carries it).","type":"integer"}},"required":["pid","value"],"type":"object"},"name":"set_value","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"capabilities":["input.pointer.scroll","accessibility.element_tokens","input.delivery_mode"],"description":"Scroll the target pid. Two paths, picked by how you address the scroll:\n\n• **Targeted wheel path** — when you pass a target, either `element_token` (preferred) or window-local `x, y` pixels: the driver synthesizes a real mouse-wheel event (CGEventCreateScrollWheelEvent, at that screen point. The renderer hit-tests the wheel at the cursor, so the scroll lands on whatever element is under the point — exactly like physically rolling the wheel over it. This is the ONLY way to scroll a nested `overflow:auto` region (e.g. a scrollable <div> with no tabindex): such regions never take keyboard focus, so the keystroke path below no-ops on them. Use this for inner/nested scrollers in web views.\n\n• **Keystroke path (focused region)** — when you pass NO target (just pid + direction): synthesizes PageDown/PageUp (by='page') or Down/Up arrows (by='line'); horizontal uses Left/Right arrows. Drives the focused / page scroller only.\n\nMapping: by='page' → larger step; by='line' → smaller step; amount = number of wheel notches (targeted path) or keystroke repetitions (keystroke path).","inputSchema":{"additionalProperties":false,"properties":{"amount":{"description":"Pixel-wheel path: number of wheel notches. Keystroke path: number of keystroke repetitions. Larger requests are clamped to the maximum. Default: 3.","maximum":50,"minimum":1,"type":"integer"},"by":{"description":"Scroll granularity. Default: line.","enum":["line","page"],"type":"string"},"delivery_mode":{"description":"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.","enum":["background","foreground"],"type":"string"},"direction":{"description":"Scroll direction.","enum":["up","down","left","right"],"type":"string"},"element_token":{"description":"Opaque per-snapshot element handle from `structuredContent.elements[].element_token`. Returns an explicit stale error naming the current snapshots once a newer read supersedes it.","type":"string"},"pid":{"type":"integer"},"scope":{"default":"window","description":"Use desktop with x,y and no pid/window_id for native get_desktop_state screenshot coordinates.","enum":["window","desktop"],"type":"string"},"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"},"target":{"anyOf":[{"description":"Exact capture/input target selected independently for each action.\n\n`display_id=\"primary\"` is the portable desktop target in this release.\nPlatforms that cannot address another display reject it explicitly rather\nthan silently changing coordinate spaces.","oneOf":[{"additionalProperties":true,"properties":{"kind":{"const":"window","type":"string"},"pid":{"minimum":0,"type":"integer"},"window_id":{"minimum":0,"type":"integer"}},"required":["kind","pid","window_id"],"type":"object"},{"additionalProperties":true,"properties":{"display_id":{"type":"string"},"kind":{"const":"desktop","type":"string"}},"required":["kind","display_id"],"type":"object"}]},{"type":"null"}]},"window_id":{"type":"integer"},"x":{"description":"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.","type":"number"},"y":{"description":"Window-local screenshot Y. See `x`.","type":"number"}},"required":["direction"],"type":"object"},"name":"scroll","outputSchema":{"anyOf":[{"additionalProperties":false,"properties":{"delivery":{"additionalProperties":false,"properties":{"delivered_count":{"minimum":0,"type":["integer","null"]},"mode":{"enum":["background","foreground","not_applicable","unknown"],"type":"string"}},"required":["mode"],"type":["object","null"]},"effect":{"enum":["confirmed","partial","unverifiable","suspected_noop","refused"],"type":"string"},"error":{"additionalProperties":false,"properties":{"code":{"type":"string"},"hint":{"type":["string","null"]}},"required":["code"],"type":["object","null"]},"escalation":{"additionalProperties":false,"properties":{"reason":{"enum":["route_unavailable","delivery_failed","effect_unconfirmed","suspected_noop","permission_required"],"type":"string"},"target":{"enum":["pixel","foreground","page","session"],"type":"string"}},"required":["target","reason"],"type":["object","null"]},"evidence":{"items":{"additionalProperties":false,"properties":{"detail":{"type":["string","null"]},"kind":{"enum":["value_readback","window_change"],"type":"string"}},"required":["kind"],"type":"object"},"type":["array","null"]},"route":{"enum":["accessibility","synthetic_events","global_input","system_api","dom","trusted_input"],"type":"string"},"summary":{"type":["string","null"]}},"required":["effect","route"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":true},"capabilities":["clipboard.read","clipboard.types"],"description":"List available system clipboard types and optionally return privacy-sensitive plain text. Clipboard content is never retained in telemetry.","inputSchema":{"additionalProperties":false,"properties":{"include_text":{"default":false,"description":"Return plain-text clipboard content in addition to the available types.\nClipboard content is privacy-sensitive and is never retained in telemetry.","type":"boolean"},"session":{"description":"For multi-call work, prefer a short public session label and repeat it on every call that\naccepts it. Omit it to use the authenticated transport's implicit lifecycle session.","type":"string"}},"required":[],"type":"object"},"name":"clipboard_read","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"content_redacted_from_telemetry":{"type":"boolean"},"privacy_sensitive":{"type":"boolean"},"supported":{"type":"boolean"},"text":{"anyOf":[{"type":"string"},{"type":"null"}]},"types":{"items":{"type":"string"},"type":"array"}},"required":["supported","types","text","privacy_sensitive","content_redacted_from_telemetry"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r2","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"capabilities":["clipboard.write","clipboard.write.text","clipboard.write.image","clipboard.write.file_url","clipboard.types"],"description":"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. Returns the available types for read-back before paste.","inputSchema":{"additionalProperties":false,"properties":{"file_path":{"description":"Absolute path to a local file to place on the clipboard as a file URL.","type":"string"},"image_path":{"description":"Absolute path to a local image to place on the clipboard.","type":"string"},"session":{"description":"For multi-call work, prefer a short public session label and repeat it on every call that\naccepts it. Omit it to use the authenticated transport's implicit lifecycle session.","type":"string"},"text":{"description":"Plain text to place on the clipboard.","type":"string"}},"required":[],"type":"object"},"name":"clipboard_write","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"content_redacted_from_telemetry":{"type":"boolean"},"privacy_sensitive":{"type":"boolean"},"supported":{"type":"boolean"},"types":{"items":{"type":"string"},"type":"array"},"written_type":{"type":"string"}},"required":["supported","written_type","types","privacy_sensitive","content_redacted_from_telemetry"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"active","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":["screen.dimensions"],"description":"Return the logical size of the main display in points plus its backing scale factor. Agents click in points; Retina displays have scale_factor 2.0. Requires no TCC permissions.","inputSchema":{"additionalProperties":false,"properties":{"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"}},"type":"object"},"name":"get_screen_size","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"height":{"type":"number"},"scale_factor":{"type":"number"},"width":{"type":"number"}},"required":["width","height","scale_factor"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r0","enforcement":"metadata_only","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":true},"capabilities":["screen.capture","screen.dimensions"],"description":"Capture the full display in true screen pixels, full size unless `max_image_dimension` caps it. Use its PNG as the coordinate source for actions whose target is {kind:\"desktop\",display_id:\"primary\"}. Returns the true screen size and backing scale factor. Vision-only: no AX tree walk.","inputSchema":{"additionalProperties":false,"properties":{"max_image_dimension":{"description":"Optional long-edge cap for the returned PNG, in pixels (aspect ratio preserved). Omitted or 0 returns the full-size capture. When the cap downsizes the image, the response reports `screenshot_original_width/height`, and x/y read off it for this session's later scope:\"desktop\" actions (or passed with its `capture_id`) are mapped back to the full-size frame automatically.","minimum":0,"type":"integer"},"screenshot_out_file":{"description":"Write PNG here instead of base64.","type":"string"},"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"}},"type":"object"},"name":"get_desktop_state","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"agent_overlay_capture":{"additionalProperties":false,"properties":{"method":{"type":["string","null"]},"reason":{"type":["string","null"]},"status":{"oneOf":[{"const":"excluded","type":"string"},{"const":"not_present","type":"string"},{"const":"not_excluded","type":"string"}]}},"required":["status"],"type":["object","null"]},"display":{"type":"string"},"platform":{"enum":["macos","linux","windows"],"type":"string"},"scale_factor":{"type":"number"},"screen_height":{"type":"integer"},"screen_width":{"type":"integer"},"screenshot_file_path":{"type":"string"},"screenshot_height":{"type":"integer"},"screenshot_mime_type":{"const":"image/png"},"screenshot_width":{"type":"integer"}},"required":["platform","display","screenshot_width","screenshot_height","screen_width","screen_height","scale_factor","screenshot_mime_type"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r3","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":["screen.cursor.position"],"description":"Return the current mouse cursor position in screen points (origin top-left).","inputSchema":{"additionalProperties":false,"properties":{"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"}},"type":"object"},"name":"get_cursor_position","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"available":{"type":"boolean"},"source":{"type":"string"},"x":{"type":"number"},"y":{"type":"number"}},"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r0","enforcement":"metadata_only","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":[],"description":"Single-call end-to-end driver diagnostics. Designed to let downstream consumers ship one stable call instead of stitching together check_permissions, doctor, version, bundle attribution, and platform capability status. On macOS, prompt-capable direct capture is deliberately skipped; use `cua-driver permissions grant` to verify it explicitly. cua-driver owns the health model; consumers stay thin.\n\nInput — all optional:\n {\n \"include\": [\"<check_name>\", ...], // run only these\n \"skip\": [\"<check_name>\", ...] // skip these\n }\nIf both are given, `include` wins.\n\nCanonical check names:\n macOS : binary_version, platform_supported, session_active,\n bundle_identity, tcc_accessibility, tcc_screen_recording,\n ax_capability, screen_capture_capability\n Windows: binary_version, platform_supported, session_active,\n ax_capability (via UIA), screen_capture_capability (via DXGI)\n Linux : binary_version, platform_supported, session_active,\n ax_capability (via AT-SPI), screen_capture_capability (via X11)\n\nOutput — stable contract, schema_version=\"1\":\n {\n \"schema_version\": \"1\",\n \"platform\": \"darwin\" | \"win32\" | \"linux\",\n \"driver_version\": \"<semver>\",\n \"overall\": \"ok\" | \"degraded\" | \"failed\",\n \"checks\": [\n {\n \"name\": \"<one of the canonical names above>\",\n \"status\": \"pass\" | \"fail\" | \"skip\",\n \"message\": \"<one-line summary, always present>\",\n \"hint\": \"<remediation step, present when status=fail>\",\n \"data\": { /* check-specific structured fields */ }\n },\n ...\n ]\n }\n\n`overall` rules:\n - `ok` — every non-skipped check passes\n - `degraded` — at least one non-core check fails (binary is still usable)\n - `failed` — any core check fails (binary_version, platform_supported, session_active)\n\nStability: schema_version=\"1\" is the contract. Future breaking changes will be `\"2\"`. Adding new check names under the same schema_version is non-breaking; consumers must tolerate unknown check names.","inputSchema":{"additionalProperties":false,"properties":{"include":{"description":"Only run these checks (canonical names). Wins over `skip`.","items":{"type":"string"},"type":"array"},"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"},"skip":{"description":"Skip these checks (canonical names). Ignored when `include` is set.","items":{"type":"string"},"type":"array"}},"type":"object"},"name":"health_report","risk":{"class":"r0","enforcement":"metadata_only","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":["accessibility.tree","accessibility.tree.structured"],"description":"Return a lightweight snapshot of the desktop: running regular apps and on-screen visible windows with their bounds, z-order, and owner pid.\n\nFor the full AX subtree of a single window (with interactive element indices you can click by), use `get_window_state` instead — that's the heavy per-window tool. This one is a fast discovery read that needs no TCC grants.","inputSchema":{"additionalProperties":false,"properties":{"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"}},"type":"object"},"name":"get_accessibility_tree","risk":{"class":"r2","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":["screen.capture","screen.capture.window","screen.capture.region"],"description":"Capture a cropped JPEG of a window region (x1,y1)–(x2,y2) in screenshot pixel coordinates, with 20% padding added on each side. The output image is at most 500 px wide.\n\nAfter a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordinates back to full-window space. Coordinate actions return `screenshot_context_missing` when no current snapshot contains a screenshot owned by this session. `from_zoom` actions return `zoom_context_missing` when the zoom was never created or was replaced; call `get_window_state`, then `zoom`, again on the same connection.","inputSchema":{"additionalProperties":false,"properties":{"pid":{"description":"Optional target pid. When omitted, the driver resolves the unique current snapshot for this session and window.","type":"integer"},"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"},"window_id":{"description":"CGWindowID from list_windows.","type":"integer"},"x1":{"description":"Left edge of region in screenshot pixels.","type":"number"},"x2":{"description":"Right edge of region in screenshot pixels.","type":"number"},"y1":{"description":"Top edge of region in screenshot pixels.","type":"number"},"y2":{"description":"Bottom edge of region in screenshot pixels.","type":"number"}},"required":["window_id","x1","y1","x2","y2"],"type":"object"},"name":"zoom","risk":{"class":"r2","enforcement":"active","operation_sensitive":true,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"capabilities":["session.lifecycle.start","session.capture_scope"],"description":"Optionally create or return a lifecycle session before acting. For multi-call work, prefer a short public `session` label and repeat it on every call that accepts it; an omitted value uses the authenticated transport lease's implicit session instead. This tool is optional because an ordinary action can create or reuse a named run directly. Use it to set the initial cursor theme before acting or to revive a public name after it has ended; ordinary actions never revive ended names. `capture_scope` is deprecated compatibility input; new callers select window or desktop modality per action. Idempotent.","inputSchema":{"additionalProperties":true,"properties":{"capture_scope":{"description":"Deprecated compatibility policy. New callers select window or desktop\nmodality on each action instead of storing it on the session.","enum":["auto","window","desktop"],"type":"string"},"cursor_theme":{"description":"Optional initial cursor theme. The host applies it before the cursor is\nfirst made visible, avoiding a flash of the default theme.","properties":{"reduced_motion":{"default":"auto","enum":["auto","on","off"],"type":"string"},"theme_id":{"type":"string"}},"required":["theme_id"],"type":["object","null"]},"session":{"description":"Optional stable public label for this run (e.g. \"research-run-1\").\nWhen omitted, the authenticated transport lease's implicit session is\ncreated or returned.","type":"string"}},"required":[],"type":"object"},"name":"start_session","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"active":{"type":"boolean"},"capture_scope":{"enum":["auto","window","desktop"],"type":"string"},"desktop_capture_authorized":{"type":"boolean"},"desktop_unlocked":{"type":"boolean"},"effective_scope":{"enum":["window","desktop"],"type":"string"},"escalation_detail":{"anyOf":[{"type":"string"},{"type":"null"}]},"escalation_reason":{"anyOf":[{"enum":["ax_tree_pixel_mismatch","background_delivery_failed","foreground_ineffective","no_window_target","other"],"type":"string"},{"type":"null"}]},"revived":{"type":"boolean"},"session":{"type":"string"}},"required":["session","capture_scope","effective_scope","desktop_capture_authorized","desktop_unlocked","escalation_reason","escalation_detail","active","revived"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"metadata_only","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":["session.lifecycle.read"],"description":"Read content-free lifecycle, cursor, recording, and idle status for one session visible to this authenticated transport. Omit `session` to inspect its implicit session.","inputSchema":{"additionalProperties":true,"properties":{"session":{"description":"Optional public label. When omitted, inspect the caller's attached\nimplicit session.","type":"string"}},"required":[],"type":"object"},"name":"get_session","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"client_kind":{"enum":["cli","direct","mcp","python_sdk","typescript_sdk"],"type":"string"},"cursor_visible":{"type":"boolean"},"expires_in_seconds":{"minimum":0,"type":"integer"},"idle_seconds":{"minimum":0,"type":"integer"},"implicit":{"type":"boolean"},"recording_active":{"type":"boolean"},"session":{"anyOf":[{"type":"string"},{"type":"null"}]},"state":{"enum":["active","ending"],"type":"string"},"transport":{"enum":["cli","daemon","mcp_stdio","mcp_http"],"type":"string"}},"required":["session","implicit","state","client_kind","transport","cursor_visible","recording_active","idle_seconds","expires_in_seconds"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r0","enforcement":"metadata_only","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"capabilities":["session.lifecycle.list"],"description":"List content-free lifecycle summaries attached to this authenticated transport lease. It does not enumerate other callers' sessions.","inputSchema":{"additionalProperties":true,"properties":{"cursor":{"description":"Opaque continuation cursor returned by a previous call.","type":"string"},"limit":{"description":"Maximum number of content-free summaries to return (default 50, max\n100). Ordinary agent transports are scoped to their own lease.","minimum":0,"type":["integer","null"]}},"required":[],"type":"object"},"name":"list_sessions","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"next_cursor":{"anyOf":[{"type":"string"},{"type":"null"}]},"sessions":{"items":{"properties":{"client_kind":{"enum":["cli","direct","mcp","python_sdk","typescript_sdk"],"type":"string"},"cursor_visible":{"type":"boolean"},"expires_in_seconds":{"minimum":0,"type":"integer"},"idle_seconds":{"minimum":0,"type":"integer"},"implicit":{"type":"boolean"},"recording_active":{"type":"boolean"},"session":{"anyOf":[{"type":"string"},{"type":"null"}]},"state":{"enum":["active","ending"],"type":"string"},"transport":{"enum":["cli","daemon","mcp_stdio","mcp_http"],"type":"string"}},"required":["session","implicit","state","client_kind","transport","cursor_visible","recording_active","idle_seconds","expires_in_seconds"],"type":"object"},"type":"array"}},"required":["sessions","next_cursor"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r0","enforcement":"metadata_only","operation_sensitive":false,"version":"1"}},{"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"capabilities":["session.lifecycle.end"],"description":"End one visible lifecycle session and run its cursor, recording, configuration, and other cleanup hooks exactly once. Omit `session` to end the authenticated transport's implicit session. Idempotent.","inputSchema":{"additionalProperties":true,"properties":{"session":{"description":"Optional public label to end. When omitted, end the caller's attached\nimplicit session.","type":"string"}},"required":[],"type":"object"},"name":"end_session","outputSchema":{"anyOf":[{"additionalProperties":true,"properties":{"active":{"const":false},"session":{"type":"string"}},"required":["session","active"],"type":"object"},{"additionalProperties":true,"anyOf":[{"required":["refusal"]},{"required":["status"]},{"required":["code"]}],"type":"object"}],"type":"object"},"risk":{"class":"r1","enforcement":"metadata_only","operation_sensitive":false,"version":"1"}}]}
diff --git a/desktop/runtime-host/src/computer_use.rs b/desktop/runtime-host/src/computer_use.rs
index ab122b776..0814ee8a0 100644
--- a/desktop/runtime-host/src/computer_use.rs
+++ b/desktop/runtime-host/src/computer_use.rs
@@ -18,7 +18,7 @@ pub const COMPUTER_USE_STATE_FILE: &str = "computer-use.json";
pub const COMPUTER_USE_LOCK_FILE: &str = "computer-use.lock";
pub const COMPUTER_USE_SOCKET_FILE: &str = "cua-driver.sock";
pub const COMPUTER_USE_DRIVER_VERSION: &str = "0.31.0";
-pub const COMPUTER_USE_TOOL_SNAPSHOT_SHA256: &str = "4257e598f5a6ad7e632b48e96c03257d7c5ed618a93b72820b2d4fef0f196acf";
+pub const COMPUTER_USE_TOOL_SNAPSHOT_SHA256: &str = "4c6a9c351f9ead8dac182ee8b9e4bb2ec5b9f66f35e4d36373643792e97a8d67";
pub const RUNTIME_TOO_OLD_REASON: &str = "runtime_too_old";
pub const RUNTIME_UNAVAILABLE_REASON: &str = "runtime_unavailable";
pub const FAILURE_LIMIT: usize = 3;
diff --git a/desktop/scripts/prepare-cua-driver.py b/desktop/scripts/prepare-cua-driver.py
index 42ccdfab3..114b61201 100644
--- a/desktop/scripts/prepare-cua-driver.py
+++ b/desktop/scripts/prepare-cua-driver.py
@@ -69,7 +69,8 @@ def load_manifest(path: Path = SOURCES) -> dict:
or driver["patch"].get("file")
!= "patches/0001-macos-raw-single-click.patch"
or SHA256.fullmatch(str(driver["patch"].get("sha256"))) is None
- or driver["patch"].get("contract") != "click.click_mode=raw"
+ or driver["patch"].get("contract")
+ != "click.click_mode=raw; embedded parent-liveness cleanup"
or not isinstance(driver["patch"].get("upstream_refs"), list)
or not driver["patch"]["upstream_refs"]
or not isinstance(driver["patch"].get("upgrade_plan"), str)
diff --git a/desktop/src-tauri/src/computer_use.rs b/desktop/src-tauri/src/computer_use.rs
index 15588844d..633e31917 100644
--- a/desktop/src-tauri/src/computer_use.rs
+++ b/desktop/src-tauri/src/computer_use.rs
@@ -744,18 +744,10 @@ impl RuntimeState {
}
async fn stop_daemon(&mut self) {
- let Some(mut daemon) = self.daemon.take() else {
+ let Some(daemon) = self.daemon.take() else {
return;
};
- drop(daemon.stdin.take());
- if timeout(PROCESS_STOP_TIMEOUT, daemon.child.wait()).await.is_err() {
- let _ = daemon.child.kill().await;
- let _ = daemon.child.wait().await;
- }
- if let Ok(Ok(stderr_tail)) = timeout(PROCESS_STOP_TIMEOUT, daemon.stderr_tail).await {
- record_daemon_stderr(&self.diagnostics, &stderr_tail);
- }
- let _ = std::fs::remove_file(&self.paths.socket);
+ stop_daemon_process(daemon, &self.paths.socket, &self.diagnostics, PROCESS_STOP_TIMEOUT).await;
}
async fn start_permission_probe(&mut self) {
@@ -1001,6 +993,56 @@ async fn socket_accepts(path: &Path) -> bool {
.is_ok_and(|result| result.is_ok())
}
+async fn request_daemon_shutdown(socket: &Path, pid: u32) -> io::Result<()> {
+ let stream = tokio::net::UnixStream::connect(socket).await?;
+ let (reader, mut writer) = stream.into_split();
+ write_json_line(
+ &mut writer,
+ &json!({
+ "method": "shutdown_if_pid",
+ "args": {"expected_pid": pid},
+ }),
+ )
+ .await?;
+ let mut reader = BufReader::new(reader);
+ let mut line = String::new();
+ if reader.read_line(&mut line).await? == 0 {
+ return Err(io::Error::new(
+ io::ErrorKind::UnexpectedEof,
+ "computer-use daemon closed the shutdown connection without a response",
+ ));
+ }
+ let response = serde_json::from_str::<Value>(&line).map_err(io::Error::other)?;
+ if response.get("ok").and_then(Value::as_bool) != Some(true) {
+ return Err(io::Error::other(
+ "computer-use daemon rejected the pid-bound shutdown request",
+ ));
+ }
+ Ok(())
+}
+
+async fn stop_daemon_process(mut daemon: Daemon, socket: &Path, diagnostics: &BootstrapLog, stop_timeout: Duration) {
+ let deadline = tokio::time::Instant::from_std(Instant::now() + stop_timeout);
+ let graceful_shutdown_requested = match daemon.child.id() {
+ Some(pid) => timeout_at(deadline, request_daemon_shutdown(socket, pid))
+ .await
+ .is_ok_and(|result| result.is_ok()),
+ None => false,
+ };
+ if !graceful_shutdown_requested {
+ drop(daemon.stdin.take());
+ }
+ if timeout_at(deadline, daemon.child.wait()).await.is_err() {
+ let _ = daemon.child.kill().await;
+ let _ = daemon.child.wait().await;
+ }
+ drop(daemon.stdin.take());
+ if let Ok(Ok(stderr_tail)) = timeout(stop_timeout, daemon.stderr_tail).await {
+ record_daemon_stderr(diagnostics, &stderr_tail);
+ }
+ let _ = std::fs::remove_file(socket);
+}
+
fn spawn_daemon(driver: &Path, socket: &Path, host_bundle_id: &str, policy: &Path) -> io::Result<Daemon> {
let mut command = driver_command(driver);
command
@@ -2249,6 +2291,28 @@ esac
path
}
+ fn write_graceful_daemon_driver(root: &Path, socket: &Path, request_path: &Path) -> PathBuf {
+ let path = root.join("fake-graceful-cua-driver");
+ let executable = std::env::current_exe().expect("current test executable");
+ let body = format!(
+ "#!/bin/sh\n\
+ AVIBE_TEST_GRACEFUL_DAEMON_CHILD=1 \\\n\
+ AVIBE_TEST_GRACEFUL_DAEMON_SOCKET={} \\\n\
+ AVIBE_TEST_GRACEFUL_DAEMON_REQUEST={} \\\n\
+ exec {} --exact computer_use::tests::intentional_stop_daemon_child --nocapture\n",
+ shell_quote(socket),
+ shell_quote(request_path),
+ shell_quote(&executable),
+ );
+ std::fs::write(&path, body).expect("fake graceful driver");
+ let mut permissions = std::fs::metadata(&path)
+ .expect("fake graceful driver metadata")
+ .permissions();
+ permissions.set_mode(0o755);
+ std::fs::set_permissions(&path, permissions).expect("fake graceful driver executable");
+ path
+ }
+
fn read_environment(path: &Path) -> BTreeMap<String, String> {
std::fs::read_to_string(path)
.unwrap_or_else(|error| panic!("{} is readable: {error}", path.display()))
@@ -2260,6 +2324,117 @@ esac
.collect()
}
+ fn pinned_shutdown_response(request: &Value, actual_pid: u32) -> (Value, bool) {
+ let expected_pid = request
+ .pointer("/args/expected_pid")
+ .and_then(Value::as_u64)
+ .and_then(|pid| u32::try_from(pid).ok())
+ .filter(|pid| *pid != 0);
+ let Some(expected_pid) = expected_pid else {
+ return (
+ json!({
+ "ok": false,
+ "error": "shutdown_if_pid requires a positive integer expected_pid",
+ "exit_code": 64,
+ }),
+ false,
+ );
+ };
+ if expected_pid != actual_pid {
+ return (
+ json!({
+ "ok": false,
+ "error": format!(
+ "daemon pid mismatch (expected {expected_pid}, found {actual_pid})"
+ ),
+ "exit_code": 1,
+ }),
+ false,
+ );
+ }
+ (json!({"ok": true, "result": {"shutdown": true}}), true)
+ }
+
+ #[test]
+ fn intentional_stop_pinned_shutdown_contract_rejects_legacy_pid_field() {
+ let (response, should_shutdown) = pinned_shutdown_response(
+ &json!({
+ "method": "shutdown_if_pid",
+ "args": {"pid": std::process::id()},
+ }),
+ std::process::id(),
+ );
+
+ assert!(!should_shutdown);
+ assert_eq!(response.get("ok").and_then(Value::as_bool), Some(false));
+ assert_eq!(response.get("exit_code").and_then(Value::as_u64), Some(64));
+ assert_eq!(
+ response.get("error").and_then(Value::as_str),
+ Some("shutdown_if_pid requires a positive integer expected_pid")
+ );
+ }
+
+ #[tokio::test]
+ async fn intentional_stop_daemon_child() {
+ if std::env::var_os("AVIBE_TEST_GRACEFUL_DAEMON_CHILD").is_none() {
+ return;
+ }
+ let socket = PathBuf::from(std::env::var_os("AVIBE_TEST_GRACEFUL_DAEMON_SOCKET").expect("socket path"));
+ let request_path = PathBuf::from(std::env::var_os("AVIBE_TEST_GRACEFUL_DAEMON_REQUEST").expect("request path"));
+ let listener = tokio::net::UnixListener::bind(&socket).expect("bind fake daemon");
+ let (stream, _) = listener.accept().await.expect("accept shutdown request");
+ let (reader, mut writer) = stream.into_split();
+ let mut reader = BufReader::new(reader);
+ let mut line = String::new();
+ assert_ne!(reader.read_line(&mut line).await.expect("read shutdown request"), 0);
+ let request: Value = serde_json::from_str(&line).expect("parse shutdown request");
+ assert_eq!(request.get("method").and_then(Value::as_str), Some("shutdown_if_pid"));
+ std::fs::write(&request_path, &line).expect("record shutdown request");
+ let (response, should_shutdown) = pinned_shutdown_response(&request, std::process::id());
+ write_json_line(&mut writer, &response)
+ .await
+ .expect("write pinned shutdown response");
+ if !should_shutdown {
+ let mut stdin = std::io::stdin();
+ let mut byte = [0_u8; 1];
+ let _ = stdin.read(&mut byte);
+ }
+ }
+
+ #[tokio::test]
+ async fn intentional_stop_requests_graceful_shutdown_before_closing_parent_liveness() {
+ let temporary = tempfile::tempdir().expect("temporary directory");
+ let socket = temporary.path().join("driver.sock");
+ let request_path = temporary.path().join("shutdown-request.json");
+ let policy = temporary.path().join("policy.yaml");
+ std::fs::write(&policy, "version: 1\n").expect("policy fixture");
+ let driver = write_graceful_daemon_driver(temporary.path(), &socket, &request_path);
+ let daemon =
+ spawn_daemon(&driver, &socket, "bot.avibe.desktop.test", &policy).expect("spawn graceful daemon fixture");
+ let daemon_pid = daemon.child.id().expect("spawned daemon pid");
+ let deadline = Instant::now() + Duration::from_secs(5);
+ while !socket.exists() {
+ assert!(Instant::now() < deadline, "timed out waiting for fake daemon socket");
+ sleep(Duration::from_millis(20)).await;
+ }
+
+ let diagnostics = BootstrapLog::at(temporary.path().join(BOOTSTRAP_LOG_NAME));
+ stop_daemon_process(daemon, &socket, &diagnostics, Duration::from_secs(3)).await;
+
+ let request: Value = serde_json::from_slice(&std::fs::read(&request_path).expect("graceful shutdown request"))
+ .expect("recorded request");
+ assert_eq!(request.get("method").and_then(Value::as_str), Some("shutdown_if_pid"));
+ assert_eq!(
+ request.pointer("/args/expected_pid").and_then(Value::as_u64),
+ Some(daemon_pid.into())
+ );
+ assert!(
+ request.pointer("/args/pid").is_none(),
+ "legacy pid field bypassed the pinned shutdown parser contract"
+ );
+ assert!(!socket.exists(), "stopped daemon socket survived cleanup");
+ }
+
fn assert_shared_driver_environment(environment: &BTreeMap<String, String>) {
for (name, expected) in [
("CUA_DRIVER_EMBEDDED", "1"),
diff --git a/tests/test_computer_server.py b/tests/test_computer_server.py
index 3b8e9fe76..ef1a3c9e0 100644
--- a/tests/test_computer_server.py
+++ b/tests/test_computer_server.py
@@ -215,12 +215,25 @@ class _BlockedStream:
return b""
+class _LinesStream:
+ def __init__(self, lines: list[bytes]) -> None:
+ self.lines = iter([*lines, b""])
+
+ async def readline(self) -> bytes:
+ return next(self.lines)
+
+
+class _RaisingStream:
+ async def readline(self) -> bytes:
+ raise RuntimeError("stream reader failed\nwith details")
+
+
class _TransportProcess:
- def __init__(self, stdout, *, stdin=None) -> None:
+ def __init__(self, stdout, *, stdin=None, stderr=None) -> None:
self.returncode = None
self.stdin = stdin or _TestStdin()
self.stdout = stdout
- self.stderr = _EofStream()
+ self.stderr = stderr or _EofStream()
async def wait(self) -> int:
self.returncode = 0
@@ -230,6 +243,116 @@ class _TransportProcess:
self.returncode = -9
+def _write_fake_mcp_proxy(path: Path) -> None:
+ path.write_text(
+ """#!/usr/bin/env python3
+import base64
+import json
+import sys
+
+
+def send(request_id, result):
+ print(
+ json.dumps(
+ {"jsonrpc": "2.0", "id": request_id, "result": result},
+ separators=(",", ":"),
+ ),
+ flush=True,
+ )
+
+
+for line in sys.stdin:
+ message = json.loads(line)
+ request_id = message.get("id")
+ if request_id is None:
+ continue
+ method = message.get("method")
+ if method == "initialize":
+ send(request_id, {"protocolVersion": "2025-06-18"})
+ continue
+ params = message.get("params") or {}
+ if method != "tools/call":
+ send(request_id, {})
+ continue
+ name = params.get("name")
+ arguments = params.get("arguments") or {}
+ if name == "start_session":
+ send(
+ request_id,
+ {
+ "content": [{"type": "text", "text": "session started"}],
+ "structuredContent": {"active": True},
+ },
+ )
+ continue
+ if name == "get_window_state" and arguments.get("window_id") == 6285:
+ send(
+ request_id,
+ {
+ "content": [
+ {
+ "type": "text",
+ "text": "simulated owner lookup failure from the driver",
+ }
+ ],
+ "structuredContent": {
+ "exit_code": 1,
+ "code": "tool_invocation_failed",
+ },
+ "isError": True,
+ },
+ )
+ continue
+ if name == "get_window_state":
+ label = "q" * 500
+ elements = [
+ {
+ "element_index": index,
+ "role": "group",
+ "label": label,
+ "depth": 1,
+ }
+ for index in range(330)
+ ]
+ tree_markdown = "\\n".join(
+ f"- [element_index {index}] group {label}" for index in range(330)
+ )
+ send(
+ request_id,
+ {
+ "content": [
+ {
+ "type": "image",
+ "data": base64.b64encode(b"p" * 900000).decode("ascii"),
+ "mimeType": "image/png",
+ }
+ ],
+ "structuredContent": {
+ "pid": arguments["pid"],
+ "window_id": arguments["window_id"],
+ "element_count": len(elements),
+ "elements": elements,
+ "tree_markdown": tree_markdown,
+ "screenshot_width": 1568,
+ "screenshot_height": 1442,
+ "screenshot_mime_type": "image/png",
+ },
+ },
+ )
+ continue
+ send(
+ request_id,
+ {
+ "content": [{"type": "text", "text": "unexpected tool"}],
+ "isError": True,
+ },
+ )
+""",
+ encoding="utf-8",
+ )
+ path.chmod(0o755)
+
+
def _acquire_lease_in_process(
directory: str,
session: str,
@@ -404,6 +527,392 @@ def test_result_folding_preserves_images_and_moves_structured_content() -> None:
assert "outputSchema" not in result
+def test_result_folding_preserves_driver_error_code_params_and_detail() -> None:
+ result = _fold_tool_result(
+ {
+ "result": {
+ "content": [{"type": "text", "text": "fallback driver text"}],
+ "structuredContent": {
+ "code": "capture_failed",
+ "params": {"scope": "window"},
+ "reason": "ScreenCaptureKit window was unavailable",
+ },
+ "isError": True,
+ }
+ }
+ )
+
+ payload = json.loads(result["content"][0]["text"])
+ assert payload == {
+ "code": "capture_failed",
+ "detail": "ScreenCaptureKit window was unavailable",
+ "params": {"scope": "window"},
+ }
+
+
+def test_result_folding_preserves_bounded_detail_inside_driver_params() -> None:
+ result = _fold_tool_result(
+ {
+ "result": {
+ "content": [{"type": "text", "text": "fallback driver text"}],
+ "structuredContent": {
+ "code": "capture_failed",
+ "params": {
+ "detail": "api_key=supersecretvalue123456\ncapture failed",
+ "scope": "window",
+ },
+ },
+ "isError": True,
+ }
+ }
+ )
+
+ payload = json.loads(result["content"][0]["text"])
+ assert payload == {
+ "code": "capture_failed",
+ "detail": "api_key=[redacted] capture failed",
+ "params": {
+ "detail": "api_key=[redacted] capture failed",
+ "scope": "window",
+ },
+ }
+ assert "supersecretvalue123456" not in result["content"][0]["text"]
+
+
+def test_result_folding_preserves_real_driver_exit_code_and_content_detail() -> None:
+ result = _fold_tool_result(
+ {
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": "window ownership lookup failed in the driver",
+ }
+ ],
+ "structuredContent": {
+ "exit_code": 1,
+ "code": "tool_invocation_failed",
+ },
+ "isError": True,
+ }
+ }
+ )
+
+ payload = json.loads(result["content"][0]["text"])
+ assert payload == {
+ "code": "tool_invocation_failed",
+ "detail": "window ownership lookup failed in the driver",
+ "params": {"exit_code": 1},
+ }
+
+
+def test_result_folding_uses_bounded_content_text_for_unstructured_driver_errors() -> None:
+ result = _fold_tool_result(
+ {
+ "result": {
+ "content": [
+ {"type": "text", "text": "driver detail\nwith \x00 controls"},
+ ],
+ "isError": True,
+ },
+ },
+ tool_name="get_window_state",
+ )
+
+ payload = json.loads(result["content"][0]["text"])
+ assert payload == {
+ "code": "upstream_tool_error",
+ "detail": "driver detail with controls",
+ "params": {"tool": "get_window_state"},
+ }
+
+
+def test_result_folding_preserves_json_rpc_error_code_and_detail() -> None:
+ result = _fold_tool_result(
+ {
+ "error": {
+ "code": -32001,
+ "message": "driver rejected request",
+ "data": {"reason": "window no longer exists"},
+ }
+ }
+ )
+
+ payload = json.loads(result["content"][0]["text"])
+ assert payload == {
+ "code": "upstream_error",
+ "detail": "driver rejected request",
+ "params": {"rpc_code": -32001},
+ }
+
+
+def test_diagnostic_text_is_bounded_and_single_line() -> None:
+ result = _fold_tool_result(
+ {
+ "result": {
+ "content": [
+ {"type": "text", "text": "\x1b[31m" + ("x" * 3_000)},
+ ],
+ "isError": True,
+ }
+ }
+ )
+
+ payload = json.loads(result["content"][0]["text"])
+ detail = payload["detail"]
+ assert len(detail) == 2048
+ assert "\n" not in detail
+ assert "\x1b" not in detail
+ assert detail.endswith("...")
+
+
+def test_driver_error_detail_redacts_credential_material() -> None:
+ result = _fold_tool_result(
+ {
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": "capture failed with api_key=supersecretvalue123456",
+ },
+ ],
+ "structuredContent": {
+ "code": "capture_failed",
+ "params": {"scope": "window"},
+ },
+ "isError": True,
+ }
+ }
+ )
+
+ payload = json.loads(result["content"][0]["text"])
+ assert payload == {
+ "code": "capture_failed",
+ "detail": "capture failed with api_key=[redacted]",
+ "params": {"scope": "window"},
+ }
+ assert "supersecretvalue123456" not in result["content"][0]["text"]
+
+
+def test_driver_error_detail_redacts_before_flattening_lines() -> None:
+ result = _fold_tool_result(
+ {
+ "result": {
+ "content": [
+ {
+ "type": "text",
+ "text": "api_key=supersecretvalue123456\ncapture failed",
+ },
+ ],
+ "isError": True,
+ }
+ }
+ )
+
+ payload = json.loads(result["content"][0]["text"])
+ assert payload["detail"] == "api_key=[redacted] capture failed"
+ assert "supersecretvalue123456" not in result["content"][0]["text"]
+
+
+async def test_upstream_stderr_and_malformed_json_are_logged(caplog: pytest.LogCaptureFixture) -> None:
+ caplog.set_level("WARNING", logger="core.computer_server")
+ upstream = JsonRpcUpstream(
+ _TransportProcess(
+ _LinesStream([b"{not-json\n"]),
+ stdin=_TestStdin(),
+ stderr=_LinesStream([b"driver stderr detail\n"]),
+ )
+ )
+
+ await asyncio.gather(upstream._reader_task, upstream._stderr_task)
+ assert "malformed JSON" in caplog.text
+ assert "driver stderr detail" in caplog.text
+ await upstream.close()
+
+
+async def test_upstream_diagnostic_logging_is_line_bounded(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ caplog.set_level("WARNING", logger="core.computer_server")
+ malformed = [f"malformed-{index:02d}\\n".encode() for index in range(25)]
+ stderr = [f"stderr-{index:02d}\\n".encode() for index in range(25)]
+ upstream = JsonRpcUpstream(
+ _TransportProcess(
+ _LinesStream(malformed),
+ stdin=_TestStdin(),
+ stderr=_LinesStream(stderr),
+ )
+ )
+
+ await asyncio.gather(upstream._reader_task, upstream._stderr_task)
+ assert "malformed-19" in caplog.text
+ assert "malformed-20" not in caplog.text
+ assert "stderr-19" in caplog.text
+ assert "stderr-20" not in caplog.text
+ assert caplog.text.count("further lines suppressed") == 2
+ await upstream.close()
+
+
+async def test_upstream_stderr_log_redacts_credential_material(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ caplog.set_level("WARNING", logger="core.computer_server")
+ upstream = JsonRpcUpstream(
+ _TransportProcess(
+ _EofStream(),
+ stdin=_TestStdin(),
+ stderr=_LinesStream(
+ [b"request failed with Authorization: Bearer tokenvalue1234\n"]
+ ),
+ )
+ )
+
+ await asyncio.gather(upstream._reader_task, upstream._stderr_task)
+ assert "Authorization: Bearer [redacted]" in caplog.text
+ assert "tokenvalue1234" not in caplog.text
+ await upstream.close()
+
+
+async def test_upstream_reader_exception_is_logged_and_preserved_for_pending_request(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ caplog.set_level("WARNING", logger="core.computer_server")
+ upstream = JsonRpcUpstream(
+ _TransportProcess(_RaisingStream(), stdin=_TestStdin())
+ )
+ with pytest.raises(UpstreamUnavailable, match="stream reader failed"):
+ await upstream.request("tools/call", {"name": "list_apps"})
+
+ assert "computer-use upstream reader failed" in caplog.text
+ assert "stream reader failed with details" in caplog.text
+ await upstream.close()
+
+
+async def test_upstream_reader_exception_redacts_detail_from_result_and_log(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ class _SecretRaisingStream:
+ async def readline(self) -> bytes:
+ raise RuntimeError("reader failed with api_key=supersecretvalue123456")
+
+ caplog.set_level("WARNING", logger="core.computer_server")
+ upstream = JsonRpcUpstream(
+ _TransportProcess(_SecretRaisingStream(), stdin=_TestStdin())
+ )
+ with pytest.raises(UpstreamUnavailable) as caught:
+ await upstream.request("tools/call", {"name": "list_apps"})
+
+ assert "api_key=[redacted]" in str(caught.value)
+ assert "supersecretvalue123456" not in str(caught.value)
+ assert "api_key=[redacted]" in caplog.text
+ assert "supersecretvalue123456" not in caplog.text
+ await upstream.close()
+
+
+async def test_call_tool_preserves_upstream_unavailable_detail_and_logs(
+ tmp_path: Path,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ caplog.set_level("WARNING", logger="core.computer_server")
+ state_path, state = _state(tmp_path)
+ upstream = FakeUpstream()
+ upstream.fail_transport = True
+ server = ComputerUseServer(
+ state_path=state_path,
+ status_reader=lambda: ComputerUseStatus("ready", None, state),
+ upstream_factory=lambda _state: asyncio.sleep(0, result=upstream),
+ lease_manager=FakeLeaseManager(), # type: ignore[arg-type]
+ )
+
+ result = await server.call_tool("list_apps", {"session": "ses-a"})
+ payload = json.loads(result["content"][0]["text"])
+ assert payload == {
+ "code": "upstream_unavailable",
+ "detail": "transport failed",
+ "params": {},
+ }
+ assert "transport failed" in caplog.text
+
+
+async def test_real_stdio_proxy_preserves_large_window_state_response(
+ tmp_path: Path,
+) -> None:
+ state_path, state = _state(tmp_path)
+ _write_fake_mcp_proxy(Path(state.proxy_executable))
+ server = ComputerUseServer(
+ state_path=state_path,
+ status_reader=lambda: ComputerUseStatus("ready", None, state),
+ )
+
+ try:
+ result = await server.call_tool(
+ "get_window_state",
+ {
+ "session": "ses-large-window",
+ "pid": 97470,
+ "window_id": 6286,
+ },
+ )
+ finally:
+ await server.close()
+
+ assert result.get("isError") is not True
+ image = next(item for item in result["content"] if item.get("type") == "image")
+ assert len(image["data"]) == 1_200_000
+ structured_text = next(
+ item["text"]
+ for item in result["content"]
+ if item.get("type") == "text"
+ and item.get("text", "").startswith("Structured content:\n")
+ )
+ payload = json.loads(structured_text.split("\n", 1)[1])
+ assert payload["pid"] == 97470
+ assert payload["window_id"] == 6286
+ assert payload["element_count"] == 330
+ assert len(payload["elements"]) == 330
+ assert len(payload["tree_markdown"]) > 165_000
+ assert payload["screenshot_width"] == 1568
+ assert payload["screenshot_height"] == 1442
+
+
+async def test_real_stdio_proxy_preserves_driver_failure_detail(
+ tmp_path: Path,
+) -> None:
+ state_path, state = _state(tmp_path)
+ _write_fake_mcp_proxy(Path(state.proxy_executable))
+ server = ComputerUseServer(
+ state_path=state_path,
+ status_reader=lambda: ComputerUseStatus("ready", None, state),
+ )
+
+ try:
+ result = await server.call_tool(
+ "get_window_state",
+ {
+ "session": "ses-driver-error",
+ "pid": 97470,
+ "window_id": 6285,
+ },
+ )
+ finally:
+ await server.close()
+
+ payload = json.loads(result["content"][0]["text"])
+ assert payload == {
+ "code": "tool_invocation_failed",
+ "detail": "simulated owner lookup failure from the driver",
+ "params": {"exit_code": 1},
+ }
+
+
@pytest.mark.asyncio
async def test_one_sessions_calls_are_serial_and_end_releases_after_queue(
tmp_path: Path,
@@ -703,6 +1212,7 @@ async def test_failed_explicit_start_does_not_change_committed_epoch(
payload = json.loads(result["content"][0]["text"])
assert payload == {
"code": "upstream_tool_error",
+ "detail": "tool failed",
"params": {"tool": "start_session"},
}
assert [params["name"] for _method, params in upstream.calls][-1] == "start_session"
diff --git a/tests/test_cua_driver_packaging.py b/tests/test_cua_driver_packaging.py
index c83c78fd2..cbdd5e149 100644
--- a/tests/test_cua_driver_packaging.py
+++ b/tests/test_cua_driver_packaging.py
@@ -33,7 +33,10 @@ def test_patched_source_manifest_hash_locks_the_divergence() -> None:
(Path("desktop/cua-driver") / manifest["tool_snapshot"]).read_text()
)
- assert driver["patch"]["contract"] == "click.click_mode=raw"
+ assert (
+ driver["patch"]["contract"]
+ == "click.click_mode=raw; embedded parent-liveness cleanup"
+ )
assert driver["patch"]["upstream_refs"]
assert driver["patch"]["upgrade_plan"]
assert _SCRIPT["digest"](patch) == driver["patch"]["sha256"]