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 = super::path_arg(&args)
101 .ok_or_else(|| anyhow::anyhow!("Missing required parameter: path"))?;
102 let content = super::content_arg(&args)
103 .ok_or_else(|| anyhow::anyhow!("Missing required parameter: content"))?;
104 let create_dirs = args["create_dirs"].as_bool().unwrap_or(true);
105
106 if content.len() > MAX_CONTENT_SIZE {
107 anyhow::bail!(
108 "Content too large: {} bytes (max {})",
109 content.len(),
110 MAX_CONTENT_SIZE
111 );
112 }
113
114 let backend = self.backend.clone();
115 let path = backend.resolve_path(path_str).await?;
116
117 if create_dirs {
119 if let Some(parent) = path.parent() {
120 backend.create_dir_all(&parent).await?;
121 }
122 } else if let Some(parent) = path.parent()
123 && !backend
124 .metadata(&parent)
125 .await
126 .is_ok_and(|metadata| metadata.is_dir())
127 {
128 return Err(crate::TargetNotFound(format!(
129 "Parent directory does not exist: {parent}. Set create_dirs=true to create it."
130 ))
131 .into());
132 }
133
134 let mode = args["mode"].as_str().unwrap_or("overwrite");
138 if mode != "overwrite" && mode != "append" {
139 anyhow::bail!(
140 "Invalid mode: \"{}\" (expected \"overwrite\" or \"append\")",
141 mode
142 );
143 }
144
145 let write_guard = match crate::semantics::file_fence(facts) {
147 Some(fence) => Some(
148 fence
149 .begin_write(path_str)
150 .await
151 .map_err(|why| anyhow::anyhow!(why))?,
152 ),
153 None => None,
154 };
155
156 if mode == "append" {
157 let existing_size = backend
158 .metadata(&path)
159 .await
160 .map(|metadata| metadata.len)
161 .unwrap_or(0);
162 backend
163 .write(&path, content.as_bytes(), WriteMode::Append, create_dirs)
164 .await?;
165 if let Some(write_guard) = write_guard {
166 write_guard.committed().await;
167 }
168
169 let appended = content.len();
170 let appended_lines = content.lines().count();
171 let total = existing_size + appended as u64;
172 let delivery = self
173 .policy
174 .delivery_hint()
175 .map(|hint| format!(" {hint}"))
176 .unwrap_or_default();
177 return Ok(ToolCallOutcome::from_output(format!(
178 "Appended {} bytes ({} lines) to {} (now {} bytes total). \
179 To add more, call write_file again with mode=\"append\".{}",
180 appended, appended_lines, path_str, total, delivery
181 )));
182 }
183
184 let existing_metadata = backend.metadata(&path).await.ok();
186 let existed = existing_metadata.is_some();
187 let old_size = if existed {
188 let size = existing_metadata
189 .as_ref()
190 .map_or(0, |metadata| metadata.len);
191 self.policy.backup_before_overwrite(&backend, &path).await;
193 Some(size)
194 } else {
195 None
196 };
197
198 backend
199 .write(&path, content.as_bytes(), WriteMode::Overwrite, create_dirs)
200 .await?;
201 if let Some(write_guard) = write_guard {
202 write_guard.committed().await;
203 }
204
205 let new_size = content.len();
206 let line_count = content.lines().count();
207
208 let action = if existed { "Updated" } else { "Created" };
209 let size_info = if let Some(old) = old_size {
210 let backup = if self.policy.keeps_backups() {
211 ", backup saved"
212 } else {
213 ""
214 };
215 format!(" (was {} bytes{})", old, backup)
216 } else {
217 String::new()
218 };
219
220 let diagnostics = self
221 .policy
222 .post_write_diagnostics(&*backend, std::path::Path::new(path.as_str()))
223 .await;
224
225 Ok(ToolCallOutcome::from_output(format!(
226 "{} {}\n{} bytes, {} lines{}{}",
227 action, path_str, new_size, line_count, size_info, diagnostics
228 )))
229 }
230}
231
232core_tool!(
233 WriteFile,
234 annotations: ToolAnnotations::WRITE,
236 access: |this, arguments| AccessManifest {
237 writes: path_arg(arguments)
238 .map(|path| vec![this.policy.declare_path(path)])
239 .unwrap_or_default(),
240 ..Default::default()
241 }
242);
243
244#[async_trait::async_trait]
245#[async_trait]
246impl crate::semantics::ToolSemantics for WriteFile {
247 fn dispatch_facts(&self) -> crate::semantics::ToolDispatchFacts {
248 crate::semantics::ToolDispatchFacts {
249 offering: crate::semantics::Offering::Core,
250 checkpoints_writes: true,
251 file_guard: crate::semantics::FileGuard::Writes,
252 recap: crate::semantics::RecapKind::FileWrite,
253 activity: crate::semantics::ToolActivity::Fixed(
254 aidaemon_core::card::ActivityKind::Write,
255 ),
256 opens_project_instructions: true,
257 semantic_scope: Some(crate::semantics::ToolSemanticScope::LocalWorkspace),
258 low_signal_result: true,
259 status_label: Some("writing a file"),
260 ..Default::default()
261 }
262 }
263
264 fn tool_role(&self) -> ToolRole {
265 ToolRole::Action
266 }
267
268 fn capabilities(&self) -> ToolCapabilities {
269 ToolCapabilities {
270 read_only: false,
271 external_side_effect: false,
272 needs_approval: false,
273 idempotent: false,
274 high_impact_write: false,
279 }
280 }
281
282 fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
283 let path = serde_json::from_str::<Value>(arguments)
284 .ok()
285 .and_then(|args| {
286 for key in ["path", "file_path", "file", "filename"] {
287 if let Some(path) = args.get(key).and_then(|value| value.as_str()) {
288 return Some(path.to_string());
289 }
290 }
291 None
292 })
293 .unwrap_or_default();
294
295 ToolCallSemantics::mutation_with(ToolMutationEffects::LOCAL_SOURCE_WRITE)
296 .with_target_hint(ToolTargetHintKind::Path, path)
297 }
298
299 fn call_file_write(&self, arguments: &str) -> Option<crate::semantics::FileWrite> {
300 let args: Value = serde_json::from_str(arguments).ok()?;
301 Some(crate::semantics::FileWrite {
302 path: path_arg(&args)?.to_string(),
303 kind: if args["mode"].as_str() == Some("append") {
304 crate::semantics::FileWriteKind::Append
305 } else {
306 crate::semantics::FileWriteKind::Replace
307 },
308 })
309 }
310
311 fn file_write_result(
312 &self,
313 arguments: &str,
314 current: Option<&[u8]>,
315 ) -> Option<Result<Vec<u8>, String>> {
316 let args: Value = serde_json::from_str(arguments).ok()?;
317 let content = super::content_arg(&args)?;
318 let mut result = match args["mode"].as_str() {
319 Some("append") => current.unwrap_or_default().to_vec(),
320 Some("overwrite") | None => Vec::new(),
321 Some(_) => return None,
322 };
323 result.extend_from_slice(content.as_bytes());
324 Some(Ok(result))
325 }
326
327 fn call_effects(&self, arguments: &str) -> aidaemon_core::CallEffects {
330 self.policy.write_effects(&*self.backend, arguments)
331 }
332
333 async fn owner_approval_request(
336 &self,
337 call: &crate::semantics::ApprovalCall<'_>,
338 facts: &ToolCallContext,
339 ) -> crate::semantics::OwnerApprovalNeed {
340 super::persistence_write_approval(
341 &self.backend,
342 &*self.policy,
343 "write_file",
344 call.arguments,
345 self.call_effects(&call.arguments.to_string()),
346 facts,
347 )
348 .await
349 }
350
351 fn call_annotations_in(
352 &self,
353 arguments: &str,
354 _roots: &crate::semantics::TrustRoots<'_>,
355 ) -> aidaemon_core::ToolAnnotations {
356 let semantics = self.call_semantics(arguments);
357 super::write_call_annotations(self.capabilities(), &semantics, &*self.policy)
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 if args["mode"].as_str().unwrap_or("overwrite") != "overwrite" {
367 return DurableReplayDecision::Replay;
368 }
369 let Some(path_str) = super::path_arg(&args) else {
370 return DurableReplayDecision::Replay;
371 };
372 let Some(content) = super::content_arg(&args) else {
373 return DurableReplayDecision::Replay;
374 };
375
376 let backend = self.backend.clone();
377 let path = match backend.resolve_path(path_str).await {
378 Ok(path) => path,
379 Err(error) => {
380 return DurableReplayDecision::Block {
381 reason: format!(
382 "the prior file-write target can no longer be resolved safely: {error}"
383 ),
384 };
385 }
386 };
387 match backend.read(&path).await {
388 Ok(current) if current == content.as_bytes() => DurableReplayDecision::Replay,
389 Ok(_) => DurableReplayDecision::Block {
390 reason: format!(
391 "the file at {path_str} exists but no longer matches the successful write receipt; inspect and reconcile the current content before overwriting it"
392 ),
393 },
394 Err(read_error) => {
395 let Some(parent) = path.parent() else {
396 return DurableReplayDecision::Block {
397 reason: format!(
398 "the prior file-write target could not be inspected: {read_error}"
399 ),
400 };
401 };
402 match backend.read_dir(&parent).await {
403 Ok(entries) if entries.iter().all(|entry| entry.path != path) => {
404 DurableReplayDecision::Reexecute {
405 reason: format!(
406 "the exact overwrite target {path_str} is absent, so the prior successful receipt no longer satisfies current state"
407 ),
408 }
409 }
410 Ok(_) => DurableReplayDecision::Block {
411 reason: format!(
412 "the file at {path_str} still exists but could not be read; refusing to overwrite unreconciled current state"
413 ),
414 },
415 Err(parent_error) => DurableReplayDecision::Block {
416 reason: format!(
417 "the prior file-write target and its parent could not be inspected safely: {read_error}; {parent_error}"
418 ),
419 },
420 }
421 }
422 }
423 }
424}