1use std::path::PathBuf;
4
5use async_trait::async_trait;
6use serde::Deserialize;
7use serde_json::{json, Value};
8use tokio_util::sync::CancellationToken;
9
10use crate::agent::tool::{AgentTool, ToolResult};
11use crate::tools::file_mutex::with_file_lock;
12use crate::tools::util::{display_path, resolve_to_cwd};
13
14pub struct WriteTool {
15 pub cwd: PathBuf,
16}
17
18#[derive(Debug, Deserialize)]
19struct WriteInput {
20 #[serde(default)]
21 path: Option<String>,
22 #[serde(default, alias = "file_path")]
23 file_path: Option<String>,
24 #[serde(default)]
25 content: Option<String>,
26}
27
28#[async_trait]
29impl AgentTool for WriteTool {
30 fn name(&self) -> &str {
31 "write"
32 }
33 fn description(&self) -> &str {
34 "Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates parent directories."
35 }
36 fn input_schema(&self) -> Value {
37 json!({
38 "type": "object",
39 "properties": {
40 "path": { "type": "string", "description": "Path to the file to write (relative or absolute)" },
41 "content": { "type": "string", "description": "Content to write to the file" }
42 },
43 "required": ["path", "content"]
44 })
45 }
46
47 async fn execute(&self, args: Value, _cancel: CancellationToken) -> anyhow::Result<ToolResult> {
48 let input: WriteInput = serde_json::from_value(args)?;
49 let path_str = input
50 .path
51 .or(input.file_path)
52 .ok_or_else(|| anyhow::anyhow!("write requires a 'path' parameter"))?;
53 let content = input.content.unwrap_or_default();
54 let abs = resolve_to_cwd(&path_str, &self.cwd);
55 let display = display_path(&path_str, &self.cwd);
56
57 with_file_lock(&abs, async {
58 if let Some(parent) = abs.parent() {
59 tokio::fs::create_dir_all(parent).await?;
60 }
61 tokio::fs::write(&abs, content.as_bytes()).await?;
62 Ok::<(), anyhow::Error>(())
63 })
64 .await?;
65
66 Ok(ToolResult::text(format!(
67 "Successfully wrote {} bytes to {display}",
68 content.len()
69 )))
70 }
71}