Skip to main content

vtcode_llm/providers/anthropic/
computer_use.rs

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