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
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
30pub 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#[derive(Debug, Clone)]
60pub struct ToolText {
61 pub short: String,
63 pub schema: String,
65}
66
67#[async_trait]
69pub trait FilePolicy: Send + Sync {
70 fn is_secret(&self, path: &Path) -> bool;
72 fn is_secret_ignoring_name_shape(&self, path: &Path) -> bool;
75 fn is_sensitive(&self, path: &Path) -> bool;
78
79 fn declare_path(&self, path: &str) -> String {
81 path.to_string()
82 }
83 fn attaches_images(&self) -> bool {
85 false
86 }
87 fn shell_tool_name(&self) -> &str {
89 "shell"
90 }
91 fn delivery_hint(&self) -> Option<&str> {
93 None
94 }
95 fn keeps_backups(&self) -> bool {
97 false
98 }
99 async fn backup_before_overwrite(&self, _backend: &SharedBackend, _path: &BackendPath) {}
102 async fn post_write_diagnostics(
104 &self,
105 _backend: &dyn ExecutionBackend,
106 _path: &Path,
107 ) -> String {
108 String::new()
109 }
110 fn write_effects(&self, _backend: &dyn ExecutionBackend, _arguments: &str) -> CallEffects {
112 CallEffects::unknown()
113 }
114 fn plants_configuration(&self, _path: &str) -> bool {
117 false
118 }
119 fn refusal_hint(&self, _path: &Path) -> Option<String> {
122 None
123 }
124}
125
126#[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#[derive(Debug, Clone, Default)]
162pub struct HostFilePolicySettings {
163 pub shell_tool_name: String,
165 pub delivery_hint: Option<String>,
167 pub own_file_hint: Option<String>,
170 pub keeps_backups: bool,
172 pub backup_root: Option<std::path::PathBuf>,
174}
175
176#[derive(Debug, Clone)]
183pub struct HostFilePolicy {
184 paths: crate::path_class::DaemonPaths,
185 settings: HostFilePolicySettings,
186}
187
188impl HostFilePolicy {
189 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
259pub(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
266pub 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}