vtcode_core/tools/exec_session/
monitor.rs1use super::*;
10use crate::types::CompactStr;
11use vtcode_commons::sanitizer::{redact_secrets, sanitize_terminal_text};
12
13pub(crate) const MONITOR_DEFAULT_MAX_LINES: usize = 50;
15pub(crate) const MONITOR_DEFAULT_MAX_BYTES: usize = 4_096;
17const MONITOR_MAX_LINES_HARD_CAP: usize = 500;
19const MONITOR_MAX_BYTES_HARD_CAP: usize = 16_384;
21const MONITOR_MIN_BYTES: usize = 256;
23const MONITOR_FILTER_MAX_CHARS: usize = 256;
25const MONITOR_LINE_MAX_CHARS: usize = 512;
27pub(crate) const MONITOR_WAKE_MAX_SESSIONS: usize = 8;
29const MONITOR_REMAINDER_MAX_BYTES: usize = 64 * 1024;
32
33#[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 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 #[must_use]
72 pub(crate) fn matches(&self, line: &str) -> bool {
73 line.contains(self.filter.as_str())
74 }
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
79pub(crate) struct MonitorDigest {
80 pub(crate) lines: Vec<String>,
82 pub(crate) dropped_lines: u64,
84 pub(crate) dropped_bytes: u64,
86 pub(crate) total_seen: u64,
88}
89
90impl MonitorDigest {
91 #[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#[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 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 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 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 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 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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
250pub struct MonitorWakeNote {
251 pub session_id: String,
253 pub command: String,
255 pub text: String,
257 pub dropped_lines: u64,
259 pub dropped_bytes: u64,
261 pub total_seen: u64,
263}
264
265impl PipeSessionManager {
266 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 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}