1use std::sync::Arc;
13use std::time::Duration;
14
15use adk_core::egress::ToolEgress;
16use adk_core::{
17 ActuationOutput, AdkError, BatchGroup, ComputerAction, ComputerActionKind, ComputerActuator,
18 InlineDataPart, MouseButton, ReadonlyContext, Result, ScreenPoint, ScrollDirection, Tool,
19 ToolContext, ToolEffect, Toolset,
20};
21use async_trait::async_trait;
22use serde_json::{Map, Value, json};
23
24pub const COMPUTER_TOOLSET: &str = "computer";
26
27pub const COMPUTER_BATCH_HALT_TEXT: &str =
29 "Not executed: an earlier computer action in this turn failed.";
30
31const MEMBER_KEY: &str = "x-adk-anthropic-toolset-member";
33
34const MAX_DURATION: Duration = Duration::from_secs(300);
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48pub enum ComputerUseMember {
49 Screenshot,
51 Zoom,
53 LeftClick,
55 RightClick,
57 MiddleClick,
59 DoubleClick,
61 TripleClick,
63 LeftClickDrag,
65 MouseMove,
67 LeftMouseDown,
69 LeftMouseUp,
71 CursorPosition,
73 Scroll,
75 Type,
77 Key,
79 HoldKey,
81 Wait,
83}
84
85impl ComputerUseMember {
86 pub const ALL: &'static [Self] = &[
88 Self::Screenshot,
89 Self::Zoom,
90 Self::LeftClick,
91 Self::RightClick,
92 Self::MiddleClick,
93 Self::DoubleClick,
94 Self::TripleClick,
95 Self::LeftClickDrag,
96 Self::MouseMove,
97 Self::LeftMouseDown,
98 Self::LeftMouseUp,
99 Self::CursorPosition,
100 Self::Scroll,
101 Self::Type,
102 Self::Key,
103 Self::HoldKey,
104 Self::Wait,
105 ];
106
107 pub fn as_str(self) -> &'static str {
109 match self {
110 Self::Screenshot => "screenshot",
111 Self::Zoom => "zoom",
112 Self::LeftClick => "left_click",
113 Self::RightClick => "right_click",
114 Self::MiddleClick => "middle_click",
115 Self::DoubleClick => "double_click",
116 Self::TripleClick => "triple_click",
117 Self::LeftClickDrag => "left_click_drag",
118 Self::MouseMove => "mouse_move",
119 Self::LeftMouseDown => "left_mouse_down",
120 Self::LeftMouseUp => "left_mouse_up",
121 Self::CursorPosition => "cursor_position",
122 Self::Scroll => "scroll",
123 Self::Type => "type",
124 Self::Key => "key",
125 Self::HoldKey => "hold_key",
126 Self::Wait => "wait",
127 }
128 }
129
130 pub fn tool_name(self) -> String {
132 format!("{COMPUTER_TOOLSET}.{}", self.as_str())
133 }
134
135 pub fn action_kind(self) -> ComputerActionKind {
137 match self {
138 Self::Screenshot => ComputerActionKind::Screenshot,
139 Self::Zoom => ComputerActionKind::Zoom,
140 Self::LeftClick
141 | Self::RightClick
142 | Self::MiddleClick
143 | Self::DoubleClick
144 | Self::TripleClick => ComputerActionKind::Click,
145 Self::LeftClickDrag => ComputerActionKind::Drag,
146 Self::MouseMove => ComputerActionKind::MoveTo,
147 Self::LeftMouseDown => ComputerActionKind::MouseDown,
148 Self::LeftMouseUp => ComputerActionKind::MouseUp,
149 Self::CursorPosition => ComputerActionKind::CursorPosition,
150 Self::Scroll => ComputerActionKind::Scroll,
151 Self::Type => ComputerActionKind::Type,
152 Self::Key => ComputerActionKind::Key,
153 Self::HoldKey => ComputerActionKind::HoldKey,
154 Self::Wait => ComputerActionKind::Wait,
155 }
156 }
157
158 fn description(self) -> &'static str {
159 match self {
160 Self::Screenshot => "Capture the full display as an image.",
161 Self::Zoom => "Capture a region of the display at full resolution.",
162 Self::LeftClick => "Left-click at a coordinate or at the cursor.",
163 Self::RightClick => "Right-click at a coordinate or at the cursor.",
164 Self::MiddleClick => "Middle-click at a coordinate or at the cursor.",
165 Self::DoubleClick => "Double-click at a coordinate or at the cursor.",
166 Self::TripleClick => "Triple-click at a coordinate or at the cursor.",
167 Self::LeftClickDrag => "Press at one coordinate, drag to another, and release.",
168 Self::MouseMove => "Move the cursor to a coordinate.",
169 Self::LeftMouseDown => "Press the left mouse button at the cursor.",
170 Self::LeftMouseUp => "Release the left mouse button at the cursor.",
171 Self::CursorPosition => "Report the cursor position.",
172 Self::Scroll => "Scroll at a coordinate or at the cursor.",
173 Self::Type => "Type text at the keyboard focus.",
174 Self::Key => "Press a key or key combination.",
175 Self::HoldKey => "Hold a key or key combination down for a duration.",
176 Self::Wait => "Pause before the next action.",
177 }
178 }
179}
180
181pub struct ComputerUseToolset {
214 actuator: Arc<dyn ComputerActuator>,
215 display: Option<(u32, u32)>,
216 withheld: Vec<ComputerUseMember>,
217 egress: ToolEgress,
218}
219
220impl ComputerUseToolset {
221 pub fn new(actuator: Arc<dyn ComputerActuator>) -> Self {
223 let display = actuator.display_size();
224 Self { actuator, display, withheld: Vec::new(), egress: ToolEgress::Undeclared }
225 }
226
227 pub fn with_display(mut self, width: u32, height: u32) -> Self {
230 self.display = Some((width, height));
231 self
232 }
233
234 pub fn without(mut self, member: ComputerUseMember) -> Self {
236 self.withheld.push(member);
237 self
238 }
239
240 pub fn with_egress(mut self, egress: ToolEgress) -> Self {
244 self.egress = egress;
245 self
246 }
247
248 pub fn members(&self) -> Vec<ComputerUseMember> {
250 ComputerUseMember::ALL
251 .iter()
252 .copied()
253 .filter(|member| !self.withheld.contains(member))
254 .filter(|member| {
255 *member == ComputerUseMember::Wait || self.actuator.supports(member.action_kind())
256 })
257 .collect()
258 }
259
260 pub fn member_tools(&self) -> Vec<Arc<dyn Tool>> {
262 self.members()
263 .into_iter()
264 .map(|member| {
265 Arc::new(ComputerUseTool {
266 member,
267 name: member.tool_name(),
268 actuator: self.actuator.clone(),
269 display: self.display,
270 egress: self.egress.clone(),
271 }) as Arc<dyn Tool>
272 })
273 .collect()
274 }
275}
276
277#[async_trait]
278impl Toolset for ComputerUseToolset {
279 fn name(&self) -> &str {
280 "computer_use"
281 }
282
283 async fn tools(&self, _ctx: Arc<dyn ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>> {
284 Ok(self.member_tools())
285 }
286}
287
288struct ComputerUseTool {
290 member: ComputerUseMember,
291 name: String,
292 actuator: Arc<dyn ComputerActuator>,
293 display: Option<(u32, u32)>,
294 egress: ToolEgress,
295}
296
297fn invalid(member: ComputerUseMember, message: impl std::fmt::Display) -> AdkError {
298 AdkError::tool(format!("Error: invalid input for {}: {message}", member.as_str()))
299}
300
301impl ComputerUseTool {
302 fn point(&self, input: &Map<String, Value>, field: &str) -> Result<Option<ScreenPoint>> {
303 let Some(value) = input.get(field) else { return Ok(None) };
304 let pair = value.as_array().filter(|pair| pair.len() == 2);
305 let (Some(x), Some(y)) =
306 (pair.and_then(|pair| pair[0].as_i64()), pair.and_then(|pair| pair[1].as_i64()))
307 else {
308 return Err(invalid(
309 self.member,
310 format!("{field} must be [x, y] in screenshot pixels"),
311 ));
312 };
313 if let Some((width, height)) = self.display
314 && (x < 0 || y < 0 || x >= i64::from(width) || y >= i64::from(height))
315 {
316 return Err(AdkError::tool(format!(
317 "Error: coordinate ({x}, {y}) is outside the {width}x{height} display"
318 )));
319 }
320 Ok(Some(ScreenPoint::new(x, y)))
321 }
322
323 fn required_point(&self, input: &Map<String, Value>, field: &str) -> Result<ScreenPoint> {
324 self.point(input, field)?
325 .ok_or_else(|| invalid(self.member, format!("{field} is required")))
326 }
327
328 fn text(&self, input: &Map<String, Value>) -> Result<String> {
329 input
330 .get("text")
331 .and_then(Value::as_str)
332 .map(str::to_string)
333 .ok_or_else(|| invalid(self.member, "text is required"))
334 }
335
336 fn duration(&self, input: &Map<String, Value>) -> Result<Duration> {
337 let seconds = input
338 .get("duration")
339 .and_then(Value::as_f64)
340 .filter(|seconds| seconds.is_finite() && *seconds >= 0.0)
341 .ok_or_else(|| invalid(self.member, "duration must be a number of seconds"))?;
342 Ok(Duration::from_secs_f64(seconds).min(MAX_DURATION))
343 }
344
345 fn action(&self, input: &Map<String, Value>) -> Result<ComputerAction> {
346 let modifiers = || -> Vec<String> {
347 input
348 .get("text")
349 .and_then(Value::as_str)
350 .map(|chord| {
351 chord
352 .split('+')
353 .map(str::trim)
354 .filter(|key| !key.is_empty())
355 .map(str::to_string)
356 .collect()
357 })
358 .unwrap_or_default()
359 };
360 let click = |button: MouseButton, count: u8| -> Result<ComputerAction> {
361 Ok(ComputerAction::Click {
362 button,
363 count,
364 at: self.point(input, "coordinate")?,
365 modifiers: modifiers(),
366 })
367 };
368 Ok(match self.member {
369 ComputerUseMember::Screenshot => ComputerAction::Screenshot,
370 ComputerUseMember::Zoom => {
371 let region: Vec<i64> = input
372 .get("region")
373 .and_then(Value::as_array)
374 .map(|region| region.iter().filter_map(Value::as_i64).collect())
375 .unwrap_or_default();
376 let [x0, y0, x1, y1] = region[..] else {
377 return Err(invalid(self.member, "region must be [x0, y0, x1, y1]"));
378 };
379 if x1 <= x0 || y1 <= y0 {
380 return Err(invalid(
381 self.member,
382 "region must have a positive width and height",
383 ));
384 }
385 ComputerAction::Zoom { region: [x0, y0, x1, y1] }
386 }
387 ComputerUseMember::LeftClick => click(MouseButton::Left, 1)?,
388 ComputerUseMember::RightClick => click(MouseButton::Right, 1)?,
389 ComputerUseMember::MiddleClick => click(MouseButton::Middle, 1)?,
390 ComputerUseMember::DoubleClick => click(MouseButton::Left, 2)?,
391 ComputerUseMember::TripleClick => click(MouseButton::Left, 3)?,
392 ComputerUseMember::LeftClickDrag => ComputerAction::Drag {
393 from: self.required_point(input, "start_coordinate")?,
394 to: self.required_point(input, "coordinate")?,
395 modifiers: modifiers(),
396 },
397 ComputerUseMember::MouseMove => {
398 ComputerAction::MoveTo { at: self.required_point(input, "coordinate")? }
399 }
400 ComputerUseMember::LeftMouseDown => ComputerAction::MouseDown,
401 ComputerUseMember::LeftMouseUp => ComputerAction::MouseUp,
402 ComputerUseMember::CursorPosition => ComputerAction::CursorPosition,
403 ComputerUseMember::Scroll => {
404 let direction = match input.get("scroll_direction").and_then(Value::as_str) {
405 Some("up") => ScrollDirection::Up,
406 Some("down") => ScrollDirection::Down,
407 Some("left") => ScrollDirection::Left,
408 Some("right") => ScrollDirection::Right,
409 _ => {
410 return Err(invalid(
411 self.member,
412 "scroll_direction must be up, down, left or right",
413 ));
414 }
415 };
416 let amount = input.get("scroll_amount").and_then(Value::as_u64).unwrap_or(3);
417 ComputerAction::Scroll {
418 at: self.point(input, "coordinate")?,
419 direction,
420 amount: amount.clamp(1, 100) as u32,
421 modifiers: modifiers(),
422 }
423 }
424 ComputerUseMember::Type => ComputerAction::Type { text: self.text(input)? },
425 ComputerUseMember::Key => ComputerAction::Key {
426 keys: self.text(input)?,
427 repeat: input.get("repeat").and_then(Value::as_u64).unwrap_or(1).clamp(1, 100)
428 as u32,
429 },
430 ComputerUseMember::HoldKey => {
431 ComputerAction::HoldKey { keys: self.text(input)?, duration: self.duration(input)? }
432 }
433 ComputerUseMember::Wait => ComputerAction::Wait { duration: self.duration(input)? },
434 })
435 }
436}
437
438#[async_trait]
439impl Tool for ComputerUseTool {
440 fn name(&self) -> &str {
441 &self.name
442 }
443
444 fn description(&self) -> &str {
445 self.member.description()
446 }
447
448 fn declaration(&self) -> Value {
449 let mut member = json!({ "toolset": COMPUTER_TOOLSET, "member": self.member.as_str() });
450 if let Some((width, height)) = self.display {
451 member["display_width_px"] = json!(width);
452 member["display_height_px"] = json!(height);
453 }
454 json!({ "name": self.name, "description": self.description(), MEMBER_KEY: member })
455 }
456
457 fn is_read_only(&self) -> bool {
458 self.member.action_kind().is_observation()
459 }
460
461 fn effect(&self) -> ToolEffect {
462 if self.is_read_only() { ToolEffect::ReadOnly } else { ToolEffect::NonIdempotent }
463 }
464
465 fn batch_group(&self) -> Option<BatchGroup> {
466 Some(BatchGroup::new(COMPUTER_TOOLSET, COMPUTER_BATCH_HALT_TEXT))
467 }
468
469 fn egress(&self, _args: &Value) -> ToolEgress {
470 match self.member {
471 ComputerUseMember::Screenshot
472 | ComputerUseMember::Zoom
473 | ComputerUseMember::CursorPosition
474 | ComputerUseMember::Wait => ToolEgress::None,
475 _ => self.egress.clone(),
476 }
477 }
478
479 async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
480 let input = match args {
481 Value::Object(input) => input,
482 Value::Null => Map::new(),
483 _ => return Err(invalid(self.member, "input must be an object")),
484 };
485 let action = self.action(&input)?;
486 if let ComputerAction::Wait { duration } = action
487 && !self.actuator.supports(ComputerActionKind::Wait)
488 {
489 tokio::time::sleep(duration).await;
490 return Ok(Value::String("OK".into()));
491 }
492 tracing::debug!(computer.member = self.member.as_str(), "performing computer action");
493 Ok(match self.actuator.perform(action).await? {
494 ActuationOutput::Done => Value::String("OK".into()),
495 ActuationOutput::Cursor(point) => {
496 Value::String(format!("X={}, Y={}", point.x, point.y))
497 }
498 ActuationOutput::Image(image) => {
499 let caption = if self.member == ComputerUseMember::Zoom {
500 "Zoomed region captured."
501 } else {
502 "Screenshot captured."
503 };
504 let inline = InlineDataPart {
505 mime_type: image.mime_type,
506 data: image.data,
507 uri: None,
508 annotations: None,
509 };
510 json!({ "response": caption, "inline_data": [inline] })
511 }
512 other => {
513 return Err(AdkError::tool(format!(
514 "Error: the actuator returned an unexpected result for {}: {other:?}",
515 self.member.as_str()
516 )));
517 }
518 })
519 }
520}