Skip to main content

vtcode_llm/open_responses/
integration.rs

1//! Integration layer for Open Responses with VT Code agent infrastructure.
2//!
3//! This module provides the glue between VT Code's internal event system
4//! and the Open Responses specification. It uses configuration from
5//! `vtcode.toml` to control when and how Open Responses events are emitted.
6
7use std::sync::Arc;
8
9use parking_lot::Mutex;
10
11use crate::provider::NormalizedStreamEvent;
12use vtcode_config::OpenResponsesConfig;
13use vtcode_exec_events::ThreadEvent;
14
15use super::{OpenUsage, OutputItem, Response, ResponseBuilder, ResponseStreamEvent, VecStreamEmitter};
16
17/// Callback type for receiving Open Responses streaming events.
18pub type OpenResponsesCallback = Arc<Mutex<Box<dyn FnMut(ResponseStreamEvent) + Send>>>;
19
20/// Open Responses integration manager.
21///
22/// This struct manages the integration between VT Code's internal event system
23/// and the Open Responses specification. It respects the configuration flags
24/// to control event emission and item mapping.
25pub struct OpenResponsesIntegration {
26    config: OpenResponsesConfig,
27    builder: Option<ResponseBuilder>,
28    events: Vec<ResponseStreamEvent>,
29    callback: Option<OpenResponsesCallback>,
30}
31
32impl std::fmt::Debug for OpenResponsesIntegration {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        f.debug_struct("OpenResponsesIntegration")
35            .field("config", &self.config)
36            .field("builder", &self.builder)
37            .field("events_count", &self.events.len())
38            .field("callback_set", &self.callback.is_some())
39            .finish()
40    }
41}
42
43impl OpenResponsesIntegration {
44    /// Creates a new integration manager with the given configuration.
45    pub fn new(config: OpenResponsesConfig) -> Self {
46        Self {
47            config,
48            builder: None,
49            events: Vec::new(),
50            callback: None,
51        }
52    }
53
54    /// Creates a new integration manager that is disabled.
55    fn disabled() -> Self {
56        Self::new(OpenResponsesConfig::default())
57    }
58
59    /// Returns true if Open Responses integration is enabled.
60    fn is_enabled(&self) -> bool {
61        self.config.enabled
62    }
63
64    /// Sets a callback for receiving Open Responses events.
65    pub fn set_callback(&mut self, callback: OpenResponsesCallback) {
66        self.callback = Some(callback);
67    }
68
69    /// Starts a new response session with the given model.
70    ///
71    /// This should be called when a new agent turn begins.
72    pub fn start_response(&mut self, model: &str) {
73        if !self.config.enabled {
74            return;
75        }
76
77        self.builder = Some(ResponseBuilder::new(model));
78        self.events.clear();
79    }
80
81    /// Processes a VT Code ThreadEvent and emits corresponding Open Responses events.
82    pub fn process_event(&mut self, event: &ThreadEvent) {
83        if !self.config.enabled || !self.config.emit_events {
84            return;
85        }
86
87        let Some(builder) = self.builder.as_mut() else {
88            return;
89        };
90
91        // Use a collecting emitter first
92        let mut collector = VecStreamEmitter::new();
93        builder.process_event(event, &mut collector);
94
95        // Process collected events
96        for stream_event in collector.into_events() {
97            // Apply filtering based on config
98            if self.should_emit_event(&stream_event) {
99                self.emit_event(stream_event);
100            }
101        }
102    }
103
104    /// Processes a normalized provider stream event and emits corresponding Open Responses events.
105    fn process_normalized_event(&mut self, event: &NormalizedStreamEvent) {
106        if !self.config.enabled || !self.config.emit_events {
107            return;
108        }
109
110        let Some(builder) = self.builder.as_mut() else {
111            return;
112        };
113
114        let mut collector = VecStreamEmitter::new();
115        builder.process_normalized_event(event, &mut collector);
116
117        for stream_event in collector.into_events() {
118            if self.should_emit_event(&stream_event) {
119                self.emit_event(stream_event);
120            }
121        }
122    }
123
124    /// Returns the current response, if any.
125    fn current_response(&self) -> Option<&Response> {
126        self.builder.as_ref().map(|b| b.response())
127    }
128
129    /// Finishes the current response and returns it.
130    pub fn finish_response(&mut self) -> Option<Response> {
131        self.builder.take().map(|b| b.build())
132    }
133
134    /// Returns all collected events.
135    fn events(&self) -> &[ResponseStreamEvent] {
136        &self.events
137    }
138
139    /// Takes all collected events, leaving the internal buffer empty.
140    pub fn take_events(&mut self) -> Vec<ResponseStreamEvent> {
141        std::mem::take(&mut self.events)
142    }
143
144    fn should_emit_event(&self, event: &ResponseStreamEvent) -> bool {
145        match event {
146            // Always emit response lifecycle events
147            ResponseStreamEvent::ResponseCreated { .. }
148            | ResponseStreamEvent::ResponseInProgress { .. }
149            | ResponseStreamEvent::ResponseCompleted { .. }
150            | ResponseStreamEvent::ResponseFailed { .. }
151            | ResponseStreamEvent::ResponseIncomplete { .. } => true,
152
153            // Filter output items based on config
154            ResponseStreamEvent::OutputItemAdded { item, .. } | ResponseStreamEvent::OutputItemDone { item, .. } => {
155                self.should_include_item(item)
156            }
157
158            // Reasoning events
159            ResponseStreamEvent::ReasoningDelta { .. } | ResponseStreamEvent::ReasoningDone { .. } => {
160                self.config.include_reasoning
161            }
162
163            // Function call events
164            ResponseStreamEvent::FunctionCallArgumentsDelta { .. }
165            | ResponseStreamEvent::FunctionCallArgumentsDone { .. } => self.config.map_tool_calls,
166
167            // Extension events
168            ResponseStreamEvent::CustomEvent { .. } => self.config.include_extensions,
169
170            // Text and content events are always emitted
171            _ => true,
172        }
173    }
174
175    fn should_include_item(&self, item: &OutputItem) -> bool {
176        match item {
177            OutputItem::Reasoning(_) => self.config.include_reasoning,
178            OutputItem::FunctionCall(_) | OutputItem::FunctionCallOutput(_) => self.config.map_tool_calls,
179            OutputItem::Custom(_) => self.config.include_extensions,
180            OutputItem::Message(_) => true,
181        }
182    }
183
184    fn emit_event(&mut self, event: ResponseStreamEvent) {
185        // Store in local buffer
186        self.events.push(event.clone());
187
188        // Send to the callback if registered. `parking_lot::Mutex` never
189        // poisons, so a panic inside an arbitrary callback cannot silently drop
190        // every later event (which `if let Ok(...)` on `std::sync::Mutex` did).
191        if let Some(callback) = &self.callback {
192            let mut cb = callback.lock();
193            cb(event);
194        }
195    }
196}
197
198impl Default for OpenResponsesIntegration {
199    fn default() -> Self {
200        Self::disabled()
201    }
202}
203
204/// Trait for types that can provide Open Responses integration.
205pub trait OpenResponsesProvider {
206    /// Returns a reference to the Open Responses integration, if enabled.
207    fn open_responses(&self) -> Option<&OpenResponsesIntegration>;
208
209    /// Returns a mutable reference to the Open Responses integration, if enabled.
210    fn open_responses_mut(&mut self) -> Option<&mut OpenResponsesIntegration>;
211}
212
213/// Extension trait for converting VT Code LLM responses to Open Responses format.
214pub trait ToOpenResponse {
215    /// Converts to an Open Responses Response object.
216    fn to_open_response(&self, response_id: &str, model: &str) -> Response;
217}
218
219impl ToOpenResponse for crate::provider::LLMResponse {
220    fn to_open_response(&self, response_id: &str, model: &str) -> Response {
221        let mut response = Response::new(response_id, model);
222
223        // Add usage if available
224        if let Some(usage) = &self.usage {
225            response.usage = Some(OpenUsage::from_llm_usage(usage).into());
226        }
227
228        // Add content as message item if present
229        if let Some(content) = &self.content
230            && !content.is_empty()
231        {
232            let item = OutputItem::completed_message(
233                super::response::generate_item_id(),
234                super::items::MessageRole::Assistant,
235                vec![super::ContentPart::output_text(content)],
236            );
237            response.add_output(item);
238        }
239
240        // Add reasoning if present
241        if let Some(reasoning) = &self.reasoning
242            && !reasoning.is_empty()
243        {
244            let item = OutputItem::Reasoning(super::items::ReasoningItem {
245                id: super::response::generate_item_id().into(),
246                status: super::ItemStatus::Completed,
247                summary: None,
248                content: Some(reasoning.clone()),
249                encrypted_content: None,
250            });
251            response.add_output(item);
252        }
253
254        // Add tool calls as function call items
255        if let Some(tool_calls) = &self.tool_calls {
256            for tc in tool_calls {
257                // Extract name and arguments from the function field
258                let (name, arguments) = if let Some(ref func) = tc.function {
259                    (func.name.clone(), serde_json::from_str(&func.arguments).unwrap_or(serde_json::json!({})))
260                } else {
261                    (tc.call_type.clone(), serde_json::json!({}))
262                };
263
264                let item = OutputItem::FunctionCall(super::items::FunctionCallItem {
265                    id: tc.id.clone().into(),
266                    status: super::ItemStatus::Completed,
267                    name,
268                    arguments,
269                    call_id: Some(tc.id.clone()),
270                });
271                response.add_output(item);
272            }
273        }
274
275        response.complete();
276        response
277    }
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283    use crate::provider::{FinishReason, LLMResponse, NormalizedStreamEvent};
284
285    #[test]
286    fn test_integration_disabled_by_default() {
287        let integration = OpenResponsesIntegration::disabled();
288        assert!(!integration.is_enabled());
289    }
290
291    #[test]
292    fn test_integration_enabled() {
293        let config = OpenResponsesConfig { enabled: true, ..Default::default() };
294        let integration = OpenResponsesIntegration::new(config);
295        assert!(integration.is_enabled());
296    }
297
298    #[test]
299    fn test_start_response() {
300        let config = OpenResponsesConfig { enabled: true, ..Default::default() };
301        let mut integration = OpenResponsesIntegration::new(config);
302        integration.start_response("gpt-5");
303        assert!(integration.current_response().is_some());
304    }
305
306    #[test]
307    fn test_disabled_skips_events() {
308        let mut integration = OpenResponsesIntegration::disabled();
309        integration.start_response("gpt-5");
310        // Should not create a builder when disabled
311        assert!(integration.current_response().is_none());
312    }
313
314    #[test]
315    fn integration_processes_normalized_events() {
316        let mut integration = OpenResponsesIntegration::new(OpenResponsesConfig {
317            enabled: true,
318            emit_events: true,
319            ..Default::default()
320        });
321        integration.start_response("gpt-5");
322
323        integration.process_normalized_event(&NormalizedStreamEvent::TextDelta { delta: "hello".to_string() });
324        integration.process_normalized_event(&NormalizedStreamEvent::Done {
325            response: Box::new(LLMResponse {
326                content: Some("hello".to_string()),
327                model: "gpt-5".to_string(),
328                tool_calls: None,
329                usage: None,
330                finish_reason: FinishReason::Stop,
331                reasoning: None,
332                reasoning_details: None,
333                organization_id: None,
334                request_id: None,
335                tool_references: Vec::new(),
336                compaction: None,
337            }),
338        });
339
340        assert!(integration.events().iter().any(|event| matches!(
341            event,
342            ResponseStreamEvent::OutputTextDelta { delta, .. } if delta == "hello"
343        )));
344        assert!(
345            integration
346                .events()
347                .iter()
348                .any(|event| matches!(event, ResponseStreamEvent::ResponseCompleted { .. }))
349        );
350    }
351
352    /// A callback that panics must not disable delivery of later events.
353    /// With `std::sync::Mutex` the panic poisons the lock and the old
354    /// `if let Ok(...)` branch silently dropped every subsequent event.
355    #[test]
356    fn callback_panic_does_not_silently_drop_later_events() {
357        use std::panic::{AssertUnwindSafe, catch_unwind};
358        use std::sync::atomic::{AtomicUsize, Ordering};
359
360        let delivered = Arc::new(AtomicUsize::new(0));
361        let seen = Arc::clone(&delivered);
362        let callback: OpenResponsesCallback = Arc::new(Mutex::new(Box::new(move |_event| {
363            if seen.fetch_add(1, Ordering::SeqCst) == 0 {
364                panic!("callback failed once");
365            }
366        })));
367
368        let config = OpenResponsesConfig {
369            enabled: true,
370            emit_events: true,
371            ..Default::default()
372        };
373        let mut integration = OpenResponsesIntegration::new(config);
374        integration.start_response("gpt-5");
375        integration.set_callback(callback);
376
377        let first = ResponseStreamEvent::ResponseCreated { response: Response::new("resp-1", "gpt-5") };
378        assert!(catch_unwind(AssertUnwindSafe(|| integration.emit_event(first))).is_err());
379
380        let second = ResponseStreamEvent::ResponseCreated { response: Response::new("resp-2", "gpt-5") };
381        integration.emit_event(second);
382        assert_eq!(delivered.load(Ordering::SeqCst), 2, "later events must survive an earlier callback panic");
383    }
384}