1use 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; pub struct WriteFile {
22 backend: SharedBackend,
23 policy: Arc<dyn FilePolicy>,
24 text: ToolText,
25}
26
27impl WriteFile {
28 pub fn new(workspace: Workspace) -> Self {
30 let (backend, policy) = workspace_parts(workspace);
31 Self::on_backend(backend, policy)
32 }
33
34 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 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 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 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 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 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 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 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 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]
253#[async_trait]
254impl crate::semantics::ToolSemantics for WriteFile {
255 fn dispatch_facts(&self) -> crate::semantics::ToolDispatchFacts {
256 crate::semantics::ToolDispatchFacts {
257 offering: crate::semantics::Offering::Core,
258 checkpoints_writes: true,
259 file_guard: crate::semantics::FileGuard::Writes,
260 recap: crate::semantics::RecapKind::FileWrite,
261 activity: crate::semantics::ToolActivity::Fixed(
262 aidaemon_core::card::ActivityKind::Write,
263 ),
264 opens_project_instructions: true,
265 semantic_scope: Some(crate::semantics::ToolSemanticScope::LocalWorkspace),
266 low_signal_result: true,
267 status_label: Some("writing a file"),
268 ..Default::default()
269 }
270 }
271
272 fn tool_role(&self) -> ToolRole {
273 ToolRole::Action
274 }
275
276 fn capabilities(&self) -> ToolCapabilities {
277 ToolCapabilities {
278 read_only: false,
279 external_side_effect: false,
280 needs_approval: false,
281 idempotent: false,
282 high_impact_write: false,
287 }
288 }
289
290 fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
291 let path = serde_json::from_str::<Value>(arguments)
292 .ok()
293 .and_then(|args| {
294 for key in ["path", "file_path", "file", "filename"] {
295 if let Some(path) = args.get(key).and_then(|value| value.as_str()) {
296 return Some(path.to_string());
297 }
298 }
299 None
300 })
301 .unwrap_or_default();
302
303 ToolCallSemantics::mutation_with(ToolMutationEffects::LOCAL_SOURCE_WRITE)
304 .with_target_hint(ToolTargetHintKind::Path, path)
305 }
306
307 fn call_file_write(&self, arguments: &str) -> Option<crate::semantics::FileWrite> {
308 let args: Value = serde_json::from_str(arguments).ok()?;
309 Some(crate::semantics::FileWrite {
310 path: path_arg(&args)?.to_string(),
311 kind: if args["mode"].as_str() == Some("append") {
312 crate::semantics::FileWriteKind::Append
313 } else {
314 crate::semantics::FileWriteKind::Replace
315 },
316 })
317 }
318
319 fn file_write_result(
320 &self,
321 arguments: &str,
322 current: Option<&[u8]>,
323 ) -> Option<Result<Vec<u8>, String>> {
324 let args: Value = serde_json::from_str(arguments).ok()?;
325 let content = ["content", "data", "text"]
326 .iter()
327 .find_map(|key| args.get(*key).and_then(Value::as_str))?;
328 let mut result = match args["mode"].as_str() {
329 Some("append") => current.unwrap_or_default().to_vec(),
330 Some("overwrite") | None => Vec::new(),
331 Some(_) => return None,
332 };
333 result.extend_from_slice(content.as_bytes());
334 Some(Ok(result))
335 }
336
337 fn call_effects(&self, arguments: &str) -> aidaemon_core::CallEffects {
340 self.policy.write_effects(&*self.backend, arguments)
341 }
342
343 async fn owner_approval_request(
346 &self,
347 call: &crate::semantics::ApprovalCall<'_>,
348 facts: &ToolCallContext,
349 ) -> crate::semantics::OwnerApprovalNeed {
350 super::persistence_write_approval(
351 &self.backend,
352 &*self.policy,
353 "write_file",
354 call.arguments,
355 self.call_effects(&call.arguments.to_string()),
356 facts,
357 )
358 .await
359 }
360
361 fn call_annotations_in(
362 &self,
363 arguments: &str,
364 _roots: &crate::semantics::TrustRoots<'_>,
365 ) -> aidaemon_core::ToolAnnotations {
366 let semantics = self.call_semantics(arguments);
367 let mut annotations =
368 crate::semantics::default_call_annotations(self.capabilities(), &semantics);
369 let plants_git_config = semantics
372 .target_hints
373 .iter()
374 .any(|hint| self.policy.plants_configuration(&hint.value));
375 annotations.egress |= plants_git_config;
376 annotations
377 }
378
379 async fn durable_replay_decision(&self, arguments: &str) -> DurableReplayDecision {
380 let Ok(args) = serde_json::from_str::<Value>(arguments) else {
381 return DurableReplayDecision::Replay;
382 };
383 if args["mode"].as_str().unwrap_or("overwrite") != "overwrite" {
386 return DurableReplayDecision::Replay;
387 }
388 let Some(path_str) = args["path"]
389 .as_str()
390 .or_else(|| args["file_path"].as_str())
391 .or_else(|| args["file"].as_str())
392 .or_else(|| args["filename"].as_str())
393 else {
394 return DurableReplayDecision::Replay;
395 };
396 let Some(content) = args["content"]
397 .as_str()
398 .or_else(|| args["data"].as_str())
399 .or_else(|| args["text"].as_str())
400 else {
401 return DurableReplayDecision::Replay;
402 };
403
404 let backend = self.backend.clone();
405 let path = match backend.resolve_path(path_str).await {
406 Ok(path) => path,
407 Err(error) => {
408 return DurableReplayDecision::Block {
409 reason: format!(
410 "the prior file-write target can no longer be resolved safely: {error}"
411 ),
412 };
413 }
414 };
415 match backend.read(&path).await {
416 Ok(current) if current == content.as_bytes() => DurableReplayDecision::Replay,
417 Ok(_) => DurableReplayDecision::Block {
418 reason: format!(
419 "the file at {path_str} exists but no longer matches the successful write receipt; inspect and reconcile the current content before overwriting it"
420 ),
421 },
422 Err(read_error) => {
423 let Some(parent) = path.parent() else {
424 return DurableReplayDecision::Block {
425 reason: format!(
426 "the prior file-write target could not be inspected: {read_error}"
427 ),
428 };
429 };
430 match backend.read_dir(&parent).await {
431 Ok(entries) if entries.iter().all(|entry| entry.path != path) => {
432 DurableReplayDecision::Reexecute {
433 reason: format!(
434 "the exact overwrite target {path_str} is absent, so the prior successful receipt no longer satisfies current state"
435 ),
436 }
437 }
438 Ok(_) => DurableReplayDecision::Block {
439 reason: format!(
440 "the file at {path_str} still exists but could not be read; refusing to overwrite unreconciled current state"
441 ),
442 },
443 Err(parent_error) => DurableReplayDecision::Block {
444 reason: format!(
445 "the prior file-write target and its parent could not be inspected safely: {read_error}; {parent_error}"
446 ),
447 },
448 }
449 }
450 }
451 }
452}