Skip to main content

vtcode_llm/provider/
native.rs

1//! Provider-native computer-use calls for bound routes.
2//!
3//! Ordinary `LLMResponse.tool_calls` carry function calls. Bound computer-use
4//! turns return [`NativeResponse`] instead: decoded native calls plus any
5//! ordinary calls from the same turn, with the verbatim assistant blocks the
6//! next request replays. Native payloads stay in memory and move by value:
7//! these types implement neither serialization nor `Clone`, and their manual
8//! `Debug` impls reveal routing metadata only.
9
10use serde_json::Value;
11use std::pin::Pin;
12use vtcode_computer_use::Action;
13
14use super::{FinishReason, LLMError, ToolCall, Usage};
15
16/// Which provider produced a native call.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum NativeProvider {
19    /// OpenAI Responses `computer_call` item.
20    OpenAi,
21    /// Anthropic Messages computer-toolset `tool_use` block.
22    Anthropic,
23}
24
25impl NativeProvider {
26    fn as_str(self) -> &'static str {
27        match self {
28            Self::OpenAi => "openai",
29            Self::Anthropic => "anthropic",
30        }
31    }
32}
33
34/// One decoded native call in wire order.
35pub struct NativeCall {
36    /// Provider call identity (`call_id` or tool-use `id`).
37    pub id: String,
38    /// Which provider produced the call.
39    pub provider: NativeProvider,
40    /// Position in the original content/output array, so results merge back
41    /// with ordinary calls after the computer batch runs.
42    pub index: usize,
43    /// Decoded provider-native body.
44    pub body: NativeCallBody,
45}
46
47/// Decoded provider-native call body.
48pub enum NativeCallBody {
49    /// Ordered OpenAI actions with their original item for stateless replay.
50    OpenAi {
51        /// Original `computer_call` item, owned for replay.
52        replay_item: Value,
53        /// Actions in execution order, ending in a screenshot capture.
54        actions: Vec<Action>,
55    },
56    /// One Anthropic member call. A malformed member retains its correlation
57    /// identity with the decode failure so the runtime can answer that block
58    /// and halt the batch.
59    Anthropic {
60        /// Toolset member name, e.g. `"left_click"`.
61        name: String,
62        /// Decoded action or its failure message.
63        action: Result<Action, String>,
64    },
65}
66
67/// Bound-route response: ordinary calls for existing dispatch, natives for
68/// the computer controller, verbatim blocks for history replay.
69pub struct NativeResponse {
70    /// Joined text content, when the turn produced any.
71    pub content: Option<String>,
72    /// Model that generated the response.
73    pub model: String,
74    /// Token usage statistics.
75    pub usage: Option<Usage>,
76    /// Why the response finished.
77    pub finish_reason: FinishReason,
78    /// Joined thinking text, when the turn produced any.
79    pub reasoning: Option<String>,
80    /// Ordinary function calls in wire order.
81    pub tool_calls: Vec<ToolCall>,
82    /// Decoded native calls in wire order.
83    pub native_calls: Vec<NativeCall>,
84    /// Verbatim assistant content blocks for replay on the next request.
85    pub assistant_blocks: Vec<Value>,
86    /// Request ID from the provider.
87    pub request_id: Option<String>,
88    /// Organization ID from the provider.
89    pub organization_id: Option<String>,
90}
91
92// Debug reveals routing metadata only. Text content, thinking, assistant
93// blocks, and decoded actions never implement it, so payloads cannot reach
94// logs through these types.
95impl std::fmt::Debug for NativeCall {
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        let body = match &self.body {
98            NativeCallBody::OpenAi { actions, .. } => format!("openai:{}actions", actions.len()),
99            NativeCallBody::Anthropic { name, action } => {
100                format!("anthropic:{name}:{}", if action.is_ok() { "valid" } else { "invalid" })
101            }
102        };
103        f.debug_struct("NativeCall")
104            .field("id", &self.id)
105            .field("provider", &self.provider.as_str())
106            .field("index", &self.index)
107            .field("body", &body)
108            .finish()
109    }
110}
111
112impl std::fmt::Debug for NativeResponse {
113    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114        f.debug_struct("NativeResponse")
115            .field("model", &self.model)
116            .field("finish_reason", &self.finish_reason)
117            .field("usage", &self.usage)
118            .field("tool_call_ids", &self.tool_calls.iter().map(|call| call.id.as_str()).collect::<Vec<_>>())
119            .field("native_calls", &self.native_calls)
120            .finish()
121    }
122}
123
124/// One streamed bound-route event. Deltas mirror the ordinary stream
125/// contract; the completed response is the authoritative decode and matches
126/// the non-streaming route byte-for-byte by construction.
127pub enum NativeStreamEvent {
128    /// Assistant text fragment.
129    TextDelta {
130        /// Text fragment.
131        delta: String,
132    },
133    /// Thinking fragment.
134    ReasoningDelta {
135        /// Reasoning fragment.
136        delta: String,
137    },
138    /// Final accumulated response, decoded by the same parser the
139    /// non-streaming route uses.
140    Completed(Box<NativeResponse>),
141}
142
143impl std::fmt::Debug for NativeStreamEvent {
144    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145        match self {
146            Self::TextDelta { delta } => f.debug_struct("TextDelta").field("bytes", &delta.len()).finish(),
147            Self::ReasoningDelta { delta } => f.debug_struct("ReasoningDelta").field("bytes", &delta.len()).finish(),
148            Self::Completed(response) => f.debug_tuple("Completed").field(response).finish(),
149        }
150    }
151}
152
153/// Streamed bound computer-use route.
154pub type NativeStream = Pin<Box<dyn futures::Stream<Item = Result<NativeStreamEvent, LLMError>> + Send>>;