agent_commander/streaming/
output_stream.rs1use super::ndjson::parse_ndjson_line;
5use serde_json::Value;
6
7#[derive(Debug, Clone)]
9pub struct ParseError {
10 pub line: String,
11 pub line_number: usize,
12}
13
14pub struct JsonOutputStream {
17 buffer: String,
18 messages: Vec<Value>,
19 errors: Vec<ParseError>,
20 line_count: usize,
21 on_message: Option<Box<dyn Fn(&Value, usize)>>,
22 on_error: Option<Box<dyn Fn(&ParseError)>>,
23 on_raw_line: Option<Box<dyn Fn(&str, usize)>>,
24}
25
26impl std::fmt::Debug for JsonOutputStream {
27 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28 f.debug_struct("JsonOutputStream")
29 .field("buffer", &self.buffer)
30 .field("messages", &self.messages)
31 .field("errors", &self.errors)
32 .field("line_count", &self.line_count)
33 .finish()
34 }
35}
36
37impl Default for JsonOutputStream {
38 fn default() -> Self {
39 Self::new()
40 }
41}
42
43impl JsonOutputStream {
44 pub fn new() -> Self {
46 Self {
47 buffer: String::new(),
48 messages: Vec::new(),
49 errors: Vec::new(),
50 line_count: 0,
51 on_message: None,
52 on_error: None,
53 on_raw_line: None,
54 }
55 }
56
57 pub fn set_on_message<F>(&mut self, callback: F)
59 where
60 F: Fn(&Value, usize) + 'static,
61 {
62 self.on_message = Some(Box::new(callback));
63 }
64
65 pub fn set_on_error<F>(&mut self, callback: F)
67 where
68 F: Fn(&ParseError) + 'static,
69 {
70 self.on_error = Some(Box::new(callback));
71 }
72
73 pub fn set_on_raw_line<F>(&mut self, callback: F)
75 where
76 F: Fn(&str, usize) + 'static,
77 {
78 self.on_raw_line = Some(Box::new(callback));
79 }
80
81 pub fn process(&mut self, chunk: &str) -> Vec<Value> {
89 self.buffer.push_str(chunk);
90
91 let lines: Vec<String> = self.buffer.split('\n').map(|s| s.to_string()).collect();
93 let (complete_lines, last) = lines.split_at(lines.len().saturating_sub(1));
94
95 self.buffer = last.first().cloned().unwrap_or_default();
97
98 let mut new_messages = Vec::new();
99
100 for line in complete_lines {
101 self.line_count += 1;
102
103 if let Some(ref callback) = self.on_raw_line {
104 callback(line, self.line_count);
105 }
106
107 if let Some(parsed) = parse_ndjson_line(line) {
108 self.messages.push(parsed.clone());
109 new_messages.push(parsed.clone());
110
111 if let Some(ref callback) = self.on_message {
112 callback(&parsed, self.line_count);
113 }
114 } else if line.trim().starts_with('{') {
115 let error = ParseError {
117 line: line.to_string(),
118 line_number: self.line_count,
119 };
120 self.errors.push(error.clone());
121
122 if let Some(ref callback) = self.on_error {
123 callback(&error);
124 }
125 }
126 }
127
128 new_messages
129 }
130
131 pub fn flush(&mut self) -> Vec<Value> {
136 if self.buffer.trim().is_empty() {
137 return Vec::new();
138 }
139
140 let line = std::mem::take(&mut self.buffer);
141 self.line_count += 1;
142
143 if let Some(ref callback) = self.on_raw_line {
144 callback(&line, self.line_count);
145 }
146
147 if let Some(parsed) = parse_ndjson_line(&line) {
148 self.messages.push(parsed.clone());
149
150 if let Some(ref callback) = self.on_message {
151 callback(&parsed, self.line_count);
152 }
153
154 return vec![parsed];
155 } else if line.trim().starts_with('{') {
156 let error = ParseError {
157 line,
158 line_number: self.line_count,
159 };
160 self.errors.push(error.clone());
161
162 if let Some(ref callback) = self.on_error {
163 callback(&error);
164 }
165 }
166
167 Vec::new()
168 }
169
170 pub fn get_messages(&self) -> &[Value] {
172 &self.messages
173 }
174
175 pub fn get_errors(&self) -> &[ParseError] {
177 &self.errors
178 }
179
180 pub fn reset(&mut self) {
182 self.buffer.clear();
183 self.messages.clear();
184 self.errors.clear();
185 self.line_count = 0;
186 }
187
188 pub fn filter_by_type(&self, msg_type: &str) -> Vec<&Value> {
193 self.messages
194 .iter()
195 .filter(|msg| msg.get("type").and_then(|t| t.as_str()) == Some(msg_type))
196 .collect()
197 }
198
199 pub fn find<F>(&self, predicate: F) -> Option<&Value>
204 where
205 F: Fn(&Value) -> bool,
206 {
207 self.messages.iter().find(|msg| predicate(msg))
208 }
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214 use serde_json::json;
215
216 #[test]
217 fn test_process_single_json_line() {
218 let mut stream = JsonOutputStream::new();
219 let messages = stream.process("{\"type\":\"hello\"}\n");
220
221 assert_eq!(messages.len(), 1);
222 assert_eq!(messages[0], json!({"type": "hello"}));
223 }
224
225 #[test]
226 fn test_process_multiple_json_lines() {
227 let mut stream = JsonOutputStream::new();
228 let messages = stream.process("{\"a\":1}\n{\"b\":2}\n");
229
230 assert_eq!(messages.len(), 2);
231 assert_eq!(messages[0], json!({"a": 1}));
232 assert_eq!(messages[1], json!({"b": 2}));
233 }
234
235 #[test]
236 fn test_handles_partial_lines_across_chunks() {
237 let mut stream = JsonOutputStream::new();
238
239 let messages1 = stream.process("{\"type\":\"mes");
241 assert_eq!(messages1.len(), 0);
242
243 let messages2 = stream.process("sage\"}\n");
245 assert_eq!(messages2.len(), 1);
246 assert_eq!(messages2[0], json!({"type": "message"}));
247 }
248
249 #[test]
250 fn test_get_messages_returns_all() {
251 let mut stream = JsonOutputStream::new();
252 stream.process("{\"a\":1}\n");
253 stream.process("{\"b\":2}\n");
254
255 let messages = stream.get_messages();
256 assert_eq!(messages.len(), 2);
257 }
258
259 #[test]
260 fn test_flush_processes_remaining_buffer() {
261 let mut stream = JsonOutputStream::new();
262 stream.process("{\"type\":\"final\"}"); assert_eq!(stream.get_messages().len(), 0);
266
267 let flushed = stream.flush();
269 assert_eq!(flushed.len(), 1);
270 assert_eq!(flushed[0], json!({"type": "final"}));
271 }
272
273 #[test]
274 fn test_filter_by_type() {
275 let mut stream = JsonOutputStream::new();
276 stream.process("{\"type\":\"a\"}\n{\"type\":\"b\"}\n{\"type\":\"a\"}\n");
277
278 let filtered = stream.filter_by_type("a");
279 assert_eq!(filtered.len(), 2);
280 }
281
282 #[test]
283 fn test_reset_clears_state() {
284 let mut stream = JsonOutputStream::new();
285 stream.process("{\"a\":1}\n");
286 stream.reset();
287
288 assert_eq!(stream.get_messages().len(), 0);
289 }
290}