Skip to main content

aidaemon_tools/fs/
mod.rs

1//! `read_file`, `write_file` and `edit_file`, over an [`ExecutionBackend`].
2//!
3//! [`FilePolicy`] holds what differs between applications: which paths are
4//! refused, whether a change is backed up, and what is reported after a write.
5
6use std::path::Path;
7use std::sync::Arc;
8
9use async_trait::async_trait;
10use serde_json::Value;
11
12use aidaemon_core::CallEffects;
13
14use crate::backend::{BackendPath, ExecutionBackend};
15use crate::path_class::PathClassifier;
16use crate::workspace::Workspace;
17
18mod edit;
19mod guard;
20mod read;
21mod workspace_backend;
22mod write;
23
24#[cfg(test)]
25mod edit_tests;
26#[cfg(test)]
27mod read_tests;
28#[cfg(test)]
29pub(crate) mod test_support;
30#[cfg(test)]
31mod write_tests;
32
33pub use edit::EditFile;
34pub use guard::ProtectedPathGuard;
35pub use read::{MAX_READ_CHARS, ReadFile, render_read_file_output, render_read_file_output_within};
36pub use workspace_backend::WorkspaceBackend;
37pub use write::WriteFile;
38
39/// Directories to skip during recursive file walks.
40pub const DEFAULT_IGNORE_DIRS: &[&str] = &[
41    ".git",
42    "node_modules",
43    "target",
44    "__pycache__",
45    ".venv",
46    "venv",
47    ".tox",
48    ".mypy_cache",
49    ".pytest_cache",
50    "dist",
51    "build",
52    ".next",
53    ".nuxt",
54    ".svelte-kit",
55    ".cache",
56    ".parcel-cache",
57    "coverage",
58    ".turbo",
59    ".gradle",
60    ".idea",
61    ".vs",
62];
63
64pub(crate) type SharedBackend = Arc<dyn ExecutionBackend>;
65
66/// A tool's model-facing descriptions, for an application that words them
67/// for its own tool set.
68#[derive(Debug, Clone)]
69pub struct ToolText {
70    /// One-line description.
71    pub short: String,
72    /// The description in the tool's schema.
73    pub schema: String,
74}
75
76/// What an application decides about the file tools.
77#[async_trait]
78pub trait FilePolicy: Send + Sync {
79    /// Files `read_file` refuses because they hold secrets.
80    fn is_secret(&self, path: &Path) -> bool;
81    /// [`FilePolicy::is_secret`] without name-shape rules, for `.env.example`
82    /// style templates, which are judged by where they live.
83    fn is_secret_ignoring_name_shape(&self, path: &Path) -> bool;
84    /// Paths the file tools must not change. [`ProtectedPathGuard`] enforces
85    /// these three; add it to the agent.
86    fn is_sensitive(&self, path: &Path) -> bool;
87
88    /// The path a kernel access manifest declares for a path argument.
89    fn declare_path(&self, path: &str) -> String {
90        path.to_string()
91    }
92    /// Whether images are returned as attachments the caller can deliver.
93    fn attaches_images(&self) -> bool {
94        false
95    }
96    /// The tool named in hints that suggest running a command.
97    fn shell_tool_name(&self) -> &str {
98        "shell"
99    }
100    /// A sentence added after an append, on delivering the finished file.
101    fn delivery_hint(&self) -> Option<&str> {
102        None
103    }
104    /// Whether [`FilePolicy::backup_before_overwrite`] keeps a copy.
105    fn keeps_backups(&self) -> bool {
106        false
107    }
108    /// Keep a copy of `path` before it is replaced. Best effort: a failed
109    /// backup never blocks the change.
110    async fn backup_before_overwrite(&self, _backend: &SharedBackend, _path: &BackendPath) {}
111    /// Text appended to a successful write, such as a syntax check.
112    async fn post_write_diagnostics(
113        &self,
114        _backend: &dyn ExecutionBackend,
115        _path: &Path,
116    ) -> String {
117        String::new()
118    }
119    /// The effects of a write call.
120    fn write_effects(&self, _backend: &dyn ExecutionBackend, _arguments: &str) -> CallEffects {
121        CallEffects::unknown()
122    }
123    /// Whether writing `path` changes configuration that later commands run
124    /// (git configuration, for example).
125    fn plants_configuration(&self, _path: &str) -> bool {
126        false
127    }
128    /// Where to go instead when the file tools refuse `path`: an app's own
129    /// files can have a tool of their own (its config tool, for example).
130    fn refusal_hint(&self, _path: &Path) -> Option<String> {
131        None
132    }
133    /// Whether writing `path` plants something that runs or is obeyed later
134    /// without anyone asking (a shell start-up file, a launch agent, a git
135    /// hook, the app's own instruction files): such a write always asks
136    /// the owner.
137    fn is_persistence(&self, path: &Path) -> bool {
138        crate::path_class::is_persistence_path(path, &[])
139    }
140}
141
142/// The policy for tools confined to a [`Workspace`].
143#[derive(Debug, Clone)]
144pub struct WorkspaceFilePolicy {
145    workspace: Workspace,
146    classifier: PathClassifier,
147}
148
149impl WorkspaceFilePolicy {
150    pub fn new(workspace: Workspace) -> Self {
151        Self {
152            workspace,
153            classifier: PathClassifier::empty(),
154        }
155    }
156}
157
158impl FilePolicy for WorkspaceFilePolicy {
159    fn is_secret(&self, path: &Path) -> bool {
160        self.classifier.is_secret(path)
161    }
162
163    fn is_secret_ignoring_name_shape(&self, path: &Path) -> bool {
164        self.classifier.is_secret_ignoring_name_shape(path)
165    }
166
167    fn is_sensitive(&self, path: &Path) -> bool {
168        self.classifier.is_sensitive(path)
169    }
170
171    fn declare_path(&self, path: &str) -> String {
172        self.workspace.declare(path)
173    }
174}
175
176/// What a [`HostFilePolicy`] says and keeps, as the application words it.
177#[derive(Debug, Clone, Default)]
178pub struct HostFilePolicySettings {
179    /// The tool named in hints that suggest running a command.
180    pub shell_tool_name: String,
181    /// A sentence added after an append, on delivering the finished file.
182    pub delivery_hint: Option<String>,
183    /// Where to go instead when the refused path is one of the
184    /// application's own files.
185    pub own_file_hint: Option<String>,
186    /// Keep a copy of a file before it is replaced, under `backup_root`.
187    pub keeps_backups: bool,
188    /// Where backups go (`None`: none is kept).
189    pub backup_root: Option<std::path::PathBuf>,
190}
191
192/// The policy for file tools on the host's own filesystem: secret and
193/// sensitive paths (and the application's own files) by [`DaemonPaths`],
194/// images as attachments, backups before an overwrite, a syntax check after
195/// a write, and the effects of a write (git configuration among them).
196///
197/// [`DaemonPaths`]: crate::path_class::DaemonPaths
198#[derive(Debug, Clone)]
199pub struct HostFilePolicy {
200    paths: crate::path_class::DaemonPaths,
201    settings: HostFilePolicySettings,
202}
203
204impl HostFilePolicy {
205    /// A policy protecting `paths`, worded by `settings`.
206    pub fn new(paths: crate::path_class::DaemonPaths, settings: HostFilePolicySettings) -> Self {
207        Self { paths, settings }
208    }
209}
210
211#[async_trait]
212impl FilePolicy for HostFilePolicy {
213    fn is_secret(&self, path: &Path) -> bool {
214        self.paths.is_secret(path)
215    }
216
217    fn is_secret_ignoring_name_shape(&self, path: &Path) -> bool {
218        self.paths.is_secret_ignoring_name_shape(path)
219    }
220
221    fn is_sensitive(&self, path: &Path) -> bool {
222        self.paths.is_sensitive(path)
223    }
224
225    fn attaches_images(&self) -> bool {
226        true
227    }
228
229    fn refusal_hint(&self, path: &Path) -> Option<String> {
230        self.settings
231            .own_file_hint
232            .clone()
233            .filter(|_| self.paths.is_own_file(path))
234    }
235
236    fn shell_tool_name(&self) -> &str {
237        &self.settings.shell_tool_name
238    }
239
240    fn delivery_hint(&self) -> Option<&str> {
241        self.settings.delivery_hint.as_deref()
242    }
243
244    fn keeps_backups(&self) -> bool {
245        self.settings.keeps_backups
246    }
247
248    async fn backup_before_overwrite(&self, backend: &SharedBackend, path: &BackendPath) {
249        crate::fs_utils::backup_before_overwrite(
250            backend,
251            path,
252            self.settings.backup_root.as_deref(),
253        )
254        .await;
255    }
256
257    async fn post_write_diagnostics(&self, backend: &dyn ExecutionBackend, path: &Path) -> String {
258        crate::fs_utils::post_write_diagnostics(backend, path).await
259    }
260
261    fn write_effects(&self, backend: &dyn ExecutionBackend, arguments: &str) -> CallEffects {
262        crate::command_effects::file_tool_write_effects(backend, arguments)
263    }
264
265    fn plants_configuration(&self, path: &str) -> bool {
266        crate::command_effects::is_git_config_path(path)
267    }
268
269    fn is_persistence(&self, path: &Path) -> bool {
270        self.paths.is_persistence(path)
271    }
272}
273
274/// The owner card a file-tool write needs when its target plants
275/// persistence ([`FilePolicy::is_persistence`]), judged on the path as
276/// written, as the backend resolves it, and with its folder's symlinks
277/// resolved. `Unjudged` for any other write, so the policy's other rules
278/// decide; an exact mandate grant covers it.
279pub(crate) async fn persistence_write_approval(
280    backend: &SharedBackend,
281    policy: &dyn FilePolicy,
282    tool: &str,
283    arguments: &Value,
284    effects: CallEffects,
285    facts: &crate::semantics::ToolCallContext,
286) -> crate::semantics::OwnerApprovalNeed {
287    use crate::semantics::OwnerApprovalNeed;
288    if facts.mandate_preapproved {
289        return OwnerApprovalNeed::Unjudged;
290    }
291    let Some(raw) = path_arg(arguments).map(str::trim).filter(|p| !p.is_empty()) else {
292        return OwnerApprovalNeed::Unjudged;
293    };
294    let mut candidates = vec![std::path::PathBuf::from(
295        shellexpand::tilde(raw).into_owned(),
296    )];
297    if let Ok(resolved) = backend.resolve_path(raw).await {
298        let resolved_path = std::path::PathBuf::from(resolved.as_str());
299        if let (Some(parent), Some(name)) = (resolved_path.parent(), resolved_path.file_name())
300            && let Ok(parent) = backend
301                .canonicalize(&BackendPath::new(parent.to_string_lossy().into_owned()))
302                .await
303        {
304            candidates.push(Path::new(parent.as_str()).join(name));
305        }
306        candidates.push(resolved_path);
307    }
308    let Some(target) = candidates.iter().find(|path| policy.is_persistence(path)) else {
309        return OwnerApprovalNeed::Unjudged;
310    };
311    let target = target.display().to_string();
312    OwnerApprovalNeed::Ask(aidaemon_core::OwnerApprovalRequest {
313        effects: effects.keys,
314        summary: format!(
315            "Write {target}? What this file holds runs or is followed later without asking \
316             (a shell start-up file, login item, scheduled job, git hook or the agent's own \
317             instructions)."
318        ),
319        subject: format!("{tool} {target}"),
320        risk: aidaemon_core::ApprovalRisk::High,
321        warnings: vec![format!(
322            "{target} runs or is loaded automatically later; a change there persists beyond this task."
323        )],
324        card: None,
325    })
326}
327
328pub(crate) fn workspace_parts(workspace: Workspace) -> (SharedBackend, Arc<dyn FilePolicy>) {
329    let policy = Arc::new(WorkspaceFilePolicy::new(workspace.clone()));
330    (Arc::new(WorkspaceBackend::new(workspace)), policy)
331}
332
333/// The path argument of a file tool, under the names models commonly use.
334pub(crate) fn path_arg(arguments: &Value) -> Option<&str> {
335    ["path", "file_path", "file", "filename"]
336        .iter()
337        .find_map(|key| arguments.get(*key).and_then(Value::as_str))
338}
339
340/// Format file content with line numbers.
341pub fn format_with_line_numbers(content: &str, start_line: usize) -> String {
342    let lines: Vec<&str> = content.lines().collect();
343    let total = start_line + lines.len();
344    let width = total.to_string().len().max(3);
345    lines
346        .iter()
347        .enumerate()
348        .map(|(i, line)| format!("{:>width$} | {}", start_line + i + 1, line, width = width))
349        .collect::<Vec<_>>()
350        .join("\n")
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356    use crate::path_class::DaemonPaths;
357
358    #[test]
359    fn host_policy_points_own_files_to_the_hint_and_protects_them() {
360        let own = Path::new("/synthetic/app/config.toml");
361        let policy = HostFilePolicy::new(
362            DaemonPaths::new(vec![own.to_path_buf()]),
363            HostFilePolicySettings {
364                shell_tool_name: "terminal".to_string(),
365                own_file_hint: Some("use the config tool".to_string()),
366                ..Default::default()
367            },
368        );
369        assert!(policy.is_sensitive(own));
370        assert_eq!(
371            policy.refusal_hint(own).as_deref(),
372            Some("use the config tool")
373        );
374        assert_eq!(policy.refusal_hint(Path::new("/synthetic/other.rs")), None);
375        assert_eq!(policy.shell_tool_name(), "terminal");
376        assert!(!policy.keeps_backups());
377        assert!(policy.plants_configuration("/repo/.git/config"));
378    }
379}