vtcode_llm/providers/openai/
computer_use.rs1use 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
16pub(crate) use vtcode_computer_use::gate::OPENAI_COMPUTER_PROTOCOL as PROTOCOL;
19
20pub fn declaration() -> Value {
21 json!({"type": PROTOCOL})
22}
23
24pub struct ComputerCall<'a> {
27 id: &'a str,
28 item: &'a Value,
29 pub actions: Vec<Action>,
30}
31
32impl ComputerCall<'_> {
33 pub fn id(&self) -> &str {
34 self.id
35 }
36
37 pub fn replay_item(&self) -> &Value {
38 self.item
39 }
40
41 pub fn result(&self, screenshot: &Screenshot) -> Value {
42 json!({
43 "type": "computer_call_output",
44 "call_id": self.id,
45 "output": {
46 "type": "computer_screenshot",
47 "image_url": format!("data:image/png;base64,{}", STANDARD.encode(screenshot.as_png())),
48 "detail": "original",
49 }
50 })
51 }
52}
53
54pub fn screenshot_in_output(output: &Value) -> Option<Screenshot> {
61 let image_url = output.get("output")?.get("image_url")?.as_str()?;
62 let encoded = image_url.strip_prefix("data:image/png;base64,")?;
63 let bytes = STANDARD.decode(encoded).ok()?;
64 Screenshot::png(bytes).ok()
65}
66
67pub async fn execute_decoded_call<D: Driver>(
71 control: &mut TurnControl<D>,
72 call: NativeCall,
73 timeout: Duration,
74) -> Result<Value> {
75 let NativeCallBody::OpenAi { replay_item, actions } = call.body else {
76 bail!("mixed-provider computer batch");
77 };
78 let decoded = ComputerCall { id: &call.id, item: &replay_item, actions };
79 execute_call(control, &decoded, timeout).await
80}
81
82pub async fn execute_call<D: Driver>(
85 control: &mut TurnControl<D>,
86 call: &ComputerCall<'_>,
87 timeout: Duration,
88) -> Result<Value> {
89 let observations = match control.execute_batch(call.id(), &call.actions, timeout).await {
90 Ok(observations) => observations,
91 Err(error) => {
92 control.revoke_target();
93 return Err(error);
94 }
95 };
96 control.ensure_turn_active()?;
97 let Some(Observation::Screenshot(image)) = observations.last() else {
98 control.revoke_target();
99 bail!("OpenAI computer batch did not return its final screenshot");
100 };
101 let result = call.result(image);
102 control.ensure_turn_active()?;
103 Ok(result)
104}
105
106pub fn decode_call(item: &Value) -> Result<Option<ComputerCall<'_>>> {
110 if item["type"].as_str() != Some("computer_call") {
111 return Ok(None);
112 }
113 ensure!(item["status"].as_str() == Some("completed"), "incomplete OpenAI computer call");
114 let id = item["call_id"]
115 .as_str()
116 .filter(|id| !id.is_empty() && id.len() <= 256)
117 .ok_or_else(|| anyhow::anyhow!("invalid OpenAI computer call identity"))?;
118 ensure!(
119 item.get("pending_safety_checks")
120 .is_none_or(|checks| checks.as_array().is_some_and(Vec::is_empty)),
121 "OpenAI computer call requires a safety acknowledgement"
122 );
123 let wire_actions = item["actions"]
124 .as_array()
125 .filter(|actions| (1..=MAX_BATCH_ACTIONS).contains(&actions.len()))
126 .ok_or_else(|| anyhow::anyhow!("invalid OpenAI computer action batch"))?;
127 let mut actions = wire_actions
128 .iter()
129 .map(|action| {
130 WireAction::deserialize(action)
131 .map_err(|_private_error| anyhow::anyhow!("invalid OpenAI computer action"))?
132 .into_action()
133 })
134 .collect::<Result<Vec<_>>>()?;
135 if !matches!(actions.last(), Some(Action::Screenshot)) {
136 ensure!(actions.len() < MAX_BATCH_ACTIONS, "no room for the final computer screenshot");
137 actions.push(Action::Screenshot);
138 }
139 Ok(Some(ComputerCall { id, item, actions }))
140}
141
142#[derive(Deserialize)]
143struct WirePoint {
144 x: u32,
145 y: u32,
146}
147
148impl From<WirePoint> for Point {
149 fn from(WirePoint { x, y }: WirePoint) -> Self {
150 Self { x, y }
151 }
152}
153
154#[derive(Deserialize)]
155#[serde(rename_all = "snake_case")]
156enum WireButton {
157 Left,
158 Right,
159 Wheel,
160 Back,
161 Forward,
162}
163
164impl From<WireButton> for MouseButton {
165 fn from(button: WireButton) -> Self {
166 match button {
167 WireButton::Left => Self::Left,
168 WireButton::Right => Self::Right,
169 WireButton::Wheel => Self::Middle,
170 WireButton::Back => Self::Back,
171 WireButton::Forward => Self::Forward,
172 }
173 }
174}
175
176#[derive(Deserialize)]
177#[serde(tag = "type", rename_all = "snake_case")]
178enum WireAction {
179 Click {
180 x: u32,
181 y: u32,
182 button: WireButton,
183 keys: Option<Vec<CompactString>>,
184 },
185 DoubleClick {
186 x: u32,
187 y: u32,
188 keys: Option<Vec<CompactString>>,
189 },
190 Drag {
191 path: Vec<WirePoint>,
192 keys: Option<Vec<CompactString>>,
193 },
194 Move {
195 x: u32,
196 y: u32,
197 keys: Option<Vec<CompactString>>,
198 },
199 Scroll {
200 x: u32,
201 y: u32,
202 scroll_x: i32,
203 scroll_y: i32,
204 keys: Option<Vec<CompactString>>,
205 },
206 Keypress {
207 keys: Vec<CompactString>,
208 },
209 Type {
210 text: String,
211 },
212 Wait,
213 Screenshot,
214}
215
216impl WireAction {
217 fn into_action(self) -> Result<Action> {
218 Ok(match self {
219 Self::Click { x, y, button, keys } => Action::Click {
220 at: Some(Point { x, y }),
221 button: button.into(),
222 count: 1,
223 modifiers: keys.unwrap_or_default(),
224 },
225 Self::DoubleClick { x, y, keys } => Action::Click {
226 at: Some(Point { x, y }),
227 button: MouseButton::Left,
228 count: 2,
229 modifiers: keys.unwrap_or_default(),
230 },
231 Self::Drag { path, keys } => {
232 ensure!((2..=1024).contains(&path.len()), "invalid OpenAI computer drag path");
233 Action::Drag {
234 path: path.into_iter().map(Point::from).collect(),
235 modifiers: keys.unwrap_or_default(),
236 }
237 }
238 Self::Move { x, y, keys } => Action::Move {
239 at: Point { x, y },
240 modifiers: keys.unwrap_or_default(),
241 },
242 Self::Scroll { x, y, scroll_x, scroll_y, keys } => Action::ScrollPixels {
243 at: Point { x, y },
244 x: scroll_x,
245 y: scroll_y,
246 modifiers: keys.unwrap_or_default(),
247 },
248 Self::Keypress { keys } => {
249 ensure!(!keys.is_empty(), "empty OpenAI computer keypress");
250 Action::Key { keys, repeat: 1 }
251 }
252 Self::Type { text } => Action::Type(text),
253 Self::Wait => Action::Wait(Duration::from_secs(1)),
254 Self::Screenshot => Action::Screenshot,
255 })
256 }
257}
258
259#[cfg(test)]
260mod tests;