Skip to main content

agent_commander/streaming/
output_stream.rs

1//! JSON Output Stream processor
2//! Processes NDJSON and pretty-printed JSON output from CLI tools
3
4use super::json_records::{JsonRecordEvent, JsonRecordScanner};
5use serde_json::Value;
6
7/// Error information for failed JSON parses
8#[derive(Debug, Clone)]
9pub struct ParseError {
10    pub line: String,
11    pub line_number: usize,
12}
13
14/// JSON Output Stream class
15/// Processes streaming output and emits parsed JSON messages
16pub struct JsonOutputStream {
17    buffer: String,
18    scanner: JsonRecordScanner,
19    messages: Vec<Value>,
20    errors: Vec<ParseError>,
21    line_count: usize,
22    on_message: Option<Box<dyn Fn(&Value, usize)>>,
23    on_error: Option<Box<dyn Fn(&ParseError)>>,
24    on_raw_line: Option<Box<dyn Fn(&str, usize)>>,
25}
26
27impl std::fmt::Debug for JsonOutputStream {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        f.debug_struct("JsonOutputStream")
30            .field("buffer", &self.buffer)
31            .field("messages", &self.messages)
32            .field("errors", &self.errors)
33            .field("line_count", &self.line_count)
34            .finish()
35    }
36}
37
38impl Default for JsonOutputStream {
39    fn default() -> Self {
40        Self::new()
41    }
42}
43
44impl JsonOutputStream {
45    /// Create a new JSON output stream processor
46    pub fn new() -> Self {
47        Self {
48            buffer: String::new(),
49            scanner: JsonRecordScanner::new(),
50            messages: Vec::new(),
51            errors: Vec::new(),
52            line_count: 0,
53            on_message: None,
54            on_error: None,
55            on_raw_line: None,
56        }
57    }
58
59    /// Set callback for each parsed message
60    pub fn set_on_message<F>(&mut self, callback: F)
61    where
62        F: Fn(&Value, usize) + 'static,
63    {
64        self.on_message = Some(Box::new(callback));
65    }
66
67    /// Set callback for parse errors
68    pub fn set_on_error<F>(&mut self, callback: F)
69    where
70        F: Fn(&ParseError) + 'static,
71    {
72        self.on_error = Some(Box::new(callback));
73    }
74
75    /// Set callback for each raw line
76    pub fn set_on_raw_line<F>(&mut self, callback: F)
77    where
78        F: Fn(&str, usize) + 'static,
79    {
80        self.on_raw_line = Some(Box::new(callback));
81    }
82
83    /// Process a chunk of output data
84    ///
85    /// Complete lines are fed to a balanced JSON record scanner, so
86    /// pretty-printed records that span several lines are still emitted.
87    ///
88    /// # Arguments
89    /// * `chunk` - Data chunk to process
90    ///
91    /// # Returns
92    /// Vector of messages parsed from this chunk
93    pub fn process(&mut self, chunk: &str) -> Vec<Value> {
94        self.buffer.push_str(chunk);
95
96        // Keep the last incomplete line in the buffer
97        let Some(last_newline) = self.buffer.rfind('\n') else {
98            return Vec::new();
99        };
100        let rest = self.buffer.split_off(last_newline + 1);
101        let complete = std::mem::replace(&mut self.buffer, rest);
102
103        self.scan(&complete, false)
104    }
105
106    /// Flush any remaining data in the buffer
107    ///
108    /// # Returns
109    /// Vector of messages from flushed buffer
110    pub fn flush(&mut self) -> Vec<Value> {
111        let remaining = std::mem::take(&mut self.buffer);
112        self.scan(&remaining, true)
113    }
114
115    fn scan(&mut self, text: &str, last: bool) -> Vec<Value> {
116        let lines = if last {
117            text.split('\n').collect::<Vec<_>>()
118        } else {
119            text.split_terminator('\n').collect()
120        };
121        for line in lines {
122            if last && line.trim().is_empty() {
123                continue;
124            }
125            self.line_count += 1;
126            if let Some(ref callback) = self.on_raw_line {
127                callback(line, self.line_count);
128            }
129        }
130
131        let mut events = self.scanner.write(text);
132        if last {
133            events.extend(self.scanner.flush());
134        }
135
136        let mut new_messages = Vec::new();
137        for event in events {
138            match event {
139                JsonRecordEvent::Json { value, .. } => {
140                    self.messages.push(value.clone());
141                    if let Some(ref callback) = self.on_message {
142                        callback(&value, self.line_count);
143                    }
144                    new_messages.push(value);
145                }
146                JsonRecordEvent::Invalid(line) => {
147                    // Text that looked like JSON but failed to parse
148                    let error = ParseError {
149                        line,
150                        line_number: self.line_count,
151                    };
152                    if let Some(ref callback) = self.on_error {
153                        callback(&error);
154                    }
155                    self.errors.push(error);
156                }
157                JsonRecordEvent::Text(_) => {}
158            }
159        }
160
161        new_messages
162    }
163
164    /// Get all collected messages
165    pub fn get_messages(&self) -> &[Value] {
166        &self.messages
167    }
168
169    /// Get all parse errors
170    pub fn get_errors(&self) -> &[ParseError] {
171        &self.errors
172    }
173
174    /// Reset the stream processor
175    pub fn reset(&mut self) {
176        self.buffer.clear();
177        self.scanner = JsonRecordScanner::new();
178        self.messages.clear();
179        self.errors.clear();
180        self.line_count = 0;
181    }
182
183    /// Filter messages by type
184    ///
185    /// # Arguments
186    /// * `msg_type` - Message type to filter
187    pub fn filter_by_type(&self, msg_type: &str) -> Vec<&Value> {
188        self.messages
189            .iter()
190            .filter(|msg| msg.get("type").and_then(|t| t.as_str()) == Some(msg_type))
191            .collect()
192    }
193
194    /// Find first message matching a predicate
195    ///
196    /// # Arguments
197    /// * `predicate` - Filter function
198    pub fn find<F>(&self, predicate: F) -> Option<&Value>
199    where
200        F: Fn(&Value) -> bool,
201    {
202        self.messages.iter().find(|msg| predicate(msg))
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209    use serde_json::json;
210
211    #[test]
212    fn test_process_single_json_line() {
213        let mut stream = JsonOutputStream::new();
214        let messages = stream.process("{\"type\":\"hello\"}\n");
215
216        assert_eq!(messages.len(), 1);
217        assert_eq!(messages[0], json!({"type": "hello"}));
218    }
219
220    #[test]
221    fn test_process_multiple_json_lines() {
222        let mut stream = JsonOutputStream::new();
223        let messages = stream.process("{\"a\":1}\n{\"b\":2}\n");
224
225        assert_eq!(messages.len(), 2);
226        assert_eq!(messages[0], json!({"a": 1}));
227        assert_eq!(messages[1], json!({"b": 2}));
228    }
229
230    #[test]
231    fn test_handles_partial_lines_across_chunks() {
232        let mut stream = JsonOutputStream::new();
233
234        // First chunk: partial line
235        let messages1 = stream.process("{\"type\":\"mes");
236        assert_eq!(messages1.len(), 0);
237
238        // Second chunk: completes line
239        let messages2 = stream.process("sage\"}\n");
240        assert_eq!(messages2.len(), 1);
241        assert_eq!(messages2[0], json!({"type": "message"}));
242    }
243
244    #[test]
245    fn test_get_messages_returns_all() {
246        let mut stream = JsonOutputStream::new();
247        stream.process("{\"a\":1}\n");
248        stream.process("{\"b\":2}\n");
249
250        let messages = stream.get_messages();
251        assert_eq!(messages.len(), 2);
252    }
253
254    #[test]
255    fn test_flush_processes_remaining_buffer() {
256        let mut stream = JsonOutputStream::new();
257        stream.process("{\"type\":\"final\"}"); // No trailing newline
258
259        // Buffer should have content
260        assert_eq!(stream.get_messages().len(), 0);
261
262        // Flush should process remaining
263        let flushed = stream.flush();
264        assert_eq!(flushed.len(), 1);
265        assert_eq!(flushed[0], json!({"type": "final"}));
266    }
267
268    #[test]
269    fn test_filter_by_type() {
270        let mut stream = JsonOutputStream::new();
271        stream.process("{\"type\":\"a\"}\n{\"type\":\"b\"}\n{\"type\":\"a\"}\n");
272
273        let filtered = stream.filter_by_type("a");
274        assert_eq!(filtered.len(), 2);
275    }
276
277    #[test]
278    fn test_reset_clears_state() {
279        let mut stream = JsonOutputStream::new();
280        stream.process("{\"a\":1}\n");
281        stream.reset();
282
283        assert_eq!(stream.get_messages().len(), 0);
284    }
285}