aidaemon-tools 0.27.1

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
//! `read_file`, `write_file` and `edit_file`, over an [`ExecutionBackend`].
//!
//! [`FilePolicy`] holds what differs between applications: which paths are
//! refused, whether a change is backed up, and what is reported after a write.

use std::path::Path;
use std::sync::Arc;

use async_trait::async_trait;
use serde_json::Value;

use aidaemon_core::CallEffects;

use crate::backend::{BackendPath, ExecutionBackend};
use crate::path_class::PathClassifier;
use crate::workspace::Workspace;

mod edit;
mod guard;
mod read;
mod workspace_backend;
mod write;

#[cfg(test)]
mod edit_tests;
#[cfg(test)]
mod read_tests;
#[cfg(test)]
pub(crate) mod test_support;
#[cfg(test)]
mod write_tests;

pub use edit::EditFile;
pub use guard::ProtectedPathGuard;
pub use read::{MAX_READ_CHARS, ReadFile, render_read_file_output, render_read_file_output_within};
pub use workspace_backend::WorkspaceBackend;
pub use write::WriteFile;

/// Directories to skip during recursive file walks.
pub const DEFAULT_IGNORE_DIRS: &[&str] = &[
    ".git",
    "node_modules",
    "target",
    "__pycache__",
    ".venv",
    "venv",
    ".tox",
    ".mypy_cache",
    ".pytest_cache",
    "dist",
    "build",
    ".next",
    ".nuxt",
    ".svelte-kit",
    ".cache",
    ".parcel-cache",
    "coverage",
    ".turbo",
    ".gradle",
    ".idea",
    ".vs",
];

pub(crate) type SharedBackend = Arc<dyn ExecutionBackend>;

/// A tool's model-facing descriptions, for an application that words them
/// for its own tool set.
#[derive(Debug, Clone)]
pub struct ToolText {
    /// One-line description.
    pub short: String,
    /// The description in the tool's schema.
    pub schema: String,
}

/// What an application decides about the file tools.
#[async_trait]
pub trait FilePolicy: Send + Sync {
    /// Files `read_file` refuses because they hold secrets.
    fn is_secret(&self, path: &Path) -> bool;
    /// [`FilePolicy::is_secret`] without name-shape rules, for `.env.example`
    /// style templates, which are judged by where they live.
    fn is_secret_ignoring_name_shape(&self, path: &Path) -> bool;
    /// Paths the file tools must not change. [`ProtectedPathGuard`] enforces
    /// these three; add it to the agent.
    fn is_sensitive(&self, path: &Path) -> bool;

    /// The path a kernel access manifest declares for a path argument.
    fn declare_path(&self, path: &str) -> String {
        path.to_string()
    }
    /// Whether images are returned as attachments the caller can deliver.
    fn attaches_images(&self) -> bool {
        false
    }
    /// The tool named in hints that suggest running a command.
    fn shell_tool_name(&self) -> &str {
        "shell"
    }
    /// A sentence added after an append, on delivering the finished file.
    fn delivery_hint(&self) -> Option<&str> {
        None
    }
    /// Whether [`FilePolicy::backup_before_overwrite`] keeps a copy.
    fn keeps_backups(&self) -> bool {
        false
    }
    /// Keep a copy of `path` before it is replaced. Best effort: a failed
    /// backup never blocks the change.
    async fn backup_before_overwrite(&self, _backend: &SharedBackend, _path: &BackendPath) {}
    /// Text appended to a successful write, such as a syntax check.
    async fn post_write_diagnostics(
        &self,
        _backend: &dyn ExecutionBackend,
        _path: &Path,
    ) -> String {
        String::new()
    }
    /// The effects of a write call.
    fn write_effects(&self, _backend: &dyn ExecutionBackend, _arguments: &str) -> CallEffects {
        CallEffects::unknown()
    }
    /// Whether writing `path` changes configuration that later commands run
    /// (git configuration, for example).
    fn plants_configuration(&self, _path: &str) -> bool {
        false
    }
    /// Where to go instead when the file tools refuse `path`: an app's own
    /// files can have a tool of their own (its config tool, for example).
    fn refusal_hint(&self, _path: &Path) -> Option<String> {
        None
    }
    /// Whether writing `path` plants something that runs or is obeyed later
    /// without anyone asking (a shell start-up file, a launch agent, a git
    /// hook, the app's own instruction files): such a write always asks
    /// the owner.
    fn is_persistence(&self, path: &Path) -> bool {
        crate::path_class::is_persistence_path(path, &[])
    }
}

/// The policy for tools confined to a [`Workspace`].
#[derive(Debug, Clone)]
pub struct WorkspaceFilePolicy {
    workspace: Workspace,
    classifier: PathClassifier,
}

impl WorkspaceFilePolicy {
    pub fn new(workspace: Workspace) -> Self {
        Self {
            workspace,
            classifier: PathClassifier::empty(),
        }
    }
}

impl FilePolicy for WorkspaceFilePolicy {
    fn is_secret(&self, path: &Path) -> bool {
        self.classifier.is_secret(path)
    }

    fn is_secret_ignoring_name_shape(&self, path: &Path) -> bool {
        self.classifier.is_secret_ignoring_name_shape(path)
    }

    fn is_sensitive(&self, path: &Path) -> bool {
        self.classifier.is_sensitive(path)
    }

    fn declare_path(&self, path: &str) -> String {
        self.workspace.declare(path)
    }
}

/// What a [`HostFilePolicy`] says and keeps, as the application words it.
#[derive(Debug, Clone, Default)]
pub struct HostFilePolicySettings {
    /// The tool named in hints that suggest running a command.
    pub shell_tool_name: String,
    /// A sentence added after an append, on delivering the finished file.
    pub delivery_hint: Option<String>,
    /// Where to go instead when the refused path is one of the
    /// application's own files.
    pub own_file_hint: Option<String>,
    /// Keep a copy of a file before it is replaced, under `backup_root`.
    pub keeps_backups: bool,
    /// Where backups go (`None`: none is kept).
    pub backup_root: Option<std::path::PathBuf>,
}

/// The policy for file tools on the host's own filesystem: secret and
/// sensitive paths (and the application's own files) by [`DaemonPaths`],
/// images as attachments, backups before an overwrite, a syntax check after
/// a write, and the effects of a write (git configuration among them).
///
/// [`DaemonPaths`]: crate::path_class::DaemonPaths
#[derive(Debug, Clone)]
pub struct HostFilePolicy {
    paths: crate::path_class::DaemonPaths,
    settings: HostFilePolicySettings,
}

impl HostFilePolicy {
    /// A policy protecting `paths`, worded by `settings`.
    pub fn new(paths: crate::path_class::DaemonPaths, settings: HostFilePolicySettings) -> Self {
        Self { paths, settings }
    }
}

#[async_trait]
impl FilePolicy for HostFilePolicy {
    fn is_secret(&self, path: &Path) -> bool {
        self.paths.is_secret(path)
    }

    fn is_secret_ignoring_name_shape(&self, path: &Path) -> bool {
        self.paths.is_secret_ignoring_name_shape(path)
    }

    fn is_sensitive(&self, path: &Path) -> bool {
        self.paths.is_sensitive(path)
    }

    fn attaches_images(&self) -> bool {
        true
    }

    fn refusal_hint(&self, path: &Path) -> Option<String> {
        self.settings
            .own_file_hint
            .clone()
            .filter(|_| self.paths.is_own_file(path))
    }

    fn shell_tool_name(&self) -> &str {
        &self.settings.shell_tool_name
    }

    fn delivery_hint(&self) -> Option<&str> {
        self.settings.delivery_hint.as_deref()
    }

    fn keeps_backups(&self) -> bool {
        self.settings.keeps_backups
    }

    async fn backup_before_overwrite(&self, backend: &SharedBackend, path: &BackendPath) {
        crate::fs_utils::backup_before_overwrite(
            backend,
            path,
            self.settings.backup_root.as_deref(),
        )
        .await;
    }

    async fn post_write_diagnostics(&self, backend: &dyn ExecutionBackend, path: &Path) -> String {
        crate::fs_utils::post_write_diagnostics(backend, path).await
    }

    fn write_effects(&self, backend: &dyn ExecutionBackend, arguments: &str) -> CallEffects {
        crate::command_effects::file_tool_write_effects(backend, arguments)
    }

    fn plants_configuration(&self, path: &str) -> bool {
        crate::command_effects::is_git_config_path(path)
    }

    fn is_persistence(&self, path: &Path) -> bool {
        self.paths.is_persistence(path)
    }
}

/// The owner card a file-tool write needs when its target plants
/// persistence ([`FilePolicy::is_persistence`]), judged on the path as
/// written, as the backend resolves it, and with its folder's symlinks
/// resolved. `Unjudged` for any other write, so the policy's other rules
/// decide; an exact mandate grant covers it.
pub(crate) async fn persistence_write_approval(
    backend: &SharedBackend,
    policy: &dyn FilePolicy,
    tool: &str,
    arguments: &Value,
    effects: CallEffects,
    facts: &crate::semantics::ToolCallContext,
) -> crate::semantics::OwnerApprovalNeed {
    use crate::semantics::OwnerApprovalNeed;
    if facts.mandate_preapproved {
        return OwnerApprovalNeed::Unjudged;
    }
    let Some(raw) = path_arg(arguments).map(str::trim).filter(|p| !p.is_empty()) else {
        return OwnerApprovalNeed::Unjudged;
    };
    let mut candidates = vec![std::path::PathBuf::from(
        shellexpand::tilde(raw).into_owned(),
    )];
    if let Ok(resolved) = backend.resolve_path(raw).await {
        let resolved_path = std::path::PathBuf::from(resolved.as_str());
        if let (Some(parent), Some(name)) = (resolved_path.parent(), resolved_path.file_name())
            && let Ok(parent) = backend
                .canonicalize(&BackendPath::new(parent.to_string_lossy().into_owned()))
                .await
        {
            candidates.push(Path::new(parent.as_str()).join(name));
        }
        candidates.push(resolved_path);
    }
    let Some(target) = candidates.iter().find(|path| policy.is_persistence(path)) else {
        return OwnerApprovalNeed::Unjudged;
    };
    let target = target.display().to_string();
    OwnerApprovalNeed::Ask(aidaemon_core::OwnerApprovalRequest {
        effects: effects.keys,
        summary: format!(
            "Write {target}? What this file holds runs or is followed later without asking \
             (a shell start-up file, login item, scheduled job, git hook or the agent's own \
             instructions)."
        ),
        subject: format!("{tool} {target}"),
        risk: aidaemon_core::ApprovalRisk::High,
        warnings: vec![format!(
            "{target} runs or is loaded automatically later; a change there persists beyond this task."
        )],
        card: None,
    })
}

pub(crate) fn workspace_parts(workspace: Workspace) -> (SharedBackend, Arc<dyn FilePolicy>) {
    let policy = Arc::new(WorkspaceFilePolicy::new(workspace.clone()));
    (Arc::new(WorkspaceBackend::new(workspace)), policy)
}

/// The path argument of a file tool, under the names models commonly use.
pub(crate) fn path_arg(arguments: &Value) -> Option<&str> {
    ["path", "file_path", "file", "filename"]
        .iter()
        .find_map(|key| arguments.get(*key).and_then(Value::as_str))
}

/// The content argument of `write_file`, under the names models commonly
/// use.
pub(crate) fn content_arg(arguments: &Value) -> Option<&str> {
    ["content", "data", "text"]
        .iter()
        .find_map(|key| arguments.get(*key).and_then(Value::as_str))
}

/// A file write's annotations: the defaults, plus egress when a target can
/// plant git configuration (which changes what later "read-only" git
/// commands execute).
pub(crate) fn write_call_annotations(
    capabilities: crate::semantics::ToolCapabilities,
    semantics: &crate::semantics::ToolCallSemantics,
    policy: &dyn FilePolicy,
) -> aidaemon_core::ToolAnnotations {
    let mut annotations = crate::semantics::default_call_annotations(capabilities, semantics);
    annotations.egress |= semantics
        .target_hints
        .iter()
        .any(|hint| policy.plants_configuration(&hint.value));
    annotations
}

/// Format file content with line numbers.
pub fn format_with_line_numbers(content: &str, start_line: usize) -> String {
    let lines: Vec<&str> = content.lines().collect();
    let total = start_line + lines.len();
    let width = total.to_string().len().max(3);
    lines
        .iter()
        .enumerate()
        .map(|(i, line)| format!("{:>width$} | {}", start_line + i + 1, line, width = width))
        .collect::<Vec<_>>()
        .join("\n")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::path_class::DaemonPaths;

    #[test]
    fn host_policy_points_own_files_to_the_hint_and_protects_them() {
        let own = Path::new("/synthetic/app/config.toml");
        let policy = HostFilePolicy::new(
            DaemonPaths::new(vec![own.to_path_buf()]),
            HostFilePolicySettings {
                shell_tool_name: "terminal".to_string(),
                own_file_hint: Some("use the config tool".to_string()),
                ..Default::default()
            },
        );
        assert!(policy.is_sensitive(own));
        assert_eq!(
            policy.refusal_hint(own).as_deref(),
            Some("use the config tool")
        );
        assert_eq!(policy.refusal_hint(Path::new("/synthetic/other.rs")), None);
        assert_eq!(policy.shell_tool_name(), "terminal");
        assert!(!policy.keeps_backups());
        assert!(policy.plants_configuration("/repo/.git/config"));
    }
}