aidaemon-tools 0.27.3

Ready-made tools for aidaemon agents (files, search, sandboxed shell, web, checklist); implementation crate of the aidaemon SDK, no stability promise (use it through aidaemon-sdk)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! `write_file`: create, overwrite or append.

use std::sync::Arc;

use async_trait::async_trait;
use serde_json::{Value, json};

use aidaemon_core::{AccessManifest, ToolAnnotations};

use super::{FilePolicy, SharedBackend, ToolText, path_arg, workspace_parts};
use crate::backend::WriteMode;
use crate::outcome::{OutcomeTool, core_tool};
use crate::semantics::{
    DurableReplayDecision, ToolCallContext, ToolCallOutcome, ToolCallSemantics, ToolCapabilities,
    ToolMutationEffects, ToolRole, ToolTargetHintKind,
};
use crate::workspace::Workspace;

const MAX_CONTENT_SIZE: usize = 1024 * 1024; // 1MB

pub struct WriteFile {
    backend: SharedBackend,
    policy: Arc<dyn FilePolicy>,
    text: ToolText,
}

impl WriteFile {
    /// A tool confined to `workspace`.
    pub fn new(workspace: Workspace) -> Self {
        let (backend, policy) = workspace_parts(workspace);
        Self::on_backend(backend, policy)
    }

    /// A tool working through `backend` under an application's `policy`.
    pub fn on_backend(backend: SharedBackend, policy: Arc<dyn FilePolicy>) -> Self {
        Self {
            backend,
            policy,
            text: ToolText {
                short: "Write or create a file with given content".into(),
                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(),
            },
        }
    }

    /// Replace the model-facing descriptions.
    pub fn with_text(mut self, text: ToolText) -> Self {
        self.text = text;
        self
    }
}

#[async_trait]
impl OutcomeTool for WriteFile {
    fn name(&self) -> &str {
        "write_file"
    }

    fn description(&self) -> &str {
        &self.text.short
    }

    fn schema(&self) -> Value {
        json!({
            "name": "write_file",
            "description": self.text.schema,
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Path to write to (supports ~ expansion)"
                    },
                    "content": {
                        "type": "string",
                        "description": "Content to write to the file"
                    },
                    "create_dirs": {
                        "type": "boolean",
                        "description": "Create parent directories if they don't exist (default: true)"
                    },
                    "mode": {
                        "type": "string",
                        "enum": ["overwrite", "append"],
                        "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)."
                    }
                },
                "required": ["path", "content"],
                "additionalProperties": false
            }
        })
    }

    async fn execute(
        &self,
        arguments: &str,
        facts: &ToolCallContext,
    ) -> anyhow::Result<ToolCallOutcome> {
        let args: Value = serde_json::from_str(arguments)?;
        let path_str = super::path_arg(&args)
            .ok_or_else(|| anyhow::anyhow!("Missing required parameter: path"))?;
        let content = super::content_arg(&args)
            .ok_or_else(|| anyhow::anyhow!("Missing required parameter: content"))?;
        let create_dirs = args["create_dirs"].as_bool().unwrap_or(true);

        if content.len() > MAX_CONTENT_SIZE {
            anyhow::bail!(
                "Content too large: {} bytes (max {})",
                content.len(),
                MAX_CONTENT_SIZE
            );
        }

        let backend = self.backend.clone();
        let path = backend.resolve_path(path_str).await?;

        // Create parent dirs if requested
        if create_dirs {
            if let Some(parent) = path.parent() {
                backend.create_dir_all(&parent).await?;
            }
        } else if let Some(parent) = path.parent()
            && !backend
                .metadata(&parent)
                .await
                .is_ok_and(|metadata| metadata.is_dir())
        {
            return Err(crate::TargetNotFound(format!(
                "Parent directory does not exist: {parent}. Set create_dirs=true to create it."
            ))
            .into());
        }

        // Write mode: "overwrite" (default, replaces with backup) or "append"
        // (additive, no backup — lets the model build a large file in chunks
        // instead of one oversized generation).
        let mode = args["mode"].as_str().unwrap_or("overwrite");
        if mode != "overwrite" && mode != "append" {
            anyhow::bail!(
                "Invalid mode: \"{}\" (expected \"overwrite\" or \"append\")",
                mode
            );
        }

        // Held until the write has landed.
        let write_guard = match crate::semantics::file_fence(facts) {
            Some(fence) => Some(
                fence
                    .begin_write(path_str)
                    .await
                    .map_err(|why| anyhow::anyhow!(why))?,
            ),
            None => None,
        };

        if mode == "append" {
            let existing_size = backend
                .metadata(&path)
                .await
                .map(|metadata| metadata.len)
                .unwrap_or(0);
            backend
                .write(&path, content.as_bytes(), WriteMode::Append, create_dirs)
                .await?;
            if let Some(write_guard) = write_guard {
                write_guard.committed().await;
            }

            let appended = content.len();
            let appended_lines = content.lines().count();
            let total = existing_size + appended as u64;
            let delivery = self
                .policy
                .delivery_hint()
                .map(|hint| format!(" {hint}"))
                .unwrap_or_default();
            return Ok(ToolCallOutcome::from_output(format!(
                "Appended {} bytes ({} lines) to {} (now {} bytes total). \
                 To add more, call write_file again with mode=\"append\".{}",
                appended, appended_lines, path_str, total, delivery
            )));
        }

        // Backup existing file
        let existing_metadata = backend.metadata(&path).await.ok();
        let existed = existing_metadata.is_some();
        let old_size = if existed {
            let size = existing_metadata
                .as_ref()
                .map_or(0, |metadata| metadata.len);
            // One backup per file, outside the user's tree when local.
            self.policy.backup_before_overwrite(&backend, &path).await;
            Some(size)
        } else {
            None
        };

        backend
            .write(&path, content.as_bytes(), WriteMode::Overwrite, create_dirs)
            .await?;
        if let Some(write_guard) = write_guard {
            write_guard.committed().await;
        }

        let new_size = content.len();
        let line_count = content.lines().count();

        let action = if existed { "Updated" } else { "Created" };
        let size_info = if let Some(old) = old_size {
            let backup = if self.policy.keeps_backups() {
                ", backup saved"
            } else {
                ""
            };
            format!(" (was {} bytes{})", old, backup)
        } else {
            String::new()
        };

        let diagnostics = self
            .policy
            .post_write_diagnostics(&*backend, std::path::Path::new(path.as_str()))
            .await;

        Ok(ToolCallOutcome::from_output(format!(
            "{} {}\n{} bytes, {} lines{}{}",
            action, path_str, new_size, line_count, size_info, diagnostics
        )))
    }
}

core_tool!(
    WriteFile,
    // Append mode writes more each time, so a repeat is not a no-op.
    annotations: ToolAnnotations::WRITE,
    access: |this, arguments| AccessManifest {
        writes: path_arg(arguments)
            .map(|path| vec![this.policy.declare_path(path)])
            .unwrap_or_default(),
        ..Default::default()
    }
);

#[async_trait::async_trait]
#[async_trait]
impl crate::semantics::ToolSemantics for WriteFile {
    fn dispatch_facts(&self) -> crate::semantics::ToolDispatchFacts {
        crate::semantics::ToolDispatchFacts {
            offering: crate::semantics::Offering::Core,
            checkpoints_writes: true,
            file_guard: crate::semantics::FileGuard::Writes,
            recap: crate::semantics::RecapKind::FileWrite,
            activity: crate::semantics::ToolActivity::Fixed(
                aidaemon_core::card::ActivityKind::Write,
            ),
            opens_project_instructions: true,
            semantic_scope: Some(crate::semantics::ToolSemanticScope::LocalWorkspace),
            low_signal_result: true,
            status_label: Some("writing a file"),
            ..Default::default()
        }
    }

    fn tool_role(&self) -> ToolRole {
        ToolRole::Action
    }

    fn capabilities(&self) -> ToolCapabilities {
        ToolCapabilities {
            read_only: false,
            external_side_effect: false,
            needs_approval: false,
            idempotent: false,
            // Not high-impact: creates backups before overwriting, user-scoped
            // file system only, and dedicated file tools are intentionally
            // available without terminal approval. Sensitive paths are blocked
            // before writing.
            high_impact_write: false,
        }
    }

    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
        let path = serde_json::from_str::<Value>(arguments)
            .ok()
            .and_then(|args| {
                for key in ["path", "file_path", "file", "filename"] {
                    if let Some(path) = args.get(key).and_then(|value| value.as_str()) {
                        return Some(path.to_string());
                    }
                }
                None
            })
            .unwrap_or_default();

        ToolCallSemantics::mutation_with(ToolMutationEffects::LOCAL_SOURCE_WRITE)
            .with_target_hint(ToolTargetHintKind::Path, path)
    }

    fn call_file_write(&self, arguments: &str) -> Option<crate::semantics::FileWrite> {
        let args: Value = serde_json::from_str(arguments).ok()?;
        Some(crate::semantics::FileWrite {
            path: path_arg(&args)?.to_string(),
            kind: if args["mode"].as_str() == Some("append") {
                crate::semantics::FileWriteKind::Append
            } else {
                crate::semantics::FileWriteKind::Replace
            },
        })
    }

    fn file_write_result(
        &self,
        arguments: &str,
        current: Option<&[u8]>,
    ) -> Option<Result<Vec<u8>, String>> {
        let args: Value = serde_json::from_str(arguments).ok()?;
        let content = super::content_arg(&args)?;
        let mut result = match args["mode"].as_str() {
            Some("append") => current.unwrap_or_default().to_vec(),
            Some("overwrite") | None => Vec::new(),
            Some(_) => return None,
        };
        result.extend_from_slice(content.as_bytes());
        Some(Ok(result))
    }

    /// A write of the target path (absolute; a relative path resolves where
    /// the execution backend puts it, which is not known here).
    fn call_effects(&self, arguments: &str) -> aidaemon_core::CallEffects {
        self.policy.write_effects(&*self.backend, arguments)
    }

    /// A write that plants persistence (a shell start-up file, a launch
    /// agent, a git hook, the agent's own instructions) always asks.
    async fn owner_approval_request(
        &self,
        call: &crate::semantics::ApprovalCall<'_>,
        facts: &ToolCallContext,
    ) -> crate::semantics::OwnerApprovalNeed {
        super::persistence_write_approval(
            &self.backend,
            &*self.policy,
            "write_file",
            call.arguments,
            self.call_effects(&call.arguments.to_string()),
            facts,
        )
        .await
    }

    fn call_annotations_in(
        &self,
        arguments: &str,
        _roots: &crate::semantics::TrustRoots<'_>,
    ) -> aidaemon_core::ToolAnnotations {
        let semantics = self.call_semantics(arguments);
        super::write_call_annotations(self.capabilities(), &semantics, &*self.policy)
    }

    async fn durable_replay_decision(&self, arguments: &str) -> DurableReplayDecision {
        let Ok(args) = serde_json::from_str::<Value>(arguments) else {
            return DurableReplayDecision::Replay;
        };
        // Appending the same bytes twice is not safe. Keep the durable receipt
        // authoritative for append calls; callers must issue a new operation.
        if args["mode"].as_str().unwrap_or("overwrite") != "overwrite" {
            return DurableReplayDecision::Replay;
        }
        let Some(path_str) = super::path_arg(&args) else {
            return DurableReplayDecision::Replay;
        };
        let Some(content) = super::content_arg(&args) else {
            return DurableReplayDecision::Replay;
        };

        let backend = self.backend.clone();
        let path = match backend.resolve_path(path_str).await {
            Ok(path) => path,
            Err(error) => {
                return DurableReplayDecision::Block {
                    reason: format!(
                        "the prior file-write target can no longer be resolved safely: {error}"
                    ),
                };
            }
        };
        match backend.read(&path).await {
            Ok(current) if current == content.as_bytes() => DurableReplayDecision::Replay,
            Ok(_) => DurableReplayDecision::Block {
                reason: format!(
                    "the file at {path_str} exists but no longer matches the successful write receipt; inspect and reconcile the current content before overwriting it"
                ),
            },
            Err(read_error) => {
                let Some(parent) = path.parent() else {
                    return DurableReplayDecision::Block {
                        reason: format!(
                            "the prior file-write target could not be inspected: {read_error}"
                        ),
                    };
                };
                match backend.read_dir(&parent).await {
                    Ok(entries) if entries.iter().all(|entry| entry.path != path) => {
                        DurableReplayDecision::Reexecute {
                            reason: format!(
                                "the exact overwrite target {path_str} is absent, so the prior successful receipt no longer satisfies current state"
                            ),
                        }
                    }
                    Ok(_) => DurableReplayDecision::Block {
                        reason: format!(
                            "the file at {path_str} still exists but could not be read; refusing to overwrite unreconciled current state"
                        ),
                    },
                    Err(parent_error) => DurableReplayDecision::Block {
                        reason: format!(
                            "the prior file-write target and its parent could not be inspected safely: {read_error}; {parent_error}"
                        ),
                    },
                }
            }
        }
    }
}