Skip to main content

vtcode_llm/open_responses/bridge/
mod.rs

1//! Bridge layer for converting VT Code events to Open Responses format.
2//!
3//! This module provides adapters to convert VT Code's internal `ThreadEvent`
4//! and `ThreadItem` types to Open Responses-conformant structures, enabling
5//! backwards compatibility during migration.
6
7use serde_json::json;
8use sha2::{Digest, Sha256};
9
10use super::{
11    ContentPart, CustomItem, FunctionCallItem, ItemStatus, MessageItem, MessageRole, OpenResponseError, OpenUsage,
12    OutputItem, ReasoningItem, Response, ResponseStatus, ResponseStreamEvent, StreamEventEmitter,
13    response::{generate_item_id, generate_response_id},
14};
15use crate::provider::{FinishReason, NormalizedStreamEvent, ToolCall};
16use vtcode_exec_events::{
17    CommandExecutionStatus, McpToolCallStatus, PatchApplyStatus, ThreadEvent, ThreadItem, ThreadItemDetails,
18    ToolOutputItem,
19};
20
21/// Builder for constructing Open Responses `Response` objects from VT Code events.
22///
23/// Tracks streaming state and maintains the mapping between VT Code item IDs
24/// and Open Responses output item indices.
25#[derive(Debug)]
26#[must_use = "build the response before discarding the builder"]
27pub struct ResponseBuilder {
28    response: Response,
29    next_output_index: usize,
30    item_id_to_index: hashbrown::HashMap<String, usize>,
31    active_items: hashbrown::HashMap<String, ActiveItemState>,
32    tool_call_correlation_ids: hashbrown::HashMap<String, String>,
33    used_tool_call_ids: hashbrown::HashSet<String>,
34    normalized: NormalizedBridgeState,
35}
36
37/// State for an active (in-progress) streaming item.
38#[derive(Debug, Clone)]
39struct ActiveItemState {
40    output_index: usize,
41    content_index: usize,
42    /// Previous text content for safe delta computation (avoids UTF-8 slicing issues)
43    prev_text: String,
44    tool_output_prefix: Option<ToolOutputPrefix>,
45}
46
47/// Constant-size evidence used to reconcile streamed chunks with a later snapshot.
48#[derive(Debug, Clone)]
49struct ToolOutputPrefix {
50    digest: Sha256,
51    byte_len: Option<usize>,
52}
53
54impl ToolOutputPrefix {
55    fn new(text: &str) -> Self {
56        let mut prefix = Self { digest: Sha256::new(), byte_len: Some(0) };
57        prefix.append(text);
58        prefix
59    }
60
61    fn append(&mut self, text: &str) {
62        self.digest.update(text.as_bytes());
63        self.byte_len = self.byte_len.and_then(|len| len.checked_add(text.len()));
64    }
65
66    fn suffix<'a>(&self, snapshot: &'a str) -> Option<&'a str> {
67        let len = self.byte_len?;
68        let prefix = snapshot.get(..len)?;
69        (Sha256::digest(prefix.as_bytes()) == self.digest.clone().finalize())
70            .then(|| snapshot.get(len..))
71            .flatten()
72    }
73}
74
75#[derive(Debug, Clone)]
76struct NormalizedFunctionCallState {
77    item_id: String,
78    output_index: usize,
79    name: Option<String>,
80    arguments: String,
81}
82
83#[derive(Debug, Default)]
84struct NormalizedBridgeState {
85    response_started: bool,
86    message_item_id: Option<String>,
87    reasoning_item_id: Option<String>,
88    tool_calls: hashbrown::HashMap<String, NormalizedFunctionCallState>,
89}
90impl ResponseBuilder {
91    /// Creates a new response builder with the given model.
92    pub fn new(model: impl Into<String>) -> Self {
93        let response = Response::new(generate_response_id(), model);
94        Self {
95            response,
96            next_output_index: 0,
97            item_id_to_index: hashbrown::HashMap::new(),
98            active_items: hashbrown::HashMap::new(),
99            tool_call_correlation_ids: hashbrown::HashMap::new(),
100            used_tool_call_ids: hashbrown::HashSet::new(),
101            normalized: NormalizedBridgeState::default(),
102        }
103    }
104
105    /// Returns a reference to the current response.
106    pub(crate) fn response(&self) -> &Response {
107        &self.response
108    }
109
110    /// Returns a mutable reference to the current response.
111    pub fn response_mut(&mut self) -> &mut Response {
112        &mut self.response
113    }
114
115    /// Returns the response ID.
116    pub fn response_id(&self) -> &str {
117        &self.response.id
118    }
119
120    /// Consumes the builder and returns the final response.
121    #[must_use]
122    pub fn build(self) -> Response {
123        self.response
124    }
125}
126
127mod emitter;
128mod items;
129mod normalized;
130
131pub use emitter::DualEventEmitter;
132
133#[cfg(test)]
134mod tests;