1use std::collections::VecDeque;
5use std::io::Write;
6use std::path::PathBuf;
7use std::sync::{Arc, Mutex};
8
9use adk_core::ToolContext;
10
11pub const INLINE_OUTPUT_CHARS: usize = 30_000;
21
22const KEEP_BYTES: usize = INLINE_OUTPUT_CHARS * 4;
25
26const SPILL_AT: usize = 32 * 1024;
29
30const LAST_LINE_CHARS: usize = 200;
32
33pub trait OutputStore: Send + Sync {
56 fn create(&self, ctx: &dyn ToolContext, command: &str) -> std::io::Result<OutputFile>;
63}
64
65#[derive(Debug)]
67pub struct OutputFile {
68 pub id: String,
70 pub path: PathBuf,
72 pub file: std::fs::File,
74}
75
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub(crate) enum Stream {
79 Stdout,
80 Stderr,
81}
82
83impl Stream {
84 pub(crate) fn name(self) -> &'static str {
85 match self {
86 Self::Stdout => "stdout",
87 Self::Stderr => "stderr",
88 }
89 }
90}
91
92#[derive(Default)]
94struct Kept {
95 head: Vec<u8>,
96 tail: VecDeque<u8>,
97 total: u64,
98}
99
100impl Kept {
101 fn push(&mut self, bytes: &[u8]) {
102 self.total += bytes.len() as u64;
103 let room = KEEP_BYTES.saturating_sub(self.head.len()).min(bytes.len());
104 let (head, rest) = bytes.split_at(room);
105 self.head.extend_from_slice(head);
106 let rest = &rest[rest.len().saturating_sub(KEEP_BYTES)..];
107 self.tail.extend(rest);
108 let over = self.tail.len().saturating_sub(KEEP_BYTES);
109 self.tail.drain(..over);
110 }
111
112 fn omitted(&self) -> u64 {
114 self.total - self.head.len() as u64 - self.tail.len() as u64
115 }
116
117 fn chars(&self) -> Option<usize> {
120 (self.omitted() == 0).then(|| {
121 let (front, back) = self.tail.as_slices();
122 char_count(&[self.head.as_slice(), front, back].concat())
123 })
124 }
125}
126
127enum Spill {
129 None,
131 Pending(Vec<u8>),
133 Open { file: OutputFile, written: u64, cut: bool },
135 Failed,
137}
138
139struct State {
140 stdout: Kept,
141 stderr: Kept,
142 spill: Spill,
143 kept: bool,
145 last_line: String,
147 partial: Vec<u8>,
148}
149
150pub(crate) struct Collector {
152 state: Mutex<State>,
153 store: Option<Arc<dyn OutputStore>>,
154 ctx: Arc<dyn ToolContext>,
155 command: String,
156 cap: u64,
158}
159
160pub(crate) struct Rendered {
162 pub(crate) stdout: String,
163 pub(crate) stderr: String,
164 pub(crate) truncated: bool,
165 pub(crate) output_id: Option<String>,
166}
167
168impl Collector {
169 pub(crate) fn new(
170 store: Option<Arc<dyn OutputStore>>,
171 ctx: Arc<dyn ToolContext>,
172 command: &str,
173 cap: usize,
174 ) -> Self {
175 let spill = if store.is_some() { Spill::Pending(Vec::new()) } else { Spill::None };
176 Self {
177 state: Mutex::new(State {
178 stdout: Kept::default(),
179 stderr: Kept::default(),
180 spill,
181 kept: false,
182 last_line: String::new(),
183 partial: Vec::new(),
184 }),
185 store,
186 ctx,
187 command: command.to_string(),
188 cap: cap as u64,
189 }
190 }
191
192 fn lock(&self) -> std::sync::MutexGuard<'_, State> {
193 self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
194 }
195
196 pub(crate) fn push(&self, stream: Stream, bytes: &[u8]) {
198 let mut state = self.lock();
199 match stream {
200 Stream::Stdout => state.stdout.push(bytes),
201 Stream::Stderr => state.stderr.push(bytes),
202 }
203 note_last_line(&mut state, bytes);
204 let spill_now = matches!(&state.spill, Spill::Pending(pending) if pending.len() + bytes.len() > SPILL_AT);
205 match &mut state.spill {
206 Spill::Pending(pending) if !spill_now => pending.extend_from_slice(bytes),
207 Spill::Pending(_) => {
208 self.open(&mut state);
209 self.write(&mut state, bytes);
210 }
211 Spill::Open { .. } => self.write(&mut state, bytes),
212 Spill::None | Spill::Failed => {}
213 }
214 }
215
216 fn open(&self, state: &mut State) {
218 let Spill::Pending(pending) = std::mem::replace(&mut state.spill, Spill::Failed) else {
219 return;
220 };
221 let Some(store) = &self.store else { return };
222 match store.create(self.ctx.as_ref(), &self.command) {
223 Ok(file) => {
224 state.spill = Spill::Open { file, written: 0, cut: false };
225 self.write(state, &pending);
226 }
227 Err(error) => {
228 tracing::warn!(error = %error, "could not create the file for a command's output");
229 }
230 }
231 }
232
233 fn write(&self, state: &mut State, bytes: &[u8]) {
234 let Spill::Open { file, written, cut } = &mut state.spill else { return };
235 let room = usize::try_from(self.cap.saturating_sub(*written)).unwrap_or(usize::MAX);
236 let take = room.min(bytes.len());
237 if take < bytes.len() {
238 *cut = true;
239 }
240 if take == 0 {
241 return;
242 }
243 match file.file.write_all(&bytes[..take]) {
244 Ok(()) => *written += take as u64,
245 Err(error) => {
246 tracing::warn!(error = %error, output.id = %file.id, "could not write a command's output");
247 *cut = true;
248 *written = self.cap;
249 }
250 }
251 }
252
253 pub(crate) fn total(&self) -> u64 {
255 let state = self.lock();
256 state.stdout.total + state.stderr.total
257 }
258
259 pub(crate) fn last_line(&self) -> Option<String> {
261 let state = self.lock();
262 let partial = String::from_utf8_lossy(&state.partial);
263 let line =
264 if partial.trim().is_empty() { state.last_line.as_str() } else { partial.trim() };
265 (!line.is_empty()).then(|| line.chars().take(LAST_LINE_CHARS).collect())
266 }
267
268 pub(crate) fn keep(&self) -> std::io::Result<String> {
270 let mut state = self.lock();
271 state.kept = true;
272 if matches!(state.spill, Spill::Pending(_)) {
273 self.open(&mut state);
274 }
275 match &state.spill {
276 Spill::Open { file, .. } => Ok(file.id.clone()),
277 Spill::None => Err(std::io::Error::other("no output store is configured")),
278 Spill::Pending(_) | Spill::Failed => {
279 Err(std::io::Error::other("the output file could not be created"))
280 }
281 }
282 }
283
284 pub(crate) fn render(&self) -> Rendered {
288 let mut state = self.lock();
289 let (out_share, err_share) = shares(state.stdout.chars(), state.stderr.chars());
290 let cut = state.stdout.chars().is_none_or(|chars| chars > out_share)
291 || state.stderr.chars().is_none_or(|chars| chars > err_share);
292 if cut && matches!(state.spill, Spill::Pending(_)) {
293 self.open(&mut state);
294 }
295 let output = match &state.spill {
296 Spill::Open { file, cut: file_cut, .. } if cut || state.kept => {
297 let _ = file.file.sync_data();
298 Some((file.id.clone(), *file_cut))
299 }
300 _ => None,
301 };
302 if !cut
303 && !state.kept
304 && let Spill::Open { file, .. } = &state.spill
305 && let Err(error) = std::fs::remove_file(&file.path)
306 {
307 tracing::debug!(error = %error, "could not remove an unneeded output file");
308 }
309 let marker = |left: u64| match &output {
310 Some((id, false)) => format!(
311 "\n…[{left} bytes left out; shell_output {{\"shell_id\": \"{id}\"}} reads the whole output]\n"
312 ),
313 Some((id, true)) => format!(
314 "\n…[{left} bytes left out; shell_output {{\"shell_id\": \"{id}\"}} reads the first {} bytes of the output]\n",
315 self.cap
316 ),
317 None => format!("\n…[{left} bytes left out]\n"),
318 };
319 let (stdout, out_cut) = render_stream(&state.stdout, out_share, &marker);
320 let (stderr, err_cut) = render_stream(&state.stderr, err_share, &marker);
321 Rendered {
322 stdout,
323 stderr,
324 truncated: out_cut || err_cut,
325 output_id: output.filter(|_| out_cut || err_cut).map(|(id, _)| id),
326 }
327 }
328}
329
330#[derive(Clone, Debug, PartialEq, Eq)]
332pub struct BoundedOutput {
333 pub stdout: String,
335 pub stderr: String,
337 pub truncated: bool,
339 pub output_id: Option<String>,
341}
342
343pub fn bound_output(
375 store: Option<Arc<dyn OutputStore>>,
376 ctx: Arc<dyn ToolContext>,
377 command: &str,
378 stdout: &[u8],
379 stderr: &[u8],
380 cap: usize,
381) -> BoundedOutput {
382 let collector = Collector::new(store, ctx, command, cap);
383 collector.push(Stream::Stdout, stdout);
384 collector.push(Stream::Stderr, stderr);
385 let Rendered { stdout, stderr, truncated, output_id } = collector.render();
386 BoundedOutput { stdout, stderr, truncated, output_id }
387}
388
389fn note_last_line(state: &mut State, bytes: &[u8]) {
391 state.partial.extend_from_slice(bytes);
392 if let Some(end) = state.partial.iter().rposition(|&byte| byte == b'\n') {
393 let rest = state.partial.split_off(end + 1);
394 if let Some(line) = String::from_utf8_lossy(&state.partial)
395 .lines()
396 .rev()
397 .map(str::trim)
398 .find(|line| !line.is_empty())
399 {
400 state.last_line = line.chars().take(LAST_LINE_CHARS).collect();
401 }
402 state.partial = rest;
403 }
404 if state.partial.len() > LAST_LINE_CHARS * 4 {
406 state.partial.truncate(LAST_LINE_CHARS * 4);
407 }
408}
409
410fn shares(stdout: Option<usize>, stderr: Option<usize>) -> (usize, usize) {
414 const HALF: usize = INLINE_OUTPUT_CHARS / 2;
415 match (stdout, stderr) {
416 (Some(out), Some(err)) if out + err <= INLINE_OUTPUT_CHARS => (out, err),
417 (_, Some(err)) if err <= HALF => (INLINE_OUTPUT_CHARS - err, err),
418 (Some(out), _) if out <= HALF => (out, INLINE_OUTPUT_CHARS - out),
419 _ => (HALF, HALF),
420 }
421}
422
423fn render_stream(kept: &Kept, share: usize, marker: &dyn Fn(u64) -> String) -> (String, bool) {
426 let head_chars = share / 3;
427 let tail_chars = share - head_chars;
428 let (front, back) = kept.tail.as_slices();
429 if kept.omitted() == 0 {
430 let bytes = [kept.head.as_slice(), front, back].concat();
431 if char_count(&bytes) <= share {
432 return (String::from_utf8_lossy(&bytes).into_owned(), false);
433 }
434 let end = prefix_len(&bytes, head_chars);
435 let start = suffix_start(&bytes, tail_chars).max(end);
436 let text = format!(
437 "{}{}{}",
438 String::from_utf8_lossy(&bytes[..end]),
439 marker((start - end) as u64),
440 String::from_utf8_lossy(&bytes[start..])
441 );
442 return (text, true);
443 }
444 let tail = [front, back].concat();
445 let skipped = tail.iter().take(3).take_while(|&&byte| byte & 0xC0 == 0x80).count();
447 let tail = &tail[skipped..];
448 let end = prefix_len(&kept.head, head_chars);
449 let start = suffix_start(tail, tail_chars);
450 let left = (kept.head.len() - end) as u64 + kept.omitted() + (skipped + start) as u64;
451 let text = format!(
452 "{}{}{}",
453 String::from_utf8_lossy(&kept.head[..end]),
454 marker(left),
455 String::from_utf8_lossy(&tail[start..])
456 );
457 (text, true)
458}
459
460fn char_count(bytes: &[u8]) -> usize {
462 bytes
463 .utf8_chunks()
464 .map(|chunk| chunk.valid().chars().count() + usize::from(!chunk.invalid().is_empty()))
465 .sum()
466}
467
468fn prefix_len(bytes: &[u8], chars: usize) -> usize {
470 let mut left = chars;
471 let mut at = 0;
472 for chunk in bytes.utf8_chunks() {
473 let valid = chunk.valid();
474 if let Some((index, _)) = valid.char_indices().nth(left) {
475 return at + index;
476 }
477 left -= valid.chars().count();
478 at += valid.len();
479 if !chunk.invalid().is_empty() {
480 if left == 0 {
481 return at;
482 }
483 left -= 1;
484 at += chunk.invalid().len();
485 }
486 }
487 at
488}
489
490fn suffix_start(bytes: &[u8], chars: usize) -> usize {
492 let total = char_count(bytes);
493 if chars >= total { 0 } else { prefix_len(bytes, total - chars) }
494}
495
496#[cfg(test)]
497mod tests {
498 use super::*;
499
500 fn kept(bytes: &[u8]) -> Kept {
501 let mut kept = Kept::default();
502 for chunk in bytes.chunks(8192) {
503 kept.push(chunk);
504 }
505 kept
506 }
507
508 fn marker(left: u64) -> String {
509 format!("[{left}]")
510 }
511
512 #[test]
513 fn output_within_its_share_is_unchanged() {
514 let (text, cut) = render_stream(&kept("héllo\n".as_bytes()), 100, &marker);
515 assert_eq!((text.as_str(), cut), ("héllo\n", false));
516 }
517
518 #[test]
519 fn a_long_stream_keeps_its_first_third_and_last_two_thirds() {
520 let text: String = (0..1000).map(|n| format!("{n:04}\n")).collect();
521 let (rendered, cut) = render_stream(&kept(text.as_bytes()), 30, &marker);
522 assert_eq!(rendered, "0000\n0001\n[4970]0996\n0997\n0998\n0999\n");
524 assert!(cut);
525 }
526
527 #[test]
528 fn cuts_fall_on_character_boundaries() {
529 let text = "€".repeat(30);
531 let (rendered, cut) = render_stream(&kept(text.as_bytes()), 9, &marker);
532 assert_eq!(rendered, format!("€€€[63]{}", "€".repeat(6)));
533 assert!(cut);
534 }
535
536 #[test]
537 fn a_stream_larger_than_memory_names_every_byte_it_left_out() {
538 let total = 5 * 1024 * 1024;
539 let bytes: Vec<u8> = (0..total).map(|i| b'a' + (i % 26) as u8).collect();
540 let kept = kept(&bytes);
541 assert_eq!(kept.chars(), None);
542 let (rendered, cut) = render_stream(&kept, INLINE_OUTPUT_CHARS, &marker);
543 let head = String::from_utf8_lossy(&bytes[..10_000]);
544 let tail = String::from_utf8_lossy(&bytes[total - 20_000..]);
545 assert_eq!(rendered, format!("{head}[{}]{tail}", total - 30_000));
546 assert!(cut);
547 }
548
549 #[test]
550 fn a_tail_starting_inside_a_character_drops_its_rest() {
551 let mut bytes = vec![b'a'; KEEP_BYTES + 1];
553 bytes.extend("€".repeat(KEEP_BYTES / 3 + 1).as_bytes());
554 bytes.push(b'b');
555 let kept = kept(&bytes);
556 let (rendered, _) = render_stream(&kept, 9, &marker);
557 assert!(rendered.starts_with("aaa[") && rendered.ends_with("]€€€€€b"), "{rendered}");
558 assert!(!rendered.contains('\u{FFFD}'), "{rendered}");
559 let left: u64 = rendered[3..].split(['[', ']']).nth(1).unwrap().parse().unwrap();
560 assert_eq!(left, bytes.len() as u64 - 3 - 16, "every byte not shown is counted");
561 }
562
563 #[test]
564 fn invalid_utf8_counts_one_character_per_sequence() {
565 let bytes = [b'a', 0xFF, 0xFE, b'b', b'c'];
567 assert_eq!(char_count(&bytes), 5);
568 assert_eq!(char_count(&[b'a', 0xE2, 0x82, b'b']), 3, "a cut-off `€` is one sequence");
569 assert_eq!(prefix_len(&bytes, 2), 2);
570 assert_eq!(suffix_start(&bytes, 2), 3);
571 }
572
573 #[test]
574 fn a_small_stream_keeps_all_and_the_other_takes_the_rest() {
575 assert_eq!(shares(Some(10), Some(20)), (10, 20));
576 assert_eq!(shares(None, Some(100)), (INLINE_OUTPUT_CHARS - 100, 100));
577 assert_eq!(shares(Some(100), None), (100, INLINE_OUTPUT_CHARS - 100));
578 assert_eq!(shares(None, None), (15_000, 15_000));
579 assert_eq!(shares(Some(20_000), Some(20_000)), (15_000, 15_000));
580 }
581}