Skip to main content

lash_tools/files/
write.rs

1use schemars::JsonSchema;
2use serde::{Deserialize, Serialize};
3use std::path::Path;
4
5use lash_core::{ToolCall, ToolDefinition, ToolResult};
6
7use lash_tool_support::{
8    StaticToolExecute, StaticToolProvider, ToolDefinitionLashlangExt, display_relative,
9    execute_typed_tool_result, non_empty_string, resolve_under, run_blocking,
10};
11
12const WRITE_DESCRIPTION: &str = "Write content to a file. Creates the file if it does not exist, overwrites if it does. Automatically creates parent directories. Use write only for new files or complete rewrites.";
13
14#[derive(Default)]
15pub struct Write;
16
17pub fn write_provider() -> StaticToolProvider<Write> {
18    StaticToolProvider::new(vec![write_tool_definition()], Write)
19}
20
21#[derive(Clone, Debug, Deserialize, JsonSchema)]
22#[serde(deny_unknown_fields)]
23struct WriteArgs {
24    /// Path to the file to write (relative or absolute).
25    path: String,
26    /// Content to write to the file.
27    content: String,
28}
29
30#[derive(Clone, Debug, Serialize, JsonSchema)]
31struct WriteOutput {
32    summary: String,
33    path: String,
34    bytes: usize,
35}
36
37#[async_trait::async_trait]
38impl StaticToolExecute for Write {
39    async fn execute(&self, call: ToolCall<'_>) -> ToolResult {
40        execute_typed_tool_result::<WriteArgs, _, _>(call.args, |args| async move {
41            if let Err(err) = non_empty_string(&args.path, "path") {
42                return err;
43            }
44            run_blocking(move || write_file(args)).await
45        })
46        .await
47    }
48}
49
50fn write_tool_definition() -> ToolDefinition {
51    ToolDefinition::typed::<WriteArgs, WriteOutput>("tool:write", "write", WRITE_DESCRIPTION)
52        .with_examples(vec![
53            r#"await files.write({ path: "hello.txt", content: "hello\n" })?"#.into(),
54            r#"await files.write({ path: "src/main.rs", content: "fn main() {}\n" })?"#.into(),
55        ])
56        .with_lashlang_binding(lash_tool_support::lashlang_binding(
57            ["files"],
58            "write",
59            &["write_file"],
60        ))
61}
62
63fn write_file(args: WriteArgs) -> ToolResult {
64    let cwd = match std::env::current_dir() {
65        Ok(cwd) => cwd,
66        Err(err) => return ToolResult::err_fmt(format_args!("Failed to determine cwd: {err}")),
67    };
68    let absolute_path = resolve_under(&cwd, Path::new(&args.path));
69    if let Some(parent) = absolute_path.parent()
70        && let Err(err) = std::fs::create_dir_all(parent)
71    {
72        return ToolResult::err_fmt(format_args!("Could not write file: {}. {err}.", args.path));
73    }
74    if let Err(err) = std::fs::write(&absolute_path, &args.content) {
75        return ToolResult::err_fmt(format_args!("Could not write file: {}. {err}.", args.path));
76    }
77
78    let display_path = display_relative(&cwd, &absolute_path);
79    let bytes = args.content.len();
80    lash_tool_support::typed_tool_ok(WriteOutput {
81        summary: format!("Successfully wrote {bytes} bytes to {display_path}."),
82        path: args.path,
83        bytes,
84    })
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90    use serde_json::json;
91    use tempfile::TempDir;
92
93    fn run_write(dir: &TempDir, path: &str, content: &str) -> ToolResult {
94        let path = dir.path().join(path).to_string_lossy().to_string();
95        write_file(WriteArgs {
96            path,
97            content: content.to_string(),
98        })
99    }
100
101    #[test]
102    fn write_contract_documents_pi_shape() {
103        let definition = write_tool_definition();
104        let rendered = definition.compact_contract().render_signature();
105
106        assert!(rendered.contains("path"), "{rendered}");
107        assert!(rendered.contains("content"), "{rendered}");
108        assert!(
109            definition
110                .manifest()
111                .description
112                .contains("Creates the file if it does not exist")
113        );
114    }
115
116    #[test]
117    fn write_creates_parent_directories_and_file() {
118        let dir = TempDir::new().unwrap();
119
120        let result = run_write(&dir, "nested/hello.txt", "hello\n");
121
122        assert!(result.is_success(), "{}", result.value_for_projection());
123        assert_eq!(
124            std::fs::read_to_string(dir.path().join("nested/hello.txt")).unwrap(),
125            "hello\n"
126        );
127        assert_eq!(result.value_for_projection()["bytes"], json!(6));
128    }
129
130    #[test]
131    fn write_overwrites_existing_file() {
132        let dir = TempDir::new().unwrap();
133        std::fs::write(dir.path().join("hello.txt"), "old\n").unwrap();
134
135        let result = run_write(&dir, "hello.txt", "new\n");
136
137        assert!(result.is_success(), "{}", result.value_for_projection());
138        assert_eq!(
139            std::fs::read_to_string(dir.path().join("hello.txt")).unwrap(),
140            "new\n"
141        );
142    }
143}