aidaemon-tools 0.27.2

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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! `edit_file`: exact find and replace that changes nothing when the text is
//! missing or ambiguous. A batch of `edits` applies in order, all or none, in
//! one write of the file.

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::{
    ToolCallContext, ToolCallOutcome, ToolCallSemantics, ToolCapabilities, ToolMutationEffects,
    ToolRole, ToolTargetHintKind,
};
use crate::workspace::Workspace;

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

impl EditFile {
    /// 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: "Find and replace text in a file".into(),
                schema: "Find and replace text in a file. Fails without changing anything when the text is not found or is ambiguous; read the file again and retry. For several changes to one file, pass `edits`: applied in order, all or nothing.".into(),
            },
        }
    }

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

/// The argument names a model may use for the text to find and its
/// replacement.
const OLD_KEYS: [&str; 4] = ["old_text", "old_string", "search", "find"];
const NEW_KEYS: [&str; 4] = ["new_text", "new_string", "replace", "replacement"];

fn text_arg<'a>(value: &'a Value, keys: [&str; 4]) -> Option<&'a str> {
    keys.iter()
        .find_map(|key| value.get(*key).and_then(Value::as_str))
}

/// One find-and-replace a call asks for.
struct EditArg {
    old_text: String,
    new_text: String,
    replace_all: bool,
}

/// The edits one call asks for: its `edits` list (`batch`), or the single
/// `old_text`/`new_text` pair.
struct EditRequest {
    edits: Vec<EditArg>,
    batch: bool,
}

impl EditRequest {
    /// Read the edits from a call's arguments, or say what is malformed.
    fn parse(args: &Value) -> Result<Self, String> {
        let replace_all = |value: &Value| {
            value
                .get("replace_all")
                .and_then(Value::as_bool)
                .unwrap_or(false)
        };
        let Some(list) = args.get("edits").filter(|value| !value.is_null()) else {
            let old_text = text_arg(args, OLD_KEYS)
                .ok_or("Missing required parameter: old_text (or `edits`)")?;
            let new_text =
                text_arg(args, NEW_KEYS).ok_or("Missing required parameter: new_text")?;
            return Ok(Self {
                edits: vec![EditArg {
                    old_text: old_text.to_string(),
                    new_text: new_text.to_string(),
                    replace_all: replace_all(args),
                }],
                batch: false,
            });
        };
        if text_arg(args, OLD_KEYS).is_some() || text_arg(args, NEW_KEYS).is_some() {
            return Err("Give either `edits` or `old_text`/`new_text`, not both".into());
        }
        let list = list
            .as_array()
            .ok_or("`edits` must be a list of {old_text, new_text, replace_all?}")?;
        if list.is_empty() {
            return Err("`edits` is empty; nothing to change".into());
        }
        let edits = list
            .iter()
            .enumerate()
            .map(|(index, edit)| {
                let n = index + 1;
                let old_text = text_arg(edit, OLD_KEYS)
                    .ok_or_else(|| format!("Edit {n} is missing `old_text`"))?;
                let new_text = text_arg(edit, NEW_KEYS)
                    .ok_or_else(|| format!("Edit {n} is missing `new_text`"))?;
                Ok(EditArg {
                    old_text: old_text.to_string(),
                    new_text: new_text.to_string(),
                    replace_all: replace_all(edit),
                })
            })
            .collect::<Result<Vec<_>, String>>()?;
        Ok(Self { edits, batch: true })
    }

    /// Name edit `index` in a refusal: a batch numbers its edits.
    fn prefix(&self, index: usize) -> String {
        if self.batch {
            format!("Edit {} of {}: ", index + 1, self.edits.len())
        } else {
            String::new()
        }
    }
}

/// One edit applied to a file's text.
struct AppliedEdit {
    new_content: String,
    /// Occurrences of the text that were found.
    count: usize,
    effective_new_text: String,
    used_newline_recovery: bool,
}

/// Every edit of a call applied, in order, to a file's bytes.
struct AppliedEdits {
    new_content: String,
    /// Occurrences replaced, over all the edits.
    replaced: usize,
    /// Each edit's replacement as written, for showing where it landed.
    new_texts: Vec<String>,
    used_newline_recovery: bool,
}

/// Apply every edit of `request` to `bytes`, each to the result of the one
/// before, or say which edit cannot be applied and why. The tool and its
/// `file_write_result` share this, so a predicted result is the one the call
/// writes.
fn apply_edits(
    bytes: &[u8],
    path_str: &str,
    request: &EditRequest,
) -> anyhow::Result<AppliedEdits> {
    if bytes.iter().take(8192).any(|byte| *byte == 0) {
        anyhow::bail!("Cannot edit binary file: {}", path_str);
    }
    let mut content = std::str::from_utf8(bytes)
        .map_err(|_| anyhow::anyhow!("Cannot edit non-UTF-8 file: {}", path_str))?
        .to_string();
    let mut applied_all = AppliedEdits {
        new_content: String::new(),
        replaced: 0,
        new_texts: Vec::with_capacity(request.edits.len()),
        used_newline_recovery: false,
    };
    for (index, edit) in request.edits.iter().enumerate() {
        let applied = apply_edit(&content, path_str, edit).map_err(|why| {
            if request.batch {
                anyhow::anyhow!(
                    "{}failed, so no edit was written. {}",
                    request.prefix(index),
                    why
                )
            } else {
                why
            }
        })?;
        applied_all.replaced += if edit.replace_all { applied.count } else { 1 };
        applied_all.used_newline_recovery |= applied.used_newline_recovery;
        applied_all.new_texts.push(applied.effective_new_text);
        content = applied.new_content;
    }
    applied_all.new_content = content;
    Ok(applied_all)
}

/// Apply one edit to `content`, or say why it cannot be applied.
fn apply_edit(content: &str, path_str: &str, edit: &EditArg) -> anyhow::Result<AppliedEdit> {
    let (old_text, new_text, replace_all) = (
        edit.old_text.as_str(),
        edit.new_text.as_str(),
        edit.replace_all,
    );

    // Count occurrences using exact match first.
    let mut effective_old_text = old_text.to_string();
    let mut effective_new_text = new_text.to_string();
    let mut count = content.matches(&effective_old_text).count();

    // Self-recovery path: tolerate newline-style mismatch (LF vs CRLF) while
    // preserving strict exact matching otherwise.
    if count == 0 {
        let file_newline = detect_newline_style(content);
        let normalized_old = normalize_newlines_for_style(old_text, file_newline);
        if normalized_old != old_text {
            let normalized_count = content.matches(&normalized_old).count();
            if normalized_count > 0 {
                effective_old_text = normalized_old;
                effective_new_text = normalize_newlines_for_style(new_text, file_newline);
                count = normalized_count;
            }
        }
    }

    if count == 0 {
        anyhow::bail!("{}", build_not_found_message(path_str, content, old_text));
    }

    if count > 1 && !replace_all {
        anyhow::bail!(
            "Found {} occurrences of the text in {}. Set replace_all=true to replace all, or provide more context to make old_text unique.",
            count,
            path_str
        );
    }

    let new_content = if replace_all {
        content.replace(&effective_old_text, &effective_new_text)
    } else {
        content.replacen(&effective_old_text, &effective_new_text, 1)
    };
    Ok(AppliedEdit {
        new_content,
        count,
        used_newline_recovery: effective_old_text != old_text,
        effective_new_text,
    })
}

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

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

    fn schema(&self) -> Value {
        json!({
            "name": "edit_file",
            "description": self.text.schema,
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Path to the file (supports ~ expansion)"
                    },
                    "old_text": {
                        "type": "string",
                        "description": "Exact text to find and replace"
                    },
                    "new_text": {
                        "type": "string",
                        "description": "Text to replace with"
                    },
                    "replace_all": {
                        "type": "boolean",
                        "description": "Replace all occurrences (default: false, errors if multiple found)"
                    },
                    "edits": {
                        "type": "array",
                        "description": "Several edits, in place of old_text/new_text; each applies to the result of the one before",
                        "items": {
                            "type": "object",
                            "properties": {
                                "old_text": {
                                    "type": "string",
                                    "description": "Exact text to find"
                                },
                                "new_text": {
                                    "type": "string",
                                    "description": "Text to replace with"
                                },
                                "replace_all": {
                                    "type": "boolean",
                                    "description": "Replace all occurrences (default: false)"
                                }
                            },
                            "required": ["old_text", "new_text"],
                            "additionalProperties": false
                        }
                    }
                },
                "required": ["path"],
                "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 request = EditRequest::parse(&args).map_err(|why| anyhow::anyhow!(why))?;

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

        if backend.metadata(&path).await.is_err() {
            return Err(crate::TargetNotFound(format!("File not found: {path_str}")).into());
        }

        // Held from before the read 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,
        };

        let bytes = backend.read(&path).await?;
        let AppliedEdits {
            new_content,
            replaced,
            new_texts,
            used_newline_recovery,
        } = apply_edits(&bytes, path_str, &request)?;

        // Backup + atomic write
        self.policy.backup_before_overwrite(&backend, &path).await;
        backend
            .write(&path, new_content.as_bytes(), WriteMode::Overwrite, false)
            .await?;
        if let Some(write_guard) = write_guard {
            write_guard.committed().await;
        }

        // Show context around each change (the first few of a batch).
        const SHOWN_EDITS: usize = 5;
        let mut context = new_texts
            .iter()
            .take(SHOWN_EDITS)
            .map(|new_text| get_change_context(&new_content, new_text))
            .collect::<Vec<_>>()
            .join("\n     ...\n");
        if new_texts.len() > SHOWN_EDITS {
            context.push_str(&format!(
                "\n(and {} more edits)",
                new_texts.len() - SHOWN_EDITS
            ));
        }
        let edits = if request.batch {
            format!("applied {} edits, ", request.edits.len())
        } else {
            String::new()
        };
        let diagnostics = self
            .policy
            .post_write_diagnostics(&*backend, std::path::Path::new(path.as_str()))
            .await;

        Ok(ToolCallOutcome::from_output(format!(
            "Edited {}: {}replaced {} occurrence{}{}\n\n{}{}",
            path_str,
            edits,
            replaced,
            if replaced > 1 { "s" } else { "" },
            if used_newline_recovery {
                " (newline-normalized match)"
            } else {
                ""
            },
            context,
            diagnostics
        )))
    }

    fn validate_call(&self, arguments: &Value) -> Result<(), String> {
        let request = EditRequest::parse(arguments)?;
        for (index, edit) in request.edits.iter().enumerate() {
            let prefix = request.prefix(index);
            if edit.old_text.is_empty() {
                return Err(format!(
                    "{prefix}`old_text` must not be empty; use write_file to create a file"
                ));
            }
            if edit.old_text == edit.new_text {
                return Err(format!(
                    "{prefix}`old_text` and `new_text` are identical; nothing to change"
                ));
            }
        }
        Ok(())
    }
}

core_tool!(
    EditFile,
    annotations: ToolAnnotations::WRITE,
    access: |this, arguments| {
        let paths: Vec<String> = path_arg(arguments)
            .map(|path| vec![this.policy.declare_path(path)])
            .unwrap_or_default();
        AccessManifest {
            reads: paths.clone(),
            writes: paths,
            ..Default::default()
        }
    }
);

#[async_trait]
impl crate::semantics::ToolSemantics for EditFile {
    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("editing a file"),
            evidence: crate::semantics::EvidenceSource::FileWrite,
            ..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: find-and-replace with safe failure on ambiguity.
            // Dedicated file tools are intentionally available without terminal
            // approval. Sensitive paths are blocked before editing.
            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();

        // It reads the file under its write fence and returns what the file
        // now holds around each change: a write and an observation of the
        // result, so a successful edit proves the file's current state.
        ToolCallSemantics::observation_and_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()?;
        let request = EditRequest::parse(&args).ok()?;
        let kind = if request.batch {
            crate::semantics::FileWriteKind::Edits(
                request
                    .edits
                    .into_iter()
                    .map(|edit| crate::semantics::TextEdit {
                        old_text: edit.old_text,
                        replace_all: edit.replace_all,
                    })
                    .collect(),
            )
        } else {
            let edit = request.edits.into_iter().next()?;
            crate::semantics::FileWriteKind::Edit {
                old_text: edit.old_text,
                replace_all: edit.replace_all,
            }
        };
        Some(crate::semantics::FileWrite {
            path: path_arg(&args)?.to_string(),
            kind,
        })
    }

    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 path = path_arg(&args)?;
        let request = EditRequest::parse(&args).ok()?;
        let Some(current) = current else {
            return Some(Err(format!("File not found: {path}")));
        };
        Some(
            apply_edits(current, path, &request)
                .map(|applied| applied.new_content.into_bytes())
                .map_err(|why| why.to_string()),
        )
    }

    /// 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,
            "edit_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)
    }
}

fn detect_newline_style(content: &str) -> &'static str {
    let crlf_count = content.matches("\r\n").count();
    let lf_total = content.matches('\n').count();
    let lf_only_count = lf_total.saturating_sub(crlf_count);
    if crlf_count > lf_only_count {
        "\r\n"
    } else {
        "\n"
    }
}

fn normalize_newlines_for_style(input: &str, newline: &str) -> String {
    let normalized = input.replace("\r\n", "\n").replace('\r', "\n");
    if newline == "\r\n" {
        normalized.replace('\n', "\r\n")
    } else {
        normalized
    }
}

fn truncate_with_ellipsis(input: &str, max_chars: usize) -> String {
    if input.chars().count() <= max_chars {
        return input.to_string();
    }
    let mut out: String = input.chars().take(max_chars).collect();
    out.push_str("...");
    out
}

fn build_file_preview(content: &str, max_lines: usize, max_chars: usize) -> String {
    if content.is_empty() {
        return "(file is empty)".to_string();
    }

    let mut preview_lines = Vec::new();
    for (idx, line) in content.lines().take(max_lines).enumerate() {
        preview_lines.push(format!("{:>4} | {}", idx + 1, line));
    }

    let total_lines = content.lines().count();
    if total_lines > max_lines {
        preview_lines.push(format!("... ({} more lines)", total_lines - max_lines));
    }

    let joined = preview_lines.join("\n");
    truncate_with_ellipsis(&joined, max_chars)
}

fn build_not_found_message(path: &str, content: &str, old_text: &str) -> String {
    let first_non_empty_old = old_text
        .lines()
        .find(|line| !line.trim().is_empty())
        .unwrap_or(old_text)
        .trim();
    let old_hint = if first_non_empty_old.is_empty() {
        "old_text appears empty or whitespace-only.".to_string()
    } else {
        format!(
            "old_text first non-empty line: `{}`",
            truncate_with_ellipsis(first_non_empty_old, 120)
        )
    };

    let preview = build_file_preview(content, 40, 3500);
    format!(
        "Text not found in {}. The old_text must match exactly (including whitespace and indentation).\n\
{}\n\n\
Self-recovery steps:\n\
1. Call read_file on the same path.\n\
2. Copy the exact block from the file output into old_text and retry edit_file.\n\
3. If the goal is replacing the whole file, use write_file instead of edit_file.\n\n\
File preview:\n{}",
        path, old_hint, preview
    )
}

/// Get a few lines of context around where the replacement was made.
fn get_change_context(content: &str, new_text: &str) -> String {
    let lines: Vec<&str> = content.lines().collect();
    let new_text_first_line = new_text.lines().next().unwrap_or(new_text);

    // Find the first line containing the new text
    if let Some(idx) = lines.iter().position(|l| l.contains(new_text_first_line)) {
        let start = idx.saturating_sub(2);
        let end = (idx + new_text.lines().count() + 2).min(lines.len());
        let context_lines: Vec<String> = lines[start..end]
            .iter()
            .enumerate()
            .map(|(i, line)| format!("{:>4} | {}", start + i + 1, line))
            .collect();
        context_lines.join("\n")
    } else {
        String::from("(change context not available)")
    }
}