Skip to main content

vtcode_llm/open_responses/
events.rs

1//! Semantic streaming events for Open Responses.
2//!
3//! Streaming is modeled as a series of semantic events, not raw text deltas.
4//! Events describe meaningful transitions like state changes or content deltas.
5
6use std::sync::Arc;
7
8use parking_lot::Mutex;
9use serde::{Deserialize, Serialize};
10
11use super::{ContentPart, OutputItem, Response, ResponseId};
12
13/// Semantic streaming events per the Open Responses specification.
14///
15/// These events describe meaningful transitions during response generation,
16/// enabling predictable, provider-agnostic streaming clients.
17#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
18#[serde(tag = "type")]
19pub enum ResponseStreamEvent {
20    // ============================================================
21    // Response lifecycle events
22    // ============================================================
23    /// Initial response creation event.
24    #[serde(rename = "response.created")]
25    ResponseCreated {
26        /// The response object with initial state.
27        response: Response,
28    },
29
30    /// Response has started processing.
31    #[serde(rename = "response.in_progress")]
32    ResponseInProgress {
33        /// The response object.
34        response: Response,
35    },
36
37    /// Response completed successfully.
38    #[serde(rename = "response.completed")]
39    ResponseCompleted {
40        /// The final response object.
41        response: Response,
42    },
43
44    /// Response failed with an error.
45    #[serde(rename = "response.failed")]
46    ResponseFailed {
47        /// The response object with error details.
48        response: Response,
49    },
50
51    /// Response is incomplete (e.g., token limit reached).
52    #[serde(rename = "response.incomplete")]
53    ResponseIncomplete {
54        /// The response object with incomplete details.
55        response: Response,
56    },
57
58    // ============================================================
59    // Output item events
60    // ============================================================
61    /// New output item added to the response.
62    #[serde(rename = "response.output_item.added")]
63    OutputItemAdded {
64        /// ID of the containing response.
65        response_id: ResponseId,
66        /// Index of the item in the output array.
67        output_index: usize,
68        /// The output item being added.
69        item: OutputItem,
70    },
71
72    /// Output item is complete.
73    #[serde(rename = "response.output_item.done")]
74    OutputItemDone {
75        /// ID of the containing response.
76        response_id: ResponseId,
77        /// Index of the item in the output array.
78        output_index: usize,
79        /// The completed output item.
80        item: OutputItem,
81    },
82
83    // ============================================================
84    // Content part events
85    // ============================================================
86    /// New content part added to an output item.
87    #[serde(rename = "response.content_part.added")]
88    ContentPartAdded {
89        /// ID of the containing response.
90        response_id: ResponseId,
91        /// ID of the containing output item.
92        item_id: String,
93        /// Index of the item in the output array.
94        output_index: usize,
95        /// Index of the content part within the item.
96        content_index: usize,
97        /// The content part being added.
98        part: ContentPart,
99    },
100
101    /// Content part is complete.
102    #[serde(rename = "response.content_part.done")]
103    ContentPartDone {
104        /// ID of the containing response.
105        response_id: ResponseId,
106        /// ID of the containing output item.
107        item_id: String,
108        /// Index of the item in the output array.
109        output_index: usize,
110        /// Index of the content part within the item.
111        content_index: usize,
112        /// The completed content part.
113        part: ContentPart,
114    },
115
116    // ============================================================
117    // Text streaming events
118    // ============================================================
119    /// Text content delta for incremental streaming.
120    #[serde(rename = "response.output_text.delta")]
121    OutputTextDelta {
122        /// ID of the containing response.
123        response_id: ResponseId,
124        /// ID of the containing output item.
125        item_id: String,
126        /// Index of the item in the output array.
127        output_index: usize,
128        /// Index of the content part within the item.
129        content_index: usize,
130        /// The text delta to append.
131        delta: String,
132    },
133
134    /// Text content is complete.
135    #[serde(rename = "response.output_text.done")]
136    OutputTextDone {
137        /// ID of the containing response.
138        response_id: ResponseId,
139        /// ID of the containing output item.
140        item_id: String,
141        /// Index of the item in the output array.
142        output_index: usize,
143        /// Index of the content part within the item.
144        content_index: usize,
145        /// The complete text content.
146        text: String,
147    },
148
149    // ============================================================
150    // Function call streaming events
151    // ============================================================
152    /// Function call arguments delta.
153    #[serde(rename = "response.function_call_arguments.delta")]
154    FunctionCallArgumentsDelta {
155        /// ID of the containing response.
156        response_id: ResponseId,
157        /// ID of the function call item.
158        item_id: String,
159        /// Index of the item in the output array.
160        output_index: usize,
161        /// The arguments delta to append.
162        delta: String,
163    },
164
165    /// Function call arguments are complete.
166    #[serde(rename = "response.function_call_arguments.done")]
167    FunctionCallArgumentsDone {
168        /// ID of the containing response.
169        response_id: ResponseId,
170        /// ID of the function call item.
171        item_id: String,
172        /// Index of the item in the output array.
173        output_index: usize,
174        /// The complete arguments JSON string.
175        arguments: String,
176    },
177
178    // ============================================================
179    // Reasoning events
180    // ============================================================
181    /// Reasoning content delta.
182    #[serde(rename = "response.reasoning.delta")]
183    ReasoningDelta {
184        /// ID of the containing response.
185        response_id: ResponseId,
186        /// ID of the reasoning item.
187        item_id: String,
188        /// Index of the item in the output array.
189        output_index: usize,
190        /// The reasoning delta to append.
191        delta: String,
192    },
193
194    /// Reasoning content is complete.
195    #[serde(rename = "response.reasoning.done")]
196    ReasoningDone {
197        /// ID of the containing response.
198        response_id: ResponseId,
199        /// ID of the reasoning item.
200        item_id: String,
201        /// Index of the item in the output array.
202        output_index: usize,
203        /// The reasoning item with complete content.
204        item: OutputItem,
205    },
206
207    // ============================================================
208    // Extension events
209    // ============================================================
210    /// Custom/extension streaming event.
211    ///
212    /// Custom event types must be prefixed with the implementor slug
213    /// (e.g., `vtcode.trace_event`).
214    #[serde(rename = "response.custom_event")]
215    CustomEvent {
216        /// ID of the containing response.
217        response_id: ResponseId,
218        /// Custom event type (must be prefixed, e.g., `vtcode.telemetry`).
219        event_type: String,
220        /// Sequence number for ordering.
221        sequence_number: u64,
222        /// Custom event data.
223        data: serde_json::Value,
224    },
225    /// Catch-all for unknown streaming event types added by the Open Responses spec.
226    #[serde(other)]
227    Unknown,
228}
229
230impl ResponseStreamEvent {
231    /// Returns the response ID associated with this event.
232    #[must_use]
233    pub fn response_id(&self) -> Option<&ResponseId> {
234        match self {
235            Self::ResponseCreated { response, .. }
236            | Self::ResponseInProgress { response, .. }
237            | Self::ResponseCompleted { response, .. }
238            | Self::ResponseFailed { response, .. }
239            | Self::ResponseIncomplete { response, .. } => Some(&response.id),
240
241            Self::OutputItemAdded { response_id, .. }
242            | Self::OutputItemDone { response_id, .. }
243            | Self::ContentPartAdded { response_id, .. }
244            | Self::ContentPartDone { response_id, .. }
245            | Self::OutputTextDelta { response_id, .. }
246            | Self::OutputTextDone { response_id, .. }
247            | Self::FunctionCallArgumentsDelta { response_id, .. }
248            | Self::FunctionCallArgumentsDone { response_id, .. }
249            | Self::ReasoningDelta { response_id, .. }
250            | Self::ReasoningDone { response_id, .. }
251            | Self::CustomEvent { response_id, .. } => Some(response_id),
252            Self::Unknown => None,
253        }
254    }
255
256    /// Returns the event type name.
257    pub fn event_type(&self) -> &'static str {
258        match self {
259            Self::ResponseCreated { .. } => "response.created",
260            Self::ResponseInProgress { .. } => "response.in_progress",
261            Self::ResponseCompleted { .. } => "response.completed",
262            Self::ResponseFailed { .. } => "response.failed",
263            Self::ResponseIncomplete { .. } => "response.incomplete",
264            Self::OutputItemAdded { .. } => "response.output_item.added",
265            Self::OutputItemDone { .. } => "response.output_item.done",
266            Self::ContentPartAdded { .. } => "response.content_part.added",
267            Self::ContentPartDone { .. } => "response.content_part.done",
268            Self::OutputTextDelta { .. } => "response.output_text.delta",
269            Self::OutputTextDone { .. } => "response.output_text.done",
270            Self::FunctionCallArgumentsDelta { .. } => "response.function_call_arguments.delta",
271            Self::FunctionCallArgumentsDone { .. } => "response.function_call_arguments.done",
272            Self::ReasoningDelta { .. } => "response.reasoning.delta",
273            Self::ReasoningDone { .. } => "response.reasoning.done",
274            Self::CustomEvent { .. } => "response.custom_event",
275            Self::Unknown => "unknown",
276        }
277    }
278
279    /// Returns true if this is a response lifecycle event.
280    pub fn is_response_event(&self) -> bool {
281        matches!(
282            self,
283            Self::ResponseCreated { .. }
284                | Self::ResponseInProgress { .. }
285                | Self::ResponseCompleted { .. }
286                | Self::ResponseFailed { .. }
287                | Self::ResponseIncomplete { .. }
288        )
289    }
290
291    /// Returns true if this is a terminal event.
292    fn is_terminal(&self) -> bool {
293        matches!(self, Self::ResponseCompleted { .. } | Self::ResponseFailed { .. } | Self::ResponseIncomplete { .. })
294    }
295
296    /// Returns true if this is an unknown/unsupported event type.
297    pub fn is_unknown(&self) -> bool {
298        matches!(self, Self::Unknown)
299    }
300}
301
302/// Callback type for streaming events.
303#[expect(
304    dead_code,
305    reason = "Intentional compatibility, platform, test, or API-shape suppression."
306)]
307pub type StreamEventCallback = Arc<Mutex<Box<dyn FnMut(&ResponseStreamEvent) + Send>>>;
308
309/// Trait for emitting Open Responses streaming events.
310pub trait StreamEventEmitter: Send {
311    /// Emit a streaming event.
312    fn emit(&mut self, event: ResponseStreamEvent);
313
314    /// Emit a response created event.
315    fn response_created(&mut self, response: Response) {
316        self.emit(ResponseStreamEvent::ResponseCreated { response });
317    }
318
319    /// Emit a response in progress event.
320    fn response_in_progress(&mut self, response: Response) {
321        self.emit(ResponseStreamEvent::ResponseInProgress { response });
322    }
323
324    /// Emit a response completed event.
325    fn response_completed(&mut self, response: Response) {
326        self.emit(ResponseStreamEvent::ResponseCompleted { response });
327    }
328
329    /// Emit a response failed event.
330    fn response_failed(&mut self, response: Response) {
331        self.emit(ResponseStreamEvent::ResponseFailed { response });
332    }
333
334    /// Emit an output item added event.
335    fn output_item_added(&mut self, response_id: &ResponseId, output_index: usize, item: OutputItem) {
336        self.emit(ResponseStreamEvent::OutputItemAdded {
337            response_id: response_id.clone(),
338            output_index,
339            item,
340        });
341    }
342
343    /// Emit an output item done event.
344    fn output_item_done(&mut self, response_id: &ResponseId, output_index: usize, item: OutputItem) {
345        self.emit(ResponseStreamEvent::OutputItemDone {
346            response_id: response_id.clone(),
347            output_index,
348            item,
349        });
350    }
351
352    /// Emit a text delta event.
353    fn output_text_delta(
354        &mut self,
355        response_id: &ResponseId,
356        item_id: &str,
357        output_index: usize,
358        content_index: usize,
359        delta: &str,
360    ) {
361        self.emit(ResponseStreamEvent::OutputTextDelta {
362            response_id: response_id.clone(),
363            item_id: item_id.to_string(),
364            output_index,
365            content_index,
366            delta: delta.to_string(),
367        });
368    }
369
370    /// Emit a reasoning delta event.
371    fn reasoning_delta(&mut self, response_id: &ResponseId, item_id: &str, output_index: usize, delta: &str) {
372        self.emit(ResponseStreamEvent::ReasoningDelta {
373            response_id: response_id.clone(),
374            item_id: item_id.to_string(),
375            output_index,
376            delta: delta.to_string(),
377        });
378    }
379}
380
381/// Vector-based event emitter for collecting events.
382#[derive(Debug, Default)]
383pub struct VecStreamEmitter {
384    events: Vec<ResponseStreamEvent>,
385}
386
387impl VecStreamEmitter {
388    /// Creates a new vector emitter.
389    pub fn new() -> Self {
390        Self::default()
391    }
392
393    /// Returns the collected events.
394    fn events(&self) -> &[ResponseStreamEvent] {
395        &self.events
396    }
397
398    /// Consumes and returns the collected events.
399    pub fn into_events(self) -> Vec<ResponseStreamEvent> {
400        self.events
401    }
402}
403
404impl StreamEventEmitter for VecStreamEmitter {
405    fn emit(&mut self, event: ResponseStreamEvent) {
406        self.events.push(event);
407    }
408}
409
410/// Wrapper for streaming events with sequence number for ordering.
411/// Used when serializing events for SSE transport.
412#[derive(Debug, Clone, Serialize)]
413pub struct SequencedEvent<'a> {
414    /// Monotonically increasing sequence number within the stream.
415    sequence_number: u64,
416    /// The underlying event.
417    #[serde(flatten)]
418    event: &'a ResponseStreamEvent,
419}
420
421impl<'a> SequencedEvent<'a> {
422    /// Creates a new sequenced event.
423    pub fn new(sequence_number: u64, event: &'a ResponseStreamEvent) -> Self {
424        Self { sequence_number, event }
425    }
426}
427
428#[cfg(test)]
429mod tests {
430    use super::*;
431
432    #[test]
433    fn test_event_type() {
434        let response = Response::new("resp_1", "gpt-5");
435        let event = ResponseStreamEvent::ResponseCreated { response };
436        assert_eq!(event.event_type(), "response.created");
437    }
438
439    #[test]
440    fn test_terminal_events() {
441        let response = Response::new("resp_1", "gpt-5");
442        let created = ResponseStreamEvent::ResponseCreated { response: response.clone() };
443        let completed = ResponseStreamEvent::ResponseCompleted { response };
444        assert!(!created.is_terminal());
445        assert!(completed.is_terminal());
446    }
447
448    #[test]
449    fn test_vec_emitter() {
450        let mut emitter = VecStreamEmitter::new();
451        let response = Response::new("resp_1", "gpt-5");
452        emitter.response_created(response);
453        assert_eq!(emitter.events().len(), 1);
454    }
455}