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/fs.rs | 527 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/tools/mod.rs | 148 +++++++++++++++ src/tools/shell.rs | 129 +++++++++++++ 3 files changed, 804 insertions(+) create mode 100644 src/tools/fs.rs create mode 100644 src/tools/mod.rs create mode 100644 src/tools/shell.rs (limited to 'src/tools') diff --git a/src/tools/fs.rs b/src/tools/fs.rs new file mode 100644 index 0000000..6addf8d --- /dev/null +++ b/src/tools/fs.rs @@ -0,0 +1,527 @@ +use std::fs; +use std::path::{Path, PathBuf}; + +use serde_json::Value; + +const MAX_LINE_CHARS: usize = 400; +const MAX_READ_LINES: usize = 2000; +const MAX_MATCHES: usize = 200; +const MAX_SCAN_BYTES: u64 = 4 * 1024 * 1024; +const PREVIEW_BUDGET: usize = 60; + +const SKIP_DIRS: &[&str] = &[ + ".git", + "target", + "node_modules", + "dist", + "build", + ".venv", + "vendor", + ".cache", +]; + +/// A pending file change. Built and previewed first, applied only after the +/// human agrees. +pub enum Change { + Write { path: String, content: String }, + Edit { path: String, old: String, new: String, text: String }, +} + +impl Change { + pub fn path(&self) -> &str { + match self { + Change::Write { path, .. } | Change::Edit { path, .. } => path, + } + } + + pub fn preview(&self) -> String { + match self { + Change::Write { path, content } => match fs::read_to_string(path) { + Ok(old) if old == *content => format!("{path}: unchanged"), + Ok(old) => diff_preview(&old, content), + Err(_) => new_file_preview(path, content), + }, + Change::Edit { + path, + old, + new, + text, + } => { + let at = text.find(old.as_str()).unwrap_or(0); + edit_preview(path, text, old, new, at) + } + } + } + + pub fn apply(self) -> Result { + match self { + Change::Write { path, content } => { + let parent = Path::new(&path).parent(); + if let Some(parent) = parent { + if !parent.as_os_str().is_empty() && !parent.is_dir() { + return Err(format!( + "parent directory does not exist: {} (create it with bash first)", + parent.display() + )); + } + } + fs::write(&path, &content).map_err(|e| format!("{path}: {e}"))?; + Ok(format!( + "wrote {} bytes ({} lines) to {path}", + content.len(), + content.lines().count() + )) + } + Change::Edit { + path, + old, + new, + mut text, + } => { + let at = text + .find(old.as_str()) + .ok_or_else(|| format!("{path}: text to replace disappeared"))?; + let line = text[..at].matches('\n').count() + 1; + text.replace_range(at..at + old.len(), &new); + fs::write(&path, &text).map_err(|e| format!("{path}: {e}"))?; + Ok(format!("edited {path}: 1 replacement at line {line}")) + } + } + } +} + +pub fn plan_write(args: &Value) -> Result { + Ok(Change::Write { + path: req(args, "path")?, + content: req(args, "content")?, + }) +} + +pub fn plan_edit(args: &Value) -> Result { + let path = req(args, "path")?; + let old = req(args, "old")?; + let new = req(args, "new")?; + if old.is_empty() { + return Err("`old` must not be empty; use write to create a file".into()); + } + let text = fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?; + let hits: Vec = text.match_indices(&old).map(|(i, _)| i).collect(); + match hits.len() { + 0 => Err(format!( + "text to replace was not found in {path}. Read the file and copy the exact \ + text, including indentation." + )), + 1 => Ok(Change::Edit { + path, + old, + new, + text, + }), + n => Err(format!( + "text to replace appears {n} times in {path} (lines {}); include more \ + surrounding context so it is unique.", + line_list(&text, &hits) + )), + } +} + +pub fn read(args: &Value) -> Result { + let path = req(args, "path")?; + let offset = args + .get("offset") + .and_then(|v| v.as_u64()) + .unwrap_or(1) + .max(1) as usize; + let limit = args + .get("limit") + .and_then(|v| v.as_u64()) + .unwrap_or(MAX_READ_LINES as u64) + .clamp(1, MAX_READ_LINES as u64) as usize; + + let bytes = fs::read(&path).map_err(|e| format!("{path}: {e}"))?; + if bytes.iter().take(8192).any(|&b| b == 0) { + return Err(format!( + "{path}: looks like a binary file and will not be shown" + )); + } + let text = String::from_utf8_lossy(&bytes); + let lines: Vec<&str> = text.lines().collect(); + if lines.is_empty() { + return Ok(format!("{path}: empty file")); + } + if offset > lines.len() { + return Ok(format!( + "{path} has {} lines; offset {offset} is past the end", + lines.len() + )); + } + + let end = (offset + limit - 1).min(lines.len()); + let mut out = String::with_capacity((end - offset + 2) * 40); + for number in offset..=end { + out.push_str(&format!( + "{number:>6}\t{}\n", + clip(lines[number - 1], MAX_LINE_CHARS) + )); + } + if end < lines.len() { + out.push_str(&format!( + "… {} more line(s); continue with offset={}\n", + lines.len() - end, + end + 1 + )); + } + Ok(out) +} + +pub fn grep(args: &Value) -> Result { + let pattern = req(args, "pattern")?; + if pattern.is_empty() { + return Err("pattern must not be empty".into()); + } + let base = args + .get("path") + .and_then(|v| v.as_str()) + .unwrap_or(".") + .to_string(); + let ignore_case = args + .get("ignore_case") + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let needle = if ignore_case { + pattern.to_lowercase() + } else { + pattern.clone() + }; + + let root = Path::new(&base); + let files = if root.is_file() { + vec![root.to_path_buf()] + } else { + let mut files = Vec::new(); + walk(root, &mut files); + files + }; + + let mut out = String::new(); + let mut matches = 0usize; + for file in files { + if matches >= MAX_MATCHES { + break; + } + grep_file(&file, &needle, ignore_case, &mut matches, &mut out); + } + + if matches == 0 { + return Ok(format!("no matches for `{pattern}` under {base}")); + } + if matches >= MAX_MATCHES { + out.push_str(&format!("… stopped after {MAX_MATCHES} matches\n")); + } + Ok(out) +} + +pub fn glob(args: &Value) -> Result { + let pattern = req(args, "pattern")?; + let base = args + .get("path") + .and_then(|v| v.as_str()) + .unwrap_or(".") + .to_string(); + let root = Path::new(&base); + if !root.is_dir() { + return Err(format!("not a directory: {base}")); + } + + let mut files = Vec::new(); + walk(root, &mut files); + + // A pattern without a slash is matched against the file name at any depth. + let bare = !pattern.contains('/'); + let mut hits = Vec::new(); + for file in files { + let name = file.file_name().and_then(|n| n.to_str()).unwrap_or(""); + let hit = if bare { + wildcard_match(pattern.as_bytes(), name.as_bytes()) + } else { + let relative = file + .strip_prefix(root) + .unwrap_or(&file) + .to_string_lossy() + .to_string(); + glob_match(&pattern, &relative) + }; + if hit { + hits.push(file); + if hits.len() >= MAX_MATCHES { + break; + } + } + } + + if hits.is_empty() { + return Ok(format!("no files match `{pattern}` under {base}")); + } + + let mut out = String::new(); + for hit in &hits { + out.push_str(&hit.display().to_string()); + out.push('\n'); + } + if hits.len() >= MAX_MATCHES { + out.push_str(&format!("… stopped after {MAX_MATCHES} files\n")); + } + Ok(out) +} + +fn grep_file(path: &Path, needle_lower: &str, ignore_case: bool, count: &mut usize, out: &mut String) { + let meta = match fs::metadata(path) { + Ok(m) => m, + Err(_) => return, + }; + if meta.len() > MAX_SCAN_BYTES { + return; + } + let bytes = match fs::read(path) { + Ok(b) => b, + Err(_) => return, + }; + if bytes.iter().take(8192).any(|&b| b == 0) { + return; + } + let text = String::from_utf8_lossy(&bytes); + let mut needle = needle_lower.to_string(); + if !ignore_case { + needle = needle.to_string(); + } + + for (index, line) in text.lines().enumerate() { + if *count >= MAX_MATCHES { + return; + } + let hit = if ignore_case { + line.to_lowercase().contains(&needle) + } else { + line.contains(&needle) + }; + if hit { + *count += 1; + out.push_str(&format!( + "{}:{}: {}\n", + path.display(), + index + 1, + clip(line.trim_end(), 200) + )); + } + } +} + +fn walk(dir: &Path, out: &mut Vec) { + let entries = match fs::read_dir(dir) { + Ok(entries) => entries, + Err(_) => return, + }; + for entry in entries.flatten() { + let file_type = match entry.file_type() { + Ok(t) => t, + Err(_) => continue, + }; + let path = entry.path(); + if file_type.is_dir() { + let name = entry.file_name(); + if SKIP_DIRS.iter().any(|skip| name == *skip) { + continue; + } + walk(&path, out); + } else if file_type.is_file() { + out.push(path); + } + } +} + +fn glob_match(pattern: &str, path: &str) -> bool { + let p: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect(); + let s: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect(); + match_segments(&p, &s) +} + +fn match_segments(pattern: &[&str], path: &[&str]) -> bool { + match pattern.split_first() { + None => path.is_empty(), + Some((&"**", rest)) => { + if match_segments(rest, path) { + return true; + } + for skip in 0..path.len() { + if match_segments(rest, &path[skip + 1..]) { + return true; + } + } + false + } + Some((segment, rest)) => match path.split_first() { + None => false, + Some((name, tail)) => { + wildcard_match(segment.as_bytes(), name.as_bytes()) && match_segments(rest, tail) + } + }, + } +} + +fn wildcard_match(pattern: &[u8], text: &[u8]) -> bool { + match pattern.split_first() { + None => text.is_empty(), + Some((&b'*', rest)) => (0..=text.len()).any(|skip| wildcard_match(rest, &text[skip..])), + Some((&b'?', rest)) => !text.is_empty() && wildcard_match(rest, &text[1..]), + Some((byte, rest)) => match text.split_first() { + Some((first, tail)) => first == byte && wildcard_match(rest, tail), + None => false, + }, + } +} + +fn new_file_preview(path: &str, content: &str) -> String { + let lines: Vec<&str> = content.lines().collect(); + let mut out = format!("@@ new file {path} ({} lines) @@\n", lines.len()); + for line in lines.iter().take(PREVIEW_BUDGET) { + out.push_str(&format!("+ {}\n", clip(line, 200))); + } + if lines.len() > PREVIEW_BUDGET { + out.push_str(&format!("… {} more line(s)\n", lines.len() - PREVIEW_BUDGET)); + } + out +} + +fn diff_preview(old: &str, new: &str) -> String { + let a: Vec<&str> = old.lines().collect(); + let b: Vec<&str> = new.lines().collect(); + + let mut prefix = 0; + while prefix < a.len() && prefix < b.len() && a[prefix] == b[prefix] { + prefix += 1; + } + let mut suffix = 0; + while suffix < a.len().saturating_sub(prefix) + && suffix < b.len().saturating_sub(prefix) + && a[a.len() - 1 - suffix] == b[b.len() - 1 - suffix] + { + suffix += 1; + } + + let start = prefix.saturating_sub(2); + let a_end = a.len() - suffix; + let b_end = b.len() - suffix; + + let mut out = format!( + "@@ -{},{} +{},{} @@\n", + start + 1, + a_end.saturating_sub(start), + start + 1, + b_end.saturating_sub(start) + ); + let mut budget = PREVIEW_BUDGET; + + for line in &a[start..prefix] { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!(" {}\n", clip(line, 200))); + } + for line in &a[prefix..a_end] { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!("- {}\n", clip(line, 200))); + } + for line in &b[prefix..b_end] { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!("+ {}\n", clip(line, 200))); + } + for line in a[a_end..(a_end + 2).min(a.len())].iter() { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!(" {}\n", clip(line, 200))); + } + if budget == 0 { + out.push_str("… diff truncated\n"); + } + out +} + +fn edit_preview(path: &str, text: &str, old: &str, new: &str, at: usize) -> String { + let lines: Vec<&str> = text.lines().collect(); + let line_no = text[..at].matches('\n').count() + 1; + let old_lines = old.lines().count().max(1); + + let mut out = format!("@@ {path}:{line_no} @@\n"); + let mut budget = PREVIEW_BUDGET; + + let before_start = (line_no - 1).saturating_sub(2); + for line in &lines[before_start..line_no.saturating_sub(1)] { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!(" {}\n", clip(line, 200))); + } + for line in old.lines() { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!("- {}\n", clip(line, 200))); + } + for line in new.lines() { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!("+ {}\n", clip(line, 200))); + } + let after_start = (line_no - 1 + old_lines).min(lines.len()); + for line in &lines[after_start..(after_start + 2).min(lines.len())] { + if budget == 0 { + break; + } + budget -= 1; + out.push_str(&format!(" {}\n", clip(line, 200))); + } + if budget == 0 { + out.push_str("… diff truncated\n"); + } + out +} + +fn line_list(text: &str, offsets: &[usize]) -> String { + let mut numbers: Vec = offsets + .iter() + .take(10) + .map(|&at| (text[..at].matches('\n').count() + 1).to_string()) + .collect(); + if offsets.len() > 10 { + numbers.push("…".into()); + } + numbers.join(", ") +} + +fn req(args: &Value, key: &str) -> Result { + match args.get(key).and_then(|v| v.as_str()) { + Some(value) => Ok(value.to_string()), + None => Err(format!("missing required argument `{key}`")), + } +} + +fn clip(s: &str, max: usize) -> String { + if s.chars().count() <= max { + return s.to_string(); + } + let cut: String = s.chars().take(max).collect(); + format!("{cut}…") +} diff --git a/src/tools/mod.rs b/src/tools/mod.rs new file mode 100644 index 0000000..503de08 --- /dev/null +++ b/src/tools/mod.rs @@ -0,0 +1,148 @@ +pub mod fs; +pub mod shell; + +use serde_json::{json, Value}; + +use fs::Change; + +/// When a tool needs a human before it runs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Approval { + /// Read-only or harmless. + Never, + /// Prompts on first use per session, then remembers. + Once, + /// Prompts on every call, no memory. + EveryCall, +} + +pub fn approval(name: &str) -> Approval { + match name { + "write" | "edit" => Approval::Once, + "bash" => Approval::EveryCall, + _ => Approval::Never, + } +} + +/// Tools that execute immediately. +pub fn run(name: &str, args: &Value) -> Result { + match name { + "read" => fs::read(args), + "grep" => fs::grep(args), + "glob" => fs::glob(args), + "bash" => shell::bash(args, std::time::Duration::from_secs(120)), + other => Err(unknown(other)), + } +} + +/// Tools that produce a change needing approval before it is applied. +pub fn plan(name: &str, args: &Value) -> Result { + match name { + "write" => fs::plan_write(args), + "edit" => fs::plan_edit(args), + other => Err(unknown(other)), + } +} + +fn unknown(name: &str) -> String { + format!("unknown tool `{name}`; available: read, write, edit, bash, grep, glob") +} + +/// Static and in a fixed order, so the serialised prefix never changes. +pub fn schemas() -> Vec { + vec![ + json!({ + "type": "function", + "function": { + "name": "read", + "description": "Read a text file. Returns numbered lines. Read before editing.", + "parameters": { + "type": "object", + "properties": { + "path": { "type": "string", "description": "file path" }, + "offset": { "type": "integer", "description": "first line, 1-based (default 1)" }, + "limit": { "type": "integer", "description": "maximum lines (default and cap 2000)" } + }, + "required": ["path"] + } + } + }), + json!({ + "type": "function", + "function": { + "name": "write", + "description": "Create or replace a whole file. The parent directory must already exist.", + "parameters": { + "type": "object", + "properties": { + "path": { "type": "string" }, + "content": { "type": "string" } + }, + "required": ["path", "content"] + } + } + }), + json!({ + "type": "function", + "function": { + "name": "edit", + "description": "Replace one exact occurrence of `old` with `new`. Fails if `old` is missing or appears more than once, so include enough context to be unique.", + "parameters": { + "type": "object", + "properties": { + "path": { "type": "string" }, + "old": { "type": "string", "description": "exact existing text, including indentation" }, + "new": { "type": "string", "description": "replacement text" } + }, + "required": ["path", "old", "new"] + } + } + }), + json!({ + "type": "function", + "function": { + "name": "bash", + "description": "Run a shell command. Each call is a fresh shell at the working directory, so `cd` does not persist; pass cwd instead. Times out after 120s. Returns combined output and the exit code.", + "parameters": { + "type": "object", + "properties": { + "cmd": { "type": "string" }, + "cwd": { "type": "string", "description": "working directory (default: project root)" } + }, + "required": ["cmd"] + } + } + }), + json!({ + "type": "function", + "function": { + "name": "grep", + "description": "Search file contents for a literal string, recursively. Skips .git, target, node_modules and similar.", + "parameters": { + "type": "object", + "properties": { + "pattern": { "type": "string" }, + "path": { "type": "string", "description": "file or directory (default .)" }, + "ignore_case": { "type": "boolean" } + }, + "required": ["pattern"] + } + } + }), + json!({ + "type": "function", + "function": { + "name": "glob", + "description": "List files matching a glob. Supports *, ? and ** across path segments, e.g. **/*.rs.", + "parameters": { + "type": "object", + "properties": { + "pattern": { "type": "string" }, + "path": { "type": "string", "description": "directory to search (default .)" } + }, + "required": ["pattern"] + } + } + }), + ] +} 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