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
24pub use edit::EditFile;
25pub use guard::ProtectedPathGuard;
26pub use read::{MAX_READ_CHARS, ReadFile, render_read_file_output, render_read_file_output_within};
27pub use workspace_backend::WorkspaceBackend;
28pub use write::WriteFile;
29
30/// Directories to skip during recursive file walks.
31pub const DEFAULT_IGNORE_DIRS: &[&str] = &[
32    ".git",
33    "node_modules",
34    "target",
35    "__pycache__",
36    ".venv",
37    "venv",
38    ".tox",
39    ".mypy_cache",
40    ".pytest_cache",
41    "dist",
42    "build",
43    ".next",
44    ".nuxt",
45    ".svelte-kit",
46    ".cache",
47    ".parcel-cache",
48    "coverage",
49    ".turbo",
50    ".gradle",
51    ".idea",
52    ".vs",
53];
54
55pub(crate) type SharedBackend = Arc<dyn ExecutionBackend>;
56
57/// A tool's model-facing descriptions, for an application that words them
58/// for its own tool set.
59#[derive(Debug, Clone)]
60pub struct ToolText {
61    /// One-line description.
62    pub short: String,
63    /// The description in the tool's schema.
64    pub schema: String,
65}
66
67/// What an application decides about the file tools.
68#[async_trait]
69pub trait FilePolicy: Send + Sync {
70    /// Files `read_file` refuses because they hold secrets.
71    fn is_secret(&self, path: &Path) -> bool;
72    /// [`FilePolicy::is_secret`] without name-shape rules, for `.env.example`
73    /// style templates, which are judged by where they live.
74    fn is_secret_ignoring_name_shape(&self, path: &Path) -> bool;
75    /// Paths the file tools must not change. [`ProtectedPathGuard`] enforces
76    /// these three; add it to the agent.
77    fn is_sensitive(&self, path: &Path) -> bool;
78
79    /// The path a kernel access manifest declares for a path argument.
80    fn declare_path(&self, path: &str) -> String {
81        path.to_string()
82    }
83    /// Whether images are returned as attachments the caller can deliver.
84    fn attaches_images(&self) -> bool {
85        false
86    }
87    /// The tool named in hints that suggest running a command.
88    fn shell_tool_name(&self) -> &str {
89        "shell"
90    }
91    /// A sentence added after an append, on delivering the finished file.
92    fn delivery_hint(&self) -> Option<&str> {
93        None
94    }
95    /// Whether [`FilePolicy::backup_before_overwrite`] keeps a copy.
96    fn keeps_backups(&self) -> bool {
97        false
98    }
99    /// Keep a copy of `path` before it is replaced. Best effort: a failed
100    /// backup never blocks the change.
101    async fn backup_before_overwrite(&self, _backend: &SharedBackend, _path: &BackendPath) {}
102    /// Text appended to a successful write, such as a syntax check.
103    async fn post_write_diagnostics(
104        &self,
105        _backend: &dyn ExecutionBackend,
106        _path: &Path,
107    ) -> String {
108        String::new()
109    }
110    /// The effects of a write call.
111    fn write_effects(&self, _backend: &dyn ExecutionBackend, _arguments: &str) -> CallEffects {
112        CallEffects::unknown()
113    }
114    /// Whether writing `path` changes configuration that later commands run
115    /// (git configuration, for example).
116    fn plants_configuration(&self, _path: &str) -> bool {
117        false
118    }
119    /// Where to go instead when the file tools refuse `path`: an app's own
120    /// files can have a tool of their own (its config tool, for example).
121    fn refusal_hint(&self, _path: &Path) -> Option<String> {
122        None
123    }
124}
125
126/// The policy for tools confined to a [`Workspace`].
127#[derive(Debug, Clone)]
128pub struct WorkspaceFilePolicy {
129    workspace: Workspace,
130    classifier: PathClassifier,
131}
132
133impl WorkspaceFilePolicy {
134    pub fn new(workspace: Workspace) -> Self {
135        Self {
136            workspace,
137            classifier: PathClassifier::empty(),
138        }
139    }
140}
141
142impl FilePolicy for WorkspaceFilePolicy {
143    fn is_secret(&self, path: &Path) -> bool {
144        self.classifier.is_secret(path)
145    }
146
147    fn is_secret_ignoring_name_shape(&self, path: &Path) -> bool {
148        self.classifier.is_secret_ignoring_name_shape(path)
149    }
150
151    fn is_sensitive(&self, path: &Path) -> bool {
152        self.classifier.is_sensitive(path)
153    }
154
155    fn declare_path(&self, path: &str) -> String {
156        self.workspace.declare(path)
157    }
158}
159
160/// What a [`HostFilePolicy`] says and keeps, as the application words it.
161#[derive(Debug, Clone, Default)]
162pub struct HostFilePolicySettings {
163    /// The tool named in hints that suggest running a command.
164    pub shell_tool_name: String,
165    /// A sentence added after an append, on delivering the finished file.
166    pub delivery_hint: Option<String>,
167    /// Where to go instead when the refused path is one of the
168    /// application's own files.
169    pub own_file_hint: Option<String>,
170    /// Keep a copy of a file before it is replaced, under `backup_root`.
171    pub keeps_backups: bool,
172    /// Where backups go (`None`: none is kept).
173    pub backup_root: Option<std::path::PathBuf>,
174}
175
176/// The policy for file tools on the host's own filesystem: secret and
177/// sensitive paths (and the application's own files) by [`DaemonPaths`],
178/// images as attachments, backups before an overwrite, a syntax check after
179/// a write, and the effects of a write (git configuration among them).
180///
181/// [`DaemonPaths`]: crate::path_class::DaemonPaths
182#[derive(Debug, Clone)]
183pub struct HostFilePolicy {
184    paths: crate::path_class::DaemonPaths,
185    settings: HostFilePolicySettings,
186}
187
188impl HostFilePolicy {
189    /// A policy protecting `paths`, worded by `settings`.
190    pub fn new(paths: crate::path_class::DaemonPaths, settings: HostFilePolicySettings) -> Self {
191        Self { paths, settings }
192    }
193}
194
195#[async_trait]
196impl FilePolicy for HostFilePolicy {
197    fn is_secret(&self, path: &Path) -> bool {
198        self.paths.is_secret(path)
199    }
200
201    fn is_secret_ignoring_name_shape(&self, path: &Path) -> bool {
202        self.paths.is_secret_ignoring_name_shape(path)
203    }
204
205    fn is_sensitive(&self, path: &Path) -> bool {
206        self.paths.is_sensitive(path)
207    }
208
209    fn attaches_images(&self) -> bool {
210        true
211    }
212
213    fn refusal_hint(&self, path: &Path) -> Option<String> {
214        self.settings
215            .own_file_hint
216            .clone()
217            .filter(|_| self.paths.is_own_file(path))
218    }
219
220    fn shell_tool_name(&self) -> &str {
221        &self.settings.shell_tool_name
222    }
223
224    fn delivery_hint(&self) -> Option<&str> {
225        self.settings.delivery_hint.as_deref()
226    }
227
228    fn keeps_backups(&self) -> bool {
229        self.settings.keeps_backups
230    }
231
232    async fn backup_before_overwrite(&self, backend: &SharedBackend, path: &BackendPath) {
233        crate::fs_utils::backup_before_overwrite(
234            backend,
235            path,
236            self.settings.backup_root.as_deref(),
237        )
238        .await;
239    }
240
241    async fn post_write_diagnostics(&self, backend: &dyn ExecutionBackend, path: &Path) -> String {
242        crate::fs_utils::post_write_diagnostics(backend, path).await
243    }
244
245    fn write_effects(&self, backend: &dyn ExecutionBackend, arguments: &str) -> CallEffects {
246        crate::command_effects::file_tool_write_effects(backend, arguments)
247    }
248
249    fn plants_configuration(&self, path: &str) -> bool {
250        crate::command_effects::is_git_config_path(path)
251    }
252}
253
254pub(crate) fn workspace_parts(workspace: Workspace) -> (SharedBackend, Arc<dyn FilePolicy>) {
255    let policy = Arc::new(WorkspaceFilePolicy::new(workspace.clone()));
256    (Arc::new(WorkspaceBackend::new(workspace)), policy)
257}
258
259/// The path argument of a file tool, under the names models commonly use.
260pub(crate) fn path_arg(arguments: &Value) -> Option<&str> {
261    ["path", "file_path", "file", "filename"]
262        .iter()
263        .find_map(|key| arguments.get(*key).and_then(Value::as_str))
264}
265
266/// Format file content with line numbers.
267pub fn format_with_line_numbers(content: &str, start_line: usize) -> String {
268    let lines: Vec<&str> = content.lines().collect();
269    let total = start_line + lines.len();
270    let width = total.to_string().len().max(3);
271    lines
272        .iter()
273        .enumerate()
274        .map(|(i, line)| format!("{:>width$} | {}", start_line + i + 1, line, width = width))
275        .collect::<Vec<_>>()
276        .join("\n")
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282    use crate::path_class::DaemonPaths;
283
284    #[test]
285    fn host_policy_points_own_files_to_the_hint_and_protects_them() {
286        let own = Path::new("/synthetic/app/config.toml");
287        let policy = HostFilePolicy::new(
288            DaemonPaths::new(vec![own.to_path_buf()]),
289            HostFilePolicySettings {
290                shell_tool_name: "terminal".to_string(),
291                own_file_hint: Some("use the config tool".to_string()),
292                ..Default::default()
293            },
294        );
295        assert!(policy.is_sensitive(own));
296        assert_eq!(
297            policy.refusal_hint(own).as_deref(),
298            Some("use the config tool")
299        );
300        assert_eq!(policy.refusal_hint(Path::new("/synthetic/other.rs")), None);
301        assert_eq!(policy.shell_tool_name(), "terminal");
302        assert!(!policy.keeps_backups());
303        assert!(policy.plants_configuration("/repo/.git/config"));
304    }
305}