Skip to main content

vtcode_llm/providers/openai/
computer_use.rs

1//! Responses wire codec for the batched `computer` tool.
2
3use std::time::Duration;
4
5use anyhow::{Result, bail, ensure};
6use base64::{Engine, engine::general_purpose::STANDARD};
7use compact_str::CompactString;
8use serde::Deserialize;
9use serde_json::{Value, json};
10use vtcode_computer_use::{
11    Action, Driver, MAX_BATCH_ACTIONS, MouseButton, Observation, Point, Screenshot, TurnControl,
12};
13
14use crate::provider::{NativeCall, NativeCallBody};
15
16/// Native protocol version declared on the wire and checked by the gate.
17pub(crate) const PROTOCOL: &str = "computer";
18
19pub fn declaration() -> Value {
20    json!({"type": PROTOCOL})
21}
22
23/// Carries the original item for turn-local stateless replay. This type
24/// deliberately has no serialization or debug implementation.
25pub struct ComputerCall<'a> {
26    id: &'a str,
27    item: &'a Value,
28    pub actions: Vec<Action>,
29}
30
31impl ComputerCall<'_> {
32    pub fn id(&self) -> &str {
33        self.id
34    }
35
36    pub fn replay_item(&self) -> &Value {
37        self.item
38    }
39
40    pub fn result(&self, screenshot: &Screenshot) -> Value {
41        json!({
42            "type": "computer_call_output",
43            "call_id": self.id,
44            "output": {
45                "type": "computer_screenshot",
46                "image_url": format!("data:image/png;base64,{}", STANDARD.encode(screenshot.as_png())),
47                "detail": "original",
48            }
49        })
50    }
51}
52
53/// Execute one bound-route call decoded by `generate_native`. The replay
54/// item and actions ride along from the decoded body; anything else bails
55/// before the driver runs.
56pub async fn execute_decoded_call<D: Driver>(
57    control: &mut TurnControl<D>,
58    call: NativeCall,
59    timeout: Duration,
60) -> Result<Value> {
61    let NativeCallBody::OpenAi { replay_item, actions } = call.body else {
62        bail!("mixed-provider computer batch");
63    };
64    let decoded = ComputerCall { id: &call.id, item: &replay_item, actions };
65    execute_call(control, &decoded, timeout).await
66}
67
68/// Execute an admitted Responses call and prepare its private wire result.
69/// An ambiguous or incomplete batch ends the target lease.
70pub async fn execute_call<D: Driver>(
71    control: &mut TurnControl<D>,
72    call: &ComputerCall<'_>,
73    timeout: Duration,
74) -> Result<Value> {
75    let observations = match control.execute_batch(call.id(), &call.actions, timeout).await {
76        Ok(observations) => observations,
77        Err(error) => {
78            control.revoke_target();
79            return Err(error);
80        }
81    };
82    control.ensure_turn_active()?;
83    let Some(Observation::Screenshot(image)) = observations.last() else {
84        control.revoke_target();
85        bail!("OpenAI computer batch did not return its final screenshot");
86    };
87    let result = call.result(image);
88    control.ensure_turn_active()?;
89    Ok(result)
90}
91
92/// Decode a completed output item and ensure the batch ends with a screenshot.
93/// Calls requiring a safety acknowledgement remain blocked until a dedicated
94/// approval flow can verify and acknowledge the individual check IDs.
95pub fn decode_call(item: &Value) -> Result<Option<ComputerCall<'_>>> {
96    if item["type"].as_str() != Some("computer_call") {
97        return Ok(None);
98    }
99    ensure!(item["status"].as_str() == Some("completed"), "incomplete OpenAI computer call");
100    let id = item["call_id"]
101        .as_str()
102        .filter(|id| !id.is_empty() && id.len() <= 256)
103        .ok_or_else(|| anyhow::anyhow!("invalid OpenAI computer call identity"))?;
104    ensure!(
105        item.get("pending_safety_checks")
106            .is_none_or(|checks| checks.as_array().is_some_and(Vec::is_empty)),
107        "OpenAI computer call requires a safety acknowledgement"
108    );
109    let wire_actions = item["actions"]
110        .as_array()
111        .filter(|actions| (1..=MAX_BATCH_ACTIONS).contains(&actions.len()))
112        .ok_or_else(|| anyhow::anyhow!("invalid OpenAI computer action batch"))?;
113    let mut actions = wire_actions
114        .iter()
115        .map(|action| {
116            WireAction::deserialize(action)
117                .map_err(|_private_error| anyhow::anyhow!("invalid OpenAI computer action"))?
118                .into_action()
119        })
120        .collect::<Result<Vec<_>>>()?;
121    if !matches!(actions.last(), Some(Action::Screenshot)) {
122        ensure!(actions.len() < MAX_BATCH_ACTIONS, "no room for the final computer screenshot");
123        actions.push(Action::Screenshot);
124    }
125    Ok(Some(ComputerCall { id, item, actions }))
126}
127
128#[derive(Deserialize)]
129struct WirePoint {
130    x: u32,
131    y: u32,
132}
133
134impl From<WirePoint> for Point {
135    fn from(WirePoint { x, y }: WirePoint) -> Self {
136        Self { x, y }
137    }
138}
139
140#[derive(Deserialize)]
141#[serde(rename_all = "snake_case")]
142enum WireButton {
143    Left,
144    Right,
145    Wheel,
146    Back,
147    Forward,
148}
149
150impl From<WireButton> for MouseButton {
151    fn from(button: WireButton) -> Self {
152        match button {
153            WireButton::Left => Self::Left,
154            WireButton::Right => Self::Right,
155            WireButton::Wheel => Self::Middle,
156            WireButton::Back => Self::Back,
157            WireButton::Forward => Self::Forward,
158        }
159    }
160}
161
162#[derive(Deserialize)]
163#[serde(tag = "type", rename_all = "snake_case")]
164enum WireAction {
165    Click {
166        x: u32,
167        y: u32,
168        button: WireButton,
169        keys: Option<Vec<CompactString>>,
170    },
171    DoubleClick {
172        x: u32,
173        y: u32,
174        keys: Option<Vec<CompactString>>,
175    },
176    Drag {
177        path: Vec<WirePoint>,
178        keys: Option<Vec<CompactString>>,
179    },
180    Move {
181        x: u32,
182        y: u32,
183        keys: Option<Vec<CompactString>>,
184    },
185    Scroll {
186        x: u32,
187        y: u32,
188        scroll_x: i32,
189        scroll_y: i32,
190        keys: Option<Vec<CompactString>>,
191    },
192    Keypress {
193        keys: Vec<CompactString>,
194    },
195    Type {
196        text: String,
197    },
198    Wait,
199    Screenshot,
200}
201
202impl WireAction {
203    fn into_action(self) -> Result<Action> {
204        Ok(match self {
205            Self::Click { x, y, button, keys } => Action::Click {
206                at: Some(Point { x, y }),
207                button: button.into(),
208                count: 1,
209                modifiers: keys.unwrap_or_default(),
210            },
211            Self::DoubleClick { x, y, keys } => Action::Click {
212                at: Some(Point { x, y }),
213                button: MouseButton::Left,
214                count: 2,
215                modifiers: keys.unwrap_or_default(),
216            },
217            Self::Drag { path, keys } => {
218                ensure!((2..=1024).contains(&path.len()), "invalid OpenAI computer drag path");
219                Action::Drag {
220                    path: path.into_iter().map(Point::from).collect(),
221                    modifiers: keys.unwrap_or_default(),
222                }
223            }
224            Self::Move { x, y, keys } => Action::Move {
225                at: Point { x, y },
226                modifiers: keys.unwrap_or_default(),
227            },
228            Self::Scroll { x, y, scroll_x, scroll_y, keys } => Action::ScrollPixels {
229                at: Point { x, y },
230                x: scroll_x,
231                y: scroll_y,
232                modifiers: keys.unwrap_or_default(),
233            },
234            Self::Keypress { keys } => {
235                ensure!(!keys.is_empty(), "empty OpenAI computer keypress");
236                Action::Key { keys, repeat: 1 }
237            }
238            Self::Type { text } => Action::Type(text),
239            Self::Wait => Action::Wait(Duration::from_secs(1)),
240            Self::Screenshot => Action::Screenshot,
241        })
242    }
243}
244
245#[cfg(test)]
246mod tests;