use std::collections::HashMap;
use std::fs;
use crate::extract_args;
use crate::tools::tool::{BoxFuture, ToolCategory, build_string_params_schema, make_tool};
pub fn edit_tool_entry() -> crate::tools::tool::Tool {
make_tool(
"edit",
"Edit a file by finding an exact string and replacing it with new text. The old_str must appear exactly once in the file. Use this for targeted edits instead of rewriting the entire file.",
ToolCategory::Destructive,
build_string_params_schema(
&[
("path", "The absolute path to the file to edit"),
(
"old_str",
"The exact string to find in the file (must appear exactly once)",
),
("new_str", "The replacement string"),
],
&[],
),
|args| Box::pin(edit_tool(args)),
)
}
pub fn edit_tool(args: HashMap<String, String>) -> BoxFuture<'static, String> {
Box::pin(async move {
extract_args!(args, path, old_str, new_str);
let content = match fs::read_to_string(&path) {
Ok(c) => c,
Err(e) => return format!("Error: Failed to read file '{}': {}", path, e),
};
let count = content.matches(&old_str).count();
if count == 0 {
return format!(
"Error: 'old_str' not found in '{}'. The exact text to replace must appear in the file.",
path
);
}
if count > 1 {
return format!(
"Error: 'old_str' appears {} times in '{}'. The old_str must appear exactly once. Found {} occurrences.",
count, path, count
);
}
let new_content = content.replace(&old_str, &new_str);
match fs::write(&path, &new_content) {
Ok(_) => format!("Edited '{}' ({} chars replaced).", path, old_str.len()),
Err(e) => format!("Error: Failed to write file '{}': {}", path, e),
}
})
}