1use 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
39pub 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#[derive(Debug, Clone)]
69pub struct ToolText {
70 pub short: String,
72 pub schema: String,
74}
75
76#[async_trait]
78pub trait FilePolicy: Send + Sync {
79 fn is_secret(&self, path: &Path) -> bool;
81 fn is_secret_ignoring_name_shape(&self, path: &Path) -> bool;
84 fn is_sensitive(&self, path: &Path) -> bool;
87
88 fn declare_path(&self, path: &str) -> String {
90 path.to_string()
91 }
92 fn attaches_images(&self) -> bool {
94 false
95 }
96 fn shell_tool_name(&self) -> &str {
98 "shell"
99 }
100 fn delivery_hint(&self) -> Option<&str> {
102 None
103 }
104 fn keeps_backups(&self) -> bool {
106 false
107 }
108 async fn backup_before_overwrite(&self, _backend: &SharedBackend, _path: &BackendPath) {}
111 async fn post_write_diagnostics(
113 &self,
114 _backend: &dyn ExecutionBackend,
115 _path: &Path,
116 ) -> String {
117 String::new()
118 }
119 fn write_effects(&self, _backend: &dyn ExecutionBackend, _arguments: &str) -> CallEffects {
121 CallEffects::unknown()
122 }
123 fn plants_configuration(&self, _path: &str) -> bool {
126 false
127 }
128 fn refusal_hint(&self, _path: &Path) -> Option<String> {
131 None
132 }
133 fn is_persistence(&self, path: &Path) -> bool {
138 crate::path_class::is_persistence_path(path, &[])
139 }
140}
141
142#[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#[derive(Debug, Clone, Default)]
178pub struct HostFilePolicySettings {
179 pub shell_tool_name: String,
181 pub delivery_hint: Option<String>,
183 pub own_file_hint: Option<String>,
186 pub keeps_backups: bool,
188 pub backup_root: Option<std::path::PathBuf>,
190}
191
192#[derive(Debug, Clone)]
199pub struct HostFilePolicy {
200 paths: crate::path_class::DaemonPaths,
201 settings: HostFilePolicySettings,
202}
203
204impl HostFilePolicy {
205 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
274pub(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
333pub(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
340pub(crate) fn content_arg(arguments: &Value) -> Option<&str> {
343 ["content", "data", "text"]
344 .iter()
345 .find_map(|key| arguments.get(*key).and_then(Value::as_str))
346}
347
348pub(crate) fn write_call_annotations(
352 capabilities: crate::semantics::ToolCapabilities,
353 semantics: &crate::semantics::ToolCallSemantics,
354 policy: &dyn FilePolicy,
355) -> aidaemon_core::ToolAnnotations {
356 let mut annotations = crate::semantics::default_call_annotations(capabilities, semantics);
357 annotations.egress |= semantics
358 .target_hints
359 .iter()
360 .any(|hint| policy.plants_configuration(&hint.value));
361 annotations
362}
363
364pub fn format_with_line_numbers(content: &str, start_line: usize) -> String {
366 let lines: Vec<&str> = content.lines().collect();
367 let total = start_line + lines.len();
368 let width = total.to_string().len().max(3);
369 lines
370 .iter()
371 .enumerate()
372 .map(|(i, line)| format!("{:>width$} | {}", start_line + i + 1, line, width = width))
373 .collect::<Vec<_>>()
374 .join("\n")
375}
376
377#[cfg(test)]
378mod tests {
379 use super::*;
380 use crate::path_class::DaemonPaths;
381
382 #[test]
383 fn host_policy_points_own_files_to_the_hint_and_protects_them() {
384 let own = Path::new("/synthetic/app/config.toml");
385 let policy = HostFilePolicy::new(
386 DaemonPaths::new(vec![own.to_path_buf()]),
387 HostFilePolicySettings {
388 shell_tool_name: "terminal".to_string(),
389 own_file_hint: Some("use the config tool".to_string()),
390 ..Default::default()
391 },
392 );
393 assert!(policy.is_sensitive(own));
394 assert_eq!(
395 policy.refusal_hint(own).as_deref(),
396 Some("use the config tool")
397 );
398 assert_eq!(policy.refusal_hint(Path::new("/synthetic/other.rs")), None);
399 assert_eq!(policy.shell_tool_name(), "terminal");
400 assert!(!policy.keeps_backups());
401 assert!(policy.plants_configuration("/repo/.git/config"));
402 }
403}