Skip to main content

llama_cpp_v3_agent_sdk/tools/
write_file.rs

1use crate::error::AgentError;
2use crate::tool::{Tool, ToolResult};
3use std::fs;
4use std::path::Path;
5
6/// Create or overwrite files.
7pub struct WriteFileTool;
8
9impl Tool for WriteFileTool {
10    fn name(&self) -> &str {
11        "write"
12    }
13
14    fn description(&self) -> &str {
15        "Create or overwrite a file with the given content. \
16         Parent directories are created automatically if they don't exist."
17    }
18
19    fn parameters_schema(&self) -> serde_json::Value {
20        serde_json::json!({
21            "type": "object",
22            "properties": {
23                "path": {
24                    "type": "string",
25                    "description": "Path to the file to create/overwrite"
26                },
27                "content": {
28                    "type": "string",
29                    "description": "Content to write to the file"
30                }
31            },
32            "required": ["path", "content"]
33        })
34    }
35
36    fn execute(&self, args: &serde_json::Value) -> Result<ToolResult, AgentError> {
37        let path = args["path"].as_str().ok_or_else(|| AgentError::Tool {
38            tool: "write".to_string(),
39            message: "Missing 'path' argument".to_string(),
40        })?;
41
42        let content = args["content"].as_str().ok_or_else(|| AgentError::Tool {
43            tool: "write".to_string(),
44            message: "Missing 'content' argument".to_string(),
45        })?;
46
47        let file_path = Path::new(path);
48
49        // Create parent directories if needed
50        if let Some(parent) = file_path.parent() {
51            if !parent.exists() {
52                if let Err(e) = fs::create_dir_all(parent) {
53                    return Ok(ToolResult::err(format!(
54                        "Failed to create directories for '{}': {}",
55                        path, e
56                    )));
57                }
58            }
59        }
60
61        match fs::write(file_path, content) {
62            Ok(_) => {
63                let lines = content.lines().count();
64                let bytes = content.len();
65                Ok(ToolResult::ok(format!(
66                    "Wrote {} lines ({} bytes) to '{}'",
67                    lines, bytes, path
68                )))
69            }
70            Err(e) => Ok(ToolResult::err(format!(
71                "Failed to write '{}': {}",
72                path, e
73            ))),
74        }
75    }
76
77    fn requires_permission(&self) -> bool {
78        true
79    }
80}