From 343f2a8a6148b8004d6f4d74fb779b4f30c9686a Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 03:11:22 +0100 Subject: M1-M5: sessions, six tools, approvals, prompt, Ctrl-C, target gate - append-only JSONL sessions with --continue/--session; reasoning stored, stripped on replay - read/write/edit/grep/glob + bash with timeout and capped output - diff-preview approval for the first edit of a session, per-call approval for bash - system prompt frozen per session with AGENTS.md snapshot and change warning - SIGINT aborts the turn, second Ctrl-C exits - glibc gate ignores weak symbols; verified in linux/386 debian:12 - acceptance test (calculator in C) passes on both x86-64 and i386 --- src/tools/shell.rs | 129 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 src/tools/shell.rs (limited to 'src/tools/shell.rs') diff --git a/src/tools/shell.rs b/src/tools/shell.rs new file mode 100644 index 0000000..9c214fb --- /dev/null +++ b/src/tools/shell.rs @@ -0,0 +1,129 @@ +use std::fs::File; +use std::io::{Read, Seek, SeekFrom}; +use std::path::PathBuf; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use serde_json::Value; + +const HEAD_BYTES: usize = 64 * 1024; +const TAIL_BYTES: i64 = 16 * 1024; +static COUNTER: AtomicU64 = AtomicU64::new(0); + +pub fn bash(args: &Value, timeout: Duration) -> Result { + let cmd = match args.get("cmd").and_then(|v| v.as_str()) { + Some(cmd) => cmd.to_string(), + None => return Err("missing required argument `cmd`".into()), + }; + + 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 mut child = Command::new("sh") + .arg("-c") + .arg(&cmd) + .current_dir(&cwd) + .stdin(Stdio::null()) + .stdout(Stdio::from(stdout)) + .stderr(Stdio::from(stderr)) + .spawn() + .map_err(|e| format!("failed to start sh: {e}"))?; + + let deadline = Instant::now() + timeout; + let mut timed_out = false; + let status = loop { + match child.try_wait().map_err(|e| e.to_string())? { + Some(status) => break status, + None => { + if Instant::now() >= deadline { + let _ = child.kill(); + timed_out = true; + break child.wait().map_err(|e| e.to_string())?; + } + std::thread::sleep(Duration::from_millis(20)); + } + } + }; + + let output = read_capped(&mut file).map_err(|e| format!("could not read output: {e}"))?; + drop(file); + let _ = std::fs::remove_file(&path); + + let mut out = output; + if !out.is_empty() && !out.ends_with('\n') { + out.push('\n'); + } + if timed_out { + out.push_str(&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 => { + use std::os::unix::process::ExitStatusExt; + out.push_str(&format!( + "[killed by signal {}]", + status.signal().unwrap_or_default() + )); + } + } + } + Ok(out) +} + +fn resolve_cwd(cwd: Option<&str>) -> Result { + let current = std::env::current_dir().map_err(|e| e.to_string())?; + Ok(match cwd { + Some(dir) => { + let path = PathBuf::from(dir); + if path.is_absolute() { + path + } else { + current.join(path) + } + } + None => current, + }) +} + +fn read_capped(file: &mut File) -> Result { + 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())?; + } else { + file.take(HEAD_BYTES as u64) + .read_to_end(&mut out) + .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)) + .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); + } + Ok(String::from_utf8_lossy(&out).into_owned()) +} -- cgit v1.2.3