Skip to main content

adk_core/
computer.rs

1//! Provider-neutral computer actuation: the actions a computer-use model asks for, and the
2//! trait an environment implements to perform them.
3//!
4//! An actuator acts only when a tool calls it, and the tools that call it are dispatched
5//! through the governed tool path, so tool policy, confirmations, the kill switch, budgets
6//! and the action ledger decide every action before it reaches the environment.
7//!
8//! Every coordinate is in the pixel space of the screenshots the actuator returns, so a
9//! model that reads a screenshot names positions in the same frame the actuator acts in.
10
11use async_trait::async_trait;
12use serde::{Deserialize, Serialize};
13use std::time::Duration;
14
15use crate::Result;
16
17/// A position in screenshot pixels, with the origin at the top left.
18///
19/// # Example
20///
21/// ```rust
22/// use adk_core::ScreenPoint;
23///
24/// let point = ScreenPoint::new(512, 384);
25/// assert_eq!((point.x, point.y), (512, 384));
26/// ```
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
28pub struct ScreenPoint {
29    /// Pixels from the left edge.
30    pub x: i64,
31    /// Pixels from the top edge.
32    pub y: i64,
33}
34
35impl ScreenPoint {
36    /// The point at `x`, `y`.
37    pub fn new(x: i64, y: i64) -> Self {
38        Self { x, y }
39    }
40}
41
42/// A mouse button.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
44#[serde(rename_all = "snake_case")]
45pub enum MouseButton {
46    /// The primary button.
47    Left,
48    /// The secondary button.
49    Right,
50    /// The wheel button.
51    Middle,
52}
53
54/// A scroll direction.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum ScrollDirection {
58    /// Towards the top.
59    Up,
60    /// Towards the bottom.
61    Down,
62    /// Towards the left edge.
63    Left,
64    /// Towards the right edge.
65    Right,
66}
67
68/// One action on a computer.
69///
70/// Key names follow the xdotool convention (`Return`, `ctrl+s`, `alt+Tab`); modifiers are
71/// `shift`, `ctrl`, `alt` and `super`.
72///
73/// # Example
74///
75/// ```rust
76/// use adk_core::{ComputerAction, ComputerActionKind, MouseButton, ScreenPoint};
77///
78/// let click = ComputerAction::Click {
79///     button: MouseButton::Left,
80///     count: 1,
81///     at: Some(ScreenPoint::new(10, 20)),
82///     modifiers: vec!["shift".into()],
83/// };
84/// assert_eq!(click.kind(), ComputerActionKind::Click);
85/// assert!(!click.kind().is_observation());
86/// ```
87#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
88#[serde(tag = "type", rename_all = "snake_case")]
89#[non_exhaustive]
90pub enum ComputerAction {
91    /// Capture the whole display.
92    Screenshot,
93    /// Capture `[x0, y0, x1, y1]` at full resolution, scaled to the screenshot size.
94    Zoom {
95        /// Top-left and bottom-right corners.
96        region: [i64; 4],
97    },
98    /// Press and release a button `count` times, at `at` or at the cursor.
99    Click {
100        /// The button.
101        button: MouseButton,
102        /// 1 for a click, 2 for a double click, 3 for a triple click.
103        count: u8,
104        /// Where to click; the cursor position when `None`.
105        at: Option<ScreenPoint>,
106        /// Modifier keys held during the click.
107        modifiers: Vec<String>,
108    },
109    /// Press the left button at `from`, move to `to`, release.
110    Drag {
111        /// Where the drag starts.
112        from: ScreenPoint,
113        /// Where it ends.
114        to: ScreenPoint,
115        /// Modifier keys held during the drag.
116        modifiers: Vec<String>,
117    },
118    /// Move the cursor.
119    MoveTo {
120        /// The new cursor position.
121        at: ScreenPoint,
122    },
123    /// Press the left button at the cursor.
124    MouseDown,
125    /// Release the left button at the cursor.
126    MouseUp,
127    /// Report the cursor position.
128    CursorPosition,
129    /// Scroll `amount` wheel notches, at `at` or at the cursor.
130    Scroll {
131        /// Where to scroll; the cursor position when `None`.
132        at: Option<ScreenPoint>,
133        /// Which way.
134        direction: ScrollDirection,
135        /// Wheel notches.
136        amount: u32,
137        /// Modifier keys held while scrolling.
138        modifiers: Vec<String>,
139    },
140    /// Type literal text at the keyboard focus.
141    Type {
142        /// The text.
143        text: String,
144    },
145    /// Press a key or `+`-joined chord, `repeat` times.
146    Key {
147        /// The key or chord.
148        keys: String,
149        /// How many times.
150        repeat: u32,
151    },
152    /// Hold a key or chord down.
153    HoldKey {
154        /// The key or chord.
155        keys: String,
156        /// How long.
157        duration: Duration,
158    },
159    /// Pause before the next action.
160    Wait {
161        /// How long.
162        duration: Duration,
163    },
164}
165
166/// The kind of a [`ComputerAction`], without its parameters.
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
168#[serde(rename_all = "snake_case")]
169#[non_exhaustive]
170pub enum ComputerActionKind {
171    /// [`ComputerAction::Screenshot`].
172    Screenshot,
173    /// [`ComputerAction::Zoom`].
174    Zoom,
175    /// [`ComputerAction::Click`].
176    Click,
177    /// [`ComputerAction::Drag`].
178    Drag,
179    /// [`ComputerAction::MoveTo`].
180    MoveTo,
181    /// [`ComputerAction::MouseDown`].
182    MouseDown,
183    /// [`ComputerAction::MouseUp`].
184    MouseUp,
185    /// [`ComputerAction::CursorPosition`].
186    CursorPosition,
187    /// [`ComputerAction::Scroll`].
188    Scroll,
189    /// [`ComputerAction::Type`].
190    Type,
191    /// [`ComputerAction::Key`].
192    Key,
193    /// [`ComputerAction::HoldKey`].
194    HoldKey,
195    /// [`ComputerAction::Wait`].
196    Wait,
197}
198
199impl ComputerActionKind {
200    /// Whether the action only reads the screen or cursor and changes nothing.
201    pub fn is_observation(self) -> bool {
202        matches!(self, Self::Screenshot | Self::Zoom | Self::CursorPosition)
203    }
204}
205
206impl ComputerAction {
207    /// The action's kind.
208    pub fn kind(&self) -> ComputerActionKind {
209        match self {
210            Self::Screenshot => ComputerActionKind::Screenshot,
211            Self::Zoom { .. } => ComputerActionKind::Zoom,
212            Self::Click { .. } => ComputerActionKind::Click,
213            Self::Drag { .. } => ComputerActionKind::Drag,
214            Self::MoveTo { .. } => ComputerActionKind::MoveTo,
215            Self::MouseDown => ComputerActionKind::MouseDown,
216            Self::MouseUp => ComputerActionKind::MouseUp,
217            Self::CursorPosition => ComputerActionKind::CursorPosition,
218            Self::Scroll { .. } => ComputerActionKind::Scroll,
219            Self::Type { .. } => ComputerActionKind::Type,
220            Self::Key { .. } => ComputerActionKind::Key,
221            Self::HoldKey { .. } => ComputerActionKind::HoldKey,
222            Self::Wait { .. } => ComputerActionKind::Wait,
223        }
224    }
225}
226
227/// A captured image of the display or of a region of it.
228#[derive(Debug, Clone, PartialEq, Eq)]
229pub struct Screenshot {
230    /// The image's MIME type, `image/png` or `image/jpeg`.
231    pub mime_type: String,
232    /// The encoded image.
233    pub data: Vec<u8>,
234    /// Width in pixels.
235    pub width: u32,
236    /// Height in pixels.
237    pub height: u32,
238}
239
240impl Screenshot {
241    /// A PNG image, with its size read from the PNG header.
242    ///
243    /// Returns `None` when `data` is not a PNG.
244    ///
245    /// # Example
246    ///
247    /// ```rust
248    /// use adk_core::Screenshot;
249    ///
250    /// let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".to_vec();
251    /// png.extend_from_slice(&1280u32.to_be_bytes());
252    /// png.extend_from_slice(&800u32.to_be_bytes());
253    /// let shot = Screenshot::png(png).unwrap();
254    /// assert_eq!((shot.width, shot.height), (1280, 800));
255    /// ```
256    pub fn png(data: Vec<u8>) -> Option<Self> {
257        if data.len() < 24 || &data[..8] != b"\x89PNG\r\n\x1a\n" || &data[12..16] != b"IHDR" {
258            return None;
259        }
260        let width = u32::from_be_bytes([data[16], data[17], data[18], data[19]]);
261        let height = u32::from_be_bytes([data[20], data[21], data[22], data[23]]);
262        Some(Self { mime_type: "image/png".to_string(), data, width, height })
263    }
264
265    /// Whether the image fits the limits Claude Opus 4.7 and later models accept without a
266    /// resize: 2,576 pixels on the long edge and 4,784 visual tokens, one token per 28×28
267    /// pixel tile.
268    pub fn fits_current_claude_limits(&self) -> bool {
269        let tiles = self.width.div_ceil(28) as u64 * self.height.div_ceil(28) as u64;
270        self.width.max(self.height) <= 2_576 && tiles <= 4_784
271    }
272}
273
274/// What an action produced.
275#[derive(Debug, Clone, PartialEq, Eq)]
276#[non_exhaustive]
277pub enum ActuationOutput {
278    /// The action ran and has nothing to report.
279    Done,
280    /// An image: the result of a screenshot or a zoom.
281    Image(Screenshot),
282    /// A position, from a cursor query.
283    Cursor(ScreenPoint),
284}
285
286/// An environment that performs [`ComputerAction`]s: a virtual desktop, a remote desktop
287/// session, or a browser viewport.
288///
289/// Implementations act on whatever they are connected to, so give an agent one only through
290/// tools that run on the governed path, and only in an isolated environment with no
291/// credentials it does not need.
292///
293/// # Example
294///
295/// ```rust
296/// use adk_core::{ActuationOutput, ComputerAction, ComputerActionKind, ComputerActuator, Result};
297/// use async_trait::async_trait;
298///
299/// /// An actuator that records actions and performs none.
300/// struct Recorder(std::sync::Mutex<Vec<ComputerAction>>);
301///
302/// #[async_trait]
303/// impl ComputerActuator for Recorder {
304///     fn display_size(&self) -> Option<(u32, u32)> {
305///         Some((1280, 800))
306///     }
307///
308///     fn supports(&self, kind: ComputerActionKind) -> bool {
309///         kind != ComputerActionKind::Zoom
310///     }
311///
312///     async fn perform(&self, action: ComputerAction) -> Result<ActuationOutput> {
313///         self.0.lock().unwrap().push(action);
314///         Ok(ActuationOutput::Done)
315///     }
316/// }
317/// ```
318#[async_trait]
319pub trait ComputerActuator: Send + Sync {
320    /// The size of the screenshots the actuator returns, when it is known before the first
321    /// one: the coordinate space of every action.
322    fn display_size(&self) -> Option<(u32, u32)>;
323
324    /// Whether the actuator can perform actions of `kind`. Tools withhold the rest from the
325    /// model. Every kind but [`ComputerActionKind::Zoom`] by default.
326    fn supports(&self, kind: ComputerActionKind) -> bool {
327        kind != ComputerActionKind::Zoom
328    }
329
330    /// Performs one action.
331    ///
332    /// # Errors
333    ///
334    /// Returns an error when the action cannot be performed: a coordinate outside the
335    /// display, an unknown key name, or a failure of the environment.
336    async fn perform(&self, action: ComputerAction) -> Result<ActuationOutput>;
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342
343    #[test]
344    fn png_size_comes_from_the_header() {
345        assert!(Screenshot::png(b"not a png".to_vec()).is_none());
346        let mut data = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".to_vec();
347        data.extend_from_slice(&3024u32.to_be_bytes());
348        data.extend_from_slice(&1964u32.to_be_bytes());
349        let shot = Screenshot::png(data).unwrap();
350        assert_eq!((shot.width, shot.height), (3024, 1964));
351        assert!(!shot.fits_current_claude_limits());
352        let fitting = Screenshot { width: 1280, height: 800, ..shot };
353        assert!(fitting.fits_current_claude_limits());
354    }
355
356    #[test]
357    fn actions_serialize_with_their_kind() {
358        let action = ComputerAction::Scroll {
359            at: None,
360            direction: ScrollDirection::Down,
361            amount: 3,
362            modifiers: Vec::new(),
363        };
364        let json = serde_json::to_value(&action).unwrap();
365        assert_eq!(json["type"], "scroll");
366        assert_eq!(serde_json::from_value::<ComputerAction>(json).unwrap(), action);
367    }
368}