aidaemon-tools 0.25.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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! The host's own filesystem and processes as an [`ExecutionBackend`].

use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;

use async_trait::async_trait;
use tokio::io::AsyncWriteExt;
use tokio::process::Command;

use crate::backend::{
    BackendDirEntry, BackendFileType, BackendKind, BackendMetadata, BackendPath, CommandSpec,
    ExecutionBackend, ExecutionRequest, ProcessHandle, SpawnedProcess, WriteMode,
    normalize_local_lexically,
};
use crate::process_control::{configure_command_for_process_group, send_sigkill, send_sigterm};

/// Build the executable search path used by local agent processes.
///
/// Service managers commonly start daemons with only the system directories in
/// `PATH`, even when the owner installed development tools in user-local
/// prefixes.  Keep one backend-owned search contract instead of teaching each
/// tool about individual executables. Explicit per-request PATH values and
/// removals still win at the spawn boundary.
pub fn local_execution_search_path(home: &BackendPath) -> String {
    let mut directories = Vec::<String>::new();
    let mut push = |value: String| {
        if !value.trim().is_empty() && !directories.iter().any(|existing| existing == &value) {
            directories.push(value);
        }
    };

    if let Some(path) = std::env::var_os("PATH") {
        for directory in std::env::split_paths(&path) {
            if directory.is_absolute() {
                push(directory.to_string_lossy().into_owned());
            }
        }
    }
    for relative in [
        ".local/bin",
        ".cargo/bin",
        ".npm-global/bin",
        ".bun/bin",
        ".deno/bin",
        "go/bin",
        "miniforge3/bin",
        "anaconda3/bin",
        "bin",
    ] {
        push(home.join(relative).to_string());
    }
    #[cfg(unix)]
    for directory in [
        "/opt/homebrew/bin",
        "/opt/homebrew/sbin",
        "/usr/local/bin",
        "/usr/local/sbin",
        "/usr/bin",
        "/bin",
        "/usr/sbin",
        "/sbin",
    ] {
        push(directory.to_string());
    }
    std::env::join_paths(directories)
        .unwrap_or_default()
        .to_string_lossy()
        .into_owned()
}

/// The local backend: the host filesystem, confined to a workspace unless
/// told otherwise.
pub struct LocalBackend {
    id: String,
    approval_scope: String,
    workspace_root: BackendPath,
    canonical_workspace_root: PathBuf,
    home: BackendPath,
    allow_outside_workspace: bool,
    /// Host variables a command inherits. Everything else in the daemon's
    /// environment (provider keys, the encryption key) stays out.
    env_allowlist: Vec<String>,
}

/// Host variables a local command inherits by default: what shells, build
/// tools and version managers need to find things, and nothing that carries
/// a credential. A name ending in `*` is a prefix. `[execution]
/// env_allowlist` adds names.
pub const LOCAL_ENV_ALLOWLIST: &[&str] = &[
    "HOME",
    "USER",
    "LOGNAME",
    "SHELL",
    "LANG",
    "LANGUAGE",
    "LC_*",
    "TERM",
    "COLORTERM",
    "TZ",
    "TMPDIR",
    "TMP",
    "TEMP",
    "XDG_*",
    "SSH_AUTH_SOCK",
    "DISPLAY",
    "WAYLAND_DISPLAY",
    "DBUS_SESSION_BUS_ADDRESS",
    "EDITOR",
    "VISUAL",
    "PAGER",
    "CARGO_HOME",
    "RUSTUP_HOME",
    "GOPATH",
    "GOROOT",
    "JAVA_HOME",
    "NVM_DIR",
    "PYENV_ROOT",
    "VIRTUAL_ENV",
    "CONDA_PREFIX",
    "HOMEBREW_PREFIX",
    "HOMEBREW_CELLAR",
    "HOMEBREW_REPOSITORY",
    "__CF_USER_TEXT_ENCODING",
    // Windows: what PowerShell and Windows programs need to start and find
    // things (names there match whatever their case).
    "SYSTEMROOT",
    "SYSTEMDRIVE",
    "COMSPEC",
    "PATHEXT",
    "WINDIR",
    "USERPROFILE",
    "USERNAME",
    "USERDOMAIN",
    "HOMEDRIVE",
    "HOMEPATH",
    "APPDATA",
    "LOCALAPPDATA",
    "PROGRAMDATA",
    "PROGRAMFILES",
    "PROGRAMFILES(X86)",
    "PROGRAMW6432",
    "COMMONPROGRAMFILES",
    "COMMONPROGRAMFILES(X86)",
    "COMMONPROGRAMW6432",
    "ALLUSERSPROFILE",
    "PUBLIC",
    "PSMODULEPATH",
    "OS",
    "PROCESSOR_ARCHITECTURE",
    "NUMBER_OF_PROCESSORS",
    // Paths to the daemon's own config, env file and working directory
    // (never their contents), for an `aidaemon` command run from a shell.
    "AIDAEMON_RUNTIME_*",
];

fn env_name_allowed(allowlist: &[String], name: &str) -> bool {
    // Windows variable names have no case: `windir` is `WINDIR`.
    let same = |a: &str, b: &str| {
        if cfg!(windows) {
            a.eq_ignore_ascii_case(b)
        } else {
            a == b
        }
    };
    allowlist.iter().any(|entry| match entry.strip_suffix('*') {
        Some(prefix) => name
            .get(..prefix.len())
            .is_some_and(|start| same(start, prefix)),
        None => same(entry, name),
    })
}

fn default_env_allowlist() -> Vec<String> {
    LOCAL_ENV_ALLOWLIST.iter().map(|s| s.to_string()).collect()
}

impl LocalBackend {
    /// The current directory as workspace, with no confinement: for tests
    /// that construct a tool directly.
    pub fn current_unrestricted() -> Self {
        let workspace = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        let canonical_workspace_root =
            dunce::canonicalize(&workspace).unwrap_or_else(|_| workspace.clone());
        let workspace_root =
            BackendPath::new(canonical_workspace_root.to_string_lossy().into_owned());
        let home = dirs::home_dir().unwrap_or_else(|| canonical_workspace_root.clone());
        Self {
            id: format!("local:{}", workspace_root.as_str()),
            approval_scope: "local".to_string(),
            workspace_root,
            canonical_workspace_root,
            home: BackendPath::new(home.to_string_lossy().into_owned()),
            allow_outside_workspace: true,
            env_allowlist: default_env_allowlist(),
        }
    }

    /// Let commands also inherit these host variables (a trailing `*` is a
    /// prefix), on top of [`LOCAL_ENV_ALLOWLIST`].
    pub fn with_env_allowlist(
        mut self,
        names: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.env_allowlist.extend(names.into_iter().map(Into::into));
        self
    }

    /// A backend rooted at `workspace_root` (`~` expanded; default: the
    /// current directory, created if missing). Paths outside it are refused
    /// unless `allow_outside_workspace`.
    pub async fn new(
        workspace_root: Option<&str>,
        allow_outside_workspace: bool,
    ) -> anyhow::Result<Self> {
        let cwd = std::env::current_dir()?;
        let workspace = workspace_root
            .map(expand_local_path)
            .transpose()?
            .unwrap_or(cwd);
        tokio::fs::create_dir_all(&workspace).await?;
        let canonical_workspace_root = tokio::fs::canonicalize(&workspace)
            .await
            .map(|p| dunce::simplified(&p).to_path_buf())?;
        let workspace_root =
            BackendPath::new(canonical_workspace_root.to_string_lossy().into_owned());
        let home = dirs::home_dir().unwrap_or_else(|| canonical_workspace_root.clone());
        Ok(Self {
            id: format!("local:{}", workspace_root.as_str()),
            approval_scope: "local".to_string(),
            workspace_root,
            canonical_workspace_root,
            home: BackendPath::new(home.to_string_lossy().into_owned()),
            allow_outside_workspace,
            env_allowlist: default_env_allowlist(),
        })
    }

    fn host_path(&self, path: &BackendPath) -> PathBuf {
        PathBuf::from(path.as_str())
    }

    async fn ensure_allowed(&self, path: &Path) -> anyhow::Result<()> {
        if self.allow_outside_workspace {
            return Ok(());
        }
        let canonical = canonicalize_existing_or_parent(path).await?;
        anyhow::ensure!(
            canonical.starts_with(&self.canonical_workspace_root),
            "Path is outside execution workspace {}: {}",
            self.workspace_root,
            path.display()
        );
        Ok(())
    }
}

#[async_trait]
impl ExecutionBackend for LocalBackend {
    fn kind(&self) -> BackendKind {
        BackendKind::Local
    }

    fn id(&self) -> &str {
        &self.id
    }

    fn approval_scope(&self) -> &str {
        &self.approval_scope
    }

    fn workspace_root(&self) -> &BackendPath {
        &self.workspace_root
    }

    fn home_hint(&self) -> &BackendPath {
        &self.home
    }

    fn allows_outside_workspace(&self) -> bool {
        self.allow_outside_workspace
    }

    async fn home_dir(&self) -> anyhow::Result<BackendPath> {
        Ok(self.home.clone())
    }

    async fn resolve_path(&self, path: &str) -> anyhow::Result<BackendPath> {
        let expanded = if path == "~" {
            self.home.as_str().to_string()
        } else if let Some(rest) = path.strip_prefix("~/") {
            self.home.join(rest).as_str().to_string()
        } else {
            path.to_string()
        };
        let candidate = PathBuf::from(&expanded);
        let joined = if candidate.is_absolute() {
            candidate
        } else {
            self.host_path(&self.workspace_root).join(candidate)
        };
        let normalized = normalize_local_lexically(&joined)?;
        self.ensure_allowed(&normalized).await?;
        Ok(BackendPath::new(normalized.to_string_lossy().into_owned()))
    }

    async fn canonicalize(&self, path: &BackendPath) -> anyhow::Result<BackendPath> {
        let host = self.host_path(path);
        self.ensure_allowed(&host).await?;
        let canonical = tokio::fs::canonicalize(host)
            .await
            .map(|p| dunce::simplified(&p).to_path_buf())?;
        self.ensure_allowed(&canonical).await?;
        Ok(BackendPath::new(canonical.to_string_lossy().into_owned()))
    }

    async fn metadata(&self, path: &BackendPath) -> anyhow::Result<BackendMetadata> {
        let host = self.host_path(path);
        self.ensure_allowed(&host).await?;
        let metadata = tokio::fs::symlink_metadata(host).await?;
        Ok(metadata_from_std(metadata))
    }

    async fn read(&self, path: &BackendPath) -> anyhow::Result<Vec<u8>> {
        let host = self.host_path(path);
        self.ensure_allowed(&host).await?;
        Ok(tokio::fs::read(host).await?)
    }

    async fn write(
        &self,
        path: &BackendPath,
        content: &[u8],
        mode: WriteMode,
        create_parents: bool,
    ) -> anyhow::Result<()> {
        let host = self.host_path(path);
        self.ensure_allowed(&host).await?;
        if create_parents && let Some(parent) = host.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }
        match mode {
            WriteMode::Append => {
                let mut file = tokio::fs::OpenOptions::new()
                    .create(true)
                    .append(true)
                    .open(host)
                    .await?;
                file.write_all(content).await?;
                file.flush().await?;
            }
            WriteMode::Overwrite => {
                let temp = sibling_temp_path(&host, "write");
                tokio::fs::write(&temp, content).await?;
                tokio::fs::rename(temp, host).await?;
            }
        }
        Ok(())
    }

    async fn create_dir_all(&self, path: &BackendPath) -> anyhow::Result<()> {
        let host = self.host_path(path);
        self.ensure_allowed(&host).await?;
        tokio::fs::create_dir_all(host).await?;
        Ok(())
    }

    async fn copy(&self, source: &BackendPath, destination: &BackendPath) -> anyhow::Result<()> {
        let source = self.host_path(source);
        let destination = self.host_path(destination);
        self.ensure_allowed(&source).await?;
        self.ensure_allowed(&destination).await?;
        tokio::fs::copy(source, destination).await?;
        Ok(())
    }

    #[allow(dead_code)]
    async fn rename(&self, source: &BackendPath, destination: &BackendPath) -> anyhow::Result<()> {
        let source = self.host_path(source);
        let destination = self.host_path(destination);
        self.ensure_allowed(&source).await?;
        self.ensure_allowed(&destination).await?;
        tokio::fs::rename(source, destination).await?;
        Ok(())
    }

    #[allow(dead_code)]
    async fn remove_file(&self, path: &BackendPath) -> anyhow::Result<()> {
        let host = self.host_path(path);
        self.ensure_allowed(&host).await?;
        tokio::fs::remove_file(host).await?;
        Ok(())
    }

    async fn remove_empty_dir(&self, path: &BackendPath) -> anyhow::Result<()> {
        let host = self.host_path(path);
        self.ensure_allowed(&host).await?;
        tokio::fs::remove_dir(host).await?;
        Ok(())
    }

    async fn read_dir(&self, path: &BackendPath) -> anyhow::Result<Vec<BackendDirEntry>> {
        let host = self.host_path(path);
        self.ensure_allowed(&host).await?;
        let mut entries = tokio::fs::read_dir(host).await?;
        let mut output = Vec::new();
        while let Some(entry) = entries.next_entry().await? {
            output.push(BackendDirEntry {
                path: BackendPath::new(entry.path().to_string_lossy().into_owned()),
                metadata: metadata_from_std(entry.metadata().await?),
            });
        }
        Ok(output)
    }

    async fn spawn(&self, request: ExecutionRequest) -> anyhow::Result<SpawnedProcess> {
        let cwd = request.cwd.as_ref().unwrap_or(&self.workspace_root).clone();
        let cwd_host = self.host_path(&cwd);
        self.ensure_allowed(&cwd_host).await?;

        let explicit_path = request.env.contains_key("PATH");
        let removes_path = request.env_remove.iter().any(|name| name == "PATH");

        let mut command = match request.command {
            CommandSpec::Shell(shell) => crate::platform_shell::shell_command(&shell),
            CommandSpec::Argv { program, args } => {
                let mut command = Command::new(program);
                command.args(args);
                command
            }
        };
        command.env_clear();
        command.envs(std::env::vars_os().filter(|(name, _)| {
            name.to_str()
                .is_some_and(|name| env_name_allowed(&self.env_allowlist, name))
        }));
        command
            .current_dir(cwd_host)
            .envs(request.env)
            .stdin(if request.stdin.is_some() || request.keep_stdin {
                Stdio::piped()
            } else {
                Stdio::null()
            })
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .kill_on_drop(true);
        if !explicit_path && !removes_path {
            command.env("PATH", local_execution_search_path(&self.home));
        }
        for name in request.env_remove {
            command.env_remove(name);
        }
        configure_command_for_process_group(&mut command);
        let mut child = command.spawn()?;
        if request.keep_stdin {
            // The caller writes for the process's life; what it gave up
            // front goes first.
            if let (Some(stdin), Some(pipe)) = (request.stdin, child.stdin.as_mut()) {
                pipe.write_all(&stdin).await?;
            }
        } else if let (Some(stdin), Some(mut pipe)) = (request.stdin, child.stdin.take()) {
            tokio::spawn(async move {
                let _ = pipe.write_all(&stdin).await;
            });
        }
        let pid = child.id().unwrap_or(0);
        Ok(SpawnedProcess::new(
            ProcessHandle::new(pid, Some(pid), None),
            child,
        ))
    }

    async fn terminate(&self, handle: &ProcessHandle, grace: Duration) -> anyhow::Result<()> {
        let Some(pid) = handle.local_pid() else {
            return Ok(());
        };
        if send_sigterm(pid) {
            tokio::time::sleep(grace).await;
        }
        send_sigkill(pid);
        Ok(())
    }

    async fn import_local_file(
        &self,
        local_path: &Path,
        destination: &BackendPath,
    ) -> anyhow::Result<BackendPath> {
        if !self.allow_outside_workspace {
            let bytes = tokio::fs::read(local_path).await?;
            self.write(destination, &bytes, WriteMode::Overwrite, true)
                .await?;
            return Ok(destination.clone());
        }
        let path = BackendPath::new(local_path.to_string_lossy().into_owned());
        self.ensure_allowed(local_path).await?;
        Ok(path)
    }

    async fn export_local_file(
        &self,
        source: &BackendPath,
        local_path: &Path,
    ) -> anyhow::Result<()> {
        let source = self.host_path(source);
        self.ensure_allowed(&source).await?;
        if source == local_path {
            return Ok(());
        }
        if let Some(parent) = local_path.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }
        tokio::fs::copy(source, local_path).await?;
        Ok(())
    }
}

fn metadata_from_std(metadata: std::fs::Metadata) -> BackendMetadata {
    let file_type = metadata.file_type();
    BackendMetadata {
        file_type: if file_type.is_symlink() {
            BackendFileType::Symlink
        } else if file_type.is_file() {
            BackendFileType::File
        } else if file_type.is_dir() {
            BackendFileType::Directory
        } else {
            BackendFileType::Other
        },
        len: metadata.len(),
        modified: metadata.modified().ok(),
    }
}

/// The file `path` names after every symlink (a broken one to its target)
/// and `..`, by the resolver the scope guard uses.
async fn canonicalize_existing_or_parent(path: &Path) -> anyhow::Result<PathBuf> {
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()?.join(path)
    };
    Ok(aidaemon_policies::resolve_path(&absolute)?)
}

fn sibling_temp_path(path: &Path, purpose: &str) -> PathBuf {
    let suffix = uuid::Uuid::new_v4().simple().to_string();
    let name = path
        .file_name()
        .and_then(OsStr::to_str)
        .unwrap_or("aidaemon-file");
    path.with_file_name(format!(".{name}.aidaemon-{purpose}-{suffix}"))
}

/// Expand `~` in a host path.
pub fn expand_local_path(path: &str) -> anyhow::Result<PathBuf> {
    Ok(PathBuf::from(shellexpand::tilde(path).to_string()))
}