agent_commander/streaming/
json_records.rs1use serde_json::Value;
11
12pub const DEFAULT_MAX_PENDING_BYTES: usize = 4 * 1024 * 1024;
14
15#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum JsonRecordEvent {
18 Json { value: Value, raw: String },
20 Text(String),
22 Invalid(String),
24}
25
26#[derive(Debug, Clone)]
28pub struct JsonRecordScanner {
29 pending: String,
30 max_pending_bytes: usize,
31}
32
33impl Default for JsonRecordScanner {
34 fn default() -> Self {
35 Self::new()
36 }
37}
38
39fn is_opener(byte: u8) -> bool {
40 byte == b'{' || byte == b'['
41}
42
43fn find_value_end(buffer: &[u8], start: usize) -> Option<usize> {
45 let mut depth: i64 = 0;
46 let mut in_string = false;
47 let mut escaped = false;
48
49 for (index, &byte) in buffer.iter().enumerate().skip(start) {
50 if in_string {
51 if escaped {
52 escaped = false;
53 } else if byte == b'\\' {
54 escaped = true;
55 } else if byte == b'"' {
56 in_string = false;
57 }
58 continue;
59 }
60 match byte {
61 b'"' => in_string = true,
62 b'{' | b'[' => depth += 1,
63 b'}' | b']' => {
64 depth -= 1;
65 if depth == 0 {
66 return Some(index + 1);
67 }
68 if depth < 0 {
69 return None;
70 }
71 }
72 _ => {}
73 }
74 }
75
76 None
77}
78
79fn push_text(text: &str, events: &mut Vec<JsonRecordEvent>) {
80 for line in text.split('\n') {
81 let value = line.strip_suffix('\r').unwrap_or(line);
82 if !value.trim().is_empty() {
83 events.push(JsonRecordEvent::Text(value.to_string()));
84 }
85 }
86}
87
88impl JsonRecordScanner {
89 pub fn new() -> Self {
91 Self::with_max_pending_bytes(DEFAULT_MAX_PENDING_BYTES)
92 }
93
94 pub fn with_max_pending_bytes(max_pending_bytes: usize) -> Self {
96 Self {
97 pending: String::new(),
98 max_pending_bytes,
99 }
100 }
101
102 pub fn write(&mut self, chunk: &str) -> Vec<JsonRecordEvent> {
104 self.pending.push_str(chunk);
105 self.scan(false)
106 }
107
108 pub fn flush(&mut self) -> Vec<JsonRecordEvent> {
110 let events = self.scan(true);
111 self.pending.clear();
112 events
113 }
114
115 pub fn pending(&self) -> &str {
117 &self.pending
118 }
119
120 fn scan(&mut self, last: bool) -> Vec<JsonRecordEvent> {
121 let mut events = Vec::new();
122 let mut index = 0;
123 let pending = std::mem::take(&mut self.pending);
124 let bytes = pending.as_bytes();
125
126 while index < bytes.len() {
127 let byte = bytes[index];
128 if byte.is_ascii_whitespace() {
129 index += 1;
130 continue;
131 }
132
133 if is_opener(byte) {
134 match find_value_end(bytes, index) {
135 Some(end) => {
136 let raw = &pending[index..end];
137 if let Ok(value) = serde_json::from_str::<Value>(raw) {
138 events.push(JsonRecordEvent::Json {
139 value,
140 raw: raw.to_string(),
141 });
142 index = end;
143 continue;
144 }
145 if byte == b'{' && (last || pending[index..].contains('\n')) {
147 events.push(JsonRecordEvent::Invalid(raw.to_string()));
148 }
149 }
150 None if !last => break,
151 None => {}
152 }
153 }
156
157 let newline = pending[index..].find('\n').map(|offset| index + offset);
158 if newline.is_none() && !last {
159 break;
160 }
161 let line_end = newline.unwrap_or(bytes.len());
162 push_text(&pending[index..line_end], &mut events);
163 index = line_end + 1;
164 }
165
166 self.pending = pending[index.min(bytes.len())..].to_string();
167 if self.pending.len() > self.max_pending_bytes {
168 push_text(&std::mem::take(&mut self.pending), &mut events);
169 }
170 events
171 }
172}
173
174pub fn parse_json_records(output: &str) -> Vec<Value> {
176 let mut scanner = JsonRecordScanner::new();
177 let mut events = scanner.write(output);
178 events.extend(scanner.flush());
179 events
180 .into_iter()
181 .filter_map(|event| match event {
182 JsonRecordEvent::Json { value, .. } => Some(value),
183 _ => None,
184 })
185 .collect()
186}