Skip to main content

agent_commander/streaming/
json_records.rs

1//! Balanced JSON record scanner for native CLI output
2//!
3//! Line-based NDJSON parsing drops every structured event when a tool prints
4//! pretty-printed JSON (the `@link-assistant/agent` CLI does so unless
5//! `--compact-json` is passed), concatenates records without a separator, or
6//! splits one record across process chunks. Scanning for balanced JSON values
7//! handles all three shapes, and NDJSON is the single-line special case.
8//! Ported from Hive Mind `src/json-stream.lib.mjs` (hive-mind#2119, #1250).
9
10use serde_json::Value;
11
12/// An unbalanced fragment (prose starting with `{`) is released past this size.
13pub const DEFAULT_MAX_PENDING_BYTES: usize = 4 * 1024 * 1024;
14
15/// Event emitted by [`JsonRecordScanner`]
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum JsonRecordEvent {
18    /// A complete JSON value and its raw text
19    Json { value: Value, raw: String },
20    /// A non-empty line that is not part of a JSON value
21    Text(String),
22    /// A balanced `{...}` fragment that is not valid JSON (followed by its text line)
23    Invalid(String),
24}
25
26/// Stateful scanner that turns output text into JSON and text events
27#[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
43/// Find the index just past the JSON value that starts at `start`
44fn 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    /// Create a scanner with the default pending-buffer limit
90    pub fn new() -> Self {
91        Self::with_max_pending_bytes(DEFAULT_MAX_PENDING_BYTES)
92    }
93
94    /// Create a scanner that releases an unbalanced buffer past `max_pending_bytes`
95    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    /// Feed a chunk and return the events it completes
103    pub fn write(&mut self, chunk: &str) -> Vec<JsonRecordEvent> {
104        self.pending.push_str(chunk);
105        self.scan(false)
106    }
107
108    /// Return the events left in the buffer at end of output
109    pub fn flush(&mut self) -> Vec<JsonRecordEvent> {
110        let events = self.scan(true);
111        self.pending.clear();
112        events
113    }
114
115    /// Text buffered while waiting for the rest of a record or line
116    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                        // Bracketed prose such as "[INFO] ..." stays one text line.
146                        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                // Not JSON, or the output ended inside this value: keep the line
154                // as text and resume on the next line so later records are not lost.
155            }
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
174/// Extract every complete JSON value from finished output, in stream order
175pub 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}