//! Tool registry, validation, built-in file effects, and the durable //! outcome boundary between successful effects and recorded session frames. use crate::frame::{Frame, canonical_json}; use crate::session::{Entry, EntryContent, Session}; use crate::store::SessionWriter; use smith::error::{Result, SmithError}; use smith::id::ToolCallId; use smith::tool::ToolMetadata; use std::collections::HashMap; use std::fs; use std::io::{BufRead, BufReader, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicUsize, Ordering}; const HARD_OUTPUT_CAP: usize = 256 * 1024; const DEFAULT_OUTPUT_CAP: usize = 64 * 1024; const MAX_LIST_ENTRIES: usize = 1000; const MAX_GREP_MATCHES: usize = 200; const MAX_EDIT_FILE_BYTES: usize = 8 * 1024 * 1024; /// Registry of available tools. #[derive(Clone, Debug, Default)] pub struct ToolRegistry { /// Tools by name. pub tools: HashMap, } impl ToolRegistry { /// An empty registry. pub fn new() -> Self { Self::default() } /// Register or replace a tool definition. pub fn register(&mut self, meta: ToolMetadata) { self.tools.insert(meta.name.clone(), meta); } /// A registry with the seven built-in coding tools and real schemas. pub fn with_builtins() -> Self { let mut reg = Self::new(); for meta in builtin_tools() { reg.register(meta); } reg } } /// Built-in tool definitions with schemas used for argument validation. pub fn builtin_tools() -> Vec { let object = |required: &[&str], props: serde_json::Value| { serde_json::json!({ "type": "object", "required": required, "properties": props, }) }; vec![ ToolMetadata::new("read", "Read a bounded line window from a file.").with_schema(object( &["path"], serde_json::json!({ "path": {"type": "string"}, "offset": {"type": "integer"}, "limit": {"type": "integer"}, "max_bytes": {"type": "integer"}, }), )), ToolMetadata::new("write", "Atomically replace a file, creating parents.").with_schema( object( &["path", "content"], serde_json::json!({ "path": {"type": "string"}, "content": {"type": "string"}, }), ), ), ToolMetadata::new("edit", "Apply one exact, unambiguous replacement.").with_schema(object( &["path", "old_string", "new_string"], serde_json::json!({ "path": {"type": "string"}, "old_string": {"type": "string"}, "new_string": {"type": "string"}, }), )), ToolMetadata::new("ls", "List a directory deterministically.") .with_schema(object(&[], serde_json::json!({"path": {"type": "string"}}))), ToolMetadata::new("find", "Find directory entries matching a substring.").with_schema( object( &["pattern"], serde_json::json!({ "path": {"type": "string"}, "pattern": {"type": "string"}, }), ), ), ToolMetadata::new("grep", "Return bounded matching lines from a file.").with_schema( object( &["path", "query"], serde_json::json!({ "path": {"type": "string"}, "query": {"type": "string"}, }), ), ), ToolMetadata::new("bash", "Run a bounded cancellable shell command.").with_schema(object( &["command"], serde_json::json!({ "command": {"type": "string"}, "timeout_ms": {"type": "integer"}, }), )), ] } /// Bundles the registry, the live session, and the durable writer so a /// successful mutation can never be reported while its recording failed. pub struct ToolSession { registry: ToolRegistry, /// Live session state; entries are appended as they are recorded. pub session: Session, writer: Option, /// All file effects resolve relative to this directory. pub working_dir: PathBuf, } impl ToolSession { /// A tool session over built-in tools, no persistence. pub fn new(working_dir: impl Into) -> Self { Self { registry: ToolRegistry::with_builtins(), session: Session::new(), writer: None, working_dir: working_dir.into(), } } /// Attach a durable writer; every recorded entry is appended to it. pub fn with_writer(working_dir: impl Into, writer: SessionWriter) -> Self { Self { writer: Some(writer), ..Self::new(working_dir) } } /// Register or replace a tool definition. pub fn register(&mut self, meta: ToolMetadata) { self.registry.register(meta); } /// Validate arguments against the registered schema (required fields and /// declared property types) before any effect can run. pub fn validate(&self, name: &str, input: &serde_json::Value) -> Result<()> { let meta = self.registry.tools.get(name).ok_or_else(|| { tool_err( "TOOL_NOT_REGISTERED", format!("tool '{name}' not registered"), ) })?; let obj = input .as_object() .ok_or_else(|| tool_err("INVALID_INPUT", "input must be a JSON object"))?; let schema = &meta.input_schema; for req in schema .get("required") .and_then(|v| v.as_array()) .into_iter() .flatten() { let key = req.as_str().unwrap_or_default(); if !obj.contains_key(key) { return Err(tool_err( "VALIDATION", format!("missing required field '{key}' for tool '{name}'"), )); } } if let Some(props) = schema.get("properties").and_then(|v| v.as_object()) { for (key, value) in obj { if let Some(expected) = props .get(key) .and_then(|p| p.get("type")) .and_then(|t| t.as_str()) { if !json_type_matches(expected, value) { return Err(tool_err( "VALIDATION", format!("field '{key}' for tool '{name}' must be of type {expected}"), )); } } } } Ok(()) } /// Validate, execute, and durably record one tool call. /// /// Recording order: call entry, effect, result entry. If the effect /// succeeds but any recording step fails, an explicit `RECORD_FAILED` /// error is returned instead of an unrecorded success. pub fn invoke(&mut self, name: &str, input: serde_json::Value) -> Result { self.validate(name, &input)?; let call_id = ToolCallId::new(); let canonical_input = canonical_json(&input); let parent = self.session.selected_id(); // Execute the effect. let effect = execute_file_effect(name, &canonical_input, &self.working_dir); let ok = effect.is_ok(); let output = match &effect { Ok(text) => text.clone(), Err(err) => err.to_string(), }; let outcome = ToolOutcome { call_id, name: name.to_string(), ok, output: output.clone(), timestamp_ms: now_ms(), }; // Record call entry. self.record_entry(Entry::new( parent, EntryContent::ToolCall { name: name.to_string(), input: canonical_input, call_id, }, ))?; // Record result entry. self.record_entry(Entry::new( self.session.selected_id(), EntryContent::ToolResult { ok, output, call_id, }, ))?; effect.map(move |_| outcome) } fn record_entry(&mut self, entry: Entry) -> Result<()> { if let Some(writer) = &mut self.writer { writer.append_frame(&Frame::Known { entry: entry.clone(), })?; } self.session.append_to_active(entry); Ok(()) } } /// A recorded tool outcome returned to the caller. #[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)] pub struct ToolOutcome { /// Tool call ID. pub call_id: ToolCallId, /// Tool name. pub name: String, /// Whether the effect succeeded. pub ok: bool, /// Recorded output or error message. pub output: String, /// Timestamp of outcome. pub timestamp_ms: i64, } fn tool_err(code: &str, message: impl Into) -> SmithError { SmithError::Tool { code: code.to_string(), message: message.into(), } } fn io_tool_err(code: &'static str) -> impl Fn(std::io::Error) -> SmithError { move |e| tool_err(code, e.to_string()) } fn json_type_matches(expected: &str, value: &serde_json::Value) -> bool { match expected { "string" => value.is_string(), "number" => value.is_number(), "integer" => value.is_i64() || value.is_u64(), "boolean" => value.is_boolean(), "array" => value.is_array(), "object" => value.is_object(), "null" => value.is_null(), _ => true, } } fn resolve_path(input_path: &str, working_dir: &Path) -> PathBuf { let p = Path::new(input_path); if p.is_absolute() { p.to_path_buf() } else { working_dir.join(p) } } /// Execute a built-in file effect. All outputs are bounded and deterministic; /// filesystem errors are surfaced, never converted to empty success. fn execute_file_effect( name: &str, input: &serde_json::Value, working_dir: &Path, ) -> std::result::Result { let path_str = input.get("path").and_then(|v| v.as_str()).unwrap_or(""); match name { "read" => { let path = resolve_path(path_str, working_dir); let offset = input.get("offset").and_then(|v| v.as_u64()).unwrap_or(0) as usize; let limit = input .get("limit") .and_then(|v| v.as_u64()) .map(|v| v.min(usize::MAX as u64) as usize) .unwrap_or(usize::MAX); let max_bytes = input .get("max_bytes") .and_then(|v| v.as_u64()) .map(|v| (v as usize).min(HARD_OUTPUT_CAP)) .unwrap_or(DEFAULT_OUTPUT_CAP); read_bounded(&path, offset, limit, max_bytes) } "write" => { let content = input .get("content") .and_then(|v| v.as_str()) .ok_or_else(|| tool_err("VALIDATION", "write requires string 'content'"))?; let path = resolve_path(path_str, working_dir); write_atomic(&path, content.as_bytes())?; Ok(format!("written {} bytes", content.len())) } "edit" => { let old = input .get("old_string") .and_then(|v| v.as_str()) .unwrap_or_default(); let new = input .get("new_string") .and_then(|v| v.as_str()) .unwrap_or_default(); let path = resolve_path(path_str, working_dir); edit_exact(&path, old, new) } "ls" => { let dir = if path_str.is_empty() { working_dir.to_path_buf() } else { resolve_path(path_str, working_dir) }; let mut names: Vec = fs::read_dir(&dir) .map_err(io_tool_err("LS_ERROR"))? .collect::>>() .map_err(io_tool_err("LS_ERROR"))? .into_iter() .map(|e| e.file_name().to_string_lossy().into_owned()) .collect(); names.sort(); Ok(bounded_join(names, MAX_LIST_ENTRIES)) } "find" => { let pattern = input .get("pattern") .and_then(|v| v.as_str()) .unwrap_or_default(); let root = if path_str.is_empty() { working_dir.to_path_buf() } else { resolve_path(path_str, working_dir) }; let mut names: Vec = fs::read_dir(&root) .map_err(io_tool_err("FIND_ERROR"))? .collect::>>() .map_err(io_tool_err("FIND_ERROR"))? .into_iter() .map(|e| e.file_name().to_string_lossy().into_owned()) .filter(|n| n.contains(pattern)) .collect(); names.sort(); Ok(bounded_join(names, MAX_LIST_ENTRIES)) } "grep" => { let query = input .get("query") .and_then(|v| v.as_str()) .unwrap_or_default(); let path = resolve_path(path_str, working_dir); grep_bounded(&path, query) } _ => Err(tool_err( "TOOL_NOT_IMPLEMENTED", format!("tool '{name}' has no built-in effect"), )), } } /// Read a bounded line window without materializing the whole file. fn read_bounded( path: &Path, offset: usize, limit: usize, max_bytes: usize, ) -> std::result::Result { let file = fs::File::open(path).map_err(io_tool_err("READ_ERROR"))?; let mut reader = BufReader::with_capacity(64 * 1024, file); // Binary sniff on the first bytes. let sniff = reader.fill_buf().map_err(io_tool_err("READ_ERROR"))?; if sniff[..sniff.len().min(8192)].contains(&0) { return Err(tool_err( "BINARY_CONTENT", "file contains NUL bytes; binary content is unsupported", )); } let mut out = String::new(); let mut buf: Vec = Vec::with_capacity(8 * 1024); let mut line_no = 0usize; let mut bytes_out = 0usize; loop { buf.clear(); match reader.read_until(b'\n', &mut buf) { Ok(0) => break, Ok(_) => {} Err(e) => return Err(io_tool_err("READ_ERROR")(e)), } line_no += 1; if line_no <= offset { continue; } if out.lines().count() >= limit.min(usize::MAX - 1) && limit != usize::MAX { // limit counts lines emitted } let emit = if limit == usize::MAX { true } else { (line_no - offset) <= limit }; if !emit { break; } if bytes_out + buf.len() > max_bytes { break; // keep fitting prefix only } bytes_out += buf.len(); out.push_str(&String::from_utf8_lossy(&buf)); if bytes_out >= max_bytes { break; } } Ok(out) } /// Atomically replace `path` with `content`: temp file in the same /// directory, synced, then renamed over the destination. fn write_atomic(path: &Path, content: &[u8]) -> std::result::Result<(), SmithError> { let parent = path.parent().filter(|p| !p.as_os_str().is_empty()); if let Some(parent) = parent { fs::create_dir_all(parent).map_err(io_tool_err("WRITE_MKDIR"))?; } let tmp = temp_sibling(path); let write = |tmp: &Path| -> std::io::Result<()> { let mut f = fs::File::create(tmp)?; f.write_all(content)?; f.sync_all()?; Ok(()) }; write(&tmp).map_err(io_tool_err("WRITE_ERROR"))?; fs::rename(&tmp, path).map_err(|e| { let _ = fs::remove_file(&tmp); io_tool_err("WRITE_PUBLISH")(e) })?; Ok(()) } fn temp_sibling(path: &Path) -> PathBuf { static COUNTER: AtomicUsize = AtomicUsize::new(0); let n = COUNTER.fetch_add(1, Ordering::Relaxed); let name = path .file_name() .map(|s| s.to_string_lossy().into_owned()) .unwrap_or_else(|| "file".to_string()); path.with_file_name(format!(".{name}.tmp-{}-{n}", std::process::id())) } /// Apply exactly one unambiguous replacement, publishing atomically. fn edit_exact(path: &Path, old: &str, new: &str) -> std::result::Result { let meta = fs::metadata(path).map_err(io_tool_err("EDIT_READ_ERROR"))?; if meta.len() as usize > MAX_EDIT_FILE_BYTES { return Err(tool_err( "FILE_TOO_LARGE", "edit input exceeds the file size limit", )); } let bytes = fs::read(path).map_err(io_tool_err("EDIT_READ_ERROR"))?; let content = String::from_utf8(bytes) .map_err(|_| tool_err("EDIT_NOT_UTF8", "edit supports UTF-8 files only"))?; let count = content.matches(old).count(); if count == 0 { return Err(tool_err( "EDIT_NOT_FOUND", "old_string not found; file unchanged", )); } if count > 1 { return Err(tool_err( "EDIT_AMBIGUOUS", format!("old_string matches {count} locations; file unchanged"), )); } let updated = content.replacen(old, new, 1); write_atomic(path, updated.as_bytes())?; Ok("edited".to_string()) } /// Deterministic, bounded listing output. fn bounded_join(mut names: Vec, cap: usize) -> String { names.truncate(cap); let mut out = names.join("\n"); let max = DEFAULT_OUTPUT_CAP; if out.len() > max { out.truncate(max); out.push_str("\n"); } out } /// Stream matching lines with bounded memory and result count. fn grep_bounded(path: &Path, query: &str) -> std::result::Result { let file = fs::File::open(path).map_err(io_tool_err("GREP_READ_ERROR"))?; let reader = BufReader::with_capacity(64 * 1024, file); let mut matches: Vec = Vec::new(); let mut total_bytes = 0usize; for line in reader.lines() { let line = line.map_err(io_tool_err("GREP_READ_ERROR"))?; if line.contains(query) { if matches.len() >= MAX_GREP_MATCHES || total_bytes + line.len() > DEFAULT_OUTPUT_CAP { matches.push("".to_string()); break; } total_bytes += line.len(); matches.push(line); } } Ok(matches.join("\n")) } fn now_ms() -> i64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_millis() as i64) .unwrap_or(0) } #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod tests { use super::*; use std::path::PathBuf; fn workdir(tag: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("smith_tools_{}_{}", tag, std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); dir } #[test] fn write_requires_string_content_and_leaves_existing_file_untouched() { let dir = workdir("write_schema"); let target = dir.join("data.txt"); std::fs::write(&target, "original").unwrap(); let mut ts = ToolSession::new(&dir); let err = ts .invoke("write", serde_json::json!({"path": "data.txt"})) .unwrap_err(); assert_eq!(err.code(), "VALIDATION"); assert_eq!(std::fs::read_to_string(&target).unwrap(), "original"); let err = ts .invoke( "write", serde_json::json!({"path": "data.txt", "content": 42}), ) .unwrap_err(); assert_eq!(err.code(), "VALIDATION"); assert_eq!(std::fs::read_to_string(&target).unwrap(), "original"); let _ = std::fs::remove_dir_all(&dir); } #[test] fn write_creates_missing_parents_and_leaves_no_temp_files() { let dir = workdir("write_parents"); let mut ts = ToolSession::new(&dir); ts.invoke( "write", serde_json::json!({"path": "a/b/c.txt", "content": "deep"}), ) .unwrap(); assert_eq!( std::fs::read_to_string(dir.join("a/b/c.txt")).unwrap(), "deep" ); let leftovers: Vec<_> = std::fs::read_dir(&dir) .unwrap() .filter_map(|e| e.ok()) .flat_map(|e| { std::fs::read_dir(e.path()) .unwrap() .filter_map(|x| x.ok()) .map(|x| x.file_name().to_string_lossy().into_owned()) .collect::>() }) .filter(|n| n.contains(".tmp-")) .collect(); assert!( leftovers.is_empty(), "temp files left behind: {leftovers:?}" ); let _ = std::fs::remove_dir_all(&dir); } #[test] fn edit_rejects_ambiguous_and_missing_matches_without_changes() { let dir = workdir("edit_amb"); let target = dir.join("f.txt"); std::fs::write(&target, "a a").unwrap(); let mut ts = ToolSession::new(&dir); let err = ts .invoke( "edit", serde_json::json!({"path": "f.txt", "old_string": "a", "new_string": "b"}), ) .unwrap_err(); assert_eq!(err.code(), "EDIT_AMBIGUOUS"); assert_eq!(std::fs::read_to_string(&target).unwrap(), "a a"); let err = ts .invoke( "edit", serde_json::json!({"path": "f.txt", "old_string": "NOT_PRESENT", "new_string": "b"}), ) .unwrap_err(); assert_eq!(err.code(), "EDIT_NOT_FOUND"); assert_eq!(std::fs::read_to_string(&target).unwrap(), "a a"); // Unambiguous edit succeeds. ts.invoke( "edit", serde_json::json!({"path": "f.txt", "old_string": "a a", "new_string": "b"}), ) .unwrap(); assert_eq!(std::fs::read_to_string(&target).unwrap(), "b"); let _ = std::fs::remove_dir_all(&dir); } #[test] fn read_supports_line_windows_byte_caps_and_binary_detection() { let dir = workdir("read_caps"); let mut body = String::new(); for i in 0..100 { body.push_str(&format!("line-{i}\n")); } std::fs::write(dir.join("lines.txt"), &body).unwrap(); let mut ts = ToolSession::new(&dir); let out = ts .invoke( "read", serde_json::json!({"path": "lines.txt", "offset": 2, "limit": 3}), ) .unwrap(); assert_eq!(out.output, "line-2\nline-3\nline-4\n"); let capped = ts .invoke( "read", serde_json::json!({"path": "lines.txt", "max_bytes": 20}), ) .unwrap(); assert!(capped.output.len() <= 20); std::fs::write(dir.join("bin.dat"), [0x62, 0x00, 0x62]).unwrap(); let err = ts .invoke("read", serde_json::json!({"path": "bin.dat"})) .unwrap_err(); assert_eq!(err.code(), "BINARY_CONTENT"); let _ = std::fs::remove_dir_all(&dir); } #[test] fn ls_and_find_are_sorted_and_surface_errors() { let dir = workdir("ls_find"); for name in ["zeta", "alpha", "mid"] { std::fs::write(dir.join(name), "").unwrap(); } let mut ts = ToolSession::new(&dir); let out = ts.invoke("ls", serde_json::json!({})).unwrap(); assert_eq!(out.output, "alpha\nmid\nzeta"); let found = ts .invoke("find", serde_json::json!({"pattern": "a"})) .unwrap(); assert_eq!(found.output, "alpha\nzeta"); let err = ts .invoke( "find", serde_json::json!({"path": "missing-dir", "pattern": "x"}), ) .unwrap_err(); assert_eq!(err.code(), "FIND_ERROR"); let _ = std::fs::remove_dir_all(&dir); } #[test] fn grep_returns_bounded_matches() { let dir = workdir("grep"); std::fs::write( dir.join("log.txt"), "hit one\nmiss\nhit two\nmiss\nhit three\n", ) .unwrap(); let mut ts = ToolSession::new(&dir); let out = ts .invoke( "grep", serde_json::json!({"path": "log.txt", "query": "hit"}), ) .unwrap(); assert_eq!(out.output, "hit one\nhit two\nhit three"); let _ = std::fs::remove_dir_all(&dir); } #[test] fn unregistered_tools_and_non_object_input_are_rejected() { let dir = workdir("registry"); let mut ts = ToolSession::new(&dir); let err = ts.invoke("rm", serde_json::json!({})).unwrap_err(); assert_eq!(err.code(), "TOOL_NOT_REGISTERED"); let err = ts .invoke("read", serde_json::json!("not-an-object")) .unwrap_err(); assert_eq!(err.code(), "INVALID_INPUT"); let _ = std::fs::remove_dir_all(&dir); } #[test] fn failed_effects_are_recorded_as_failures() { let dir = workdir("record_fail"); let mut ts = ToolSession::new(&dir); let res = ts.invoke("read", serde_json::json!({"path": "nope.txt"})); assert!(res.is_err()); // Two entries: call + failed result, both recorded. assert_eq!(ts.session.active_branch().entries.len(), 2); let last = &ts.session.active_branch().entries[1]; match &last.content { EntryContent::ToolResult { ok, .. } => assert!(!ok), other => panic!("unexpected {other:?}"), } let _ = std::fs::remove_dir_all(&dir); } }