use std::path::PathBuf;
use async_trait::async_trait;
use serde_json::{Value, json};
use crate::tools::fs::{FsError, scoped_path};
use crate::tools::traits::{ToolExecutor, ToolResult};
pub const WRITE_FILES_TOOL_NAME: &str = "write_files";
pub struct WriteFilesTool {
working_dir: PathBuf,
}
impl WriteFilesTool {
pub fn new(working_dir: impl Into<PathBuf>) -> Self {
Self {
working_dir: working_dir.into(),
}
}
fn write_one(&self, path: &str, content: &str) -> Result<(), FsError> {
let scoped = scoped_path(&self.working_dir, std::path::Path::new(path))?;
if let Some(parent) = scoped.parent() {
std::fs::create_dir_all(parent).map_err(|e| FsError::io(parent, e))?;
}
std::fs::write(&scoped, content).map_err(|e| FsError::io(&scoped, e))?;
Ok(())
}
}
#[async_trait]
impl ToolExecutor for WriteFilesTool {
fn name(&self) -> &str {
WRITE_FILES_TOOL_NAME
}
fn schema(&self) -> Value {
json!({
"type": "function",
"function": {
"name": WRITE_FILES_TOOL_NAME,
"description": "Create or overwrite MULTIPLE files in a single call. Prefer this over several separate write_file calls when scaffolding independent files — it writes them all in one turn. Parent directories are created automatically. Each path must be inside the working directory.",
"parameters": {
"type": "object",
"properties": {
"files": {
"type": "array",
"description": "The files to write. Each element is an object with a path and its full content.",
"items": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Relative or absolute path (must be inside the working directory)."
},
"content": {
"type": "string",
"description": "Full text content to write to the file."
}
},
"required": ["path", "content"],
"additionalProperties": false
}
}
},
"required": ["files"],
"additionalProperties": false
}
}
})
}
async fn execute(&self, args: Value) -> ToolResult {
let Some(files) = args.get("files").and_then(Value::as_array) else {
return ToolResult::err("write_files: missing required argument 'files' (an array)");
};
if files.is_empty() {
return ToolResult::err("write_files: 'files' array is empty — nothing to write");
}
let mut lines = Vec::with_capacity(files.len());
let mut ok_count = 0usize;
let mut written_paths = Vec::with_capacity(files.len());
for (i, entry) in files.iter().enumerate() {
let path = entry.get("path").and_then(Value::as_str);
let content = entry.get("content").and_then(Value::as_str);
match (path, content) {
(Some(p), Some(c)) => match self.write_one(p, c) {
Ok(()) => {
ok_count += 1;
lines.push(format!("wrote {p}"));
written_paths.push(PathBuf::from(p));
}
Err(e) => lines.push(format!("FAILED {p}: {e}")),
},
_ => lines.push(format!(
"FAILED entry {i}: each element needs both 'path' and 'content'"
)),
}
}
if !written_paths.is_empty() {
trusty_common::search_index::index_files_best_effort(&self.working_dir, &written_paths);
}
let summary = lines.join("\n");
if ok_count == 0 {
ToolResult::err(summary)
} else {
ToolResult::ok(format!(
"{summary}\n({ok_count}/{} files written)",
files.len()
))
}
}
}
#[cfg(test)]
mod tests {
use std::fs;
use serde_json::json;
use super::*;
use crate::tools::traits::ToolExecutor;
#[tokio::test]
async fn write_files_writes_all() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = WriteFilesTool::new(tmp.path());
let result = tool
.execute(json!({
"files": [
{"path": "a.py", "content": "# a"},
{"path": "pkg/b.py", "content": "# b"},
{"path": "src/main.rs", "content": "fn main() {}"}
]
}))
.await;
assert!(!result.is_error(), "unexpected error: {}", result.content());
assert_eq!(fs::read_to_string(tmp.path().join("a.py")).unwrap(), "# a");
assert_eq!(
fs::read_to_string(tmp.path().join("pkg/b.py")).unwrap(),
"# b"
);
assert_eq!(
fs::read_to_string(tmp.path().join("src/main.rs")).unwrap(),
"fn main() {}"
);
assert!(result.content().contains("3/3"), "{}", result.content());
}
#[tokio::test]
async fn write_files_partial_failure() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = WriteFilesTool::new(tmp.path());
let result = tool
.execute(json!({
"files": [
{"path": "good.py", "content": "ok"},
{"path": "../../evil.sh", "content": "harm"}
]
}))
.await;
assert!(!result.is_error(), "{}", result.content());
assert_eq!(
fs::read_to_string(tmp.path().join("good.py")).unwrap(),
"ok"
);
assert!(result.content().contains("wrote good.py"));
assert!(
result.content().contains("FAILED"),
"must flag the failed entry: {}",
result.content()
);
}
#[tokio::test]
async fn write_files_all_fail_is_error() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = WriteFilesTool::new(tmp.path());
let result = tool
.execute(json!({"files": [{"path": "../../evil.sh", "content": "x"}]}))
.await;
assert!(result.is_error());
assert!(result.content().contains("FAILED"));
}
#[tokio::test]
async fn write_files_empty_array_errors() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = WriteFilesTool::new(tmp.path());
let result = tool.execute(json!({"files": []})).await;
assert!(result.is_error());
assert!(result.content().contains("empty"));
}
#[test]
fn schema_requires_files_array() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = WriteFilesTool::new(tmp.path());
let schema = tool.schema();
let required = schema["function"]["parameters"]["required"]
.as_array()
.expect("required array");
assert!(
required.iter().any(|v| v.as_str() == Some("files")),
"schema must list 'files' as required"
);
}
}