Skip to main content

vtcode_core/tools/exec_session/
monitor.rs

1//! Pipe-session line monitor: substring filter with bounded match buffering.
2//!
3//! Taps decoded pipe output line by line, keeps only lines matching a
4//! subscriber filter, and exposes a bounded digest through peek/drain
5//! semantics that mirror [`PipeOutputBuffer`]. Tool responses drain windows
6//! per read; the runloop drains leftovers for idle wake. Every buffer here
7//! is capped, including the unterminated-line remainder.
8
9use super::*;
10use crate::types::CompactStr;
11use vtcode_commons::sanitizer::{redact_secrets, sanitize_terminal_text};
12
13/// Default cap on buffered matched lines per drain window.
14pub(crate) const MONITOR_DEFAULT_MAX_LINES: usize = 50;
15/// Default cap on buffered matched bytes per drain window.
16pub(crate) const MONITOR_DEFAULT_MAX_BYTES: usize = 4_096;
17/// Hard ceiling for `max_lines`; keeps one subscription from owning memory.
18const MONITOR_MAX_LINES_HARD_CAP: usize = 500;
19/// Hard ceiling for `max_bytes`; keeps one digest inside a tool result.
20const MONITOR_MAX_BYTES_HARD_CAP: usize = 16_384;
21/// Floor for `max_bytes` so a digest can always hold one short line.
22const MONITOR_MIN_BYTES: usize = 256;
23/// Longest accepted filter in characters; filters are keywords, not documents.
24const MONITOR_FILTER_MAX_CHARS: usize = 256;
25/// Longest retained line in characters; matches the completion-field budget.
26const MONITOR_LINE_MAX_CHARS: usize = 512;
27/// Most sessions drained per idle-wake tick; leftovers stay buffered.
28pub(crate) const MONITOR_WAKE_MAX_SESSIONS: usize = 8;
29/// Longest unterminated tail kept verbatim; past this the head force-flushes
30/// as a line so newline-less output cannot grow memory without bound.
31const MONITOR_REMAINDER_MAX_BYTES: usize = 64 * 1024;
32
33/// Validated subscription: which lines to keep and how much to buffer.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub(crate) struct MonitorSpec {
36    filter: CompactStr,
37    max_lines: usize,
38    max_bytes: usize,
39}
40
41impl MonitorSpec {
42    /// Parse untrusted subscription input into a validated spec.
43    ///
44    /// The filter must be non-empty after trimming and fit
45    /// `MONITOR_FILTER_MAX_CHARS`. Caps fall back to defaults when omitted
46    /// and clamp into `[1, HARD_CAP]` / `[MIN, HARD_CAP]`.
47    ///
48    /// # Errors
49    ///
50    /// Returns an error when the filter is empty or too long.
51    pub(crate) fn new(filter: &str, max_lines: Option<usize>, max_bytes: Option<usize>) -> Result<Self> {
52        let trimmed = filter.trim();
53        if trimmed.is_empty() {
54            bail!("monitor filter must not be empty");
55        }
56        if trimmed.chars().count() > MONITOR_FILTER_MAX_CHARS {
57            bail!("monitor filter exceeds {MONITOR_FILTER_MAX_CHARS} characters");
58        }
59        Ok(Self {
60            filter: CompactStr::new(trimmed),
61            max_lines: max_lines
62                .unwrap_or(MONITOR_DEFAULT_MAX_LINES)
63                .clamp(1, MONITOR_MAX_LINES_HARD_CAP),
64            max_bytes: max_bytes
65                .unwrap_or(MONITOR_DEFAULT_MAX_BYTES)
66                .clamp(MONITOR_MIN_BYTES, MONITOR_MAX_BYTES_HARD_CAP),
67        })
68    }
69
70    /// Case-sensitive substring match against one decoded line.
71    #[must_use]
72    pub(crate) fn matches(&self, line: &str) -> bool {
73        line.contains(self.filter.as_str())
74    }
75}
76
77/// Bounded view of one drain window: matched lines plus drop accounting.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub(crate) struct MonitorDigest {
80    /// Redacted, terminal-sanitized matched lines in arrival order.
81    pub(crate) lines: Vec<String>,
82    /// Matched lines dropped by the window caps.
83    pub(crate) dropped_lines: u64,
84    /// Bytes of dropped matched lines.
85    pub(crate) dropped_bytes: u64,
86    /// Matched lines seen in this window, accepted plus dropped.
87    pub(crate) total_seen: u64,
88}
89
90impl MonitorDigest {
91    /// Render lines with a drop-count tail so truncation stays visible.
92    #[must_use]
93    pub(crate) fn render(&self) -> String {
94        let mut rendered = self.lines.join("\n");
95        if self.dropped_lines > 0 {
96            if !rendered.is_empty() {
97                rendered.push('\n');
98            }
99            rendered.push_str(&format!(
100                "[monitor digest truncated: {} lines, {} bytes dropped]",
101                self.dropped_lines, self.dropped_bytes
102            ));
103        }
104        rendered
105    }
106}
107
108/// Mutable per-session monitor state: spec, pending window, line remainder.
109#[derive(Debug, Clone)]
110pub(crate) struct MonitorState {
111    spec: MonitorSpec,
112    pending: Vec<String>,
113    pending_bytes: usize,
114    remainder: String,
115    dropped_lines: u64,
116    dropped_bytes: u64,
117    total_seen: u64,
118}
119
120impl MonitorState {
121    pub(crate) fn new(spec: MonitorSpec) -> Self {
122        Self {
123            spec,
124            pending: Vec::new(),
125            pending_bytes: 0,
126            remainder: String::new(),
127            dropped_lines: 0,
128            dropped_bytes: 0,
129            total_seen: 0,
130        }
131    }
132
133    /// Feed decoded text; splits on line breaks, so boundaries stay char-safe.
134    pub(crate) fn push_text(&mut self, text: &str) {
135        if text.is_empty() {
136            return;
137        }
138        self.remainder.push_str(text);
139        self.split_complete_lines();
140        self.force_flush_oversize_remainder();
141    }
142
143    /// Split off every newline-terminated line, keeping the tail.
144    ///
145    /// Both `\n` and `\r` end a line so carriage-return progress output
146    /// cannot pile up behind one giant remainder.
147    fn split_complete_lines(&mut self) {
148        if !self.remainder.contains('\n') && !self.remainder.contains('\r') {
149            return;
150        }
151        let combined = std::mem::take(&mut self.remainder);
152        let mut lines: Vec<&str> = combined.split(['\n', '\r']).collect();
153        // `split` always yields a trailing segment after the last break; it
154        // is empty exactly when the input ends with a break.
155        let trailing = lines.pop().unwrap_or_default();
156        if !combined.ends_with(['\n', '\r']) {
157            self.remainder.push_str(trailing);
158        }
159        for line in lines {
160            self.push_line(line);
161        }
162    }
163
164    /// Force-flush an overgrown tail so memory stays bounded.
165    ///
166    /// Keeps a filter-length overlap so a match spanning the cut is still
167    /// found exactly once, in the next line. The overlap is excluded from
168    /// the flushed head, so fully overlapped matches never double-report.
169    fn force_flush_oversize_remainder(&mut self) {
170        if self.remainder.len() <= MONITOR_REMAINDER_MAX_BYTES {
171            return;
172        }
173        let overlap_chars = self.spec.filter.as_str().chars().count().max(1);
174        let total_chars = self.remainder.chars().count();
175        let cut_chars = total_chars.saturating_sub(overlap_chars);
176        let cut_byte = self
177            .remainder
178            .char_indices()
179            .nth(cut_chars)
180            .map(|(index, _)| index)
181            .unwrap_or(self.remainder.len());
182        let tail = self.remainder.split_off(cut_byte);
183        let head = std::mem::replace(&mut self.remainder, tail);
184        self.push_line(&head);
185    }
186
187    /// Flush a final unterminated line at end of stream.
188    pub(crate) fn flush(&mut self) {
189        if self.remainder.is_empty() {
190            return;
191        }
192        let last = std::mem::take(&mut self.remainder);
193        self.push_line(&last);
194    }
195
196    fn push_line(&mut self, line: &str) {
197        if !self.spec.matches(line) {
198            return;
199        }
200        self.total_seen = self.total_seen.saturating_add(1);
201        let redacted = redact_secrets(line.to_owned());
202        let sanitized = sanitize_terminal_text(&redacted, MONITOR_LINE_MAX_CHARS);
203        let line_bytes = sanitized.len();
204        if self.pending.len() >= self.spec.max_lines
205            || self.pending_bytes.saturating_add(line_bytes) > self.spec.max_bytes
206        {
207            self.dropped_lines = self.dropped_lines.saturating_add(1);
208            self.dropped_bytes = self.dropped_bytes.saturating_add(line_bytes as u64);
209            return;
210        }
211        self.pending_bytes = self.pending_bytes.saturating_add(line_bytes);
212        self.pending.push(sanitized);
213    }
214
215    fn snapshot(&self) -> MonitorDigest {
216        MonitorDigest {
217            lines: self.pending.clone(),
218            dropped_lines: self.dropped_lines,
219            dropped_bytes: self.dropped_bytes,
220            total_seen: self.total_seen,
221        }
222    }
223
224    /// Non-consuming view; `None` when no matched line arrived this window.
225    pub(crate) fn peek_digest(&self) -> Option<MonitorDigest> {
226        if self.total_seen == 0 {
227            None
228        } else {
229            Some(self.snapshot())
230        }
231    }
232
233    /// Consuming view; resets the window counts with the lines.
234    pub(crate) fn drain_digest(&mut self) -> Option<MonitorDigest> {
235        if self.total_seen == 0 {
236            return None;
237        }
238        let digest = self.snapshot();
239        self.pending.clear();
240        self.pending_bytes = 0;
241        self.dropped_lines = 0;
242        self.dropped_bytes = 0;
243        self.total_seen = 0;
244        Some(digest)
245    }
246}
247
248/// One drained monitor window for idle wake, rendered by the runloop.
249#[derive(Debug, Clone, PartialEq, Eq)]
250pub struct MonitorWakeNote {
251    /// Session that produced the matches.
252    pub session_id: String,
253    /// Program the session runs, for note headers.
254    pub command: String,
255    /// Rendered matched lines with any drop-count tail.
256    pub text: String,
257    /// Matched lines dropped by the window caps.
258    pub dropped_lines: u64,
259    /// Bytes of dropped matched lines.
260    pub dropped_bytes: u64,
261    /// Matched lines seen in this window, accepted plus dropped.
262    pub total_seen: u64,
263}
264
265impl PipeSessionManager {
266    /// Attach or replace the line filter; resets any buffered window.
267    pub(crate) async fn set_monitor_filter(&self, session_id: &str, spec: MonitorSpec) -> Result<()> {
268        let record = self.session_record(session_id).await?;
269        *record.monitor.lock() = Some(MonitorState::new(spec));
270        Ok(())
271    }
272
273    /// Peek or drain the bounded match digest; `None` when nothing matched.
274    pub(crate) async fn read_monitor_digest(&self, session_id: &str, drain: bool) -> Result<Option<MonitorDigest>> {
275        let record = self.session_record(session_id).await?;
276        let mut guard = record.monitor.lock();
277        let Some(state) = guard.as_mut() else {
278            return Ok(None);
279        };
280        if drain {
281            Ok(state.drain_digest())
282        } else {
283            Ok(state.peek_digest())
284        }
285    }
286}