Skip to main content

adk_devtools/tools/
output.rs

1//! A command's output: its start and end in memory for the result, and all of it in a file
2//! an [`OutputStore`] names (spec 3.1 §7.33 fix 8, §10 D10).
3
4use std::collections::VecDeque;
5use std::io::Write;
6use std::path::PathBuf;
7use std::sync::{Arc, Mutex};
8
9use adk_core::ToolContext;
10
11/// The most characters of output one `bash` result carries, stdout and stderr together
12/// (spec 3.1 §7.33 fix 8). A longer stream keeps its first third and its last two thirds of
13/// its share, around a marker naming the bytes left out.
14///
15/// # Example
16///
17/// ```rust
18/// assert_eq!(adk_devtools::INLINE_OUTPUT_CHARS, 30_000);
19/// ```
20pub const INLINE_OUTPUT_CHARS: usize = 30_000;
21
22/// Bytes a stream keeps from its start and from its end in memory: enough for every inline
23/// character at four bytes each.
24const KEEP_BYTES: usize = INLINE_OUTPUT_CHARS * 4;
25
26/// Output held in memory before an output file is created, so a command whose output fits
27/// inline leaves no file behind.
28const SPILL_AT: usize = 32 * 1024;
29
30/// The longest last line [`OutputStore`] callers are told about.
31const LAST_LINE_CHARS: usize = 200;
32
33/// Keeps the full output of `bash` commands whose result is cut (spec 3.1 §10 D10).
34///
35/// The harness keeps each file in the session's scratch directory and reads it back with
36/// `shell_output`; without a store, a cut result names only the bytes it left out.
37///
38/// # Example
39///
40/// ```rust
41/// use adk_core::ToolContext;
42/// use adk_devtools::{OutputFile, OutputStore};
43///
44/// struct InDir(std::path::PathBuf);
45///
46/// impl OutputStore for InDir {
47///     fn create(&self, ctx: &dyn ToolContext, _command: &str) -> std::io::Result<OutputFile> {
48///         let id = ctx.function_call_id().to_string();
49///         let path = self.0.join(format!("{id}.log"));
50///         let file = std::fs::File::options().write(true).create_new(true).open(&path)?;
51///         Ok(OutputFile { id, path, file })
52///     }
53/// }
54/// ```
55pub trait OutputStore: Send + Sync {
56    /// Creates a new, empty file for the output of `command`, run by the call `ctx`.
57    ///
58    /// # Errors
59    ///
60    /// Returns the I/O error when the file cannot be created; the result then names only
61    /// the bytes it left out.
62    fn create(&self, ctx: &dyn ToolContext, command: &str) -> std::io::Result<OutputFile>;
63}
64
65/// A file a command's full output goes to, as an [`OutputStore`] creates it.
66#[derive(Debug)]
67pub struct OutputFile {
68    /// The name a caller passes back to read the file, such as `shell_output`'s `shell_id`.
69    pub id: String,
70    /// Where the file is; it is removed when the result turns out to need none.
71    pub path: PathBuf,
72    /// The file, open for writing.
73    pub file: std::fs::File,
74}
75
76/// The stream a chunk of output came from.
77#[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/// The start and end of one stream, and how many bytes it had.
93#[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    /// Bytes between the head and the tail that memory did not keep.
113    fn omitted(&self) -> u64 {
114        self.total - self.head.len() as u64 - self.tail.len() as u64
115    }
116
117    /// The stream's characters, or `None` when memory did not keep all of it, which means
118    /// more than any inline budget.
119    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
127/// Where the output goes besides memory.
128enum Spill {
129    /// No store: memory only.
130    None,
131    /// Not created yet: everything so far, in arrival order.
132    Pending(Vec<u8>),
133    /// Created.
134    Open { file: OutputFile, written: u64, cut: bool },
135    /// The store could not create the file, or it could not be written.
136    Failed,
137}
138
139struct State {
140    stdout: Kept,
141    stderr: Kept,
142    spill: Spill,
143    /// Whether the file stays whatever the result needs (a background command's log).
144    kept: bool,
145    /// The last line of output, and the partial line after it.
146    last_line: String,
147    partial: Vec<u8>,
148}
149
150/// One command's output, filled by the pumps of both streams.
151pub(crate) struct Collector {
152    state: Mutex<State>,
153    store: Option<Arc<dyn OutputStore>>,
154    ctx: Arc<dyn ToolContext>,
155    command: String,
156    /// The most bytes the file holds: `Workspace::max_output`, the disk bound.
157    cap: u64,
158}
159
160/// A rendered result: each stream within its share of [`INLINE_OUTPUT_CHARS`].
161pub(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    /// Takes `bytes` read from `stream`.
197    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    /// Creates the file and writes what was pending.
217    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    /// Bytes read from both streams so far.
254    pub(crate) fn total(&self) -> u64 {
255        let state = self.lock();
256        state.stdout.total + state.stderr.total
257    }
258
259    /// The last line of output so far, at most 200 characters.
260    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    /// Keeps the output in a file from now on, whatever the result needs, and names it.
269    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    /// The streams as the result carries them, each within its share of
285    /// [`INLINE_OUTPUT_CHARS`]. A cut result names the file that holds the whole output; a
286    /// file the result does not need is removed.
287    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/// A finished command's output as a `bash` result carries it (spec 3.1 §7.33 fix 8).
331#[derive(Clone, Debug, PartialEq, Eq)]
332pub struct BoundedOutput {
333    /// Standard output, within its share of [`INLINE_OUTPUT_CHARS`].
334    pub stdout: String,
335    /// Standard error, within its share.
336    pub stderr: String,
337    /// Whether either was cut.
338    pub truncated: bool,
339    /// The file that holds the whole output when either was cut and `store` kept it.
340    pub output_id: Option<String>,
341}
342
343/// Bounds the whole output of a finished command as [`BashTool`](crate::BashTool) bounds
344/// what it reads: at most [`INLINE_OUTPUT_CHARS`] characters, the whole output in a file
345/// from `store` when cut, of at most `cap` bytes. For a runner that receives a command's
346/// output at once, such as a container's.
347///
348/// # Example
349///
350/// ```rust
351/// use std::sync::Arc;
352///
353/// # struct Ctx;
354/// # #[async_trait::async_trait] impl adk_core::ReadonlyContext for Ctx {
355/// #     fn invocation_id(&self) -> &str { "i" } fn agent_name(&self) -> &str { "a" }
356/// #     fn user_id(&self) -> &str { "u" } fn app_name(&self) -> &str { "app" }
357/// #     fn session_id(&self) -> &str { "s" } fn branch(&self) -> &str { "" }
358/// #     fn user_content(&self) -> &adk_core::Content { unimplemented!() }
359/// # }
360/// # #[async_trait::async_trait] impl adk_core::CallbackContext for Ctx {
361/// #     fn artifacts(&self) -> Option<Arc<dyn adk_core::Artifacts>> { None }
362/// # }
363/// # #[async_trait::async_trait] impl adk_core::ToolContext for Ctx {
364/// #     fn function_call_id(&self) -> &str { "c" }
365/// #     fn actions(&self) -> adk_core::EventActions { Default::default() }
366/// #     fn set_actions(&self, _: adk_core::EventActions) {}
367/// #     async fn search_memory(&self, _: &str) -> adk_core::Result<Vec<adk_core::MemoryEntry>> { Ok(vec![]) }
368/// # }
369/// let long = "x".repeat(40_000);
370/// let bounded = adk_devtools::bound_output(None, Arc::new(Ctx), "make", long.as_bytes(), b"", 1 << 20);
371/// assert!(bounded.truncated);
372/// assert!(bounded.stdout.contains("[10000 bytes left out]"));
373/// ```
374pub 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
389/// Records the last complete, non-blank line of `bytes`, keeping the partial line after it.
390fn 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    // A line longer than anything shown is cut to its start.
405    if state.partial.len() > LAST_LINE_CHARS * 4 {
406        state.partial.truncate(LAST_LINE_CHARS * 4);
407    }
408}
409
410/// Each stream's share of [`INLINE_OUTPUT_CHARS`], from its characters (`None`: more than
411/// any share). A stream within half of it keeps all of it, and the other stream takes the
412/// rest.
413fn 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
423/// `kept` within `share` characters: whole when it fits, else its first third and last two
424/// thirds around `marker`, which names the bytes left out. Returns whether it was cut.
425fn 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    // The tail can begin inside a character that the bytes memory dropped began.
446    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
460/// The characters of `bytes` decoded lossily: each invalid sequence is one character.
461fn 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
468/// The bytes of the first `chars` characters of `bytes` decoded lossily.
469fn 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
490/// Where the last `chars` characters of `bytes`, decoded lossily, begin.
491fn 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        // 10 characters from the start, 20 from the end, 5000 - 30 bytes between.
523        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        // `€` is three bytes: 30 characters of 90 bytes, cut to 3 and 6.
530        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        // The trailing `b` puts the start of the kept tail one byte into a three-byte `€`.
552        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        // `0xFF` and `0xFE` begin no sequence, so each is one replacement character.
566        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}