Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(computer-use): add granted-control contracts and host refusals

vastsa49fad3fca1fb
diff --git a/crates/host-core/src/computer/backend.rs b/crates/host-core/src/computer/backend.rs
new file mode 100644
index 000000000..0c60932de
--- /dev/null
+++ b/crates/host-core/src/computer/backend.rs
@@ -0,0 +1,206 @@
+//! The platform contract for computer use, plus the fallback that exists on
+//! every target so an unimplemented platform is a refusal rather than a
+//! compile error or a silent no-op (ADR 0340 §11).
+//!
+//! A backend may only *attempt* work. It never decides whether a request is
+//! allowed: policy has already admitted the request by the time a backend sees
+//! it, and the grant's own re-measurement happens above this layer.
+
+use serde::{Deserialize, Serialize};
+
+use super::{Action, Capabilities, Fidelity, Node, PermissionState, Rect};
+
+/// A platform handle for one target. The renderer never receives one of these,
+/// and a caller cannot construct one: it only comes back from `list_targets`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct TargetRef {
+ /// Opaque, host-minted. Encodes the platform handle so a later call cannot
+ /// smuggle a different window in under a known id.
+ pub target_id: String,
+ pub pid: i32,
+ /// Platform window handle: CGWindowID, HWND, or X11 window id.
+ pub window: u64,
+ /// Bundle id, executable name, or WM class — whatever the platform proves.
+ pub app_key: String,
+}
+
+#[derive(Debug, Clone)]
+pub struct RawTarget {
+ pub target: TargetRef,
+ pub app_name: String,
+ pub title: String,
+ pub bounds: Rect,
+ /// Set when the platform itself knows the window cannot be driven, e.g. a
+ /// higher-integrity owner on Windows.
+ pub elevated: bool,
+}
+
+/// What a re-measurement found. `None` means the window is gone, which is a
+/// scope violation rather than an element error.
+#[derive(Debug, Clone)]
+pub struct Measured {
+ pub bounds: Rect,
+ pub app_key: String,
+ pub title: String,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum Dispatched {
+ /// The platform's own accessibility action ran. No pointer was involved.
+ AccessibilityAction,
+ /// A window-targeted event was posted. Still no global pointer warp.
+ WindowEvent,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum DesktopError {
+ /// No backend on this platform, or no input path in this session type.
+ Unsupported,
+ PermissionMissing,
+ TargetGone,
+ Elevated,
+ ElementNotFound,
+ NotActionable,
+ Timeout,
+ Failed(String),
+}
+
+pub struct RawInspection {
+ pub nodes: Vec<Node>,
+ pub truncated: bool,
+ pub fidelity: Fidelity,
+}
+
+pub trait Desktop: Send + Sync {
+ fn capabilities(&self) -> Capabilities;
+
+ /// Every window the platform can enumerate, unfiltered. Policy removes and
+ /// annotates entries; a backend never hides one, because a target the user
+ /// can see but the picker silently dropped is indistinguishable from a bug.
+ fn list_targets(&self) -> Result<Vec<RawTarget>, DesktopError>;
+
+ /// Re-read the live geometry and identity of one target.
+ fn measure(&self, target: &TargetRef) -> Result<Measured, DesktopError>;
+
+ fn inspect(&self, target: &TargetRef, max_nodes: usize) -> Result<RawInspection, DesktopError>;
+
+ /// Whether the OS reports a secure input state right now. A backend that
+ /// cannot tell must answer `true`: refusing is the safe default, since the
+ /// alternative is typing into a password field.
+ fn secure_input_active(&self) -> bool;
+
+ fn perform(
+ &self,
+ target: &TargetRef,
+ uid: Option<&str>,
+ action: &Action,
+ ) -> Result<Dispatched, DesktopError>;
+
+ /// Process ids that belong to this application, so policy can refuse our
+ /// own windows without trusting a name comparison.
+ ///
+ /// host-core has no windows of its own — the windows to refuse belong to
+ /// the Electron process that spawned it. The parent pid is therefore part
+ /// of the answer, and it is discovered here rather than supplied by a
+ /// request, so no caller can shrink this set.
+ fn self_pids(&self) -> Vec<i32> {
+ let mut pids = vec![std::process::id() as i32];
+ #[cfg(unix)]
+ {
+ // SAFETY: `getppid` takes no arguments and cannot fail.
+ let parent = unsafe { libc::getppid() };
+ if parent > 1 {
+ pids.push(parent);
+ }
+ }
+ pids
+ }
+}
+
+/// The backend every platform has: it exists so that an unimplemented platform
+/// answers with a code instead of panicking or pretending to work.
+pub struct UnsupportedDesktop {
+ platform: &'static str,
+ reason: &'static str,
+}
+
+impl UnsupportedDesktop {
+ pub fn new(platform: &'static str, reason: &'static str) -> Self {
+ Self { platform, reason }
+ }
+}
+
+impl Desktop for UnsupportedDesktop {
+ fn capabilities(&self) -> Capabilities {
+ Capabilities {
+ platform: self.platform.to_string(),
+ backend: "unsupported".into(),
+ fidelity: Fidelity::None,
+ accessibility: PermissionState::Unsupported,
+ capture: PermissionState::Unsupported,
+ session_type: None,
+ input_unsupported_reason: Some(self.reason.to_string()),
+ }
+ }
+
+ fn list_targets(&self) -> Result<Vec<RawTarget>, DesktopError> {
+ Err(DesktopError::Unsupported)
+ }
+
+ fn measure(&self, _target: &TargetRef) -> Result<Measured, DesktopError> {
+ Err(DesktopError::Unsupported)
+ }
+
+ fn inspect(
+ &self,
+ _target: &TargetRef,
+ _max_nodes: usize,
+ ) -> Result<RawInspection, DesktopError> {
+ Err(DesktopError::Unsupported)
+ }
+
+ fn secure_input_active(&self) -> bool {
+ true
+ }
+
+ fn perform(
+ &self,
+ _target: &TargetRef,
+ _uid: Option<&str>,
+ _action: &Action,
+ ) -> Result<Dispatched, DesktopError> {
+ Err(DesktopError::Unsupported)
+ }
+}
+
+/// The backend for this build. Each platform arm is compiled only on its own
+/// target, so an unported platform cannot fail to build.
+pub fn active() -> Box<dyn Desktop> {
+ #[cfg(target_os = "macos")]
+ {
+ Box::new(super::macos::MacDesktop::new())
+ }
+ #[cfg(target_os = "windows")]
+ {
+ Box::new(UnsupportedDesktop::new(
+ "win32",
+ "the Windows UI Automation backend lands in stage 2",
+ ))
+ }
+ #[cfg(all(unix, not(target_os = "macos")))]
+ {
+ Box::new(UnsupportedDesktop::new(
+ "linux",
+ "the Linux AT-SPI backend lands in stage 2",
+ ))
+ }
+ #[cfg(not(any(target_os = "macos", target_os = "windows", unix)))]
+ {
+ Box::new(UnsupportedDesktop::new(
+ "other",
+ "no backend for this platform",
+ ))
+ }
+}
diff --git a/crates/host-core/src/computer/macos.rs b/crates/host-core/src/computer/macos.rs
new file mode 100644
index 000000000..805e896b0
--- /dev/null
+++ b/crates/host-core/src/computer/macos.rs
@@ -0,0 +1,1005 @@
+//! The macOS computer-use backend: accessibility inspection and actions over
+//! `AXUIElement`, window enumeration over `CGWindowList`, and key input posted
+//! to the granted application's process.
+//!
+//! This is hand-declared framework FFI rather than a new crate, to keep the
+//! supply-chain rule intact for the first stage (ADR 0340). The declarations
+//! are the published C API; nothing here is a private symbol.
+//!
+//! The pointer is never warped. Element actions go through `AXUIElementPerformAction`
+//! and values through `AXUIElementSetAttributeValue`, so the user keeps their
+//! mouse while the agent works. Keys are posted with `CGEventPostToPid`, which
+//! delivers to the granted process rather than to whatever has focus.
+
+#![allow(non_upper_case_globals, non_snake_case)]
+
+use std::ffi::c_void;
+
+use super::backend::{
+ Desktop, DesktopError, Dispatched, Measured, RawInspection, RawTarget, TargetRef,
+};
+use super::{
+ Action, ActionKind, Capabilities, Fidelity, Node, PermissionState, Rect, MAX_LABEL_CHARS,
+};
+
+type Boolean = u8;
+type CFIndex = isize;
+type CFTypeRef = *const c_void;
+type CFStringRef = *const c_void;
+type CFArrayRef = *const c_void;
+type CFDictionaryRef = *const c_void;
+type AXUIElementRef = *const c_void;
+type AXValueRef = *const c_void;
+type AXError = i32;
+type CGEventRef = *const c_void;
+type CGEventSourceRef = *const c_void;
+
+const kAXErrorSuccess: AXError = 0;
+const kCFStringEncodingUTF8: u32 = 0x0800_0100;
+/// `kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements`
+const WINDOW_LIST_OPTIONS: u32 = 1 | 16;
+const kCGNullWindowID: u32 = 0;
+const kAXValueTypeCGPoint: u32 = 1;
+const kAXValueTypeCGSize: u32 = 2;
+/// `kCFNumberSInt64Type` and `kCFNumberDoubleType`
+const kCFNumberSInt64Type: CFIndex = 4;
+const kCFNumberDoubleType: CFIndex = 13;
+#[repr(C)]
+#[derive(Clone, Copy, Default)]
+struct CGPoint {
+ x: f64,
+ y: f64,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy, Default)]
+struct CGSize {
+ width: f64,
+ height: f64,
+}
+
+#[link(name = "CoreFoundation", kind = "framework")]
+extern "C" {
+ fn CFRelease(cf: CFTypeRef);
+ fn CFRetain(cf: CFTypeRef) -> CFTypeRef;
+ fn CFGetTypeID(cf: CFTypeRef) -> usize;
+ fn CFStringGetTypeID() -> usize;
+ fn CFArrayGetTypeID() -> usize;
+ fn CFBooleanGetTypeID() -> usize;
+ fn CFNumberGetTypeID() -> usize;
+ fn CFDictionaryGetTypeID() -> usize;
+ fn CFStringCreateWithBytes(
+ alloc: CFTypeRef,
+ bytes: *const u8,
+ num_bytes: CFIndex,
+ encoding: u32,
+ is_external_representation: Boolean,
+ ) -> CFStringRef;
+ fn CFStringGetLength(value: CFStringRef) -> CFIndex;
+ fn CFStringGetCString(
+ value: CFStringRef,
+ buffer: *mut i8,
+ buffer_size: CFIndex,
+ encoding: u32,
+ ) -> Boolean;
+ fn CFArrayGetCount(array: CFArrayRef) -> CFIndex;
+ fn CFArrayGetValueAtIndex(array: CFArrayRef, index: CFIndex) -> CFTypeRef;
+ fn CFDictionaryGetValue(dict: CFDictionaryRef, key: CFTypeRef) -> CFTypeRef;
+ fn CFBooleanGetValue(value: CFTypeRef) -> Boolean;
+ fn CFNumberGetValue(value: CFTypeRef, number_type: CFIndex, out: *mut c_void) -> Boolean;
+}
+
+#[link(name = "ApplicationServices", kind = "framework")]
+extern "C" {
+ fn AXIsProcessTrusted() -> Boolean;
+ fn AXUIElementCreateApplication(pid: i32) -> AXUIElementRef;
+ fn AXUIElementCopyAttributeValue(
+ element: AXUIElementRef,
+ attribute: CFStringRef,
+ value: *mut CFTypeRef,
+ ) -> AXError;
+ fn AXUIElementSetAttributeValue(
+ element: AXUIElementRef,
+ attribute: CFStringRef,
+ value: CFTypeRef,
+ ) -> AXError;
+ fn AXUIElementCopyActionNames(element: AXUIElementRef, names: *mut CFArrayRef) -> AXError;
+ fn AXUIElementPerformAction(element: AXUIElementRef, action: CFStringRef) -> AXError;
+ fn AXValueGetValue(value: AXValueRef, value_type: u32, out: *mut c_void) -> Boolean;
+ fn CGWindowListCopyWindowInfo(option: u32, relative_to_window: u32) -> CFArrayRef;
+ fn CGEventCreateKeyboardEvent(
+ source: CGEventSourceRef,
+ virtual_key: u16,
+ key_down: Boolean,
+ ) -> CGEventRef;
+ fn CGEventSetFlags(event: CGEventRef, flags: u64);
+ fn CGEventPostToPid(pid: i32, event: CGEventRef);
+}
+
+#[link(name = "Carbon", kind = "framework")]
+extern "C" {
+ fn IsSecureEventInputEnabled() -> Boolean;
+}
+
+/// A CFString we own. `Drop` releases it, so no attribute lookup can leak.
+struct CfString(CFStringRef);
+
+impl CfString {
+ fn new(value: &str) -> Option<Self> {
+ // SAFETY: the bytes outlive the call, and CoreFoundation copies them.
+ let raw = unsafe {
+ CFStringCreateWithBytes(
+ std::ptr::null(),
+ value.as_ptr(),
+ value.len() as CFIndex,
+ kCFStringEncodingUTF8,
+ 0,
+ )
+ };
+ if raw.is_null() {
+ None
+ } else {
+ Some(Self(raw))
+ }
+ }
+
+ fn as_ref(&self) -> CFStringRef {
+ self.0
+ }
+}
+
+impl Drop for CfString {
+ fn drop(&mut self) {
+ if !self.0.is_null() {
+ // SAFETY: we created this string and hold the only reference.
+ unsafe { CFRelease(self.0) };
+ }
+ }
+}
+
+/// A CFType we received from a `Copy`/`Create` call and must release.
+struct CfOwned(CFTypeRef);
+
+impl CfOwned {
+ fn as_ref(&self) -> CFTypeRef {
+ self.0
+ }
+}
+
+impl Drop for CfOwned {
+ fn drop(&mut self) {
+ if !self.0.is_null() {
+ // SAFETY: the value came from a Copy/Create call, so we own it.
+ unsafe { CFRelease(self.0) };
+ }
+ }
+}
+
+fn cf_string_value(value: CFTypeRef) -> Option<String> {
+ if value.is_null() {
+ return None;
+ }
+ // SAFETY: both calls are null-checked and the type is verified first.
+ unsafe {
+ if CFGetTypeID(value) != CFStringGetTypeID() {
+ return None;
+ }
+ let length = CFStringGetLength(value);
+ // UTF-8 can take up to 4 bytes per UTF-16 unit, plus a terminator.
+ let capacity = (length * 4 + 1).max(1) as usize;
+ let mut buffer = vec![0i8; capacity];
+ if CFStringGetCString(
+ value,
+ buffer.as_mut_ptr(),
+ capacity as CFIndex,
+ kCFStringEncodingUTF8,
+ ) == 0
+ {
+ return None;
+ }
+ let bytes: Vec<u8> = buffer
+ .into_iter()
+ .take_while(|byte| *byte != 0)
+ .map(|byte| byte as u8)
+ .collect();
+ String::from_utf8(bytes).ok()
+ }
+}
+
+fn cf_number_f64(value: CFTypeRef) -> Option<f64> {
+ if value.is_null() {
+ return None;
+ }
+ // SAFETY: type-checked before reading, and the out pointer is sized.
+ unsafe {
+ if CFGetTypeID(value) != CFNumberGetTypeID() {
+ return None;
+ }
+ let mut out: f64 = 0.0;
+ if CFNumberGetValue(
+ value,
+ kCFNumberDoubleType,
+ &mut out as *mut f64 as *mut c_void,
+ ) == 0
+ {
+ return None;
+ }
+ Some(out)
+ }
+}
+
+fn cf_number_i64(value: CFTypeRef) -> Option<i64> {
+ if value.is_null() {
+ return None;
+ }
+ // SAFETY: type-checked before reading, and the out pointer is sized.
+ unsafe {
+ if CFGetTypeID(value) != CFNumberGetTypeID() {
+ return None;
+ }
+ let mut out: i64 = 0;
+ if CFNumberGetValue(
+ value,
+ kCFNumberSInt64Type,
+ &mut out as *mut i64 as *mut c_void,
+ ) == 0
+ {
+ return None;
+ }
+ Some(out)
+ }
+}
+
+fn cf_bool(value: CFTypeRef) -> Option<bool> {
+ if value.is_null() {
+ return None;
+ }
+ // SAFETY: type-checked before reading.
+ unsafe {
+ if CFGetTypeID(value) != CFBooleanGetTypeID() {
+ return None;
+ }
+ Some(CFBooleanGetValue(value) != 0)
+ }
+}
+
+fn dict_value(dict: CFDictionaryRef, key: &str) -> Option<CFTypeRef> {
+ if dict.is_null() {
+ return None;
+ }
+ // SAFETY: the dictionary type is verified and the key is owned locally.
+ unsafe {
+ if CFGetTypeID(dict) != CFDictionaryGetTypeID() {
+ return None;
+ }
+ let cf_key = CfString::new(key)?;
+ let value = CFDictionaryGetValue(dict, cf_key.as_ref());
+ if value.is_null() {
+ None
+ } else {
+ Some(value)
+ }
+ }
+}
+
+/// Read one AX attribute. The result is owned by the caller.
+fn attribute(element: AXUIElementRef, name: &str) -> Option<CfOwned> {
+ let attr = CfString::new(name)?;
+ let mut out: CFTypeRef = std::ptr::null();
+ // SAFETY: `out` is a valid slot; on failure AX leaves it untouched.
+ let status = unsafe { AXUIElementCopyAttributeValue(element, attr.as_ref(), &mut out) };
+ if status != kAXErrorSuccess || out.is_null() {
+ return None;
+ }
+ Some(CfOwned(out))
+}
+
+fn attribute_string(element: AXUIElementRef, name: &str) -> Option<String> {
+ let value = attribute(element, name)?;
+ cf_string_value(value.as_ref())
+}
+
+fn attribute_bool(element: AXUIElementRef, name: &str) -> Option<bool> {
+ let value = attribute(element, name)?;
+ cf_bool(value.as_ref())
+}
+
+fn attribute_point(element: AXUIElementRef, name: &str) -> Option<CGPoint> {
+ let value = attribute(element, name)?;
+ let mut point = CGPoint::default();
+ // SAFETY: the out type matches `kAXValueTypeCGPoint`.
+ let ok = unsafe {
+ AXValueGetValue(
+ value.as_ref() as AXValueRef,
+ kAXValueTypeCGPoint,
+ &mut point as *mut CGPoint as *mut c_void,
+ )
+ };
+ if ok == 0 {
+ None
+ } else {
+ Some(point)
+ }
+}
+
+fn attribute_size(element: AXUIElementRef, name: &str) -> Option<CGSize> {
+ let value = attribute(element, name)?;
+ let mut size = CGSize::default();
+ // SAFETY: the out type matches `kAXValueTypeCGSize`.
+ let ok = unsafe {
+ AXValueGetValue(
+ value.as_ref() as AXValueRef,
+ kAXValueTypeCGSize,
+ &mut size as *mut CGSize as *mut c_void,
+ )
+ };
+ if ok == 0 {
+ None
+ } else {
+ Some(size)
+ }
+}
+
+/// Children of an element, each retained so it stays valid after the array
+/// that produced it is released. Returning borrowed references instead would
+/// hand out pointers whose owner is already gone.
+fn children(element: AXUIElementRef) -> Vec<CfOwned> {
+ let Some(value) = attribute(element, "AXChildren") else {
+ return Vec::new();
+ };
+ // SAFETY: type-checked; every child is retained before the array drops.
+ unsafe {
+ if CFGetTypeID(value.as_ref()) != CFArrayGetTypeID() {
+ return Vec::new();
+ }
+ let count = CFArrayGetCount(value.as_ref());
+ let mut out = Vec::new();
+ for index in 0..count {
+ let child = CFArrayGetValueAtIndex(value.as_ref(), index);
+ if !child.is_null() {
+ out.push(CfOwned(CFRetain(child)));
+ }
+ }
+ out
+ }
+}
+
+fn action_names(element: AXUIElementRef) -> Vec<String> {
+ let mut array: CFArrayRef = std::ptr::null();
+ // SAFETY: `array` is a valid slot; AX leaves it null on failure.
+ let status = unsafe { AXUIElementCopyActionNames(element, &mut array) };
+ if status != kAXErrorSuccess || array.is_null() {
+ return Vec::new();
+ }
+ let owned = CfOwned(array);
+ let mut names = Vec::new();
+ // SAFETY: the array is owned and its element type is CFString.
+ unsafe {
+ let count = CFArrayGetCount(owned.as_ref());
+ for index in 0..count {
+ if let Some(name) = cf_string_value(CFArrayGetValueAtIndex(owned.as_ref(), index)) {
+ names.push(name);
+ }
+ }
+ }
+ names
+}
+
+/// The AX actions we expose, mapped from the platform's own action names.
+fn supported_actions(names: &[String]) -> Vec<ActionKind> {
+ let mut actions = Vec::new();
+ let has = |needle: &str| names.iter().any(|name| name == needle);
+ if has("AXPress") {
+ actions.push(ActionKind::Click);
+ }
+ if has("AXShowMenu") {
+ actions.push(ActionKind::RightClick);
+ }
+ if has("AXIncrement") || has("AXDecrement") {
+ actions.push(ActionKind::Scroll);
+ }
+ if has("AXPick") {
+ actions.push(ActionKind::Select);
+ }
+ actions
+}
+
+/// `uid` encodes the path from the window root plus a digest of the role and
+/// label it had when inspected. A later action re-walks the path and checks the
+/// digest, so a tree that changed underneath refuses instead of acting on
+/// whatever now sits at that position. No native reference is kept between
+/// calls, which is also why a uid cannot outlive what it describes.
+fn make_uid(path: &[usize], role: &str, label: Option<&str>) -> String {
+ let joined = path
+ .iter()
+ .map(|index| index.to_string())
+ .collect::<Vec<_>>()
+ .join(".");
+ format!("{joined}#{:x}", identity_digest(role, label))
+}
+
+fn identity_digest(role: &str, label: Option<&str>) -> u32 {
+ // FNV-1a over role and label. This is a change detector, not a secret.
+ let mut hash: u32 = 0x811c_9dc5;
+ for byte in role.as_bytes().iter().chain(label.unwrap_or("").as_bytes()) {
+ hash ^= u32::from(*byte);
+ hash = hash.wrapping_mul(0x0100_0193);
+ }
+ hash
+}
+
+fn parse_uid(uid: &str) -> Option<(Vec<usize>, u32)> {
+ let (path, digest) = uid.split_once('#')?;
+ let indices = path
+ .split('.')
+ .filter(|part| !part.is_empty())
+ .map(|part| part.parse::<usize>().ok())
+ .collect::<Option<Vec<_>>>()?;
+ let digest = u32::from_str_radix(digest, 16).ok()?;
+ Some((indices, digest))
+}
+
+pub struct MacDesktop;
+
+impl MacDesktop {
+ pub fn new() -> Self {
+ Self
+ }
+
+ fn trusted(&self) -> bool {
+ // SAFETY: the call takes no arguments and only reads TCC state.
+ unsafe { AXIsProcessTrusted() != 0 }
+ }
+
+ /// The AX element for one window, re-resolved from the application each
+ /// time: holding an `AXUIElementRef` across calls would mean acting on a
+ /// window that may already be gone.
+ fn window_element(&self, target: &TargetRef) -> Result<CfOwned, DesktopError> {
+ if !self.trusted() {
+ return Err(DesktopError::PermissionMissing);
+ }
+ // SAFETY: the pid is validated by the caller's grant; a dead pid
+ // yields an element whose attribute reads fail, which we map below.
+ let app = unsafe { AXUIElementCreateApplication(target.pid) };
+ if app.is_null() {
+ return Err(DesktopError::TargetGone);
+ }
+ let app = CfOwned(app);
+ let windows = attribute(app.as_ref(), "AXWindows").ok_or(DesktopError::TargetGone)?;
+ // SAFETY: type-checked; entries are borrowed from an array we keep.
+ let found = unsafe {
+ if CFGetTypeID(windows.as_ref()) != CFArrayGetTypeID() {
+ return Err(DesktopError::TargetGone);
+ }
+ let count = CFArrayGetCount(windows.as_ref());
+ let mut found: Option<CFTypeRef> = None;
+ for index in 0..count {
+ let window = CFArrayGetValueAtIndex(windows.as_ref(), index);
+ if window.is_null() {
+ continue;
+ }
+ // `AXWindowNumber` is not public API on every release, so the
+ // window is matched on geometry and title, the two things
+ // `CGWindowList` also gave us. A mismatch is a refusal, not a
+ // guess at which window the user meant.
+ if self.window_matches(window, target) {
+ found = Some(window);
+ break;
+ }
+ }
+ found
+ };
+ let window = found.ok_or(DesktopError::TargetGone)?;
+ // Retain before the window array drops, so the caller holds a
+ // reference that outlives the enumeration it came from.
+ // SAFETY: `window` is a live entry of an array we still own here.
+ let retained = unsafe { CFRetain(window) };
+ drop(windows);
+ Ok(CfOwned(retained))
+ }
+
+ fn window_matches(&self, window: AXUIElementRef, target: &TargetRef) -> bool {
+ // The window id is encoded in `target_id` as `<pid>:<window>`, and the
+ // AX side cannot read it, so geometry is the join key. `measure` is the
+ // authority on whether the grant still describes this window.
+ let Some(position) = attribute_point(window, "AXPosition") else {
+ return false;
+ };
+ let Some(size) = attribute_size(window, "AXSize") else {
+ return false;
+ };
+ let bounds = Rect {
+ x: position.x,
+ y: position.y,
+ width: size.width,
+ height: size.height,
+ };
+ self.cg_bounds(target)
+ .map(|cg| cg.matches(&bounds))
+ .unwrap_or(false)
+ }
+
+ /// Window geometry straight from `CGWindowList`, which does not need the
+ /// Accessibility grant and is therefore also the pre-permission answer.
+ fn cg_bounds(&self, target: &TargetRef) -> Option<Rect> {
+ self.enumerate()
+ .ok()?
+ .into_iter()
+ .find(|item| item.target.window == target.window && item.target.pid == target.pid)
+ .map(|item| item.bounds)
+ }
+
+ fn enumerate(&self) -> Result<Vec<RawTarget>, DesktopError> {
+ // SAFETY: the returned array is owned by us and released by `CfOwned`.
+ let array = unsafe { CGWindowListCopyWindowInfo(WINDOW_LIST_OPTIONS, kCGNullWindowID) };
+ if array.is_null() {
+ return Err(DesktopError::Failed("window list unavailable".into()));
+ }
+ let owned = CfOwned(array);
+ let mut targets = Vec::new();
+ // SAFETY: the array is owned and holds CFDictionary entries.
+ unsafe {
+ let count = CFArrayGetCount(owned.as_ref());
+ for index in 0..count {
+ let dict = CFArrayGetValueAtIndex(owned.as_ref(), index);
+ if dict.is_null() {
+ continue;
+ }
+ // Layer 0 is the normal application layer: menu bar extras,
+ // the Dock, and overlays sit above it and are not targets a
+ // user would mean when they say "this window".
+ let layer = dict_value(dict, "kCGWindowLayer")
+ .and_then(cf_number_i64)
+ .unwrap_or(0);
+ if layer != 0 {
+ continue;
+ }
+ let Some(pid) = dict_value(dict, "kCGWindowOwnerPID").and_then(cf_number_i64)
+ else {
+ continue;
+ };
+ let Some(window) = dict_value(dict, "kCGWindowNumber").and_then(cf_number_i64)
+ else {
+ continue;
+ };
+ let app_name = dict_value(dict, "kCGWindowOwnerName")
+ .and_then(cf_string_value)
+ .unwrap_or_default();
+ let title = dict_value(dict, "kCGWindowName")
+ .and_then(cf_string_value)
+ .unwrap_or_default();
+ let bounds_dict = dict_value(dict, "kCGWindowBounds").unwrap_or(std::ptr::null());
+ let read = |key: &str| {
+ dict_value(bounds_dict, key)
+ .and_then(cf_number_f64)
+ .unwrap_or(0.0)
+ };
+ let bounds = Rect {
+ x: read("X"),
+ y: read("Y"),
+ width: read("Width"),
+ height: read("Height"),
+ };
+ // A zero-area window is not something a user can point at.
+ if bounds.width < 1.0 || bounds.height < 1.0 {
+ continue;
+ }
+ targets.push(RawTarget {
+ target: TargetRef {
+ target_id: format!("{pid}:{window}"),
+ pid: pid as i32,
+ window: window as u64,
+ // macOS does not publish the bundle id here; the owner
+ // name is what the platform can prove, and `measure`
+ // compares it to catch a reused window handle.
+ app_key: app_name.to_ascii_lowercase(),
+ },
+ app_name,
+ title,
+ bounds,
+ elevated: false,
+ });
+ }
+ }
+ Ok(targets)
+ }
+
+ fn walk(
+ &self,
+ element: AXUIElementRef,
+ path: &mut Vec<usize>,
+ parent: Option<usize>,
+ nodes: &mut Vec<Node>,
+ max_nodes: usize,
+ ) -> bool {
+ if nodes.len() >= max_nodes {
+ return true;
+ }
+ let role = attribute_string(element, "AXRole").unwrap_or_else(|| "AXUnknown".into());
+ let label = attribute_string(element, "AXTitle")
+ .or_else(|| attribute_string(element, "AXDescription"))
+ .or_else(|| attribute_string(element, "AXLabel"))
+ .map(|value| value.chars().take(MAX_LABEL_CHARS).collect::<String>())
+ .filter(|value| !value.trim().is_empty());
+ let has_value = attribute(element, "AXValue").is_some();
+ let enabled = attribute_bool(element, "AXEnabled").unwrap_or(true);
+ let focused = attribute_bool(element, "AXFocused").unwrap_or(false);
+ let bounds = match (
+ attribute_point(element, "AXPosition"),
+ attribute_size(element, "AXSize"),
+ ) {
+ (Some(position), Some(size)) => Some(Rect {
+ x: position.x,
+ y: position.y,
+ width: size.width,
+ height: size.height,
+ }),
+ _ => None,
+ };
+ let names = action_names(element);
+ let mut actions = supported_actions(&names);
+ // A settable value is how text gets entered without typing into
+ // whatever happens to have focus.
+ if has_value && enabled {
+ actions.push(ActionKind::SetValue);
+ }
+ let index = nodes.len();
+ nodes.push(Node {
+ uid: make_uid(path, &role, label.as_deref()),
+ role,
+ label,
+ has_value,
+ enabled,
+ focused,
+ bounds,
+ parent,
+ actions,
+ });
+ for (child_index, child) in children(element).into_iter().enumerate() {
+ path.push(child_index);
+ let truncated = self.walk(child.as_ref(), path, Some(index), nodes, max_nodes);
+ path.pop();
+ if truncated {
+ return true;
+ }
+ }
+ false
+ }
+
+ /// Re-walk a `uid` path and verify the identity digest still matches.
+ fn resolve(
+ &self,
+ window: AXUIElementRef,
+ uid: &str,
+ ) -> Result<(CfOwned, Option<Rect>), DesktopError> {
+ let (path, digest) = parse_uid(uid).ok_or(DesktopError::ElementNotFound)?;
+ // SAFETY: the window reference is owned by the caller for this call.
+ let mut current = CfOwned(unsafe { CFRetain(window) });
+ for index in &path {
+ let mut kids = children(current.as_ref());
+ if *index >= kids.len() {
+ return Err(DesktopError::ElementNotFound);
+ }
+ current = kids.swap_remove(*index);
+ }
+ let element = current.as_ref();
+ let role = attribute_string(element, "AXRole").unwrap_or_else(|| "AXUnknown".into());
+ let label = attribute_string(element, "AXTitle")
+ .or_else(|| attribute_string(element, "AXDescription"))
+ .or_else(|| attribute_string(element, "AXLabel"))
+ .map(|value| value.chars().take(MAX_LABEL_CHARS).collect::<String>())
+ .filter(|value| !value.trim().is_empty());
+ if identity_digest(&role, label.as_deref()) != digest {
+ // The position still exists but holds something else now.
+ return Err(DesktopError::ElementNotFound);
+ }
+ let bounds = match (
+ attribute_point(element, "AXPosition"),
+ attribute_size(element, "AXSize"),
+ ) {
+ (Some(position), Some(size)) => Some(Rect {
+ x: position.x,
+ y: position.y,
+ width: size.width,
+ height: size.height,
+ }),
+ _ => None,
+ };
+ Ok((current, bounds))
+ }
+
+ fn perform_ax_action(&self, element: CFTypeRef, name: &str) -> Result<(), DesktopError> {
+ let action =
+ CfString::new(name).ok_or_else(|| DesktopError::Failed("action name".into()))?;
+ // SAFETY: the element came from a verified walk in this same call.
+ let status = unsafe { AXUIElementPerformAction(element, action.as_ref()) };
+ if status == kAXErrorSuccess {
+ Ok(())
+ } else {
+ Err(DesktopError::NotActionable)
+ }
+ }
+
+ fn set_value(&self, element: CFTypeRef, text: &str) -> Result<(), DesktopError> {
+ let attr =
+ CfString::new("AXValue").ok_or_else(|| DesktopError::Failed("attribute".into()))?;
+ let value = CfString::new(text).ok_or_else(|| DesktopError::Failed("value".into()))?;
+ // SAFETY: both strings outlive the call; AX copies the value.
+ let status =
+ unsafe { AXUIElementSetAttributeValue(element, attr.as_ref(), value.as_ref()) };
+ if status == kAXErrorSuccess {
+ Ok(())
+ } else {
+ Err(DesktopError::NotActionable)
+ }
+ }
+
+ /// Post one key chord to the granted process. The event never enters the
+ /// HID tap, so it cannot land in another application if focus moves.
+ fn press_keys(&self, pid: i32, chords: &[String]) -> Result<(), DesktopError> {
+ for chord in chords {
+ let (flags, key) = parse_chord(chord).ok_or(DesktopError::NotActionable)?;
+ for down in [1u8, 0u8] {
+ // SAFETY: a null source is documented as "use a private
+ // source"; the event is released before the next iteration.
+ let event = unsafe { CGEventCreateKeyboardEvent(std::ptr::null(), key, down) };
+ if event.is_null() {
+ return Err(DesktopError::Failed("key event".into()));
+ }
+ // SAFETY: the event is ours until it is released.
+ unsafe {
+ CGEventSetFlags(event, flags);
+ CGEventPostToPid(pid, event);
+ CFRelease(event);
+ }
+ }
+ }
+ Ok(())
+ }
+}
+
+/// Modifier bits as `CGEventFlags`.
+const FLAG_SHIFT: u64 = 0x0002_0000;
+const FLAG_CONTROL: u64 = 0x0004_0000;
+const FLAG_OPTION: u64 = 0x0008_0000;
+const FLAG_COMMAND: u64 = 0x0010_0000;
+
+/// Map a chord like `cmd+a` onto flags and a virtual key code.
+///
+/// The accepted set is deliberately small: a key the table does not name is a
+/// refusal, so a model cannot reach an arbitrary system shortcut by spelling.
+fn parse_chord(chord: &str) -> Option<(u64, u16)> {
+ let mut flags = 0u64;
+ let mut key: Option<u16> = None;
+ for part in chord.split('+') {
+ let token = part.trim().to_ascii_lowercase();
+ match token.as_str() {
+ "" => return None,
+ "cmd" | "command" | "meta" => flags |= FLAG_COMMAND,
+ "shift" => flags |= FLAG_SHIFT,
+ "alt" | "option" | "opt" => flags |= FLAG_OPTION,
+ "ctrl" | "control" => flags |= FLAG_CONTROL,
+ other => {
+ if key.is_some() {
+ return None;
+ }
+ key = virtual_key(other);
+ key?;
+ }
+ }
+ }
+ key.map(|value| (flags, value))
+}
+
+fn virtual_key(name: &str) -> Option<u16> {
+ let code = match name {
+ "a" => 0,
+ "b" => 11,
+ "c" => 8,
+ "d" => 2,
+ "e" => 14,
+ "f" => 3,
+ "g" => 5,
+ "h" => 4,
+ "i" => 34,
+ "j" => 38,
+ "k" => 40,
+ "l" => 37,
+ "m" => 46,
+ "n" => 45,
+ "o" => 31,
+ "p" => 35,
+ "q" => 12,
+ "r" => 15,
+ "s" => 1,
+ "t" => 17,
+ "u" => 32,
+ "v" => 9,
+ "w" => 13,
+ "x" => 7,
+ "y" => 16,
+ "z" => 6,
+ "0" => 29,
+ "1" => 18,
+ "2" => 19,
+ "3" => 20,
+ "4" => 21,
+ "5" => 23,
+ "6" => 22,
+ "7" => 26,
+ "8" => 28,
+ "9" => 25,
+ "return" | "enter" => 36,
+ "tab" => 48,
+ "space" => 49,
+ "delete" | "backspace" => 51,
+ "escape" | "esc" => 53,
+ "left" => 123,
+ "right" => 124,
+ "down" => 125,
+ "up" => 126,
+ _ => return None,
+ };
+ Some(code)
+}
+
+impl Desktop for MacDesktop {
+ fn capabilities(&self) -> Capabilities {
+ let accessibility = if self.trusted() {
+ PermissionState::Granted
+ } else {
+ // macOS does not distinguish "never asked" from "refused" here;
+ // reporting `not-requested` keeps the doctor view honest, because
+ // the next request is what produces the prompt or the refusal.
+ PermissionState::NotRequested
+ };
+ Capabilities {
+ platform: "darwin".into(),
+ backend: "macos-ax".into(),
+ fidelity: Fidelity::Full,
+ accessibility,
+ // The capture path is Chromium's in main, so the host reports what
+ // it knows: the window list works without a capture grant.
+ capture: PermissionState::NotRequested,
+ session_type: None,
+ input_unsupported_reason: None,
+ }
+ }
+
+ fn list_targets(&self) -> Result<Vec<RawTarget>, DesktopError> {
+ self.enumerate()
+ }
+
+ fn measure(&self, target: &TargetRef) -> Result<Measured, DesktopError> {
+ let found = self
+ .enumerate()?
+ .into_iter()
+ .find(|item| item.target.window == target.window && item.target.pid == target.pid)
+ .ok_or(DesktopError::TargetGone)?;
+ Ok(Measured {
+ bounds: found.bounds,
+ app_key: found.target.app_key,
+ title: found.title,
+ })
+ }
+
+ fn inspect(&self, target: &TargetRef, max_nodes: usize) -> Result<RawInspection, DesktopError> {
+ let window = self.window_element(target)?;
+ let mut nodes = Vec::new();
+ let mut path = Vec::new();
+ let truncated = self.walk(window.as_ref(), &mut path, None, &mut nodes, max_nodes);
+ Ok(RawInspection {
+ nodes,
+ truncated,
+ fidelity: Fidelity::Full,
+ })
+ }
+
+ fn secure_input_active(&self) -> bool {
+ // SAFETY: the call takes no arguments and only reads global state.
+ unsafe { IsSecureEventInputEnabled() != 0 }
+ }
+
+ fn perform(
+ &self,
+ target: &TargetRef,
+ uid: Option<&str>,
+ action: &Action,
+ ) -> Result<Dispatched, DesktopError> {
+ let kind = action.kind.ok_or(DesktopError::NotActionable)?;
+ if kind == ActionKind::PressKeys {
+ let keys = action.keys.as_ref().ok_or(DesktopError::NotActionable)?;
+ self.press_keys(target.pid, keys)?;
+ return Ok(Dispatched::WindowEvent);
+ }
+ let window = self.window_element(target)?;
+ let uid = uid.ok_or(DesktopError::ElementNotFound)?;
+ let (resolved, _bounds) = self.resolve(window.as_ref(), uid)?;
+ let element = resolved.as_ref();
+ match kind {
+ ActionKind::Click | ActionKind::DoubleClick => {
+ self.perform_ax_action(element, "AXPress")?;
+ if kind == ActionKind::DoubleClick {
+ self.perform_ax_action(element, "AXPress")?;
+ }
+ }
+ ActionKind::RightClick => self.perform_ax_action(element, "AXShowMenu")?,
+ ActionKind::Select => self.perform_ax_action(element, "AXPick")?,
+ ActionKind::SetValue => {
+ let text = action.text.as_deref().ok_or(DesktopError::NotActionable)?;
+ self.set_value(element, text)?;
+ }
+ ActionKind::Scroll => {
+ let scroll = action.scroll.ok_or(DesktopError::NotActionable)?;
+ let name = if scroll.dy >= 0.0 {
+ "AXIncrement"
+ } else {
+ "AXDecrement"
+ };
+ self.perform_ax_action(element, name)?;
+ }
+ ActionKind::PressKeys => unreachable!("handled above"),
+ }
+ Ok(Dispatched::AccessibilityAction)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_uid_round_trips_its_path_and_identity() {
+ let uid = make_uid(&[0, 3, 2], "AXButton", Some("Save"));
+ let (path, digest) = parse_uid(&uid).expect("parse");
+ assert_eq!(path, vec![0, 3, 2]);
+ assert_eq!(digest, identity_digest("AXButton", Some("Save")));
+ }
+
+ #[test]
+ fn a_uid_whose_element_changed_identity_does_not_verify() {
+ let uid = make_uid(&[1], "AXButton", Some("Save"));
+ let (_, digest) = parse_uid(&uid).expect("parse");
+ assert_ne!(digest, identity_digest("AXButton", Some("Delete")));
+ assert_ne!(digest, identity_digest("AXTextField", Some("Save")));
+ }
+
+ #[test]
+ fn malformed_uids_are_refused() {
+ for uid in ["", "abc", "1.2", "1.x#ff", "1.2#zz", "-1#ff", "1.2#"] {
+ assert!(parse_uid(uid).is_none(), "accepted {uid}");
+ }
+ }
+
+ #[test]
+ fn the_scope_root_has_an_empty_path() {
+ // The inspection emits the window itself as a node, so its uid is a
+ // digest with no path. Acting on it is allowed and simply does
+ // whatever the window offers, which is usually nothing.
+ let uid = make_uid(&[], "AXWindow", Some("Document"));
+ let (path, _) = parse_uid(&uid).expect("root uid");
+ assert!(path.is_empty());
+ }
+
+ #[test]
+ fn chords_accept_known_keys_and_refuse_everything_else() {
+ assert_eq!(parse_chord("cmd+a"), Some((FLAG_COMMAND, 0)));
+ assert_eq!(parse_chord("Shift+Tab"), Some((FLAG_SHIFT, 48)));
+ assert_eq!(parse_chord("escape"), Some((0, 53)));
+ for chord in ["", "cmd", "cmd+", "cmd+a+b", "f13", "eject", "power"] {
+ assert!(parse_chord(chord).is_none(), "accepted {chord}");
+ }
+ }
+
+ #[test]
+ fn ax_actions_map_to_our_kinds() {
+ let names = vec!["AXPress".to_string(), "AXShowMenu".to_string()];
+ let actions = supported_actions(&names);
+ assert!(actions.contains(&ActionKind::Click));
+ assert!(actions.contains(&ActionKind::RightClick));
+ assert!(
+ !actions.contains(&ActionKind::SetValue),
+ "value comes from AXValue, not an action"
+ );
+ }
+}
diff --git a/crates/host-core/src/computer/mod.rs b/crates/host-core/src/computer/mod.rs
new file mode 100644
index 000000000..6844d5e9a
--- /dev/null
+++ b/crates/host-core/src/computer/mod.rs
@@ -0,0 +1,445 @@
+//! Granted native application control (ADR 0340).
+//!
+//! This module is the only place that may refuse a computer-use request, so
+//! every refusal lives here rather than in the caller: the loop that decides
+//! what to do runs in Electron main, and main is not trusted to police itself.
+//! The platform backends below it can only *attempt* work — they never see a
+//! request that policy has not already admitted.
+//!
+//! Two refusals are unconditional and have no setting, grant option, or
+//! permission mode that reaches them: this application's own windows are never
+//! a target (synthetic input into PI-Desktop would bypass the permission
+//! broker), and a secure input state refuses both inspection and input.
+
+pub mod backend;
+#[cfg(target_os = "macos")]
+mod macos;
+mod policy;
+#[cfg(test)]
+mod tests;
+
+use std::time::{Duration, Instant};
+
+use serde::{Deserialize, Serialize};
+
+pub use backend::{DesktopError, Dispatched, TargetRef};
+
+/// Hard ceiling on the tree one `inspect` returns. Mirrors
+/// `COMPUTER_MAX_NODES` in `@pi-desktop/shared`.
+pub const MAX_NODES: usize = 400;
+/// Hard ceiling on one accessible label, so a hostile window cannot pad a
+/// model context through its own titles.
+pub const MAX_LABEL_CHARS: usize = 200;
+/// Hard ceiling on text one step may type.
+pub const MAX_TEXT_CHARS: usize = 2_000;
+/// Clamp on any caller-supplied action budget.
+pub const MAX_ACTION_BUDGET: u32 = 200;
+pub const DEFAULT_ACTION_BUDGET: u32 = 40;
+pub const DEFAULT_IDLE_EXPIRY: Duration = Duration::from_secs(15 * 60);
+pub const MAX_IDLE_EXPIRY: Duration = Duration::from_secs(60 * 60);
+pub const MIN_IDLE_EXPIRY: Duration = Duration::from_secs(30);
+
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Rect {
+ pub x: f64,
+ pub y: f64,
+ pub width: f64,
+ pub height: f64,
+}
+
+impl Rect {
+ pub fn contains(&self, x: f64, y: f64) -> bool {
+ x >= 0.0 && y >= 0.0 && x <= self.width && y <= self.height
+ }
+
+ /// Geometry equality with a tolerance, because a window can be reported
+ /// with sub-pixel jitter without having actually moved.
+ pub fn matches(&self, other: &Rect) -> bool {
+ const TOLERANCE: f64 = 1.0;
+ (self.x - other.x).abs() <= TOLERANCE
+ && (self.y - other.y).abs() <= TOLERANCE
+ && (self.width - other.width).abs() <= TOLERANCE
+ && (self.height - other.height).abs() <= TOLERANCE
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum InputPolicy {
+ ConfirmEach,
+ AutonomousInScope,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum CaptureMode {
+ A11yOnly,
+ A11yAndPixels,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Fidelity {
+ Full,
+ Partial,
+ None,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum PermissionState {
+ Granted,
+ Denied,
+ NotRequested,
+ Unsupported,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "kebab-case")]
+pub enum TargetRefusal {
+ /// A PI-Desktop window. Unconditional.
+ #[serde(rename = "self")]
+ SelfTarget,
+ Denylisted,
+ Elevated,
+ NoAccessibility,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Target {
+ pub target_id: String,
+ pub app_name: String,
+ pub title: String,
+ pub app_key: String,
+ pub bounds: Rect,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub refused_reason: Option<TargetRefusal>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Capabilities {
+ pub platform: String,
+ pub backend: String,
+ pub fidelity: Fidelity,
+ pub accessibility: PermissionState,
+ pub capture: PermissionState,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub session_type: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub input_unsupported_reason: Option<String>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum GrantState {
+ Active,
+ Revoked,
+ Expired,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct GrantView {
+ pub grant_id: String,
+ pub revision: u32,
+ pub target_id: String,
+ pub target_label: String,
+ pub app_key: String,
+ pub bounds: Rect,
+ pub input_policy: InputPolicy,
+ pub capture: CaptureMode,
+ pub remaining_budget: u32,
+ pub session_id: String,
+ pub created_at: String,
+ pub expires_at: String,
+ pub state: GrantState,
+}
+
+/// The authoritative grant. It is process-local and never persisted: a restart
+/// must not hand a new process authority over the user's screen.
+#[derive(Debug, Clone)]
+pub struct Grant {
+ pub grant_id: String,
+ pub revision: u32,
+ pub target: TargetRef,
+ pub target_label: String,
+ pub bounds: Rect,
+ pub input_policy: InputPolicy,
+ pub capture: CaptureMode,
+ pub remaining_budget: u32,
+ pub session_id: String,
+ pub created_at: String,
+ pub last_activity: Instant,
+ pub idle_expiry: Duration,
+ pub state: GrantState,
+}
+
+impl Grant {
+ pub fn expired_at(&self, now: Instant) -> bool {
+ now.duration_since(self.last_activity) >= self.idle_expiry
+ }
+
+ pub fn view(&self, now: Instant) -> GrantView {
+ let state = if self.state == GrantState::Active && self.expired_at(now) {
+ GrantState::Expired
+ } else {
+ self.state
+ };
+ GrantView {
+ grant_id: self.grant_id.clone(),
+ revision: self.revision,
+ target_id: self.target.target_id.clone(),
+ target_label: self.target_label.clone(),
+ app_key: self.target.app_key.clone(),
+ bounds: self.bounds,
+ input_policy: self.input_policy,
+ capture: self.capture,
+ remaining_budget: self.remaining_budget,
+ session_id: self.session_id.clone(),
+ created_at: self.created_at.clone(),
+ expires_at: expiry_iso(&self.created_at, self.last_activity, self.idle_expiry, now),
+ state,
+ }
+ }
+}
+
+/// `expiresAt` is derived from the live idle window rather than stored, so a
+/// grant that keeps working keeps moving its own deadline.
+fn expiry_iso(
+ created_at: &str,
+ last_activity: Instant,
+ idle_expiry: Duration,
+ now: Instant,
+) -> String {
+ let remaining = idle_expiry.saturating_sub(now.duration_since(last_activity));
+ let base = chrono::DateTime::parse_from_rfc3339(created_at)
+ .map(|value| value.with_timezone(&chrono::Utc))
+ .unwrap_or_else(|_| chrono::Utc::now());
+ let deadline = chrono::Utc::now() + chrono::Duration::from_std(remaining).unwrap_or_default();
+ // A malformed `created_at` must not produce a deadline in the past.
+ if deadline < base {
+ base.to_rfc3339()
+ } else {
+ deadline.to_rfc3339()
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ActionKind {
+ Click,
+ DoubleClick,
+ RightClick,
+ SetValue,
+ PressKeys,
+ Scroll,
+ Select,
+}
+
+impl ActionKind {
+ /// Whether the action changes the target. Inspection-only actions do not
+ /// spend the grant's input budget and do not need an input-policy decision.
+ pub fn is_input(self) -> bool {
+ true
+ }
+
+ pub fn as_str(self) -> &'static str {
+ match self {
+ ActionKind::Click => "click",
+ ActionKind::DoubleClick => "double_click",
+ ActionKind::RightClick => "right_click",
+ ActionKind::SetValue => "set_value",
+ ActionKind::PressKeys => "press_keys",
+ ActionKind::Scroll => "scroll",
+ ActionKind::Select => "select",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Point {
+ pub x: f64,
+ pub y: f64,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Basis {
+ pub revision: u32,
+ pub bounds: Rect,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Scroll {
+ pub dx: f64,
+ pub dy: f64,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Action {
+ pub kind: Option<ActionKind>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub uid: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub point: Option<Point>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub basis: Option<Basis>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub text: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub keys: Option<Vec<String>>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub scroll: Option<Scroll>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub option: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Node {
+ pub uid: String,
+ pub role: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub label: Option<String>,
+ pub has_value: bool,
+ pub enabled: bool,
+ pub focused: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub bounds: Option<Rect>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub parent: Option<usize>,
+ pub actions: Vec<ActionKind>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Inspection {
+ pub grant_id: String,
+ pub revision: u32,
+ pub bounds: Rect,
+ pub fidelity: Fidelity,
+ pub nodes: Vec<Node>,
+ pub truncated: bool,
+ pub secure_input: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ActResult {
+ pub grant_id: String,
+ pub revision: u32,
+ pub remaining_budget: u32,
+ pub dispatched: Dispatched,
+}
+
+/// Every refusal the capability can produce. The variants map one-to-one onto
+/// the `COMPUTER_*` codes in `08-error-codes.md` §3.10, so a caller can always
+/// tell "there is no backend here" from "that element does not exist".
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Refusal {
+ Disabled,
+ NoGrant,
+ GrantInUse,
+ GrantExpired,
+ BudgetExhausted,
+ ScopeViolation,
+ SelfTargetRefused,
+ TargetDenylisted,
+ SecureInputRefused,
+ StaleBasis,
+ StaleRevision,
+ ElementNotFound,
+ ElementNotActionable,
+ OsPermissionMissing,
+ TargetElevated,
+ PlatformUnsupported,
+ ActionRejected(String),
+ Timeout,
+ Internal(String),
+}
+
+impl Refusal {
+ pub fn code(&self) -> &'static str {
+ match self {
+ Refusal::Disabled => "COMPUTER_DISABLED",
+ Refusal::NoGrant => "COMPUTER_NO_GRANT",
+ Refusal::GrantInUse => "COMPUTER_GRANT_IN_USE",
+ Refusal::GrantExpired => "COMPUTER_GRANT_EXPIRED",
+ Refusal::BudgetExhausted => "COMPUTER_BUDGET_EXHAUSTED",
+ Refusal::ScopeViolation => "COMPUTER_SCOPE_VIOLATION",
+ Refusal::SelfTargetRefused => "COMPUTER_SELF_TARGET_REFUSED",
+ Refusal::TargetDenylisted => "COMPUTER_TARGET_DENYLISTED",
+ Refusal::SecureInputRefused => "COMPUTER_SECURE_INPUT_REFUSED",
+ Refusal::StaleBasis => "COMPUTER_STALE_BASIS",
+ Refusal::StaleRevision => "COMPUTER_STALE_REVISION",
+ Refusal::ElementNotFound => "COMPUTER_ELEMENT_NOT_FOUND",
+ Refusal::ElementNotActionable => "COMPUTER_ELEMENT_NOT_ACTIONABLE",
+ Refusal::OsPermissionMissing => "COMPUTER_OS_PERMISSION_MISSING",
+ Refusal::TargetElevated => "COMPUTER_TARGET_ELEVATED",
+ Refusal::PlatformUnsupported => "COMPUTER_PLATFORM_UNSUPPORTED",
+ Refusal::ActionRejected(_) => "COMPUTER_ACTION_REJECTED",
+ Refusal::Timeout => "COMPUTER_TIMEOUT",
+ Refusal::Internal(_) => "INTERNAL",
+ }
+ }
+
+ /// Public message. It never carries window text, typed values, or pixels —
+ /// a refusal is attributable without leaking what was on screen.
+ pub fn message(&self) -> String {
+ match self {
+ Refusal::Disabled => "computer use is disabled".into(),
+ Refusal::NoGrant => "no active computer-use grant".into(),
+ Refusal::GrantInUse => "another session holds the active grant".into(),
+ Refusal::GrantExpired => "the computer-use grant is no longer active".into(),
+ Refusal::BudgetExhausted => "the grant's action budget is exhausted".into(),
+ Refusal::ScopeViolation => "the request resolved outside the granted scope".into(),
+ Refusal::SelfTargetRefused => "PI-Desktop windows are never a target".into(),
+ Refusal::TargetDenylisted => "the target is on the denylist".into(),
+ Refusal::SecureInputRefused => "secure input is active".into(),
+ Refusal::StaleBasis => "the coordinate basis no longer matches the scope".into(),
+ Refusal::StaleRevision => "the grant revision changed; inspect again".into(),
+ Refusal::ElementNotFound => "the element is not in the current scope".into(),
+ Refusal::ElementNotActionable => "the element offers no action for this request".into(),
+ Refusal::OsPermissionMissing => "the operating system permission is not granted".into(),
+ Refusal::TargetElevated => {
+ "the target window is owned by a higher-integrity process".into()
+ }
+ Refusal::PlatformUnsupported => "computer use is unsupported on this platform".into(),
+ Refusal::ActionRejected(reason) => format!("action rejected: {reason}"),
+ Refusal::Timeout => "the computer-use operation timed out".into(),
+ Refusal::Internal(reason) => format!("computer use failed: {reason}"),
+ }
+ }
+}
+
+impl From<DesktopError> for Refusal {
+ fn from(value: DesktopError) -> Self {
+ match value {
+ DesktopError::Unsupported => Refusal::PlatformUnsupported,
+ DesktopError::PermissionMissing => Refusal::OsPermissionMissing,
+ DesktopError::TargetGone => Refusal::ScopeViolation,
+ DesktopError::Elevated => Refusal::TargetElevated,
+ DesktopError::ElementNotFound => Refusal::ElementNotFound,
+ DesktopError::NotActionable => Refusal::ElementNotActionable,
+ DesktopError::Timeout => Refusal::Timeout,
+ DesktopError::Failed(reason) => Refusal::Internal(reason),
+ }
+ }
+}
+
+pub type ComputerResult<T> = Result<T, Refusal>;
+
+/// Truncate on a character boundary. Window titles are attacker-controlled, so
+/// a label is bounded before it can reach a model context or a log line.
+pub fn truncate_label(value: &str) -> String {
+ if value.chars().count() <= MAX_LABEL_CHARS {
+ return value.to_string();
+ }
+ value.chars().take(MAX_LABEL_CHARS).collect()
+}
diff --git a/crates/host-core/src/computer/policy.rs b/crates/host-core/src/computer/policy.rs
new file mode 100644
index 000000000..f044c78f6
--- /dev/null
+++ b/crates/host-core/src/computer/policy.rs
@@ -0,0 +1,449 @@
+//! Every computer-use refusal, and the grant lifecycle that enforces them.
+//!
+//! The rules here are deliberately mechanical: a request carries no identity
+//! the host trusts, so each one is re-checked against the live grant and a
+//! fresh measurement of the target. Nothing in this file consults a permission
+//! mode — the mode decides whether a grant may be minted and whether an input
+//! step needs a card, and both of those happen before a request arrives here.
+
+use std::time::{Duration, Instant};
+
+use super::backend::{Desktop, Measured, RawTarget};
+use super::{
+ ActResult, Action, ActionKind, Basis, CaptureMode, ComputerResult, Grant, GrantState,
+ InputPolicy, Inspection, Node, Point, Rect, Refusal, Target, TargetRefusal, MAX_ACTION_BUDGET,
+ MAX_IDLE_EXPIRY, MAX_NODES, MAX_TEXT_CHARS, MIN_IDLE_EXPIRY,
+};
+
+/// Application identifiers that may never be targeted, whatever the user
+/// configures. These are credential surfaces: driving them with synthetic
+/// input is indistinguishable from the user approving a secret release.
+pub fn built_in_denylist() -> &'static [&'static str] {
+ &[
+ // macOS
+ "com.apple.keychainaccess",
+ "com.apple.SecurityAgent",
+ "com.apple.systempreferences.securityagent",
+ "com.apple.loginwindow",
+ // Windows
+ "credentialuibroker.exe",
+ "consent.exe",
+ "lsass.exe",
+ "winlogon.exe",
+ // Linux
+ "polkit-gnome-authentication-agent-1",
+ "gnome-keyring-prompt",
+ "kwalletd5",
+ "kwalletd6",
+ "ksshaskpass",
+ // Cross-platform password managers, by the names their windows expose.
+ "1password",
+ "com.1password.1password",
+ "bitwarden",
+ "com.bitwarden.desktop",
+ "keepassxc",
+ "org.keepassxc.keepassxc",
+ ]
+}
+
+/// The denylist in force: the built-in credential surfaces, which cannot be
+/// removed, plus whatever the user added.
+#[derive(Debug, Clone, Default)]
+pub struct Denylist {
+ user: Vec<String>,
+}
+
+impl Denylist {
+ pub fn new(user_entries: &[String]) -> Self {
+ Self {
+ user: user_entries
+ .iter()
+ .map(|entry| entry.trim().to_ascii_lowercase())
+ .filter(|entry| !entry.is_empty())
+ .collect(),
+ }
+ }
+
+ pub fn refuses(&self, app_key: &str, app_name: &str) -> bool {
+ let key = app_key.trim().to_ascii_lowercase();
+ let name = app_name.trim().to_ascii_lowercase();
+ let hits = |entry: &str| !entry.is_empty() && (key.contains(entry) || name.contains(entry));
+ built_in_denylist().iter().any(|entry| hits(entry))
+ || self.user.iter().any(|entry| hits(entry))
+ }
+}
+
+/// Our own bundle identifiers. `own_pid` is the real check; these catch helper
+/// processes that run under a different pid but still draw our windows.
+const SELF_APP_KEYS: &[&str] = &[
+ "pi-desktop",
+ "pi desktop",
+ "com.pi-desktop",
+ "pi-desktop-host-core",
+];
+
+/// Why this window cannot be picked, or `None` when it can.
+///
+/// The self-target check comes first and is unconditional: a PI-Desktop window
+/// is refused even if the user added it to an allowlist, because synthetic
+/// input into our own approval cards bypasses the permission broker entirely.
+pub fn refusal_for_target(
+ raw: &RawTarget,
+ self_pids: &[i32],
+ denylist: &Denylist,
+) -> Option<TargetRefusal> {
+ if self_pids.contains(&raw.target.pid) {
+ return Some(TargetRefusal::SelfTarget);
+ }
+ let key = raw.target.app_key.trim().to_ascii_lowercase();
+ if SELF_APP_KEYS
+ .iter()
+ .any(|entry| key == *entry || key.starts_with(entry))
+ {
+ return Some(TargetRefusal::SelfTarget);
+ }
+ if denylist.refuses(&raw.target.app_key, &raw.app_name) {
+ return Some(TargetRefusal::Denylisted);
+ }
+ if raw.elevated {
+ return Some(TargetRefusal::Elevated);
+ }
+ None
+}
+
+/// Pickable and refused targets, with reasons. Refused entries stay in the
+/// list so the picker can explain itself instead of appearing to lose windows.
+pub fn list_targets(desktop: &dyn Desktop, denylist: &Denylist) -> ComputerResult<Vec<Target>> {
+ let self_pids = desktop.self_pids();
+ let raw = desktop.list_targets().map_err(Refusal::from)?;
+ Ok(raw
+ .into_iter()
+ .map(|item| {
+ let refused_reason = refusal_for_target(&item, &self_pids, denylist);
+ Target {
+ target_id: item.target.target_id.clone(),
+ app_name: super::truncate_label(&item.app_name),
+ title: super::truncate_label(&item.title),
+ app_key: item.target.app_key.clone(),
+ bounds: item.bounds,
+ refused_reason,
+ }
+ })
+ .collect())
+}
+
+pub struct GrantRequest {
+ pub target_id: String,
+ pub session_id: String,
+ pub input_policy: InputPolicy,
+ pub capture: CaptureMode,
+ pub action_budget: u32,
+ pub idle_expiry: Duration,
+}
+
+/// Mint the single active grant from a target the user picked.
+///
+/// The caller supplies a `target_id`, never a window handle, and the handle is
+/// re-resolved from a fresh enumeration here — so a stale or invented id cannot
+/// become authority over a window that now belongs to something else.
+pub fn create_grant(
+ desktop: &dyn Desktop,
+ existing: Option<&Grant>,
+ denylist: &Denylist,
+ request: GrantRequest,
+ now: Instant,
+) -> ComputerResult<Grant> {
+ if let Some(active) = existing {
+ if active.state == GrantState::Active && !active.expired_at(now) {
+ return Err(Refusal::GrantInUse);
+ }
+ }
+ let self_pids = desktop.self_pids();
+ let raw = desktop.list_targets().map_err(Refusal::from)?;
+ let found = raw
+ .into_iter()
+ .find(|item| item.target.target_id == request.target_id)
+ .ok_or(Refusal::ScopeViolation)?;
+ match refusal_for_target(&found, &self_pids, denylist) {
+ Some(TargetRefusal::SelfTarget) => return Err(Refusal::SelfTargetRefused),
+ Some(TargetRefusal::Denylisted) => return Err(Refusal::TargetDenylisted),
+ Some(TargetRefusal::Elevated) => return Err(Refusal::TargetElevated),
+ Some(TargetRefusal::NoAccessibility) => return Err(Refusal::OsPermissionMissing),
+ None => {}
+ }
+ let label = if found.title.trim().is_empty() {
+ super::truncate_label(&found.app_name)
+ } else {
+ format!(
+ "{} — {}",
+ super::truncate_label(&found.app_name),
+ super::truncate_label(&found.title)
+ )
+ };
+ Ok(Grant {
+ grant_id: format!("cug_{}", uuid::Uuid::new_v4().simple()),
+ revision: 1,
+ target: found.target,
+ target_label: label,
+ bounds: found.bounds,
+ input_policy: request.input_policy,
+ capture: request.capture,
+ remaining_budget: request.action_budget.clamp(1, MAX_ACTION_BUDGET),
+ session_id: request.session_id,
+ created_at: chrono::Utc::now().to_rfc3339(),
+ last_activity: now,
+ idle_expiry: request.idle_expiry.clamp(MIN_IDLE_EXPIRY, MAX_IDLE_EXPIRY),
+ state: GrantState::Active,
+ })
+}
+
+/// The grant a request may use, or the reason it may not.
+pub fn usable_grant<'a>(
+ grant: Option<&'a mut Grant>,
+ grant_id: &str,
+ session_id: Option<&str>,
+ now: Instant,
+) -> ComputerResult<&'a mut Grant> {
+ let grant = grant.ok_or(Refusal::NoGrant)?;
+ if grant.grant_id != grant_id {
+ return Err(Refusal::NoGrant);
+ }
+ if grant.state != GrantState::Active {
+ return Err(Refusal::GrantExpired);
+ }
+ if grant.expired_at(now) {
+ grant.state = GrantState::Expired;
+ return Err(Refusal::GrantExpired);
+ }
+ if let Some(session) = session_id {
+ if grant.session_id != session {
+ return Err(Refusal::GrantInUse);
+ }
+ }
+ Ok(grant)
+}
+
+/// Re-measure the target and fold the result into the grant.
+///
+/// A window that moved or changed identity bumps the revision, which
+/// invalidates every `uid` and `basis` the caller is holding. A window that is
+/// gone is a scope violation: there is nothing left that the grant describes.
+fn refresh(desktop: &dyn Desktop, grant: &mut Grant) -> ComputerResult<Measured> {
+ let measured = desktop.measure(&grant.target).map_err(Refusal::from)?;
+ let moved = !grant.bounds.matches(&measured.bounds);
+ let reidentified = measured.app_key != grant.target.app_key;
+ if reidentified {
+ // The handle now belongs to a different application. Nothing about
+ // this grant still describes what the user picked.
+ grant.state = GrantState::Revoked;
+ return Err(Refusal::ScopeViolation);
+ }
+ if moved {
+ grant.revision = grant.revision.saturating_add(1);
+ grant.bounds = measured.bounds;
+ }
+ Ok(measured)
+}
+
+pub fn inspect(
+ desktop: &dyn Desktop,
+ grant: &mut Grant,
+ expected_revision: Option<u32>,
+ now: Instant,
+) -> ComputerResult<Inspection> {
+ if desktop.secure_input_active() {
+ return Err(Refusal::SecureInputRefused);
+ }
+ refresh(desktop, grant)?;
+ if let Some(expected) = expected_revision {
+ if expected != grant.revision {
+ return Err(Refusal::StaleRevision);
+ }
+ }
+ let raw = desktop
+ .inspect(&grant.target, MAX_NODES)
+ .map_err(Refusal::from)?;
+ grant.last_activity = now;
+ Ok(Inspection {
+ grant_id: grant.grant_id.clone(),
+ revision: grant.revision,
+ bounds: grant.bounds,
+ fidelity: raw.fidelity,
+ nodes: bound_nodes(raw.nodes),
+ truncated: raw.truncated,
+ secure_input: false,
+ })
+}
+
+/// Labels come from windows the user does not control, so they are bounded
+/// here rather than trusted from a backend.
+fn bound_nodes(nodes: Vec<Node>) -> Vec<Node> {
+ nodes
+ .into_iter()
+ .take(MAX_NODES)
+ .map(|mut node| {
+ node.label = node.label.map(|label| super::truncate_label(&label));
+ node.role = super::truncate_label(&node.role);
+ node
+ })
+ .collect()
+}
+
+/// Validate one action against the live grant, without dispatching it.
+///
+/// Split out from `act` so the refusals can be tested without a platform and
+/// so a caller that wants to pre-flight a step gets exactly the same verdict.
+pub fn validate_action(
+ grant: &Grant,
+ action: &Action,
+ measured_bounds: &Rect,
+) -> ComputerResult<ActionKind> {
+ let kind = action
+ .kind
+ .ok_or_else(|| Refusal::ActionRejected("missing action kind".into()))?;
+ if kind.is_input() && grant.remaining_budget == 0 {
+ return Err(Refusal::BudgetExhausted);
+ }
+ if action.uid.is_none() && action.point.is_none() {
+ return Err(Refusal::ActionRejected(
+ "action names neither an element nor a point".into(),
+ ));
+ }
+ if let Some(uid) = &action.uid {
+ if uid.trim().is_empty() || uid.len() > 256 {
+ return Err(Refusal::ActionRejected("malformed element id".into()));
+ }
+ }
+ if let Some(point) = action.point {
+ let basis = action
+ .basis
+ .ok_or_else(|| Refusal::ActionRejected("coordinate action without a basis".into()))?;
+ validate_basis(grant, &basis, measured_bounds)?;
+ if !measured_bounds.contains(point.x, point.y) {
+ return Err(Refusal::ScopeViolation);
+ }
+ }
+ match kind {
+ ActionKind::SetValue => {
+ let text = action
+ .text
+ .as_deref()
+ .ok_or_else(|| Refusal::ActionRejected("set_value without text".into()))?;
+ if text.chars().count() > MAX_TEXT_CHARS {
+ return Err(Refusal::ActionRejected(
+ "text exceeds the step limit".into(),
+ ));
+ }
+ }
+ ActionKind::PressKeys => {
+ let keys = action
+ .keys
+ .as_ref()
+ .ok_or_else(|| Refusal::ActionRejected("press_keys without keys".into()))?;
+ if keys.is_empty() || keys.len() > 16 {
+ return Err(Refusal::ActionRejected(
+ "press_keys expects 1 to 16 chords".into(),
+ ));
+ }
+ if keys
+ .iter()
+ .any(|chord| chord.trim().is_empty() || chord.len() > 64)
+ {
+ return Err(Refusal::ActionRejected("malformed key chord".into()));
+ }
+ }
+ ActionKind::Select => {
+ let option = action
+ .option
+ .as_deref()
+ .ok_or_else(|| Refusal::ActionRejected("select without an option".into()))?;
+ if option.trim().is_empty() || option.chars().count() > super::MAX_LABEL_CHARS {
+ return Err(Refusal::ActionRejected("malformed select option".into()));
+ }
+ }
+ ActionKind::Scroll => {
+ let scroll = action
+ .scroll
+ .ok_or_else(|| Refusal::ActionRejected("scroll without a delta".into()))?;
+ if !scroll.dx.is_finite() || !scroll.dy.is_finite() {
+ return Err(Refusal::ActionRejected("non-finite scroll delta".into()));
+ }
+ }
+ ActionKind::Click | ActionKind::DoubleClick | ActionKind::RightClick => {}
+ }
+ Ok(kind)
+}
+
+/// A basis is only as good as the geometry it was taken against: if the window
+/// has moved since the capture, the coordinates in it now point somewhere else.
+fn validate_basis(grant: &Grant, basis: &Basis, measured_bounds: &Rect) -> ComputerResult<()> {
+ if basis.revision != grant.revision {
+ return Err(Refusal::StaleRevision);
+ }
+ if !basis.bounds.matches(measured_bounds) {
+ return Err(Refusal::StaleBasis);
+ }
+ Ok(())
+}
+
+pub fn act(
+ desktop: &dyn Desktop,
+ grant: &mut Grant,
+ expected_revision: Option<u32>,
+ action: &Action,
+ now: Instant,
+) -> ComputerResult<ActResult> {
+ if desktop.secure_input_active() {
+ return Err(Refusal::SecureInputRefused);
+ }
+ let measured = refresh(desktop, grant)?;
+ if let Some(expected) = expected_revision {
+ if expected != grant.revision {
+ return Err(Refusal::StaleRevision);
+ }
+ }
+ let kind = validate_action(grant, action, &measured.bounds)?;
+ let dispatched = desktop
+ .perform(&grant.target, action.uid.as_deref(), action)
+ .map_err(Refusal::from)?;
+ // The budget is spent on a dispatch that happened, not on an attempt that
+ // was refused: a window that rejects every action must not silently burn
+ // the grant, but a dispatched action always costs one.
+ if kind.is_input() {
+ grant.remaining_budget = grant.remaining_budget.saturating_sub(1);
+ }
+ grant.last_activity = now;
+ if grant.remaining_budget == 0 {
+ grant.state = GrantState::Expired;
+ }
+ Ok(ActResult {
+ grant_id: grant.grant_id.clone(),
+ revision: grant.revision,
+ remaining_budget: grant.remaining_budget,
+ dispatched,
+ })
+}
+
+/// Where the overlay should draw the agent's cursor for this action, in screen
+/// coordinates. Visualization only: a `None` here never blocks an action.
+pub fn cursor_point(grant: &Grant, action: &Action, node_bounds: Option<Rect>) -> Option<Point> {
+ if let Some(bounds) = node_bounds {
+ return Some(Point {
+ x: bounds.x + bounds.width / 2.0,
+ y: bounds.y + bounds.height / 2.0,
+ });
+ }
+ action.point.map(|point| Point {
+ x: grant.bounds.x + point.x,
+ y: grant.bounds.y + point.y,
+ })
+}
+
+pub fn revoke(grant: &mut Grant, expired: bool) {
+ grant.state = if expired {
+ GrantState::Expired
+ } else {
+ GrantState::Revoked
+ };
+ grant.remaining_budget = 0;
+}
diff --git a/crates/host-core/src/computer/tests.rs b/crates/host-core/src/computer/tests.rs
new file mode 100644
index 000000000..8d2df090f
--- /dev/null
+++ b/crates/host-core/src/computer/tests.rs
@@ -0,0 +1,672 @@
+//! Refusal coverage for computer use. These are the tests ADR 0340 names as
+//! landing gates, and they run on every platform because the fake backend
+//! stands in for the native one: the rules being checked are policy's, not the
+//! platform's.
+
+use std::sync::Mutex;
+use std::time::{Duration, Instant};
+
+use super::backend::{
+ Desktop, DesktopError, Dispatched, Measured, RawInspection, RawTarget, TargetRef,
+};
+use super::policy::{self, Denylist, GrantRequest};
+use super::{
+ Action, ActionKind, Basis, Capabilities, CaptureMode, Fidelity, Grant, GrantState, InputPolicy,
+ Node, PermissionState, Point, Rect, Refusal, Scroll,
+};
+
+const OWN_PID: i32 = 4_242;
+
+fn rect(x: f64, y: f64, width: f64, height: f64) -> Rect {
+ Rect {
+ x,
+ y,
+ width,
+ height,
+ }
+}
+
+fn node(uid: &str, role: &str, actions: Vec<ActionKind>) -> Node {
+ Node {
+ uid: uid.into(),
+ role: role.into(),
+ label: Some("Save".into()),
+ has_value: false,
+ enabled: true,
+ focused: false,
+ bounds: Some(rect(10.0, 20.0, 80.0, 24.0)),
+ parent: None,
+ actions,
+ }
+}
+
+struct FakeDesktop {
+ targets: Mutex<Vec<RawTarget>>,
+ measured: Mutex<Option<Measured>>,
+ secure_input: Mutex<bool>,
+ perform_result: Mutex<Result<Dispatched, DesktopError>>,
+ performed: Mutex<Vec<(Option<String>, ActionKind)>>,
+}
+
+impl FakeDesktop {
+ fn new(targets: Vec<RawTarget>) -> Self {
+ let bounds = targets
+ .first()
+ .map(|item| item.bounds)
+ .unwrap_or(rect(0.0, 0.0, 100.0, 100.0));
+ let app_key = targets
+ .first()
+ .map(|item| item.target.app_key.clone())
+ .unwrap_or_else(|| "com.example.app".into());
+ Self {
+ targets: Mutex::new(targets),
+ measured: Mutex::new(Some(Measured {
+ bounds,
+ app_key,
+ title: "Document".into(),
+ })),
+ secure_input: Mutex::new(false),
+ perform_result: Mutex::new(Ok(Dispatched::AccessibilityAction)),
+ performed: Mutex::new(Vec::new()),
+ }
+ }
+
+ fn set_measured(&self, measured: Option<Measured>) {
+ *self.measured.lock().unwrap() = measured;
+ }
+
+ fn set_secure_input(&self, value: bool) {
+ *self.secure_input.lock().unwrap() = value;
+ }
+
+ fn performed_count(&self) -> usize {
+ self.performed.lock().unwrap().len()
+ }
+}
+
+impl Desktop for FakeDesktop {
+ fn capabilities(&self) -> Capabilities {
+ Capabilities {
+ platform: "test".into(),
+ backend: "macos-ax".into(),
+ fidelity: Fidelity::Full,
+ accessibility: PermissionState::Granted,
+ capture: PermissionState::Granted,
+ session_type: None,
+ input_unsupported_reason: None,
+ }
+ }
+
+ fn list_targets(&self) -> Result<Vec<RawTarget>, DesktopError> {
+ Ok(self.targets.lock().unwrap().clone())
+ }
+
+ fn measure(&self, _target: &TargetRef) -> Result<Measured, DesktopError> {
+ self.measured
+ .lock()
+ .unwrap()
+ .clone()
+ .ok_or(DesktopError::TargetGone)
+ }
+
+ fn inspect(
+ &self,
+ _target: &TargetRef,
+ _max_nodes: usize,
+ ) -> Result<RawInspection, DesktopError> {
+ Ok(RawInspection {
+ nodes: vec![node("0.1", "AXButton", vec![ActionKind::Click])],
+ truncated: false,
+ fidelity: Fidelity::Full,
+ })
+ }
+
+ fn secure_input_active(&self) -> bool {
+ *self.secure_input.lock().unwrap()
+ }
+
+ fn perform(
+ &self,
+ _target: &TargetRef,
+ uid: Option<&str>,
+ action: &Action,
+ ) -> Result<Dispatched, DesktopError> {
+ let result = self.perform_result.lock().unwrap().clone();
+ if result.is_ok() {
+ self.performed
+ .lock()
+ .unwrap()
+ .push((uid.map(str::to_string), action.kind.unwrap()));
+ }
+ result
+ }
+
+ fn self_pids(&self) -> Vec<i32> {
+ vec![OWN_PID]
+ }
+}
+
+fn target(pid: i32, app_key: &str, app_name: &str, id: &str) -> RawTarget {
+ RawTarget {
+ target: TargetRef {
+ target_id: id.into(),
+ pid,
+ window: 7,
+ app_key: app_key.into(),
+ },
+ app_name: app_name.into(),
+ title: "Document".into(),
+ bounds: rect(100.0, 100.0, 800.0, 600.0),
+ elevated: false,
+ }
+}
+
+fn grant_for(desktop: &FakeDesktop, id: &str) -> Grant {
+ policy::create_grant(
+ desktop,
+ None,
+ &Denylist::default(),
+ GrantRequest {
+ target_id: id.into(),
+ session_id: "session-1".into(),
+ input_policy: InputPolicy::ConfirmEach,
+ capture: CaptureMode::A11yOnly,
+ action_budget: 3,
+ idle_expiry: Duration::from_secs(600),
+ },
+ Instant::now(),
+ )
+ .expect("grant")
+}
+
+fn click_uid(uid: &str) -> Action {
+ Action {
+ kind: Some(ActionKind::Click),
+ uid: Some(uid.into()),
+ ..Action::default()
+ }
+}
+
+#[test]
+fn our_own_windows_are_never_pickable() {
+ let desktop = FakeDesktop::new(vec![
+ target(OWN_PID, "com.pi-desktop", "PI-Desktop", "self-window"),
+ target(99, "com.example.app", "Example", "other-window"),
+ ]);
+ let listed = policy::list_targets(&desktop, &Denylist::default()).expect("targets");
+ let own = listed
+ .iter()
+ .find(|item| item.target_id == "self-window")
+ .expect("listed");
+ // Listed, not hidden — the picker has to be able to explain the refusal.
+ assert_eq!(own.refused_reason, Some(super::TargetRefusal::SelfTarget));
+
+ let error = policy::create_grant(
+ &desktop,
+ None,
+ &Denylist::default(),
+ GrantRequest {
+ target_id: "self-window".into(),
+ session_id: "session-1".into(),
+ input_policy: InputPolicy::AutonomousInScope,
+ capture: CaptureMode::A11yAndPixels,
+ action_budget: 10,
+ idle_expiry: Duration::from_secs(600),
+ },
+ Instant::now(),
+ )
+ .expect_err("self target must refuse");
+ assert_eq!(error, Refusal::SelfTargetRefused);
+}
+
+#[test]
+fn a_renamed_self_process_is_still_refused() {
+ // A helper process with a different pid but one of our app keys.
+ let desktop = FakeDesktop::new(vec![target(
+ 1234,
+ "pi-desktop-host-core",
+ "Helper",
+ "helper",
+ )]);
+ let error = policy::create_grant(
+ &desktop,
+ None,
+ &Denylist::default(),
+ GrantRequest {
+ target_id: "helper".into(),
+ session_id: "s".into(),
+ input_policy: InputPolicy::ConfirmEach,
+ capture: CaptureMode::A11yOnly,
+ action_budget: 1,
+ idle_expiry: Duration::from_secs(60),
+ },
+ Instant::now(),
+ )
+ .expect_err("self app key must refuse");
+ assert_eq!(error, Refusal::SelfTargetRefused);
+}
+
+#[test]
+fn built_in_credential_surfaces_cannot_be_allowlisted() {
+ let desktop = FakeDesktop::new(vec![target(
+ 31,
+ "com.apple.keychainaccess",
+ "Keychain Access",
+ "kc",
+ )]);
+ // An empty user list is the most permissive configuration there is.
+ let error = policy::create_grant(
+ &desktop,
+ None,
+ &Denylist::new(&[]),
+ GrantRequest {
+ target_id: "kc".into(),
+ session_id: "s".into(),
+ input_policy: InputPolicy::ConfirmEach,
+ capture: CaptureMode::A11yOnly,
+ action_budget: 1,
+ idle_expiry: Duration::from_secs(60),
+ },
+ Instant::now(),
+ )
+ .expect_err("credential surface must refuse");
+ assert_eq!(error, Refusal::TargetDenylisted);
+}
+
+#[test]
+fn a_user_denylist_entry_matches_key_or_name() {
+ let list = Denylist::new(&["Secret Notes".to_string()]);
+ assert!(list.refuses("com.example.notes", "Secret Notes"));
+ assert!(!list.refuses("com.example.notes", "Public Notes"));
+}
+
+#[test]
+fn secure_input_refuses_both_inspection_and_action() {
+ let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);
+ let mut grant = grant_for(&desktop, "w1");
+ desktop.set_secure_input(true);
+
+ let inspect = policy::inspect(&desktop, &mut grant, None, Instant::now()).expect_err("inspect");
+ assert_eq!(inspect, Refusal::SecureInputRefused);
+
+ let act = policy::act(
+ &desktop,
+ &mut grant,
+ None,
+ &click_uid("0.1"),
+ Instant::now(),
+ )
+ .expect_err("act");
+ assert_eq!(act, Refusal::SecureInputRefused);
+ assert_eq!(desktop.performed_count(), 0, "nothing may be dispatched");
+}
+
+#[test]
+fn a_moved_window_bumps_the_revision_and_invalidates_a_basis() {
+ let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);
+ let mut grant = grant_for(&desktop, "w1");
+ let captured = Basis {
+ revision: grant.revision,
+ bounds: grant.bounds,
+ };
+
+ desktop.set_measured(Some(Measured {
+ bounds: rect(400.0, 100.0, 800.0, 600.0),
+ app_key: "com.example.app".into(),
+ title: "Document".into(),
+ }));
+
+ let action = Action {
+ kind: Some(ActionKind::Click),
+ point: Some(Point { x: 10.0, y: 10.0 }),
+ basis: Some(captured),
+ ..Action::default()
+ };
+ let error =
+ policy::act(&desktop, &mut grant, None, &action, Instant::now()).expect_err("stale basis");
+ assert_eq!(error, Refusal::StaleRevision);
+ assert_eq!(grant.revision, 2, "the move is recorded");
+ assert_eq!(desktop.performed_count(), 0);
+}
+
+#[test]
+fn a_resized_window_with_the_same_revision_still_refuses_a_stale_basis() {
+ let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);
+ let grant = grant_for(&desktop, "w1");
+ // A basis whose geometry disagrees with the live measurement, carrying the
+ // revision the caller currently holds.
+ let action = Action {
+ kind: Some(ActionKind::Click),
+ point: Some(Point { x: 10.0, y: 10.0 }),
+ basis: Some(Basis {
+ revision: grant.revision,
+ bounds: rect(0.0, 0.0, 10.0, 10.0),
+ }),
+ ..Action::default()
+ };
+ let error = policy::validate_action(&grant, &action, &grant.bounds).expect_err("basis");
+ assert_eq!(error, Refusal::StaleBasis);
+}
+
+#[test]
+fn an_expected_revision_mismatch_refuses_before_dispatch() {
+ let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);
+ let mut grant = grant_for(&desktop, "w1");
+ let error = policy::act(
+ &desktop,
+ &mut grant,
+ Some(99),
+ &click_uid("0.1"),
+ Instant::now(),
+ )
+ .expect_err("revision");
+ assert_eq!(error, Refusal::StaleRevision);
+ assert_eq!(desktop.performed_count(), 0);
+}
+
+#[test]
+fn coordinates_outside_the_measured_window_are_refused_not_clamped() {
+ let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);
+ let grant = grant_for(&desktop, "w1");
+ let action = Action {
+ kind: Some(ActionKind::Click),
+ point: Some(Point {
+ x: 5_000.0,
+ y: 10.0,
+ }),
+ basis: Some(Basis {
+ revision: grant.revision,
+ bounds: grant.bounds,
+ }),
+ ..Action::default()
+ };
+ let error = policy::validate_action(&grant, &action, &grant.bounds).expect_err("bounds");
+ assert_eq!(error, Refusal::ScopeViolation);
+}
+
+#[test]
+fn a_coordinate_action_without_a_basis_is_refused() {
+ let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);
+ let grant = grant_for(&desktop, "w1");
+ let action = Action {
+ kind: Some(ActionKind::Click),
+ point: Some(Point { x: 10.0, y: 10.0 }),
+ ..Action::default()
+ };
+ match policy::validate_action(&grant, &action, &grant.bounds) {
+ Err(Refusal::ActionRejected(reason)) => assert!(reason.contains("basis")),
+ other => panic!("expected a rejection, got {other:?}"),
+ }
+}
+
+#[test]
+fn the_budget_closes_the_grant_and_refuses_the_next_action() {
+ let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);
+ let mut grant = grant_for(&desktop, "w1");
+ grant.remaining_budget = 1;
+
+ let first = policy::act(
+ &desktop,
+ &mut grant,
+ None,
+ &click_uid("0.1"),
+ Instant::now(),
+ )
+ .expect("first");
+ assert_eq!(first.remaining_budget, 0);
+ assert_eq!(
+ grant.state,
+ GrantState::Expired,
+ "a spent grant closes itself"
+ );
+
+ let error = policy::act(
+ &desktop,
+ &mut grant,
+ None,
+ &click_uid("0.1"),
+ Instant::now(),
+ )
+ .expect_err("budget");
+ assert_eq!(error, Refusal::BudgetExhausted);
+ assert_eq!(desktop.performed_count(), 1);
+}
+
+#[test]
+fn a_refused_dispatch_does_not_spend_the_budget() {
+ let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);
+ let mut grant = grant_for(&desktop, "w1");
+ *desktop.perform_result.lock().unwrap() = Err(DesktopError::NotActionable);
+ let before = grant.remaining_budget;
+ let error = policy::act(
+ &desktop,
+ &mut grant,
+ None,
+ &click_uid("0.1"),
+ Instant::now(),
+ )
+ .expect_err("not actionable");
+ assert_eq!(error, Refusal::ElementNotActionable);
+ assert_eq!(grant.remaining_budget, before);
+}
+
+#[test]
+fn an_idle_grant_expires_and_stays_expired() {
+ let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);
+ let mut grant = grant_for(&desktop, "w1");
+ grant.idle_expiry = Duration::from_secs(30);
+ grant.last_activity = Instant::now() - Duration::from_secs(31);
+
+ let id = grant.grant_id.clone();
+ let mut slot = Some(grant);
+ let error =
+ policy::usable_grant(slot.as_mut(), &id, None, Instant::now()).expect_err("expired");
+ assert_eq!(error, Refusal::GrantExpired);
+ assert_eq!(slot.unwrap().state, GrantState::Expired);
+}
+
+#[test]
+fn only_one_grant_is_active_per_instance() {
+ let desktop = FakeDesktop::new(vec![
+ target(5, "com.example.app", "Example", "w1"),
+ target(6, "com.other.app", "Other", "w2"),
+ ]);
+ let active = grant_for(&desktop, "w1");
+ let error = policy::create_grant(
+ &desktop,
+ Some(&active),
+ &Denylist::default(),
+ GrantRequest {
+ target_id: "w2".into(),
+ session_id: "session-2".into(),
+ input_policy: InputPolicy::ConfirmEach,
+ capture: CaptureMode::A11yOnly,
+ action_budget: 5,
+ idle_expiry: Duration::from_secs(600),
+ },
+ Instant::now(),
+ )
+ .expect_err("second grant");
+ assert_eq!(error, Refusal::GrantInUse);
+}
+
+#[test]
+fn another_session_cannot_use_the_active_grant() {
+ let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);
+ let grant = grant_for(&desktop, "w1");
+ let id = grant.grant_id.clone();
+ let mut slot = Some(grant);
+ let error = policy::usable_grant(slot.as_mut(), &id, Some("session-2"), Instant::now())
+ .expect_err("wrong session");
+ assert_eq!(error, Refusal::GrantInUse);
+ assert!(policy::usable_grant(slot.as_mut(), &id, Some("session-1"), Instant::now()).is_ok());
+}
+
+#[test]
+fn a_target_that_became_another_application_revokes_the_grant() {
+ let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);
+ let mut grant = grant_for(&desktop, "w1");
+ desktop.set_measured(Some(Measured {
+ bounds: grant.bounds,
+ app_key: "com.attacker.app".into(),
+ title: "Document".into(),
+ }));
+ let error = policy::act(
+ &desktop,
+ &mut grant,
+ None,
+ &click_uid("0.1"),
+ Instant::now(),
+ )
+ .expect_err("reidentified");
+ assert_eq!(error, Refusal::ScopeViolation);
+ assert_eq!(grant.state, GrantState::Revoked);
+ assert_eq!(desktop.performed_count(), 0);
+}
+
+#[test]
+fn a_closed_window_is_a_scope_violation() {
+ let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);
+ let mut grant = grant_for(&desktop, "w1");
+ desktop.set_measured(None);
+ let error = policy::act(
+ &desktop,
+ &mut grant,
+ None,
+ &click_uid("0.1"),
+ Instant::now(),
+ )
+ .expect_err("gone");
+ assert_eq!(error, Refusal::ScopeViolation);
+}
+
+#[test]
+fn malformed_actions_are_rejected_before_the_platform_sees_them() {
+ let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);
+ let grant = grant_for(&desktop, "w1");
+ let cases: Vec<Action> = vec![
+ Action::default(),
+ Action {
+ kind: Some(ActionKind::Click),
+ ..Action::default()
+ },
+ Action {
+ kind: Some(ActionKind::SetValue),
+ uid: Some("0.1".into()),
+ ..Action::default()
+ },
+ Action {
+ kind: Some(ActionKind::SetValue),
+ uid: Some("0.1".into()),
+ text: Some("x".repeat(super::MAX_TEXT_CHARS + 1)),
+ ..Action::default()
+ },
+ Action {
+ kind: Some(ActionKind::PressKeys),
+ uid: Some("0.1".into()),
+ keys: Some(vec![]),
+ ..Action::default()
+ },
+ Action {
+ kind: Some(ActionKind::PressKeys),
+ uid: Some("0.1".into()),
+ keys: Some(vec![" ".into()]),
+ ..Action::default()
+ },
+ Action {
+ kind: Some(ActionKind::Select),
+ uid: Some("0.1".into()),
+ ..Action::default()
+ },
+ Action {
+ kind: Some(ActionKind::Scroll),
+ uid: Some("0.1".into()),
+ ..Action::default()
+ },
+ Action {
+ kind: Some(ActionKind::Scroll),
+ uid: Some("0.1".into()),
+ scroll: Some(Scroll {
+ dx: f64::NAN,
+ dy: 0.0,
+ }),
+ ..Action::default()
+ },
+ Action {
+ kind: Some(ActionKind::Click),
+ uid: Some(" ".into()),
+ ..Action::default()
+ },
+ ];
+ for action in cases {
+ let result = policy::validate_action(&grant, &action, &grant.bounds);
+ assert!(result.is_err(), "accepted {action:?}");
+ }
+}
+
+#[test]
+fn labels_from_a_window_are_bounded() {
+ let long = "x".repeat(super::MAX_LABEL_CHARS * 3);
+ assert_eq!(
+ super::truncate_label(&long).chars().count(),
+ super::MAX_LABEL_CHARS
+ );
+ // A multi-byte label must not be cut mid-character.
+ let wide = "字".repeat(super::MAX_LABEL_CHARS + 10);
+ assert_eq!(
+ super::truncate_label(&wide).chars().count(),
+ super::MAX_LABEL_CHARS
+ );
+}
+
+#[test]
+fn an_unsupported_platform_refuses_every_operation() {
+ let desktop = super::backend::UnsupportedDesktop::new("test", "no backend");
+ assert!(
+ desktop.secure_input_active(),
+ "refusing is the safe default"
+ );
+ assert_eq!(desktop.capabilities().fidelity, Fidelity::None);
+ assert_eq!(
+ policy::list_targets(&desktop, &Denylist::default()).expect_err("targets"),
+ Refusal::PlatformUnsupported
+ );
+}
+
+#[test]
+fn the_cursor_point_is_visualization_only() {
+ let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);
+ let grant = grant_for(&desktop, "w1");
+ // Element bounds win, because that is where the action actually lands.
+ let from_node = policy::cursor_point(
+ &grant,
+ &click_uid("0.1"),
+ Some(rect(10.0, 20.0, 100.0, 40.0)),
+ );
+ assert_eq!(from_node, Some(Point { x: 60.0, y: 40.0 }));
+ // A coordinate action draws at the window-relative point, offset to screen.
+ let action = Action {
+ kind: Some(ActionKind::Click),
+ point: Some(Point { x: 5.0, y: 6.0 }),
+ ..Action::default()
+ };
+ let from_point = policy::cursor_point(&grant, &action, None).expect("point");
+ assert_eq!(from_point.x, grant.bounds.x + 5.0);
+ assert_eq!(from_point.y, grant.bounds.y + 6.0);
+ // Neither: nothing to draw, and that is not an error.
+ assert_eq!(policy::cursor_point(&grant, &Action::default(), None), None);
+}
+
+#[test]
+fn a_grant_view_reports_expiry_without_persisting_it() {
+ let desktop = FakeDesktop::new(vec![target(5, "com.example.app", "Example", "w1")]);
+ let grant = grant_for(&desktop, "w1");
+ let view = grant.view(Instant::now());
+ assert_eq!(view.state, GrantState::Active);
+ assert_eq!(view.remaining_budget, 3);
+ assert!(
+ view.expires_at > view.created_at,
+ "the deadline is ahead of creation"
+ );
+ assert_eq!(view.target_label, "Example — Document");
+}
diff --git a/crates/host-core/src/main.rs b/crates/host-core/src/main.rs
index 601ece190..ae09eb8da 100644
--- a/crates/host-core/src/main.rs
+++ b/crates/host-core/src/main.rs
@@ -3,6 +3,7 @@ mod agent_capabilities;
mod artifacts;
mod audit;
mod background_tasks;
+mod computer;
mod config_sync;
mod data_relocation;
mod db;
diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.md
index e2972cdeb..e6472fbbe 100644
--- a/docs/spec/03-runtime/08-error-codes.md
+++ b/docs/spec/03-runtime/08-error-codes.md
@@ -361,6 +361,8 @@ means the host will retry, and it never widens a scope.
| code | retriable | meaning |
|---|---|---|
| `COMPUTER_DISABLED` | no | computer use is disabled in settings |
+| `COMPUTER_NOT_CONFIGURED` | no | computer use is enabled but no model binding is configured |
+| `COMPUTER_ACTION_REJECTED` | no | the bound model answered outside the action schema, or named an element, coordinate, or target the validation refused |
| `COMPUTER_NO_GRANT` | no | no active scope grant owns this session and turn chain |
| `COMPUTER_GRANT_IN_USE` | no | another session or turn chain holds the single active grant |
| `COMPUTER_GRANT_EXPIRED` | no | the grant hit its idle expiry, was revoked, or its target closed |
diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.md
index 6f4363815..268b521de 100644
--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md
+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md
@@ -352,6 +352,8 @@ ADR 0285)。渲染进程除了一个标识徽章外看不到本地/远程之
| code | 可重试 | 含义 |
|---|---|---|
| `COMPUTER_DISABLED` | 否 | 设置中关闭了电脑操作 |
+| `COMPUTER_NOT_CONFIGURED` | 否 | 电脑操作已开启但没有配置模型绑定 |
+| `COMPUTER_ACTION_REJECTED` | 否 | 绑定模型的回答超出动作 schema,或指定了校验拒绝的元素、坐标或目标 |
| `COMPUTER_NO_GRANT` | 否 | 没有活动作用域授权属于该会话与轮次链 |
| `COMPUTER_GRANT_IN_USE` | 否 | 另一个会话或轮次链持有唯一的活动授权 |
| `COMPUTER_GRANT_EXPIRED` | 否 | 授权空闲过期、被撤销,或目标已关闭 |
diff --git a/packages/shared/src/computer-use.test.ts b/packages/shared/src/computer-use.test.ts
new file mode 100644
index 000000000..676466b89
--- /dev/null
+++ b/packages/shared/src/computer-use.test.ts
@@ -0,0 +1,81 @@
+import { expect, it } from "vitest";
+import {
+ COMPUTER_ACTION_BUDGET_LIMIT,
+ COMPUTER_MAX_STEPS_LIMIT,
+ validateComputerToolArgs,
+ validateComputerUseSettings,
+} from "./computer-use.js";
+
+it("computerUse settings accept the minimum shape", () => {
+ expect(validateComputerUseSettings({ enabled: false })).toEqual({ enabled: false });
+});
+
+it("computerUse settings keep an explicit model binding", () => {
+ const value = validateComputerUseSettings({
+ enabled: true,
+ model: { providerId: "p1", modelId: "ui-model" },
+ defaultInputPolicy: "autonomous-in-scope",
+ defaultCapture: "a11y-and-pixels",
+ denylist: ["com.apple.keychainaccess"],
+ actionBudget: 10,
+ idleExpiryMs: 60_000,
+ });
+ expect(value.model).toEqual({ providerId: "p1", modelId: "ui-model" });
+ expect(value.defaultInputPolicy).toBe("autonomous-in-scope");
+ expect(value.defaultCapture).toBe("a11y-and-pixels");
+ expect(value.denylist).toEqual(["com.apple.keychainaccess"]);
+});
+
+it("computerUse settings distinguish an absent binding from a cleared one", () => {
+ expect(validateComputerUseSettings({ enabled: true }).model).toBe(undefined);
+ expect(validateComputerUseSettings({ enabled: true, model: null }).model).toBe(null);
+});
+
+it("computerUse settings reject unknown keys and bad values", () => {
+ for (const value of [
+ { enabled: true, somethingElse: 1 },
+ { enabled: "yes" },
+ { enabled: true, model: { providerId: "p1" } },
+ { enabled: true, model: { providerId: "p1", modelId: "m", extra: 1 } },
+ { enabled: true, model: { providerId: " p1", modelId: "m" } },
+ { enabled: true, defaultInputPolicy: "whatever" },
+ { enabled: true, defaultCapture: "pixels" },
+ { enabled: true, denylist: "com.apple" },
+ { enabled: true, actionBudget: 0 },
+ { enabled: true, actionBudget: COMPUTER_ACTION_BUDGET_LIMIT + 1 },
+ { enabled: true, actionBudget: 1.5 },
+ { enabled: true, idleExpiryMs: 1_000 },
+ [],
+ null,
+ "enabled",
+ ]) {
+ expect(() => validateComputerUseSettings(value), `accepted ${JSON.stringify(value)}`).toThrow(/invalid/);
+ }
+});
+
+it("Computer tool args require an instruction and nothing else", () => {
+ expect(validateComputerToolArgs({ instruction: " open preferences " })).toEqual({
+ instruction: "open preferences",
+ });
+ expect(
+ validateComputerToolArgs({ instruction: "read it", observeOnly: true, maxSteps: 3 }),
+ ).toEqual({ instruction: "read it", maxSteps: 3, observeOnly: true });
+});
+
+it("Computer tool args refuse addressing, targets, and runaway step counts", () => {
+ for (const value of [
+ { instruction: "" },
+ { instruction: " " },
+ { instruction: "x".repeat(4_001) },
+ { instruction: "click it", uid: "node-3" },
+ { instruction: "click it", point: { x: 1, y: 2 } },
+ { instruction: "click it", targetId: "window-9" },
+ { instruction: "click it", maxSteps: 0 },
+ { instruction: "click it", maxSteps: COMPUTER_MAX_STEPS_LIMIT + 1 },
+ { instruction: "click it", observeOnly: "yes" },
+ "open preferences",
+ null,
+ ]) {
+ expect(() => validateComputerToolArgs(value), `accepted ${JSON.stringify(value)}`).toThrow(/Computer/);
+ }
+});
diff --git a/packages/shared/src/computer-use.ts b/packages/shared/src/computer-use.ts
new file mode 100644
index 000000000..7434bdb12
--- /dev/null
+++ b/packages/shared/src/computer-use.ts
@@ -0,0 +1,347 @@
+/**
+ * Public, host-authoritative contracts for computer use (ADR 0340).
+ *
+ * Nothing here carries authority by itself. The grant is minted by host-core
+ * from a target the user picked, and every field a caller could forge — the
+ * target, the revision, the budget — is re-read from the host before an action
+ * runs. These types exist so main, the renderer, and the loop agree on the
+ * shape of what the host already decided.
+ */
+
+/** Settings-level capture choice. `a11y-only` never takes a pixel. */
+export type ComputerCaptureMode = "a11y-only" | "a11y-and-pixels";
+
+/**
+ * Per-grant input policy. `confirm-each` raises an approval card for every
+ * input step and is the only policy available under permission mode `ask`.
+ */
+export type ComputerInputPolicy = "confirm-each" | "autonomous-in-scope";
+
+/** One `{ providerId, modelId }` the user picked, as in `imageGeneration`. */
+export type ComputerModelBinding = { providerId: string; modelId: string };
+
+export type ComputerUseSettings = {
+ enabled: boolean;
+ /** Absent means unconfigured; the tool refuses rather than falling back. */
+ model?: ComputerModelBinding | null;
+ defaultInputPolicy?: ComputerInputPolicy;
+ defaultCapture?: ComputerCaptureMode;
+ /**
+ * User-added application identifiers that may never be targeted. The
+ * built-in credential-surface entries live in host-core and are not listed
+ * here, because a settings write must not be able to remove them.
+ */
+ denylist?: string[];
+ /** Hard ceiling on input actions per grant; the host clamps its own bound. */
+ actionBudget?: number;
+ /** Idle milliseconds before a grant closes itself. */
+ idleExpiryMs?: number;
+};
+
+export const COMPUTER_USE_DEFAULTS = {
+ inputPolicy: "confirm-each",
+ capture: "a11y-only",
+ /** One instruction rarely needs more; a runaway loop should hit this. */
+ actionBudget: 40,
+ idleExpiryMs: 15 * 60_000,
+ /** Clamp for a single `Computer` call, independent of the grant budget. */
+ maxStepsPerCall: 12,
+} as const satisfies {
+ inputPolicy: ComputerInputPolicy;
+ capture: ComputerCaptureMode;
+ actionBudget: number;
+ idleExpiryMs: number;
+ maxStepsPerCall: number;
+};
+
+export const COMPUTER_ACTION_BUDGET_LIMIT = 200;
+export const COMPUTER_MAX_STEPS_LIMIT = 40;
+/** Bound on the tree a single `inspect` returns, so one call cannot flood. */
+export const COMPUTER_MAX_NODES = 400;
+/** Bound on one element label, so a hostile window cannot pad the context. */
+export const COMPUTER_MAX_LABEL_CHARS = 200;
+/** Bound on text the loop may type in one step. */
+export const COMPUTER_MAX_TEXT_CHARS = 2_000;
+
+export function validateComputerUseSettings(value: unknown): ComputerUseSettings {
+ const invalid = (): never => {
+ throw Object.assign(new Error("computerUse settings are invalid"), {
+ errorCode: "INVALID_PARAMS",
+ });
+ };
+ if (!value || typeof value !== "object" || Array.isArray(value)) return invalid();
+ const input = value as Record<string, unknown>;
+ const allowed = [
+ "enabled",
+ "model",
+ "defaultInputPolicy",
+ "defaultCapture",
+ "denylist",
+ "actionBudget",
+ "idleExpiryMs",
+ ];
+ if (Object.keys(input).some((key) => !allowed.includes(key))) return invalid();
+ if (typeof input.enabled !== "boolean") return invalid();
+
+ const cleanId = (item: unknown, maxLength = 256): string => {
+ if (typeof item !== "string" || !item.trim() || item.trim() !== item || item.length > maxLength) {
+ return invalid();
+ }
+ return item;
+ };
+
+ const result: ComputerUseSettings = { enabled: input.enabled };
+
+ if (input.model !== undefined && input.model !== null) {
+ if (!input.model || typeof input.model !== "object" || Array.isArray(input.model)) return invalid();
+ const model = input.model as Record<string, unknown>;
+ if (Object.keys(model).some((key) => !["providerId", "modelId"].includes(key))) return invalid();
+ result.model = { providerId: cleanId(model.providerId), modelId: cleanId(model.modelId) };
+ } else if (input.model === null) {
+ result.model = null;
+ }
+
+ if (input.defaultInputPolicy !== undefined) {
+ if (input.defaultInputPolicy !== "confirm-each" && input.defaultInputPolicy !== "autonomous-in-scope") {
+ return invalid();
+ }
+ result.defaultInputPolicy = input.defaultInputPolicy;
+ }
+ if (input.defaultCapture !== undefined) {
+ if (input.defaultCapture !== "a11y-only" && input.defaultCapture !== "a11y-and-pixels") return invalid();
+ result.defaultCapture = input.defaultCapture;
+ }
+ if (input.denylist !== undefined) {
+ if (!Array.isArray(input.denylist) || input.denylist.length > 200) return invalid();
+ result.denylist = input.denylist.map((entry) => cleanId(entry));
+ }
+ if (input.actionBudget !== undefined) {
+ if (
+ typeof input.actionBudget !== "number"
+ || !Number.isInteger(input.actionBudget)
+ || input.actionBudget < 1
+ || input.actionBudget > COMPUTER_ACTION_BUDGET_LIMIT
+ ) {
+ return invalid();
+ }
+ result.actionBudget = input.actionBudget;
+ }
+ if (input.idleExpiryMs !== undefined) {
+ if (
+ typeof input.idleExpiryMs !== "number"
+ || !Number.isInteger(input.idleExpiryMs)
+ || input.idleExpiryMs < 30_000
+ || input.idleExpiryMs > 60 * 60_000
+ ) {
+ return invalid();
+ }
+ result.idleExpiryMs = input.idleExpiryMs;
+ }
+ return result;
+}
+
+/** Why a listed target cannot be picked. Listed, never silently dropped. */
+export type ComputerTargetRefusal = "self" | "denylisted" | "elevated" | "no-accessibility";
+
+export type ComputerTarget = {
+ targetId: string;
+ appName: string;
+ title: string;
+ /** Bundle id, process name, or WM class — whatever the platform can prove. */
+ appKey: string;
+ bounds: ComputerRect;
+ refusedReason?: ComputerTargetRefusal;
+};
+
+export type ComputerRect = { x: number; y: number; width: number; height: number };
+
+/**
+ * How much of the real UI the platform backend can see. A backend that can
+ * only enumerate top-level windows reports `partial` so an empty result is not
+ * mistaken for an empty window.
+ */
+export type ComputerFidelity = "full" | "partial" | "none";
+
+export type ComputerPermissionState = "granted" | "denied" | "not-requested" | "unsupported";
+
+export type ComputerCapabilities = {
+ platform: "darwin" | "win32" | "linux" | "other";
+ backend: "macos-ax" | "windows-uia" | "linux-atspi" | "unsupported";
+ fidelity: ComputerFidelity;
+ /** Native inspection/synthesis permission (macOS Accessibility, AT-SPI bus). */
+ accessibility: ComputerPermissionState;
+ /** Window capture permission, as far as the host can tell before trying. */
+ capture: ComputerPermissionState;
+ /** `wayland` refuses input by contract; `x11` is best effort. */
+ sessionType?: "x11" | "wayland" | "unknown";
+ /** Present when the backend exists but cannot act — e.g. Wayland input. */
+ inputUnsupportedReason?: string;
+};
+
+export type ComputerGrantView = {
+ grantId: string;
+ /** Bumped whenever the measured target geometry or identity changes. */
+ revision: number;
+ targetId: string;
+ targetLabel: string;
+ appKey: string;
+ bounds: ComputerRect;
+ inputPolicy: ComputerInputPolicy;
+ capture: ComputerCaptureMode;
+ /** Input actions left before the grant closes itself. */
+ remainingBudget: number;
+ /** Session that owns the grant; a second session is refused, not queued. */
+ sessionId: string;
+ createdAt: string;
+ expiresAt: string;
+ state: "active" | "revoked" | "expired";
+};
+
+export type ComputerNode = {
+ uid: string;
+ role: string;
+ /** Accessible name, truncated. Absent when the platform exposes none. */
+ label?: string;
+ /** Whether a value exists — never the value itself (ADR 0340 §3). */
+ hasValue: boolean;
+ enabled: boolean;
+ focused: boolean;
+ bounds?: ComputerRect;
+ /** Index of the parent in the same array; absent for the scope root. */
+ parent?: number;
+ /** Platform actions this element offers, already filtered to ours. */
+ actions: ComputerActionKind[];
+};
+
+export type ComputerInspection = {
+ grantId: string;
+ revision: number;
+ bounds: ComputerRect;
+ fidelity: ComputerFidelity;
+ nodes: ComputerNode[];
+ /** True when the tree hit `COMPUTER_MAX_NODES` and was cut. */
+ truncated: boolean;
+ /** Set when the platform reports a secure input state right now. */
+ secureInput: boolean;
+};
+
+export type ComputerActionKind =
+ | "click"
+ | "double_click"
+ | "right_click"
+ | "set_value"
+ | "press_keys"
+ | "scroll"
+ | "select";
+
+/**
+ * The geometry a capture was taken against. A coordinate action carries it so
+ * the host can refuse when its own re-measurement disagrees, instead of
+ * clicking whatever now occupies those pixels.
+ */
+export type ComputerBasis = { revision: number; bounds: ComputerRect };
+
+export type ComputerAction = {
+ kind: ComputerActionKind;
+ /** Element identity from the current inspection. Preferred over `point`. */
+ uid?: string;
+ /** Scope-relative coordinate; requires `basis` and is clamped to bounds. */
+ point?: { x: number; y: number };
+ basis?: ComputerBasis;
+ text?: string;
+ /** Normalized chord list, e.g. `["cmd+a", "delete"]`. */
+ keys?: string[];
+ scroll?: { dx: number; dy: number };
+ option?: string;
+};
+
+export type ComputerActResult = {
+ grantId: string;
+ revision: number;
+ remainingBudget: number;
+ /** What the backend actually dispatched, for the audit trail and the log. */
+ dispatched: "accessibility-action" | "window-event";
+};
+
+/** One step the loop completed, as reported back to the user-facing summary. */
+export type ComputerStepRecord = {
+ index: number;
+ action: ComputerActionKind | "observe" | "done" | "ask";
+ /** Element label or coordinate description; never a typed value. */
+ target?: string;
+ ok: boolean;
+ errorCode?: string;
+};
+
+export type ComputerRunOutcome =
+ | "done"
+ | "step-limit"
+ | "budget-exhausted"
+ | "revoked"
+ | "expired"
+ | "needs-user"
+ | "failed";
+
+export type ComputerRunResult = {
+ outcome: ComputerRunOutcome;
+ /** Assembled from the steps that ran, not copied from model prose. */
+ summary: string;
+ steps: ComputerStepRecord[];
+ /** Present when `outcome` is `needs-user`: what the model wants to ask. */
+ question?: string;
+ errorCode?: string;
+};
+
+/**
+ * Draw commands for the cursor overlay. The overlay is a click-through window
+ * that visualizes where the agent is acting; it carries no authority, so these
+ * payloads are screen coordinates and a label, never an element reference.
+ */
+export type ComputerCursorEvent =
+ | { kind: "show"; grantId: string; bounds: ComputerRect }
+ | { kind: "move"; grantId: string; x: number; y: number; label?: string }
+ | { kind: "press"; grantId: string; x: number; y: number; action: ComputerActionKind }
+ | { kind: "type"; grantId: string; x: number; y: number; chars: number }
+ | { kind: "hide"; grantId: string };
+
+/** Agent-facing `Computer` tool arguments. No target, no uid, no coordinate. */
+export type ComputerToolArgs = {
+ instruction: string;
+ maxSteps?: number;
+ /** Describe the scope without acting. Needs no input-policy approval. */
+ observeOnly?: boolean;
+};
+
+export function validateComputerToolArgs(value: unknown): ComputerToolArgs {
+ const invalid = (message: string): never => {
+ throw Object.assign(new Error(message), { errorCode: "INVALID_PARAMS" });
+ };
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ return invalid("Computer expects an object with an instruction");
+ }
+ const input = value as Record<string, unknown>;
+ if (Object.keys(input).some((key) => !["instruction", "maxSteps", "observeOnly"].includes(key))) {
+ return invalid("Computer received an unknown argument");
+ }
+ const instruction = typeof input.instruction === "string" ? input.instruction.trim() : "";
+ if (!instruction || instruction.length > 4_000) {
+ return invalid("Computer expects a non-empty instruction under 4000 characters");
+ }
+ const args: ComputerToolArgs = { instruction };
+ if (input.maxSteps !== undefined) {
+ if (
+ typeof input.maxSteps !== "number"
+ || !Number.isInteger(input.maxSteps)
+ || input.maxSteps < 1
+ || input.maxSteps > COMPUTER_MAX_STEPS_LIMIT
+ ) {
+ return invalid(`Computer maxSteps must be an integer between 1 and ${COMPUTER_MAX_STEPS_LIMIT}`);
+ }
+ args.maxSteps = input.maxSteps;
+ }
+ if (input.observeOnly !== undefined) {
+ if (typeof input.observeOnly !== "boolean") return invalid("Computer observeOnly must be a boolean");
+ args.observeOnly = input.observeOnly;
+ }
+ return args;
+}
diff --git a/packages/shared/src/errors.ts b/packages/shared/src/errors.ts
index f03883189..ad5cbf248 100644
--- a/packages/shared/src/errors.ts
+++ b/packages/shared/src/errors.ts
@@ -91,6 +91,36 @@ export const ErrorCodes = {
LIVE_NETWORK_POLICY_UNSUPPORTED: "LIVE_NETWORK_POLICY_UNSUPPORTED",
LIVE_AUDIO_BACKPRESSURE: "LIVE_AUDIO_BACKPRESSURE",
LIVE_EXECUTION_NOT_CONNECTED: "LIVE_EXECUTION_NOT_CONNECTED",
+ /**
+ * Computer use (ADR 0340). Each refusal is separately attributable because a
+ * missing native capability must never read as an action that did nothing:
+ * `COMPUTER_PLATFORM_UNSUPPORTED` is a backend that does not exist here,
+ * while `COMPUTER_ELEMENT_NOT_ACTIONABLE` is a real element that offers no
+ * action. The two unconditional refusals — `COMPUTER_SELF_TARGET_REFUSED`
+ * and `COMPUTER_SECURE_INPUT_REFUSED` — are not reachable by any permission
+ * mode, setting, or grant option.
+ */
+ COMPUTER_DISABLED: "COMPUTER_DISABLED",
+ COMPUTER_NOT_CONFIGURED: "COMPUTER_NOT_CONFIGURED",
+ COMPUTER_NO_GRANT: "COMPUTER_NO_GRANT",
+ COMPUTER_GRANT_IN_USE: "COMPUTER_GRANT_IN_USE",
+ COMPUTER_GRANT_EXPIRED: "COMPUTER_GRANT_EXPIRED",
+ COMPUTER_BUDGET_EXHAUSTED: "COMPUTER_BUDGET_EXHAUSTED",
+ COMPUTER_SCOPE_VIOLATION: "COMPUTER_SCOPE_VIOLATION",
+ COMPUTER_SELF_TARGET_REFUSED: "COMPUTER_SELF_TARGET_REFUSED",
+ COMPUTER_TARGET_DENYLISTED: "COMPUTER_TARGET_DENYLISTED",
+ COMPUTER_SECURE_INPUT_REFUSED: "COMPUTER_SECURE_INPUT_REFUSED",
+ COMPUTER_STALE_BASIS: "COMPUTER_STALE_BASIS",
+ COMPUTER_STALE_REVISION: "COMPUTER_STALE_REVISION",
+ COMPUTER_ELEMENT_NOT_FOUND: "COMPUTER_ELEMENT_NOT_FOUND",
+ COMPUTER_ELEMENT_NOT_ACTIONABLE: "COMPUTER_ELEMENT_NOT_ACTIONABLE",
+ COMPUTER_INPUT_POLICY_DENIED: "COMPUTER_INPUT_POLICY_DENIED",
+ COMPUTER_OS_PERMISSION_MISSING: "COMPUTER_OS_PERMISSION_MISSING",
+ COMPUTER_TARGET_ELEVATED: "COMPUTER_TARGET_ELEVATED",
+ COMPUTER_PLATFORM_UNSUPPORTED: "COMPUTER_PLATFORM_UNSUPPORTED",
+ COMPUTER_CAPTURE_UNAVAILABLE: "COMPUTER_CAPTURE_UNAVAILABLE",
+ COMPUTER_ACTION_REJECTED: "COMPUTER_ACTION_REJECTED",
+ COMPUTER_TIMEOUT: "COMPUTER_TIMEOUT",
AGENT_BUSY: "AGENT_BUSY",
AGENT_NOT_FOUND: "AGENT_NOT_FOUND",
TURN_NOT_FOUND: "TURN_NOT_FOUND",
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index f19c7f853..17cb048b2 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -60,6 +60,7 @@ export * from "./image-dimensions.js";
export * from "./speech.js";
export * from "./gen-ui.js";
export * from "./image-generation.js";
+export * from "./computer-use.js";
export * from "./font-size.js";
export * from "./chat-content-width.js";
export * from "./startup-animation.js";
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index bbdea6855..497820fff 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -130,6 +130,18 @@ export const IPC = {
liveVoiceWidgetAction: "pi-desktop/voice/live/widget/action",
liveVoiceWidgetOwnerState: "pi-desktop/voice/live/widget/ownerState",
liveVoiceWidgetVisibility: "pi-desktop/voice/live/widget/visibility",
+ /**
+ * Computer use (ADR 0340). The renderer may read capabilities, list
+ * pickable targets while a picker is open, mint a grant from a target the
+ * user chose, and revoke one. It can never act: there is no channel that
+ * dispatches input, and `computer.act` is reachable only from main's tool
+ * handler.
+ */
+ computerCapabilities: "pi-desktop/computer/capabilities",
+ computerListTargets: "pi-desktop/computer/listTargets",
+ computerGrantCreate: "pi-desktop/computer/grant/create",
+ computerGrantRevoke: "pi-desktop/computer/grant/revoke",
+ computerGrantDescribe: "pi-desktop/computer/grant/describe",
agentCompact: "pi-desktop/agent/compact",
agentAbort: "pi-desktop/agent/abort",
agentStopSubagents: "pi-desktop/agent/stop-subagents",
@@ -520,6 +532,12 @@ export const IPC = {
liveVoiceTranscript: "pi-desktop/voice/live/event/transcript",
liveVoiceWidgetState: "pi-desktop/voice/live/event/widgetState",
liveVoiceWidgetAction: "pi-desktop/voice/live/event/widgetAction",
+ /** Active grant view for the indicator; `null` once the grant closes. */
+ computerGrantChanged: "pi-desktop/computer/event/grantChanged",
+ /** Draw commands for the click-through cursor overlay. Visualization only. */
+ computerCursor: "pi-desktop/computer/event/cursor",
+ /** One completed loop step, for the indicator's progress line. */
+ computerStep: "pi-desktop/computer/event/step",
},
} as const;
diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.ts
index a52dbd6f1..00d442fff 100644
--- a/packages/shared/src/types/settings.ts
+++ b/packages/shared/src/types/settings.ts
@@ -72,6 +72,8 @@ export type AppSettings = {
speech?: SpeechSettings;
/** App-owned real-time voice bindings; separate from local dictation. */
liveVoice?: LiveVoiceSettings;
+ /** Granted native application control (ADR 0340); off and unbound by default. */
+ computerUse?: import("../computer-use.js").ComputerUseSettings;
defaultMode: Mode;
/**
* Keep retryable provider/network failures retrying until the request succeeds.