Skip to main content

vtcode_core/skills/
streaming.rs

1//! Skill Execution Streaming
2//!
3//! Provides streaming support for long-running skill executions,
4//! enabling real-time progress updates and partial results.
5
6use crate::skills::cli_bridge::{CliToolBridge, CliToolResult};
7use anyhow::{Result, anyhow};
8use async_stream::stream;
9use futures::{Stream, StreamExt};
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12use std::pin::Pin;
13use std::process::Stdio;
14use std::time::{Duration, Instant};
15use tokio::io::{AsyncReadExt, BufReader};
16use tokio::process::Command as TokioCommand;
17use tokio::time::{interval, timeout};
18use vtcode_commons::Utf8StreamDecoder;
19
20/// Streaming execution configuration
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct StreamingConfig {
23    /// Enable streaming output
24    pub enable_streaming: bool,
25
26    /// Buffer size for reading output
27    pub buffer_size: usize,
28
29    /// Update interval for progress reports
30    pub update_interval_ms: u64,
31
32    /// Maximum execution time
33    pub max_execution_time_secs: u64,
34
35    /// Enable partial JSON parsing
36    pub enable_partial_json: bool,
37
38    /// Enable progress reporting
39    pub enable_progress_reporting: bool,
40
41    /// Include stderr in stream
42    pub include_stderr: bool,
43
44    /// Split output by lines
45    pub line_based_streaming: bool,
46}
47
48impl Default for StreamingConfig {
49    fn default() -> Self {
50        Self {
51            enable_streaming: true,
52            buffer_size: 8192,
53            update_interval_ms: 100,
54            max_execution_time_secs: 300, // 5 minutes
55            enable_partial_json: true,
56            enable_progress_reporting: true,
57            include_stderr: true,
58            line_based_streaming: true,
59        }
60    }
61}
62
63/// Streaming execution event
64#[derive(Debug, Clone, Serialize, Deserialize)]
65pub enum StreamEvent {
66    /// Progress update
67    Progress {
68        /// Progress percentage (0-100)
69        percentage: f32,
70        /// Status message
71        message: String,
72        /// Elapsed time
73        elapsed_ms: u64,
74        /// Estimated remaining time
75        estimated_remaining_ms: Option<u64>,
76    },
77    /// Output chunk
78    Output {
79        /// Output data
80        data: String,
81        /// Output type (stdout/stderr)
82        output_type: OutputType,
83        /// Whether this is partial output
84        is_partial: bool,
85    },
86    /// JSON object detected
87    JsonObject {
88        /// Parsed JSON value
89        value: Value,
90        /// Raw JSON string
91        raw: String,
92    },
93    /// Execution completed
94    Completed {
95        /// Final exit code
96        exit_code: i32,
97        /// Total execution time
98        total_time_ms: u64,
99        /// Final result
100        result: Option<CliToolResult>,
101    },
102    /// Error occurred
103    Error {
104        /// Error message
105        message: String,
106        /// Whether execution should continue
107        fatal: bool,
108    },
109    /// Execution started
110    Started {
111        /// Command being executed
112        command: String,
113        /// Arguments
114        args: Vec<String>,
115        /// Start time
116        start_time: chrono::DateTime<chrono::Utc>,
117    },
118}
119
120/// Output type
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub enum OutputType {
123    Stdout,
124    Stderr,
125}
126
127/// Streaming skill executor
128pub struct StreamingSkillExecutor {
129    config: StreamingConfig,
130}
131
132impl StreamingSkillExecutor {
133    /// Create new streaming executor with default configuration
134    pub fn new() -> Self {
135        Self::with_config(StreamingConfig::default())
136    }
137
138    /// Create new streaming executor with custom configuration
139    pub fn with_config(config: StreamingConfig) -> Self {
140        Self { config }
141    }
142}
143
144impl Default for StreamingSkillExecutor {
145    fn default() -> Self {
146        Self::new()
147    }
148}
149
150impl StreamingSkillExecutor {
151    /// Execute CLI tool with streaming output
152    pub fn execute_cli_tool_streaming(
153        &self,
154        bridge: &CliToolBridge,
155        args: Value,
156    ) -> Pin<Box<dyn Stream<Item = Result<StreamEvent>> + Send>> {
157        let config = self.config.clone();
158        let bridge = bridge.clone();
159        let args = args.clone();
160
161        Box::pin(stream! {
162            let start_time = Instant::now();
163            let start_datetime = chrono::Utc::now();
164
165            // Build command
166            let mut cmd = TokioCommand::new(&bridge.config.executable_path);
167
168            // Set working directory
169            if let Some(working_dir) = &bridge.config.working_dir {
170                cmd.current_dir(working_dir);
171            }
172
173            // Set environment variables
174            if let Some(env) = &bridge.config.environment {
175                for (key, value) in env {
176                    cmd.env(key, value);
177                }
178            }
179
180            // Configure I/O for streaming
181            cmd.stdin(Stdio::null())
182                .stdout(Stdio::piped())
183                .stderr(Stdio::piped())
184                .kill_on_drop(true);
185
186            // Add arguments
187            if let Err(e) = Self::configure_arguments(&mut cmd, &args) {
188                yield Err(anyhow!("Failed to configure arguments: {e}"));
189                return;
190            }
191
192            // Get command string for logging
193            let _command_str = format!("{cmd:?}");
194            let args: Vec<String> = cmd.as_std().get_args()
195                .map(|arg| arg.to_string_lossy().to_string())
196                .collect();
197
198            // Emit started event
199            yield Ok(StreamEvent::Started {
200                command: bridge.config.executable_path.display().to_string(),
201                args,
202                start_time: start_datetime,
203            });
204
205            // Start the process
206            let mut child = match cmd.spawn() {
207                Ok(child) => child,
208                Err(e) => {
209                    yield Err(anyhow!("Failed to spawn process: {e}"));
210                    return;
211                }
212            };
213
214            let stdout = match child.stdout.take() {
215                Some(stdout) => stdout,
216                None => {
217                    yield Err(anyhow!("Failed to capture stdout"));
218                    return;
219                }
220            };
221
222            let stderr = if config.include_stderr {
223                child.stderr.take()
224            } else {
225                None
226            };
227
228            // Create progress tracking
229            let progress_tracker = ProgressTracker::new();
230            let mut progress_interval = interval(Duration::from_millis(config.update_interval_ms));
231
232            // Stream stdout
233            let stdout_stream = Self::stream_output(
234                stdout,
235                OutputType::Stdout,
236                config.clone(),
237                progress_tracker.clone(),
238            );
239
240            // Stream stderr if enabled
241            let stderr_stream = stderr.map(|s| {
242                Self::stream_output(
243                    s,
244                    OutputType::Stderr,
245                    config.clone(),
246                    progress_tracker.clone(),
247                )
248            });
249
250            // Combine streams
251            let mut stdout_stream = Box::pin(stdout_stream);
252            let mut stderr_stream = stderr_stream.map(Box::pin);
253
254            // Stream events
255            let mut output_buffer = String::new();
256            let mut json_buffer = String::new();
257            let _is_parsing_json = false;
258
259            loop {
260                tokio::select! {
261                    // Progress updates
262                    _ = progress_interval.tick() => {
263                        let progress = progress_tracker.get_progress();
264                        yield Ok(StreamEvent::Progress {
265                            percentage: progress.percentage,
266                            message: progress.message.clone(),
267                            elapsed_ms: start_time.elapsed().as_millis() as u64,
268                            estimated_remaining_ms: progress.estimated_remaining_ms,
269                        });
270                    }
271
272                    // Stdout events
273                    Some(event) = stdout_stream.next() => {
274                        match event {
275                            Ok(StreamEvent::Output { data, output_type, is_partial }) => {
276                                output_buffer.push_str(&data);
277
278                                // Try to detect JSON objects
279                                if let Some(json_events) = Self::extract_json_objects(&mut json_buffer, &data).filter(|_| config.enable_partial_json) {
280                                        for json_event in json_events {
281                                            yield Ok(json_event);
282                                        }
283                                    }
284
285                                yield Ok(StreamEvent::Output {
286                                    data,
287                                    output_type,
288                                    is_partial,
289                                });
290                            }
291                            Ok(event) => yield Ok(event),
292                            Err(e) => {
293                                yield Err(anyhow!("Stdout stream error: {e}"));
294                                break;
295                            }
296                        }
297                    }
298
299                    // Stderr events
300                    Some(event_result) = async {
301                        match &mut stderr_stream {
302                            Some(stream) => stream.next().await,
303                            None => None,
304                        }
305                    } => {
306                        match event_result {
307                            Ok(StreamEvent::Output { data, output_type, is_partial }) => {
308                                yield Ok(StreamEvent::Output {
309                                    data,
310                                    output_type,
311                                    is_partial,
312                                });
313                            }
314                            Ok(event) => yield Ok(event),
315                            Err(e) => {
316                                yield Err(anyhow!("Stderr stream error: {e}"));
317                            }
318                        }
319                    }
320
321                    // Process completion
322                    else => {
323                        break;
324                    }
325                }
326
327                // Check timeout
328                if start_time.elapsed().as_secs() > config.max_execution_time_secs {
329                    let _ = child.kill().await;
330                    yield Err(anyhow!("Execution timed out after {} seconds", config.max_execution_time_secs));
331                    return;
332                }
333            }
334
335            // Wait for process completion
336            let exit_status = match timeout(
337                Duration::from_secs(config.max_execution_time_secs),
338                child.wait()
339            ).await {
340                Ok(Ok(status)) => status,
341                Ok(Err(e)) => {
342                    yield Err(anyhow!("Failed to wait for process: {e}"));
343                    return;
344                }
345                Err(_) => {
346                    yield Err(anyhow!("Process wait timed out"));
347                    return;
348                }
349            };
350
351            let exit_code = exit_status.code().unwrap_or(-1);
352            let total_time_ms = start_time.elapsed().as_millis() as u64;
353
354            // Create final result
355            let result = CliToolResult {
356                exit_code,
357                stdout: output_buffer.clone(),
358                stderr: String::new(), // Would need to capture stderr separately
359                json_output: None,
360                execution_time_ms: total_time_ms,
361            };
362
363            yield Ok(StreamEvent::Completed {
364                exit_code,
365                total_time_ms,
366                result: Some(result),
367            });
368        })
369    }
370
371    /// Stream output from a reader
372    fn stream_output<R>(
373        reader: R,
374        output_type: OutputType,
375        config: StreamingConfig,
376        mut progress_tracker: ProgressTracker,
377    ) -> Pin<Box<dyn Stream<Item = Result<StreamEvent>> + Send>>
378    where
379        R: AsyncReadExt + Send + Unpin + 'static,
380    {
381        Box::pin(stream! {
382            let mut reader = BufReader::new(reader);
383            let mut buffer = vec![0u8; config.buffer_size];
384            let mut line_buffer = String::new();
385            // Reads can split a multibyte character; decode across boundaries.
386            let mut decoder = Utf8StreamDecoder::new();
387
388            loop {
389                match reader.read(&mut buffer).await {
390                    Ok(0) => {
391                        // EOF reached: a truncated final sequence becomes one U+FFFD.
392                        let tail = decoder.finish();
393                        if config.line_based_streaming {
394                            line_buffer.push_str(&tail);
395                        } else if !tail.is_empty() {
396                            progress_tracker.update_with_output(&tail);
397                            yield Ok(StreamEvent::Output {
398                                data: tail,
399                                output_type: output_type.clone(),
400                                is_partial: true,
401                            });
402                        }
403                        if !line_buffer.is_empty() && config.line_based_streaming {
404                            progress_tracker.update_with_output(&line_buffer);
405                            yield Ok(StreamEvent::Output {
406                                data: line_buffer.clone(),
407                                output_type: output_type.clone(),
408                                is_partial: false,
409                            });
410                        }
411                        break;
412                    }
413                    Ok(n) => {
414                        let data = decoder.push(buffer.get(..n).unwrap_or_default());
415
416                        if config.line_based_streaming {
417                            line_buffer.push_str(&data);
418
419                            // Process complete lines
420                            while let Some(line_end) = line_buffer.find('\n') {
421                                let line = line_buffer[..line_end + 1].to_string();
422                                line_buffer.drain(..line_end + 1);
423
424                                progress_tracker.update_with_output(&line);
425                                yield Ok(StreamEvent::Output {
426                                    data: line,
427                                    output_type: output_type.clone(),
428                                    is_partial: false,
429                                });
430                            }
431                        } else {
432                            // Stream raw data
433                            progress_tracker.update_with_output(&data);
434                            yield Ok(StreamEvent::Output {
435                                data: data.to_string(),
436                                output_type: output_type.clone(),
437                                is_partial: true,
438                            });
439                        }
440                    }
441                    Err(e) => {
442                        yield Err(anyhow!("Read error: {e}"));
443                        break;
444                    }
445                }
446            }
447        })
448    }
449
450    /// Extract JSON objects from output
451    fn extract_json_objects(json_buffer: &mut String, new_data: &str) -> Option<Vec<StreamEvent>> {
452        json_buffer.push_str(new_data);
453
454        let mut events = vec![];
455
456        // Try to find complete JSON objects
457        while let Some(brace_start) = json_buffer.find('{') {
458            let mut brace_count = 0;
459            let mut end_pos = None;
460
461            // `char_indices` yields byte offsets, matching the byte-based
462            // slicing/draining below. `chars().enumerate()` would yield char
463            // indices, so any multi-byte character before the closing brace
464            // would mis-slice (`brace_start + i + 1` past a non-ASCII char) or
465            // silently drop the object.
466            for (i, ch) in json_buffer[brace_start..].char_indices() {
467                match ch {
468                    '{' => brace_count += 1,
469                    '}' => {
470                        brace_count -= 1;
471                        if brace_count == 0 {
472                            end_pos = Some(brace_start + i + 1);
473                            break;
474                        }
475                    }
476                    _ => {}
477                }
478            }
479
480            if let Some(end) = end_pos {
481                let json_str = &json_buffer[brace_start..end];
482
483                if let Ok(value) = serde_json::from_str::<Value>(json_str) {
484                    events.push(StreamEvent::JsonObject { value, raw: json_str.to_string() });
485
486                    // Remove processed JSON from buffer
487                    json_buffer.drain(..end);
488                } else {
489                    // Invalid JSON, skip this object
490                    json_buffer.drain(..brace_start + 1);
491                }
492            } else {
493                // Incomplete JSON, keep in buffer
494                break;
495            }
496        }
497
498        if events.is_empty() { None } else { Some(events) }
499    }
500
501    /// Configure command arguments from JSON
502    fn configure_arguments(cmd: &mut TokioCommand, args: &Value) -> Result<()> {
503        if args.is_null() {
504            return Ok(());
505        }
506
507        match args {
508            Value::String(s) => {
509                cmd.arg(s);
510            }
511            Value::Array(arr) => {
512                for arg in arr {
513                    if let Some(s) = arg.as_str() {
514                        cmd.arg(s);
515                    }
516                }
517            }
518            Value::Object(map) => {
519                for (key, value) in map {
520                    if let Some(s) = value.as_str() {
521                        cmd.arg(format!("--{key}"));
522                        cmd.arg(s);
523                    } else if value.as_bool().is_some_and(|flag| flag) {
524                        cmd.arg(format!("--{key}"));
525                    }
526                }
527            }
528            _ => {
529                let json_str = serde_json::to_string(args)?;
530                cmd.arg(json_str);
531            }
532        }
533
534        Ok(())
535    }
536}
537
538/// Progress tracking for streaming execution
539#[derive(Debug, Clone)]
540pub struct ProgressTracker {
541    start_time: Instant,
542    total_output_bytes: usize,
543    last_output_time: Instant,
544    estimated_total_bytes: Option<usize>,
545}
546
547impl Default for ProgressTracker {
548    fn default() -> Self {
549        Self::new()
550    }
551}
552
553impl ProgressTracker {
554    /// Create new progress tracker
555    pub fn new() -> Self {
556        Self {
557            start_time: Instant::now(),
558            total_output_bytes: 0,
559            last_output_time: Instant::now(),
560            estimated_total_bytes: None,
561        }
562    }
563
564    /// Update with new output
565    pub fn update_with_output(&mut self, output: &str) {
566        self.total_output_bytes += output.len();
567        self.last_output_time = Instant::now();
568
569        // Simple heuristic: estimate total based on output rate
570        if self.estimated_total_bytes.is_none() && self.start_time.elapsed().as_secs() > 5 {
571            let elapsed_secs = self.start_time.elapsed().as_secs().max(1);
572            let bytes_per_second = self.total_output_bytes / elapsed_secs as usize;
573
574            // Estimate 2-5 minutes of output at current rate
575            self.estimated_total_bytes = Some(bytes_per_second * 180); // 3 minutes
576        }
577    }
578
579    /// Get current progress
580    pub fn get_progress(&self) -> ProgressInfo {
581        let elapsed_ms = self.start_time.elapsed().as_millis() as u64;
582        let percentage = if let Some(estimated) = self.estimated_total_bytes {
583            if estimated > 0 {
584                ((self.total_output_bytes as f32 / estimated as f32) * 100.0).min(95.0)
585            } else {
586                0.0
587            }
588        } else {
589            // Time-based progress if no size estimate
590            let estimated_total_ms = 300_000; // 5 minutes
591            ((elapsed_ms as f32 / estimated_total_ms as f32) * 100.0).min(95.0)
592        };
593
594        let estimated_remaining_ms = if let Some(estimated) = self.estimated_total_bytes {
595            if self.total_output_bytes > 0 {
596                let bytes_remaining = estimated.saturating_sub(self.total_output_bytes);
597                let bytes_per_ms = self.total_output_bytes as f32 / elapsed_ms as f32;
598                #[allow(
599                    clippy::cast_sign_loss,
600                    reason = "Intentional compatibility, platform, or test-only suppression."
601                )]
602                let remaining_ms = ((bytes_remaining as f32 / bytes_per_ms).max(0.0)) as u64;
603                Some(remaining_ms)
604            } else {
605                None
606            }
607        } else {
608            None
609        };
610
611        let message = if percentage < 10.0 {
612            "Starting execution...".to_string()
613        } else if percentage < 50.0 {
614            "Processing...".to_string()
615        } else if percentage < 90.0 {
616            "Almost complete...".to_string()
617        } else {
618            "Finalizing...".to_string()
619        };
620
621        ProgressInfo {
622            percentage,
623            message,
624            elapsed_ms,
625            estimated_remaining_ms,
626        }
627    }
628}
629
630/// Progress information
631#[derive(Debug, Clone)]
632pub struct ProgressInfo {
633    /// Progress percentage (0-100)
634    pub percentage: f32,
635
636    /// Status message
637    pub message: String,
638
639    /// Elapsed time in milliseconds
640    pub elapsed_ms: u64,
641
642    /// Estimated remaining time
643    pub estimated_remaining_ms: Option<u64>,
644}
645
646/// Extension trait for streaming execution
647pub trait StreamingExecution {
648    /// Execute with streaming output
649    fn execute_streaming(&self, args: Value) -> Pin<Box<dyn Stream<Item = Result<StreamEvent>> + Send>>;
650}
651
652impl StreamingExecution for CliToolBridge {
653    fn execute_streaming(&self, args: Value) -> Pin<Box<dyn Stream<Item = Result<StreamEvent>> + Send>> {
654        let executor = StreamingSkillExecutor::new();
655        executor.execute_cli_tool_streaming(self, args)
656    }
657}
658
659#[cfg(test)]
660mod tests {
661    use super::*;
662
663    #[test]
664    fn test_streaming_config_default() {
665        let config = StreamingConfig::default();
666        assert!(config.enable_streaming);
667        assert_eq!(config.buffer_size, 8192);
668        assert_eq!(config.max_execution_time_secs, 300);
669    }
670
671    #[test]
672    fn test_progress_tracker() {
673        let mut tracker = ProgressTracker::new();
674
675        // Initial progress
676        let progress = tracker.get_progress();
677        assert!(progress.percentage >= 0.0 && progress.percentage <= 100.0);
678
679        // Update with output
680        tracker.update_with_output("test output");
681        let progress = tracker.get_progress();
682        // Verify message was updated
683        assert!(!progress.message.is_empty() || progress.percentage > 0.0);
684    }
685
686    #[tokio::test]
687    async fn test_json_extraction() {
688        let mut buffer = String::new();
689        let data = r#"{"key": "value"} some text {"another": "object"}"#;
690
691        let events = StreamingSkillExecutor::extract_json_objects(&mut buffer, data);
692        assert!(events.is_some());
693
694        let events = events.unwrap();
695        assert_eq!(events.len(), 2);
696
697        match &events[0] {
698            StreamEvent::JsonObject { value, .. } => {
699                assert_eq!(value["key"], "value");
700            }
701            _ => panic!("Expected JsonObject event"),
702        }
703    }
704
705    #[test]
706    fn test_json_extraction_with_multibyte_chars() {
707        // A multi-byte character before the closing brace must not shift the
708        // byte offset used to slice the object. Regression for mixing
709        // `chars().enumerate()` (char index) with byte-based slicing.
710        let mut buffer = String::new();
711        let data = r#"{"key": "café"} trailing {"emoji": "🚀"}"#;
712
713        let events = StreamingSkillExecutor::extract_json_objects(&mut buffer, data)
714            .expect("both JSON objects should be extracted");
715
716        assert_eq!(events.len(), 2);
717        match &events[0] {
718            StreamEvent::JsonObject { value, .. } => assert_eq!(value["key"], "café"),
719            _ => panic!("Expected JsonObject event"),
720        }
721        match &events[1] {
722            StreamEvent::JsonObject { value, .. } => assert_eq!(value["emoji"], "🚀"),
723            _ => panic!("Expected JsonObject event"),
724        }
725    }
726
727    async fn streamed_text(input: &'static [u8], line_based_streaming: bool) -> String {
728        let config = StreamingConfig {
729            buffer_size: 2,
730            line_based_streaming,
731            ..StreamingConfig::default()
732        };
733        let events: Vec<_> =
734            StreamingSkillExecutor::stream_output(input, OutputType::Stdout, config, ProgressTracker::new())
735                .collect()
736                .await;
737        events
738            .into_iter()
739            .filter_map(|event| match event {
740                Ok(StreamEvent::Output { data, .. }) => Some(data),
741                _ => None,
742            })
743            .collect()
744    }
745
746    #[tokio::test]
747    async fn multibyte_output_survives_read_boundaries() {
748        let text = "xin chào 世界\n";
749        for line_based in [true, false] {
750            assert_eq!(streamed_text(text.as_bytes(), line_based).await, text, "line_based={line_based}");
751        }
752    }
753
754    #[tokio::test]
755    async fn truncated_final_sequence_becomes_one_replacement_character() {
756        // `—` is 0xE2 0x80 0x94; the stream ends after its first two bytes.
757        for line_based in [true, false] {
758            assert_eq!(streamed_text(b"ok\n\xE2\x80", line_based).await, "ok\n\u{FFFD}", "line_based={line_based}");
759        }
760    }
761}