Skip to main content

aidaemon_tools/fs/
write.rs

1//! `write_file`: create, overwrite or append.
2
3use std::sync::Arc;
4
5use async_trait::async_trait;
6use serde_json::{Value, json};
7
8use aidaemon_core::{AccessManifest, ToolAnnotations};
9
10use super::{FilePolicy, SharedBackend, ToolText, path_arg, workspace_parts};
11use crate::backend::WriteMode;
12use crate::outcome::{OutcomeTool, core_tool};
13use crate::semantics::{
14    DurableReplayDecision, ToolCallContext, ToolCallOutcome, ToolCallSemantics, ToolCapabilities,
15    ToolMutationEffects, ToolRole, ToolTargetHintKind,
16};
17use crate::workspace::Workspace;
18
19const MAX_CONTENT_SIZE: usize = 1024 * 1024; // 1MB
20
21pub struct WriteFile {
22    backend: SharedBackend,
23    policy: Arc<dyn FilePolicy>,
24    text: ToolText,
25}
26
27impl WriteFile {
28    /// A tool confined to `workspace`.
29    pub fn new(workspace: Workspace) -> Self {
30        let (backend, policy) = workspace_parts(workspace);
31        Self::on_backend(backend, policy)
32    }
33
34    /// A tool working through `backend` under an application's `policy`.
35    pub fn on_backend(backend: SharedBackend, policy: Arc<dyn FilePolicy>) -> Self {
36        Self {
37            backend,
38            policy,
39            text: ToolText {
40                short: "Write or create a file with given content".into(),
41                schema: "Create a file, overwrite one, or append to one. Parent directories are created. Prefer edit_file for changing part of an existing file.".into(),
42            },
43        }
44    }
45
46    /// Replace the model-facing descriptions.
47    pub fn with_text(mut self, text: ToolText) -> Self {
48        self.text = text;
49        self
50    }
51}
52
53#[async_trait]
54impl OutcomeTool for WriteFile {
55    fn name(&self) -> &str {
56        "write_file"
57    }
58
59    fn description(&self) -> &str {
60        &self.text.short
61    }
62
63    fn schema(&self) -> Value {
64        json!({
65            "name": "write_file",
66            "description": self.text.schema,
67            "parameters": {
68                "type": "object",
69                "properties": {
70                    "path": {
71                        "type": "string",
72                        "description": "Path to write to (supports ~ expansion)"
73                    },
74                    "content": {
75                        "type": "string",
76                        "description": "Content to write to the file"
77                    },
78                    "create_dirs": {
79                        "type": "boolean",
80                        "description": "Create parent directories if they don't exist (default: true)"
81                    },
82                    "mode": {
83                        "type": "string",
84                        "enum": ["overwrite", "append"],
85                        "description": "Write mode. \"overwrite\" (default) replaces the file (a backup is kept). \"append\" adds to the end of the file without a backup — use it to build a large file in chunks across multiple calls instead of emitting everything in one call (which can exceed the output token limit)."
86                    }
87                },
88                "required": ["path", "content"],
89                "additionalProperties": false
90            }
91        })
92    }
93
94    async fn execute(
95        &self,
96        arguments: &str,
97        facts: &ToolCallContext,
98    ) -> anyhow::Result<ToolCallOutcome> {
99        let args: Value = serde_json::from_str(arguments)?;
100        // Parameter aliasing: models often use "file_path" or "file" instead of "path"
101        let path_str = args["path"]
102            .as_str()
103            .or_else(|| args["file_path"].as_str())
104            .or_else(|| args["file"].as_str())
105            .or_else(|| args["filename"].as_str())
106            .ok_or_else(|| anyhow::anyhow!("Missing required parameter: path"))?;
107        let content = args["content"]
108            .as_str()
109            .or_else(|| args["data"].as_str())
110            .or_else(|| args["text"].as_str())
111            .ok_or_else(|| anyhow::anyhow!("Missing required parameter: content"))?;
112        let create_dirs = args["create_dirs"].as_bool().unwrap_or(true);
113
114        if content.len() > MAX_CONTENT_SIZE {
115            anyhow::bail!(
116                "Content too large: {} bytes (max {})",
117                content.len(),
118                MAX_CONTENT_SIZE
119            );
120        }
121
122        let backend = self.backend.clone();
123        let path = backend.resolve_path(path_str).await?;
124
125        // Create parent dirs if requested
126        if create_dirs {
127            if let Some(parent) = path.parent() {
128                backend.create_dir_all(&parent).await?;
129            }
130        } else if let Some(parent) = path.parent()
131            && !backend
132                .metadata(&parent)
133                .await
134                .is_ok_and(|metadata| metadata.is_dir())
135        {
136            return Err(crate::TargetNotFound(format!(
137                "Parent directory does not exist: {parent}. Set create_dirs=true to create it."
138            ))
139            .into());
140        }
141
142        // Write mode: "overwrite" (default, replaces with backup) or "append"
143        // (additive, no backup — lets the model build a large file in chunks
144        // instead of one oversized generation).
145        let mode = args["mode"].as_str().unwrap_or("overwrite");
146        if mode != "overwrite" && mode != "append" {
147            anyhow::bail!(
148                "Invalid mode: \"{}\" (expected \"overwrite\" or \"append\")",
149                mode
150            );
151        }
152
153        // Held until the write has landed.
154        let write_guard = match crate::semantics::file_fence(facts) {
155            Some(fence) => Some(
156                fence
157                    .begin_write(path_str)
158                    .await
159                    .map_err(|why| anyhow::anyhow!(why))?,
160            ),
161            None => None,
162        };
163
164        if mode == "append" {
165            let existing_size = backend
166                .metadata(&path)
167                .await
168                .map(|metadata| metadata.len)
169                .unwrap_or(0);
170            backend
171                .write(&path, content.as_bytes(), WriteMode::Append, create_dirs)
172                .await?;
173            if let Some(write_guard) = write_guard {
174                write_guard.committed().await;
175            }
176
177            let appended = content.len();
178            let appended_lines = content.lines().count();
179            let total = existing_size + appended as u64;
180            let delivery = self
181                .policy
182                .delivery_hint()
183                .map(|hint| format!(" {hint}"))
184                .unwrap_or_default();
185            return Ok(ToolCallOutcome::from_output(format!(
186                "Appended {} bytes ({} lines) to {} (now {} bytes total). \
187                 To add more, call write_file again with mode=\"append\".{}",
188                appended, appended_lines, path_str, total, delivery
189            )));
190        }
191
192        // Backup existing file
193        let existing_metadata = backend.metadata(&path).await.ok();
194        let existed = existing_metadata.is_some();
195        let old_size = if existed {
196            let size = existing_metadata
197                .as_ref()
198                .map_or(0, |metadata| metadata.len);
199            // One backup per file, outside the user's tree when local.
200            self.policy.backup_before_overwrite(&backend, &path).await;
201            Some(size)
202        } else {
203            None
204        };
205
206        backend
207            .write(&path, content.as_bytes(), WriteMode::Overwrite, create_dirs)
208            .await?;
209        if let Some(write_guard) = write_guard {
210            write_guard.committed().await;
211        }
212
213        let new_size = content.len();
214        let line_count = content.lines().count();
215
216        let action = if existed { "Updated" } else { "Created" };
217        let size_info = if let Some(old) = old_size {
218            let backup = if self.policy.keeps_backups() {
219                ", backup saved"
220            } else {
221                ""
222            };
223            format!(" (was {} bytes{})", old, backup)
224        } else {
225            String::new()
226        };
227
228        let diagnostics = self
229            .policy
230            .post_write_diagnostics(&*backend, std::path::Path::new(path.as_str()))
231            .await;
232
233        Ok(ToolCallOutcome::from_output(format!(
234            "{} {}\n{} bytes, {} lines{}{}",
235            action, path_str, new_size, line_count, size_info, diagnostics
236        )))
237    }
238}
239
240core_tool!(
241    WriteFile,
242    // Append mode writes more each time, so a repeat is not a no-op.
243    annotations: ToolAnnotations::WRITE,
244    access: |this, arguments| AccessManifest {
245        writes: path_arg(arguments)
246            .map(|path| vec![this.policy.declare_path(path)])
247            .unwrap_or_default(),
248        ..Default::default()
249    }
250);
251
252#[async_trait::async_trait]
253impl crate::semantics::ToolSemantics for WriteFile {
254    fn dispatch_facts(&self) -> crate::semantics::ToolDispatchFacts {
255        crate::semantics::ToolDispatchFacts {
256            offering: crate::semantics::Offering::Core,
257            checkpoints_writes: true,
258            file_guard: crate::semantics::FileGuard::Writes,
259            recap: crate::semantics::RecapKind::FileWrite,
260            activity: crate::semantics::ToolActivity::Fixed(
261                aidaemon_core::card::ActivityKind::Write,
262            ),
263            opens_project_instructions: true,
264            semantic_scope: Some(crate::semantics::ToolSemanticScope::LocalWorkspace),
265            low_signal_result: true,
266            status_label: Some("writing a file"),
267            ..Default::default()
268        }
269    }
270
271    fn tool_role(&self) -> ToolRole {
272        ToolRole::Action
273    }
274
275    fn capabilities(&self) -> ToolCapabilities {
276        ToolCapabilities {
277            read_only: false,
278            external_side_effect: false,
279            needs_approval: false,
280            idempotent: false,
281            // Not high-impact: creates backups before overwriting, user-scoped
282            // file system only, and dedicated file tools are intentionally
283            // available without terminal approval. Sensitive paths are blocked
284            // before writing.
285            high_impact_write: false,
286        }
287    }
288
289    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
290        let path = serde_json::from_str::<Value>(arguments)
291            .ok()
292            .and_then(|args| {
293                for key in ["path", "file_path", "file", "filename"] {
294                    if let Some(path) = args.get(key).and_then(|value| value.as_str()) {
295                        return Some(path.to_string());
296                    }
297                }
298                None
299            })
300            .unwrap_or_default();
301
302        ToolCallSemantics::mutation_with(ToolMutationEffects::LOCAL_SOURCE_WRITE)
303            .with_target_hint(ToolTargetHintKind::Path, path)
304    }
305
306    fn call_file_write(&self, arguments: &str) -> Option<crate::semantics::FileWrite> {
307        let args: Value = serde_json::from_str(arguments).ok()?;
308        Some(crate::semantics::FileWrite {
309            path: path_arg(&args)?.to_string(),
310            kind: if args["mode"].as_str() == Some("append") {
311                crate::semantics::FileWriteKind::Append
312            } else {
313                crate::semantics::FileWriteKind::Replace
314            },
315        })
316    }
317
318    fn file_write_result(
319        &self,
320        arguments: &str,
321        current: Option<&[u8]>,
322    ) -> Option<Result<Vec<u8>, String>> {
323        let args: Value = serde_json::from_str(arguments).ok()?;
324        let content = ["content", "data", "text"]
325            .iter()
326            .find_map(|key| args.get(*key).and_then(Value::as_str))?;
327        let mut result = match args["mode"].as_str() {
328            Some("append") => current.unwrap_or_default().to_vec(),
329            Some("overwrite") | None => Vec::new(),
330            Some(_) => return None,
331        };
332        result.extend_from_slice(content.as_bytes());
333        Some(Ok(result))
334    }
335
336    /// A write of the target path (absolute; a relative path resolves where
337    /// the execution backend puts it, which is not known here).
338    fn call_effects(&self, arguments: &str) -> aidaemon_core::CallEffects {
339        self.policy.write_effects(&*self.backend, arguments)
340    }
341
342    fn call_annotations_in(
343        &self,
344        arguments: &str,
345        _roots: &crate::semantics::TrustRoots<'_>,
346    ) -> aidaemon_core::ToolAnnotations {
347        let semantics = self.call_semantics(arguments);
348        let mut annotations =
349            crate::semantics::default_call_annotations(self.capabilities(), &semantics);
350        // A write that can plant git configuration changes what later
351        // "read-only" git commands execute: treat it as a configuration change.
352        let plants_git_config = semantics
353            .target_hints
354            .iter()
355            .any(|hint| self.policy.plants_configuration(&hint.value));
356        annotations.egress |= plants_git_config;
357        annotations
358    }
359
360    async fn durable_replay_decision(&self, arguments: &str) -> DurableReplayDecision {
361        let Ok(args) = serde_json::from_str::<Value>(arguments) else {
362            return DurableReplayDecision::Replay;
363        };
364        // Appending the same bytes twice is not safe. Keep the durable receipt
365        // authoritative for append calls; callers must issue a new operation.
366        if args["mode"].as_str().unwrap_or("overwrite") != "overwrite" {
367            return DurableReplayDecision::Replay;
368        }
369        let Some(path_str) = args["path"]
370            .as_str()
371            .or_else(|| args["file_path"].as_str())
372            .or_else(|| args["file"].as_str())
373            .or_else(|| args["filename"].as_str())
374        else {
375            return DurableReplayDecision::Replay;
376        };
377        let Some(content) = args["content"]
378            .as_str()
379            .or_else(|| args["data"].as_str())
380            .or_else(|| args["text"].as_str())
381        else {
382            return DurableReplayDecision::Replay;
383        };
384
385        let backend = self.backend.clone();
386        let path = match backend.resolve_path(path_str).await {
387            Ok(path) => path,
388            Err(error) => {
389                return DurableReplayDecision::Block {
390                    reason: format!(
391                        "the prior file-write target can no longer be resolved safely: {error}"
392                    ),
393                };
394            }
395        };
396        match backend.read(&path).await {
397            Ok(current) if current == content.as_bytes() => DurableReplayDecision::Replay,
398            Ok(_) => DurableReplayDecision::Block {
399                reason: format!(
400                    "the file at {path_str} exists but no longer matches the successful write receipt; inspect and reconcile the current content before overwriting it"
401                ),
402            },
403            Err(read_error) => {
404                let Some(parent) = path.parent() else {
405                    return DurableReplayDecision::Block {
406                        reason: format!(
407                            "the prior file-write target could not be inspected: {read_error}"
408                        ),
409                    };
410                };
411                match backend.read_dir(&parent).await {
412                    Ok(entries) if entries.iter().all(|entry| entry.path != path) => {
413                        DurableReplayDecision::Reexecute {
414                            reason: format!(
415                                "the exact overwrite target {path_str} is absent, so the prior successful receipt no longer satisfies current state"
416                            ),
417                        }
418                    }
419                    Ok(_) => DurableReplayDecision::Block {
420                        reason: format!(
421                            "the file at {path_str} still exists but could not be read; refusing to overwrite unreconciled current state"
422                        ),
423                    },
424                    Err(parent_error) => DurableReplayDecision::Block {
425                        reason: format!(
426                            "the prior file-write target and its parent could not be inspected safely: {read_error}; {parent_error}"
427                        ),
428                    },
429                }
430            }
431        }
432    }
433}