1use std::{collections::HashSet, time::Duration};
4
5use anyhow::{Result, bail, ensure};
6use base64::{Engine, engine::general_purpose::STANDARD};
7use compact_str::CompactString;
8use serde::de::DeserializeOwned;
9use serde_json::{Value, json};
10use vtcode_computer_use::{
11 Action, Driver, MAX_BATCH_ACTIONS, MAX_SCREENSHOT_BYTES, MouseButton, Observation, Point, Screenshot,
12 ScrollDirection, TurnControl,
13};
14
15use crate::provider::{NativeCall, NativeCallBody};
16
17pub(super) const TOOLSET: &str = "computer";
18pub(crate) use vtcode_computer_use::gate::ANTHROPIC_COMPUTER_PROTOCOL as PROTOCOL;
21const NOT_EXECUTED: &str = "Not executed: an earlier computer action in this turn failed.";
22
23pub(super) fn unbound_route_error() -> crate::provider::LLMError {
24 crate::provider::LLMError::Provider {
25 message: "Anthropic computer toolset call requires an active computer-use route.".into(),
26 metadata: None,
27 }
28}
29
30pub fn declaration() -> Value {
31 json!({"type": PROTOCOL})
32}
33
34pub struct ComputerCall<'a> {
37 id: &'a str,
38 pub action: Result<Action>,
39}
40
41impl ComputerCall<'_> {
42 pub fn id(&self) -> &str {
43 self.id
44 }
45
46 pub fn result(&self, outcome: ComputerOutcome<'_>) -> Value {
47 computer_result(self.id, outcome)
48 }
49}
50
51fn computer_result(id: &str, outcome: ComputerOutcome<'_>) -> Value {
52 let (is_error, content) = match outcome {
53 ComputerOutcome::Executed(observation) => match observation {
54 Observation::Done => (false, json!("OK")),
55 Observation::CursorPosition(Point { x, y }) => (false, json!(format!("X={x}, Y={y}"))),
56 Observation::Screenshot(image) => (
57 false,
58 json!([{"type": "image", "source": {
59 "type": "base64", "media_type": "image/png", "data": STANDARD.encode(image.as_png())
60 }}]),
61 ),
62 },
63 ComputerOutcome::Failed => (true, json!("Computer action failed.")),
64 ComputerOutcome::Skipped => (true, json!(NOT_EXECUTED)),
65 };
66 json!({
67 "type": "tool_result",
68 "tool_use_id": id,
69 "toolset_name": TOOLSET,
70 "is_error": is_error,
71 "content": content,
72 })
73}
74
75pub fn screenshot_in_output(output: &Value) -> Option<Screenshot> {
82 let blocks = output.get("content")?.as_array()?;
83 let data = blocks.iter().find_map(|block| {
84 if block.get("type")?.as_str()? != "image" {
85 return None;
86 }
87 let source = block.get("source")?;
88 if source.get("type")?.as_str()? != "base64" {
89 return None;
90 }
91 if source.get("media_type")?.as_str()? != "image/png" {
92 return None;
93 }
94 source.get("data")?.as_str()
95 })?;
96 let bytes = STANDARD.decode(data).ok()?;
97 Screenshot::png(bytes).ok()
98}
99
100pub enum ComputerOutcome<'a> {
101 Executed(&'a Observation),
102 Failed,
103 Skipped,
104}
105
106pub fn decode_call(block: &Value) -> Result<Option<ComputerCall<'_>>> {
108 if block["type"].as_str() != Some("tool_use") || block["toolset_name"].as_str() != Some(TOOLSET) {
109 return Ok(None);
110 }
111 let Some(id) = block["id"].as_str().filter(|id| !id.is_empty() && id.len() <= 256) else {
112 bail!("invalid Anthropic computer call identity");
113 };
114 Ok(Some(ComputerCall {
115 id,
116 action: decode_action(block["name"].as_str().unwrap_or_default(), &block["input"]),
117 }))
118}
119
120struct PreparedCall {
122 index: usize,
123 id: String,
124 action: Result<Action>,
125}
126
127pub async fn execute_batch<D: Driver>(
130 control: &mut TurnControl<D>,
131 blocks: &[Value],
132 timeout: Duration,
133) -> Result<Vec<(usize, Value)>> {
134 let mut prepared = Vec::new();
135 for (index, block) in blocks.iter().enumerate() {
136 if let Some(call) = decode_call(block)? {
137 prepared.push(PreparedCall {
138 index,
139 id: call.id().to_string(),
140 action: call.action,
141 });
142 }
143 }
144 let result = execute_calls(control, prepared, timeout).await;
145 if result.is_err() {
146 control.revoke_target();
147 }
148 result
149}
150
151pub async fn execute_decoded<D: Driver>(
154 control: &mut TurnControl<D>,
155 calls: Vec<NativeCall>,
156 timeout: Duration,
157) -> Result<Vec<(usize, Value)>> {
158 let mut prepared = Vec::with_capacity(calls.len());
159 for call in calls {
160 let NativeCallBody::Anthropic { action, .. } = call.body else {
161 bail!("mixed-provider computer batch");
162 };
163 prepared.push(PreparedCall {
164 index: call.index,
165 id: call.id,
166 action: action.map_err(|message| anyhow::anyhow!(message)),
167 });
168 }
169 let result = execute_calls(control, prepared, timeout).await;
170 if result.is_err() {
171 control.revoke_target();
172 }
173 result
174}
175
176async fn execute_calls<D: Driver>(
177 control: &mut TurnControl<D>,
178 prepared: Vec<PreparedCall>,
179 timeout: Duration,
180) -> Result<Vec<(usize, Value)>> {
181 control.ensure_turn_active()?;
182 let mut identities = HashSet::new();
183 for call in &prepared {
184 ensure!(identities.insert(call.id.as_str()), "duplicate Anthropic computer call identity");
185 }
186 ensure!(prepared.len() <= MAX_BATCH_ACTIONS, "too many Anthropic computer actions");
187
188 let start = tokio::time::Instant::now();
189 let mut failed = false;
190 let mut screenshot_bytes = 0;
191 let mut results = Vec::with_capacity(prepared.len());
192 for call in &prepared {
193 let observations = match &call.action {
194 Ok(action) if !failed => control
195 .execute_batch(&call.id, std::slice::from_ref(action), timeout.saturating_sub(start.elapsed()))
196 .await
197 .ok(),
198 _ => None,
199 };
200 control.ensure_turn_active()?;
201 let outcome = match observations.as_deref() {
202 Some([observation]) if observation_matches(&call.action, observation, &mut screenshot_bytes) => {
203 ComputerOutcome::Executed(observation)
204 }
205 _ if failed => ComputerOutcome::Skipped,
206 _ => {
207 control.revoke_target();
208 failed = true;
209 ComputerOutcome::Failed
210 }
211 };
212 results.push((call.index, computer_result(&call.id, outcome)));
213 }
214 control.ensure_turn_active()?;
215 Ok(results)
216}
217
218fn observation_matches(action: &Result<Action>, observation: &Observation, screenshot_bytes: &mut usize) -> bool {
219 match (action, observation) {
220 (Ok(Action::Screenshot | Action::Zoom { .. }), Observation::Screenshot(image)) => {
221 *screenshot_bytes += image.as_png().len();
222 *screenshot_bytes <= MAX_SCREENSHOT_BYTES
223 }
224 (Ok(Action::CursorPosition), Observation::CursorPosition(_)) => true,
225 (Ok(Action::Screenshot | Action::Zoom { .. } | Action::CursorPosition), _) => false,
226 (Ok(_), Observation::Done) => true,
227 _ => false,
228 }
229}
230
231fn decode_action(name: &str, input: &Value) -> Result<Action> {
232 ensure!(input.is_object(), "invalid Anthropic computer action input");
233 Ok(match name {
234 "screenshot" => Action::Screenshot,
235 "cursor_position" => Action::CursorPosition,
236 "left_mouse_down" => Action::LeftMouseDown,
237 "left_mouse_up" => Action::LeftMouseUp,
238 "zoom" => {
239 let [x0, y0, x1, y1] = field(input, "region")?;
240 ensure!(x0 < x1 && y0 < y1, "invalid computer zoom region");
241 Action::Zoom {
242 top_left: Point { x: x0, y: y0 },
243 bottom_right: Point { x: x1, y: y1 },
244 }
245 }
246 "left_click" | "middle_click" | "right_click" | "double_click" | "triple_click" => {
247 let (button, count) = match name {
248 "middle_click" => (MouseButton::Middle, 1),
249 "right_click" => (MouseButton::Right, 1),
250 "double_click" => (MouseButton::Left, 2),
251 "triple_click" => (MouseButton::Left, 3),
252 _ => (MouseButton::Left, 1),
253 };
254 Action::Click {
255 at: optional_point(input)?,
256 button,
257 count,
258 modifiers: modifiers(input)?,
259 }
260 }
261 "left_click_drag" => Action::Drag {
262 path: vec![
263 point(field(input, "start_coordinate")?),
264 point(field(input, "coordinate")?),
265 ],
266 modifiers: modifiers(input)?,
267 },
268 "mouse_move" => Action::Move {
269 at: point(field(input, "coordinate")?),
270 modifiers: Vec::new(),
271 },
272 "scroll" => {
273 let amount: u32 = field(input, "scroll_amount")?;
274 ensure!(amount <= 100_000, "invalid computer scroll amount");
275 Action::ScrollTicks {
276 at: optional_point(input)?,
277 direction: match input["scroll_direction"].as_str() {
278 Some("up") => ScrollDirection::Up,
279 Some("down") => ScrollDirection::Down,
280 Some("left") => ScrollDirection::Left,
281 Some("right") => ScrollDirection::Right,
282 _ => bail!("invalid computer scroll direction"),
283 },
284 amount,
285 modifiers: modifiers(input)?,
286 }
287 }
288 "type" => Action::Type(field(input, "text")?),
289 "key" => {
290 let repeat = optional_field(input, "repeat")?.unwrap_or(1);
291 ensure!((1..=100).contains(&repeat), "invalid computer key repeat count");
292 Action::Key {
293 keys: chord(&field::<String>(input, "text")?)?,
294 repeat,
295 }
296 }
297 "hold_key" => Action::HoldKey {
298 keys: chord(&field::<String>(input, "text")?)?,
299 duration: duration(input)?,
300 },
301 "wait" => Action::Wait(duration(input)?),
302 _ => bail!("unsupported Anthropic computer action"),
303 })
304}
305
306fn point([x, y]: [u32; 2]) -> Point {
307 Point { x, y }
308}
309
310fn optional_point(input: &Value) -> Result<Option<Point>> {
311 Ok(optional_field(input, "coordinate")?.map(point))
312}
313
314fn chord(text: &str) -> Result<Vec<CompactString>> {
315 ensure!(text.len() <= 128, "computer key chord is too long");
316 text.split('+')
317 .map(|key| {
318 ensure!(!key.is_empty(), "invalid computer key chord");
319 Ok(key.into())
320 })
321 .collect()
322}
323
324fn modifiers(input: &Value) -> Result<Vec<CompactString>> {
325 let Some(text) = optional_field::<String>(input, "text")? else {
326 return Ok(Vec::new());
327 };
328 let keys = chord(&text)?;
329 ensure!(
330 keys.iter()
331 .all(|key| matches!(key.as_str(), "shift" | "ctrl" | "alt" | "super")),
332 "invalid computer modifier"
333 );
334 Ok(keys)
335}
336
337fn duration(input: &Value) -> Result<Duration> {
338 let seconds: f64 = field(input, "duration")?;
339 ensure!((0.0..=300.0).contains(&seconds), "invalid computer action duration");
340 Ok(Duration::from_secs_f64(seconds))
341}
342
343fn field<T: DeserializeOwned>(input: &Value, key: &str) -> Result<T> {
344 T::deserialize(&input[key])
345 .map_err(|_private_error| anyhow::anyhow!("invalid Anthropic computer action field {key}"))
346}
347
348fn optional_field<T: DeserializeOwned>(input: &Value, key: &str) -> Result<Option<T>> {
349 input.get(key).map(|_| field(input, key)).transpose()
350}
351
352#[cfg(test)]
353mod tests;