use std::collections::VecDeque;
use std::io::Write;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use adk_core::ToolContext;
pub const INLINE_OUTPUT_CHARS: usize = 30_000;
const KEEP_BYTES: usize = INLINE_OUTPUT_CHARS * 4;
const SPILL_AT: usize = 32 * 1024;
const LAST_LINE_CHARS: usize = 200;
pub trait OutputStore: Send + Sync {
fn create(&self, ctx: &dyn ToolContext, command: &str) -> std::io::Result<OutputFile>;
}
#[derive(Debug)]
pub struct OutputFile {
pub id: String,
pub path: PathBuf,
pub file: std::fs::File,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Stream {
Stdout,
Stderr,
}
impl Stream {
pub(crate) fn name(self) -> &'static str {
match self {
Self::Stdout => "stdout",
Self::Stderr => "stderr",
}
}
}
#[derive(Default)]
struct Kept {
head: Vec<u8>,
tail: VecDeque<u8>,
total: u64,
}
impl Kept {
fn push(&mut self, bytes: &[u8]) {
self.total += bytes.len() as u64;
let room = KEEP_BYTES.saturating_sub(self.head.len()).min(bytes.len());
let (head, rest) = bytes.split_at(room);
self.head.extend_from_slice(head);
let rest = &rest[rest.len().saturating_sub(KEEP_BYTES)..];
self.tail.extend(rest);
let over = self.tail.len().saturating_sub(KEEP_BYTES);
self.tail.drain(..over);
}
fn omitted(&self) -> u64 {
self.total - self.head.len() as u64 - self.tail.len() as u64
}
fn chars(&self) -> Option<usize> {
(self.omitted() == 0).then(|| {
let (front, back) = self.tail.as_slices();
char_count(&[self.head.as_slice(), front, back].concat())
})
}
}
enum Spill {
None,
Pending(Vec<u8>),
Open { file: OutputFile, written: u64, cut: bool },
Failed,
}
struct State {
stdout: Kept,
stderr: Kept,
spill: Spill,
kept: bool,
last_line: String,
partial: Vec<u8>,
}
pub(crate) struct Collector {
state: Mutex<State>,
store: Option<Arc<dyn OutputStore>>,
ctx: Arc<dyn ToolContext>,
command: String,
cap: u64,
}
pub(crate) struct Rendered {
pub(crate) stdout: String,
pub(crate) stderr: String,
pub(crate) truncated: bool,
pub(crate) output_id: Option<String>,
}
impl Collector {
pub(crate) fn new(
store: Option<Arc<dyn OutputStore>>,
ctx: Arc<dyn ToolContext>,
command: &str,
cap: usize,
) -> Self {
let spill = if store.is_some() { Spill::Pending(Vec::new()) } else { Spill::None };
Self {
state: Mutex::new(State {
stdout: Kept::default(),
stderr: Kept::default(),
spill,
kept: false,
last_line: String::new(),
partial: Vec::new(),
}),
store,
ctx,
command: command.to_string(),
cap: cap as u64,
}
}
fn lock(&self) -> std::sync::MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(crate) fn push(&self, stream: Stream, bytes: &[u8]) {
let mut state = self.lock();
match stream {
Stream::Stdout => state.stdout.push(bytes),
Stream::Stderr => state.stderr.push(bytes),
}
note_last_line(&mut state, bytes);
let spill_now = matches!(&state.spill, Spill::Pending(pending) if pending.len() + bytes.len() > SPILL_AT);
match &mut state.spill {
Spill::Pending(pending) if !spill_now => pending.extend_from_slice(bytes),
Spill::Pending(_) => {
self.open(&mut state);
self.write(&mut state, bytes);
}
Spill::Open { .. } => self.write(&mut state, bytes),
Spill::None | Spill::Failed => {}
}
}
fn open(&self, state: &mut State) {
let Spill::Pending(pending) = std::mem::replace(&mut state.spill, Spill::Failed) else {
return;
};
let Some(store) = &self.store else { return };
match store.create(self.ctx.as_ref(), &self.command) {
Ok(file) => {
state.spill = Spill::Open { file, written: 0, cut: false };
self.write(state, &pending);
}
Err(error) => {
tracing::warn!(error = %error, "could not create the file for a command's output");
}
}
}
fn write(&self, state: &mut State, bytes: &[u8]) {
let Spill::Open { file, written, cut } = &mut state.spill else { return };
let room = usize::try_from(self.cap.saturating_sub(*written)).unwrap_or(usize::MAX);
let take = room.min(bytes.len());
if take < bytes.len() {
*cut = true;
}
if take == 0 {
return;
}
match file.file.write_all(&bytes[..take]) {
Ok(()) => *written += take as u64,
Err(error) => {
tracing::warn!(error = %error, output.id = %file.id, "could not write a command's output");
*cut = true;
*written = self.cap;
}
}
}
pub(crate) fn total(&self) -> u64 {
let state = self.lock();
state.stdout.total + state.stderr.total
}
pub(crate) fn last_line(&self) -> Option<String> {
let state = self.lock();
let partial = String::from_utf8_lossy(&state.partial);
let line =
if partial.trim().is_empty() { state.last_line.as_str() } else { partial.trim() };
(!line.is_empty()).then(|| line.chars().take(LAST_LINE_CHARS).collect())
}
pub(crate) fn keep(&self) -> std::io::Result<String> {
let mut state = self.lock();
state.kept = true;
if matches!(state.spill, Spill::Pending(_)) {
self.open(&mut state);
}
match &state.spill {
Spill::Open { file, .. } => Ok(file.id.clone()),
Spill::None => Err(std::io::Error::other("no output store is configured")),
Spill::Pending(_) | Spill::Failed => {
Err(std::io::Error::other("the output file could not be created"))
}
}
}
pub(crate) fn render(&self) -> Rendered {
let mut state = self.lock();
let (out_share, err_share) = shares(state.stdout.chars(), state.stderr.chars());
let cut = state.stdout.chars().is_none_or(|chars| chars > out_share)
|| state.stderr.chars().is_none_or(|chars| chars > err_share);
if cut && matches!(state.spill, Spill::Pending(_)) {
self.open(&mut state);
}
let output = match &state.spill {
Spill::Open { file, cut: file_cut, .. } if cut || state.kept => {
let _ = file.file.sync_data();
Some((file.id.clone(), *file_cut))
}
_ => None,
};
if !cut
&& !state.kept
&& let Spill::Open { file, .. } = &state.spill
&& let Err(error) = std::fs::remove_file(&file.path)
{
tracing::debug!(error = %error, "could not remove an unneeded output file");
}
let marker = |left: u64| match &output {
Some((id, false)) => format!(
"\n…[{left} bytes left out; shell_output {{\"shell_id\": \"{id}\"}} reads the whole output]\n"
),
Some((id, true)) => format!(
"\n…[{left} bytes left out; shell_output {{\"shell_id\": \"{id}\"}} reads the first {} bytes of the output]\n",
self.cap
),
None => format!("\n…[{left} bytes left out]\n"),
};
let (stdout, out_cut) = render_stream(&state.stdout, out_share, &marker);
let (stderr, err_cut) = render_stream(&state.stderr, err_share, &marker);
Rendered {
stdout,
stderr,
truncated: out_cut || err_cut,
output_id: output.filter(|_| out_cut || err_cut).map(|(id, _)| id),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BoundedOutput {
pub stdout: String,
pub stderr: String,
pub truncated: bool,
pub output_id: Option<String>,
}
pub fn bound_output(
store: Option<Arc<dyn OutputStore>>,
ctx: Arc<dyn ToolContext>,
command: &str,
stdout: &[u8],
stderr: &[u8],
cap: usize,
) -> BoundedOutput {
let collector = Collector::new(store, ctx, command, cap);
collector.push(Stream::Stdout, stdout);
collector.push(Stream::Stderr, stderr);
let Rendered { stdout, stderr, truncated, output_id } = collector.render();
BoundedOutput { stdout, stderr, truncated, output_id }
}
fn note_last_line(state: &mut State, bytes: &[u8]) {
state.partial.extend_from_slice(bytes);
if let Some(end) = state.partial.iter().rposition(|&byte| byte == b'\n') {
let rest = state.partial.split_off(end + 1);
if let Some(line) = String::from_utf8_lossy(&state.partial)
.lines()
.rev()
.map(str::trim)
.find(|line| !line.is_empty())
{
state.last_line = line.chars().take(LAST_LINE_CHARS).collect();
}
state.partial = rest;
}
if state.partial.len() > LAST_LINE_CHARS * 4 {
state.partial.truncate(LAST_LINE_CHARS * 4);
}
}
fn shares(stdout: Option<usize>, stderr: Option<usize>) -> (usize, usize) {
const HALF: usize = INLINE_OUTPUT_CHARS / 2;
match (stdout, stderr) {
(Some(out), Some(err)) if out + err <= INLINE_OUTPUT_CHARS => (out, err),
(_, Some(err)) if err <= HALF => (INLINE_OUTPUT_CHARS - err, err),
(Some(out), _) if out <= HALF => (out, INLINE_OUTPUT_CHARS - out),
_ => (HALF, HALF),
}
}
fn render_stream(kept: &Kept, share: usize, marker: &dyn Fn(u64) -> String) -> (String, bool) {
let head_chars = share / 3;
let tail_chars = share - head_chars;
let (front, back) = kept.tail.as_slices();
if kept.omitted() == 0 {
let bytes = [kept.head.as_slice(), front, back].concat();
if char_count(&bytes) <= share {
return (String::from_utf8_lossy(&bytes).into_owned(), false);
}
let end = prefix_len(&bytes, head_chars);
let start = suffix_start(&bytes, tail_chars).max(end);
let text = format!(
"{}{}{}",
String::from_utf8_lossy(&bytes[..end]),
marker((start - end) as u64),
String::from_utf8_lossy(&bytes[start..])
);
return (text, true);
}
let tail = [front, back].concat();
let skipped = tail.iter().take(3).take_while(|&&byte| byte & 0xC0 == 0x80).count();
let tail = &tail[skipped..];
let end = prefix_len(&kept.head, head_chars);
let start = suffix_start(tail, tail_chars);
let left = (kept.head.len() - end) as u64 + kept.omitted() + (skipped + start) as u64;
let text = format!(
"{}{}{}",
String::from_utf8_lossy(&kept.head[..end]),
marker(left),
String::from_utf8_lossy(&tail[start..])
);
(text, true)
}
fn char_count(bytes: &[u8]) -> usize {
bytes
.utf8_chunks()
.map(|chunk| chunk.valid().chars().count() + usize::from(!chunk.invalid().is_empty()))
.sum()
}
fn prefix_len(bytes: &[u8], chars: usize) -> usize {
let mut left = chars;
let mut at = 0;
for chunk in bytes.utf8_chunks() {
let valid = chunk.valid();
if let Some((index, _)) = valid.char_indices().nth(left) {
return at + index;
}
left -= valid.chars().count();
at += valid.len();
if !chunk.invalid().is_empty() {
if left == 0 {
return at;
}
left -= 1;
at += chunk.invalid().len();
}
}
at
}
fn suffix_start(bytes: &[u8], chars: usize) -> usize {
let total = char_count(bytes);
if chars >= total { 0 } else { prefix_len(bytes, total - chars) }
}
#[cfg(test)]
mod tests {
use super::*;
fn kept(bytes: &[u8]) -> Kept {
let mut kept = Kept::default();
for chunk in bytes.chunks(8192) {
kept.push(chunk);
}
kept
}
fn marker(left: u64) -> String {
format!("[{left}]")
}
#[test]
fn output_within_its_share_is_unchanged() {
let (text, cut) = render_stream(&kept("héllo\n".as_bytes()), 100, &marker);
assert_eq!((text.as_str(), cut), ("héllo\n", false));
}
#[test]
fn a_long_stream_keeps_its_first_third_and_last_two_thirds() {
let text: String = (0..1000).map(|n| format!("{n:04}\n")).collect();
let (rendered, cut) = render_stream(&kept(text.as_bytes()), 30, &marker);
assert_eq!(rendered, "0000\n0001\n[4970]0996\n0997\n0998\n0999\n");
assert!(cut);
}
#[test]
fn cuts_fall_on_character_boundaries() {
let text = "€".repeat(30);
let (rendered, cut) = render_stream(&kept(text.as_bytes()), 9, &marker);
assert_eq!(rendered, format!("€€€[63]{}", "€".repeat(6)));
assert!(cut);
}
#[test]
fn a_stream_larger_than_memory_names_every_byte_it_left_out() {
let total = 5 * 1024 * 1024;
let bytes: Vec<u8> = (0..total).map(|i| b'a' + (i % 26) as u8).collect();
let kept = kept(&bytes);
assert_eq!(kept.chars(), None);
let (rendered, cut) = render_stream(&kept, INLINE_OUTPUT_CHARS, &marker);
let head = String::from_utf8_lossy(&bytes[..10_000]);
let tail = String::from_utf8_lossy(&bytes[total - 20_000..]);
assert_eq!(rendered, format!("{head}[{}]{tail}", total - 30_000));
assert!(cut);
}
#[test]
fn a_tail_starting_inside_a_character_drops_its_rest() {
let mut bytes = vec![b'a'; KEEP_BYTES + 1];
bytes.extend("€".repeat(KEEP_BYTES / 3 + 1).as_bytes());
bytes.push(b'b');
let kept = kept(&bytes);
let (rendered, _) = render_stream(&kept, 9, &marker);
assert!(rendered.starts_with("aaa[") && rendered.ends_with("]€€€€€b"), "{rendered}");
assert!(!rendered.contains('\u{FFFD}'), "{rendered}");
let left: u64 = rendered[3..].split(['[', ']']).nth(1).unwrap().parse().unwrap();
assert_eq!(left, bytes.len() as u64 - 3 - 16, "every byte not shown is counted");
}
#[test]
fn invalid_utf8_counts_one_character_per_sequence() {
let bytes = [b'a', 0xFF, 0xFE, b'b', b'c'];
assert_eq!(char_count(&bytes), 5);
assert_eq!(char_count(&[b'a', 0xE2, 0x82, b'b']), 3, "a cut-off `€` is one sequence");
assert_eq!(prefix_len(&bytes, 2), 2);
assert_eq!(suffix_start(&bytes, 2), 3);
}
#[test]
fn a_small_stream_keeps_all_and_the_other_takes_the_rest() {
assert_eq!(shares(Some(10), Some(20)), (10, 20));
assert_eq!(shares(None, Some(100)), (INLINE_OUTPUT_CHARS - 100, 100));
assert_eq!(shares(Some(100), None), (100, INLINE_OUTPUT_CHARS - 100));
assert_eq!(shares(None, None), (15_000, 15_000));
assert_eq!(shares(Some(20_000), Some(20_000)), (15_000, 15_000));
}
}