From 6df7a6403d88a4492ab6ea1c519dcae3a202be96 Mon Sep 17 00:00:00 2001 From: salmonik Date: Wed, 18 Nov 2026 12:01:38 +0100 Subject: 0.9.0: distinguishable tool errors, separated stderr, configurable limits From a field report porting a Neovim config to Helix: - validate() now separates 'empty value', 'wrong key (here is what you sent)' and 'no arguments at all, retry' instead of one false message for all four causes - named calls with no arguments are answered rather than dropped silently - bash keeps stdout and stderr in labelled sections when both produce output - bash gains timeout_seconds (1-600) and max_bytes, and says when output was cut - tool lines/results carry [step.call] labels when a step has several calls - invalid JSON errors include a preview of what arrived --- src/tools/shell.rs | 185 ++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 127 insertions(+), 58 deletions(-) (limited to 'src/tools/shell.rs') diff --git a/src/tools/shell.rs b/src/tools/shell.rs index 6f095c6..91f2dd9 100644 --- a/src/tools/shell.rs +++ b/src/tools/shell.rs @@ -8,11 +8,14 @@ use std::time::{Duration, Instant}; use serde_json::Value; -const HEAD_BYTES: usize = 64 * 1024; -const TAIL_BYTES: i64 = 16 * 1024; -/// The child cannot write more than this, so a runaway command cannot fill /tmp -/// and take the machine down with it. -const MAX_OUTPUT_BYTES: u64 = 64 * 1024 * 1024; +/// Default budget per stream, split 4:1 between head and tail. +const DEFAULT_MAX_BYTES: usize = 80 * 1024; +const MIN_MAX_BYTES: usize = 1024; +const MAX_MAX_BYTES: usize = 16 * 1024 * 1024; +/// The child cannot write more than this per stream, so a runaway command cannot +/// fill /tmp and take the machine down with it. +const MAX_FILE_BYTES: u64 = 64 * 1024 * 1024; + static COUNTER: AtomicU64 = AtomicU64::new(0); pub fn bash( @@ -25,25 +28,26 @@ pub fn bash( None => return Err("missing required argument `cmd`".into()), }; + let max_bytes = args + .get("max_bytes") + .and_then(|value| value.as_u64()) + .unwrap_or(DEFAULT_MAX_BYTES as u64) + .clamp(MIN_MAX_BYTES as u64, MAX_MAX_BYTES as u64) as usize; + let head_budget = max_bytes * 4 / 5; + let tail_budget = max_bytes - head_budget; + let cwd = resolve_cwd(args.get("cwd").and_then(|v| v.as_str()))?; if !cwd.is_dir() { return Err(format!("cwd is not a directory: {}", cwd.display())); } - let path = std::env::temp_dir().join(format!( - "agent686-{}-{}.out", - std::process::id(), - COUNTER.fetch_add(1, Ordering::Relaxed) - )); - let mut file = std::fs::OpenOptions::new() - .read(true) - .write(true) - .create(true) - .truncate(true) - .open(&path) - .map_err(|e| format!("{}: {e}", path.display()))?; - let stdout = file.try_clone().map_err(|e| e.to_string())?; - let stderr = file.try_clone().map_err(|e| e.to_string())?; + let serial = COUNTER.fetch_add(1, Ordering::Relaxed); + let out_path = temp_path("out", serial); + let err_path = temp_path("err", serial); + let mut out_file = create(&out_path)?; + let mut err_file = create(&err_path)?; + let stdout = out_file.try_clone().map_err(|e| e.to_string())?; + let stderr = err_file.try_clone().map_err(|e| e.to_string())?; let mut command = Command::new("sh"); command @@ -63,8 +67,8 @@ pub fn bash( command.pre_exec(|| { // rlim_t is u32 on i686 and u64 on x86-64. let limit = libc::rlimit { - rlim_cur: MAX_OUTPUT_BYTES as libc::rlim_t, - rlim_max: MAX_OUTPUT_BYTES as libc::rlim_t, + rlim_cur: MAX_FILE_BYTES as libc::rlim_t, + rlim_max: MAX_FILE_BYTES as libc::rlim_t, }; if libc::setrlimit(libc::RLIMIT_FSIZE, &limit) != 0 { return Err(std::io::Error::last_os_error()); @@ -103,38 +107,97 @@ pub fn bash( // A child that blew the file-size limit was killed by SIGXFSZ. let over_limit = status.signal() == Some(libc::SIGXFSZ); - let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?; - drop(file); - let _ = std::fs::remove_file(&path); + let (out_text, out_cut) = read_capped(&mut out_file, head_budget, tail_budget)?; + let (err_text, err_cut) = read_capped(&mut err_file, head_budget, tail_budget)?; + drop(out_file); + drop(err_file); + let _ = std::fs::remove_file(&out_path); + let _ = std::fs::remove_file(&err_path); - let mut out = output; - if !out.is_empty() && !out.ends_with('\n') { - out.push('\n'); - } - if over_limit { - out.push_str(&format!( + let marker = if over_limit { + format!( "[output exceeded {} MiB; command killed]", - MAX_OUTPUT_BYTES / (1024 * 1024) - )); + MAX_FILE_BYTES / (1024 * 1024) + ) } else if aborted { - out.push_str("[aborted by the user]"); + "[aborted by the user]".to_string() } else if timed_out { - out.push_str(&format!( - "[timed out after {:.1}s; process killed]", - timeout.as_secs_f64() - )); + format!("[timed out after {:.1}s; process killed]", timeout.as_secs_f64()) } else { match status.code() { - Some(code) => out.push_str(&format!("[exit {code}]")), - None => { - out.push_str(&format!( - "[killed by signal {}]", - status.signal().unwrap_or_default() - )); - } + Some(code) => format!("[exit {code}]"), + None => format!( + "[killed by signal {}]", + status.signal().unwrap_or_default() + ), } + }; + + Ok(format_result( + &out_text, out_cut, &err_text, err_cut, &marker, + )) +} + +/// stdout and stderr are kept apart: a program that prints its real error to +/// stderr used to be indistinguishable from one that printed it to stdout. +/// Labelling only appears when it carries information. +fn format_result( + stdout: &str, + stdout_truncated: bool, + stderr: &str, + stderr_truncated: bool, + marker: &str, +) -> String { + let has_stdout = !stdout.trim().is_empty(); + let has_stderr = !stderr.trim().is_empty(); + + let mut out = String::new(); + if has_stdout && has_stderr { + out.push_str("[stdout]\n"); + out.push_str(stdout); + end_line(&mut out, stdout); + out.push_str("[stderr]\n"); + out.push_str(stderr); + end_line(&mut out, stderr); + } else if has_stderr { + out.push_str("[stderr]\n"); + out.push_str(stderr); + end_line(&mut out, stderr); + } else if has_stdout { + out.push_str(stdout); + end_line(&mut out, stdout); } - Ok(out) + + let truncated = stdout_truncated || stderr_truncated; + out.push_str(marker); + if truncated { + out.push_str(" (output truncated; raise max_bytes or narrow the command)"); + } + out +} + +fn end_line(out: &mut String, text: &str) { + if !text.is_empty() && !text.ends_with('\n') { + out.push('\n'); + } +} + +fn temp_path(kind: &str, serial: u64) -> PathBuf { + std::env::temp_dir().join(format!( + "agent686-{}-{}-{kind}.log", + std::process::id(), + serial + )) +} + +fn create(path: &PathBuf) -> Result { + std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(true) + .open(path) + .map_err(|e| format!("{}: {e}", path.display())) } fn resolve_cwd(cwd: Option<&str>) -> Result { @@ -152,26 +215,32 @@ fn resolve_cwd(cwd: Option<&str>) -> Result { }) } -fn read_capped(file: &mut File) -> Result { +/// Reads at most `head` bytes from the start and `tail` from the end, noting +/// what was dropped. Returns the text and whether anything was cut. +fn read_capped(file: &mut File, head: usize, tail: usize) -> Result<(String, bool), String> { let len = file.metadata().map(|m| m.len()).unwrap_or(0); file.seek(SeekFrom::Start(0)).map_err(|e| e.to_string())?; - let mut out = Vec::new(); - if len <= HEAD_BYTES as u64 { - file.read_to_end(&mut out).map_err(|e| e.to_string())?; + let mut bytes = Vec::new(); + let mut truncated = false; + + if len <= (head + tail) as u64 { + file.read_to_end(&mut bytes).map_err(|e| e.to_string())?; } else { - file.take(HEAD_BYTES as u64) - .read_to_end(&mut out) + truncated = true; + file.take(head as u64) + .read_to_end(&mut bytes) .map_err(|e| e.to_string())?; - let omitted = len.saturating_sub(HEAD_BYTES as u64 + TAIL_BYTES as u64); - out.extend_from_slice(format!("\n… {omitted} bytes omitted …\n").as_bytes()); - file.seek(SeekFrom::End(-TAIL_BYTES)) + let omitted = len.saturating_sub(head as u64 + tail as u64); + bytes.extend_from_slice(format!("\n… {omitted} bytes omitted …\n").as_bytes()); + file.seek(SeekFrom::End(-(tail as i64))) .map_err(|e| e.to_string())?; - let mut tail = Vec::new(); - file.read_to_end(&mut tail).map_err(|e| e.to_string())?; - out.extend_from_slice(&tail); + let mut rest = Vec::new(); + file.read_to_end(&mut rest).map_err(|e| e.to_string())?; + bytes.extend_from_slice(&rest); } - Ok(String::from_utf8_lossy(&out).into_owned()) + + Ok((String::from_utf8_lossy(&bytes).into_owned(), truncated)) } /// SIGKILL the whole process group the command created. `child.kill()` would -- cgit v1.2.3