Skip to main content

vtcode_computer_use/
lib.rs

1//! Turn-local computer input and observation. Payloads are deliberately not serializable.
2
3use std::{collections::HashSet, time::Duration};
4
5use anyhow::{Context, Result, bail, ensure};
6use compact_str::CompactString;
7use tokio::time::{Instant, sleep_until};
8use tokio_util::sync::CancellationToken;
9
10pub mod browser;
11pub mod gate;
12
13/// Maximum number of actions admitted per batch.
14pub const MAX_BATCH_ACTIONS: usize = 128;
15/// Maximum screenshot bytes accepted per action batch.
16pub const MAX_SCREENSHOT_BYTES: usize = 8 * 1024 * 1024;
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19/// A position in the target screenshot’s pixel coordinates.
20pub struct Point {
21    /// Horizontal distance from the left edge.
22    pub x: u32,
23    /// Vertical distance from the top edge.
24    pub y: u32,
25}
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28/// A mouse button identified independently of the driver.
29pub enum MouseButton {
30    /// Left mouse button.
31    Left,
32    /// Middle mouse button.
33    Middle,
34    /// Right mouse button.
35    Right,
36    /// Back mouse button.
37    Back,
38    /// Forward mouse button.
39    Forward,
40}
41
42/// A provider-neutral request to observe or interact with the target.
43pub enum Action {
44    /// Capture the target viewport.
45    Screenshot,
46    /// Capture a rectangle within the viewport.
47    Zoom {
48        /// Top-left corner of the rectangle.
49        top_left: Point,
50        /// Bottom-right corner of the rectangle.
51        bottom_right: Point,
52    },
53    /// Deliver one or more clicks.
54    Click {
55        /// Position for the action, or the current pointer position.
56        at: Option<Point>,
57        /// Button to click.
58        button: MouseButton,
59        /// Number of clicks.
60        count: u8,
61        /// Modifier keys held during the action.
62        modifiers: Vec<CompactString>,
63    },
64    /// Deliver a drag along an ordered path.
65    Drag {
66        /// Path from the start point to the release point.
67        path: Vec<Point>,
68        /// Modifier keys held during the action.
69        modifiers: Vec<CompactString>,
70    },
71    /// Move the pointer to the given position.
72    Move {
73        /// Destination in screenshot pixels.
74        at: Point,
75        /// Modifier keys held during pointer movement.
76        modifiers: Vec<CompactString>,
77    },
78    /// Scroll by a signed pixel offset.
79    ScrollPixels {
80        /// Position at which to scroll.
81        at: Point,
82        /// Horizontal scroll offset.
83        x: i32,
84        /// Vertical scroll offset.
85        y: i32,
86        /// Modifier keys held during the action.
87        modifiers: Vec<CompactString>,
88    },
89    /// Scroll by wheel ticks.
90    ScrollTicks {
91        /// Position for the action, or the current pointer position.
92        at: Option<Point>,
93        /// Direction of movement.
94        direction: ScrollDirection,
95        /// Number of wheel ticks.
96        amount: u32,
97        /// Modifier keys held during the action.
98        modifiers: Vec<CompactString>,
99    },
100    /// Press a key or chord.
101    Key {
102        /// Key names in press order.
103        keys: Vec<CompactString>,
104        /// Number of presses.
105        repeat: u8,
106    },
107    /// Hold a key or chord before releasing it.
108    HoldKey {
109        /// Key names in press order.
110        keys: Vec<CompactString>,
111        /// Time to hold the keys.
112        duration: Duration,
113    },
114    /// Press the left mouse button at the current position.
115    LeftMouseDown,
116    /// Release the left mouse button.
117    LeftMouseUp,
118    /// Query the current pointer position.
119    CursorPosition,
120    /// Insert literal text.
121    Type(String),
122    /// Wait for a duration.
123    Wait(Duration),
124}
125
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
127/// Direction of a wheel scroll.
128pub enum ScrollDirection {
129    /// Scroll upward.
130    Up,
131    /// Scroll downward.
132    Down,
133    /// Scroll left.
134    Left,
135    /// Scroll right.
136    Right,
137}
138
139/// An in-memory screenshot bounded by the controller’s payload limit.
140pub struct Screenshot(Vec<u8>);
141
142impl Screenshot {
143    /// Accepts a bounded PNG payload from the driver.
144    ///
145    /// # Errors
146    ///
147    /// Returns an error if the signature is absent or the byte limit is exceeded.
148    pub fn png(bytes: Vec<u8>) -> Result<Self> {
149        ensure!(
150            bytes.len() <= MAX_SCREENSHOT_BYTES && bytes.starts_with(b"\x89PNG\r\n\x1a\n"),
151            "invalid computer screenshot payload"
152        );
153        Ok(Self(bytes))
154    }
155
156    /// Borrow the bytes for provider encoding within the current turn.
157    pub fn as_png(&self) -> &[u8] {
158        &self.0
159    }
160}
161
162/// The result of a single driver action.
163pub enum Observation {
164    /// An action completed without an informational result.
165    Done,
166    /// A screenshot returned by the driver.
167    Screenshot(Screenshot),
168    /// The current pointer position.
169    CursorPosition(Point),
170}
171
172/// An instance is bound to one target. The driver owns delivery checks and cleanup
173/// even when an action future is dropped while input is in flight.
174pub trait Driver {
175    /// Dispatch one action, observing revocation before and during target delivery.
176    fn execute(
177        &mut self,
178        action: &Action,
179        revoked: &CancellationToken,
180    ) -> impl Future<Output = Result<Observation>> + Send;
181}
182
183/// A unique driver lease for an approved target in one turn. The caller supplies
184/// that turn's cancellation token after approval and keeps the lease off durable history.
185pub struct TurnControl<D> {
186    driver: D,
187    turn: CancellationToken,
188    revoked: CancellationToken,
189    seen_calls: HashSet<CompactString>,
190}
191
192impl<D: Driver> TurnControl<D> {
193    /// Create the controller after the run loop grants per-turn target approval.
194    pub fn after_approval(driver: D, turn: &CancellationToken) -> Self {
195        Self {
196            driver,
197            turn: turn.clone(),
198            revoked: turn.child_token(),
199            seen_calls: HashSet::new(),
200        }
201    }
202
203    /// Check the parent turn before returning private results to the provider.
204    ///
205    /// # Errors
206    ///
207    /// Returns an error when the parent turn has ended.
208    pub fn ensure_turn_active(&self) -> Result<()> {
209        ensure!(!self.turn.is_cancelled(), "computer turn has ended");
210        Ok(())
211    }
212
213    /// End this target lease without cancelling unrelated work in the turn.
214    pub fn revoke_target(&self) {
215        self.revoked.cancel();
216    }
217
218    /// Execute an ordered batch once and return observations in the same order.
219    ///
220    /// # Errors
221    ///
222    /// Returns an error for invalid or repeated calls, an expired deadline,
223    /// revocation, driver failure, or an exceeded screenshot budget.
224    pub async fn execute_batch(
225        &mut self,
226        call_id: &str,
227        actions: &[Action],
228        timeout: Duration,
229    ) -> Result<Vec<Observation>> {
230        ensure!(!self.revoked.is_cancelled(), "computer control has ended");
231        ensure!(!call_id.is_empty() && call_id.len() <= 256, "invalid computer call identity");
232        ensure!((1..=MAX_BATCH_ACTIONS).contains(&actions.len()), "invalid computer action batch size");
233        ensure!(self.seen_calls.insert(call_id.into()), "duplicate computer call");
234
235        // Dropping this future also revokes the lease because delivery may have
236        // already happened.
237        let revoke_on_failure = self.revoked.clone().drop_guard();
238        let deadline = Instant::now()
239            .checked_add(timeout)
240            .context("invalid computer action batch timeout")?;
241        let mut timer = std::pin::pin!(sleep_until(deadline));
242        let mut observations = Vec::with_capacity(actions.len());
243        let mut screenshot_bytes = 0;
244        for action in actions {
245            ensure!(Instant::now() < deadline, "computer action batch timed out");
246            let observation = tokio::select! {
247                biased;
248                _ = self.revoked.cancelled() => bail!("computer control was revoked"),
249                _ = &mut timer => bail!("computer action batch timed out"),
250                result = self.driver.execute(action, &self.revoked) => {
251                    // Driver diagnostics can contain action payloads.
252                    result.map_err(|_private_error| anyhow::anyhow!("computer driver action failed"))?
253                }
254            };
255            ensure!(!self.revoked.is_cancelled(), "computer control was revoked");
256            ensure!(Instant::now() < deadline, "computer action batch timed out");
257            if let Observation::Screenshot(screenshot) = &observation {
258                screenshot_bytes += screenshot.as_png().len();
259                ensure!(
260                    screenshot_bytes <= MAX_SCREENSHOT_BYTES,
261                    "computer action batch exceeded its screenshot budget"
262                );
263            }
264            observations.push(observation);
265        }
266        drop(revoke_on_failure.disarm());
267        Ok(observations)
268    }
269}
270
271impl<D> Drop for TurnControl<D> {
272    fn drop(&mut self) {
273        self.revoked.cancel();
274    }
275}
276
277#[cfg(test)]
278mod tests;