aidaemon-tools 0.28.0

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
//! `shell`: run a command through a [`Sandbox`].

use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
use serde::Deserialize;
use serde_json::{Value, json};

use aidaemon_core::{
    AccessManifest, Tool, ToolAnnotations, ToolContext, ToolOutput, ToolResult, ToolSpec,
};

use crate::exec::{Sandbox, SandboxCommand, best_available_sandbox};
use crate::util::{fail, parse_args};
use crate::workspace::Workspace;

/// Host variables passed through by default.
pub const DEFAULT_ENV_ALLOWLIST: &[&str] = &[
    "PATH", "HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "LC_CTYPE", "TERM", "TZ", "TMPDIR",
];

/// Run shell commands in the workspace.
///
/// The tool is annotated destructive. It contains no approval logic: put an
/// approval [`aidaemon_core::Hook`] in front of it, and pick a contained
/// backend to limit what an approved command can reach.
///
/// Note that the agent's `Limits::tool_timeout` (120 s by default) also
/// bounds each call; raise it if you raise `max_timeout`.
#[derive(Clone)]
pub struct Shell {
    workspace: Workspace,
    backend: Arc<dyn Sandbox>,
    env_allowlist: Vec<String>,
    extra_env: Vec<(String, String)>,
    default_timeout: Duration,
    max_timeout: Duration,
    max_output_bytes: usize,
    /// `None`: the backend's default (off where it can cut the network).
    allow_network: Option<bool>,
    deny_read: Vec<std::path::PathBuf>,
}

impl std::fmt::Debug for Shell {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Shell")
            .field("workspace", &self.workspace)
            .field("backend", &self.backend.name())
            .field("allow_network", &self.allow_network)
            .finish_non_exhaustive()
    }
}

impl Shell {
    pub fn new(workspace: Workspace, backend: Arc<dyn Sandbox>) -> Self {
        Self {
            workspace,
            backend,
            env_allowlist: DEFAULT_ENV_ALLOWLIST
                .iter()
                .map(|s| s.to_string())
                .collect(),
            extra_env: Vec::new(),
            default_timeout: Duration::from_secs(60),
            max_timeout: Duration::from_secs(110),
            max_output_bytes: 20_000,
            allow_network: None,
            deny_read: Vec::new(),
        }
    }

    /// Shell with [`best_available_sandbox`]: bubblewrap on Linux and
    /// seatbelt on macOS when available, overridable with
    /// [`crate::SANDBOX_ENV`]; uncontained (with a one-time warning) when no
    /// OS sandbox is available.
    pub fn sandboxed(workspace: Workspace) -> Self {
        Self::new(workspace, best_available_sandbox())
    }

    /// Replace the list of host environment variables passed through.
    pub fn env_allowlist(mut self, names: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.env_allowlist = names.into_iter().map(Into::into).collect();
        self
    }

    /// Set a fixed variable for every command (overrides the host value).
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.extra_env.push((key.into(), value.into()));
        self
    }

    pub fn timeouts(mut self, default: Duration, max: Duration) -> Self {
        self.max_timeout = max.max(Duration::from_secs(1));
        self.default_timeout = default.min(self.max_timeout);
        self
    }

    pub fn max_output_bytes(mut self, bytes: usize) -> Self {
        self.max_output_bytes = bytes.max(64);
        self
    }

    /// Let commands use the network, or not. Unset, a backend that can cut
    /// the network ([`Sandbox::enforces_network_off`]) does, and one that
    /// cannot (`LocalSandbox`) leaves it on and says so in the tool's
    /// description. Set to `false`, commands are refused on a backend that
    /// cannot enforce it, rather than run with the network on.
    pub fn allow_network(mut self, allow: bool) -> Self {
        self.allow_network = Some(allow);
        self
    }

    /// Host paths commands must not read, for example credential
    /// directories (on top of the backend's own defaults; see
    /// [`SandboxCommand::deny_read`]). On a backend that cannot enforce it
    /// ([`Sandbox::enforces_deny_read`], for example `LocalSandbox`), every
    /// command is refused rather than run with the paths readable.
    pub fn deny_read(
        mut self,
        paths: impl IntoIterator<Item = impl Into<std::path::PathBuf>>,
    ) -> Self {
        self.deny_read.extend(paths.into_iter().map(Into::into));
        self
    }

    pub fn backend(&self) -> &Arc<dyn Sandbox> {
        &self.backend
    }

    /// Why no command may run: a restriction this shell was configured
    /// with that its backend cannot enforce. Fails closed instead of
    /// running the command without it.
    fn unenforceable(&self) -> Option<String> {
        let backend = self.backend.name();
        if !self.deny_read.is_empty() && !self.backend.enforces_deny_read() {
            let paths = self
                .deny_read
                .iter()
                .map(|p| format!("`{}`", p.display()))
                .collect::<Vec<_>>()
                .join(", ");
            return Some(format!(
                "refused: this shell must keep commands from reading {paths}, but its \
                 `{backend}` backend cannot enforce that, so the command was not run. Use a \
                 contained backend (bubblewrap, seatbelt or docker) for this shell."
            ));
        }
        if self.allow_network == Some(false) && !self.backend.enforces_network_off() {
            return Some(format!(
                "refused: this shell must run commands without network access, but its \
                 `{backend}` backend cannot cut the network, so the command was not run. Use a \
                 contained backend (bubblewrap, seatbelt or docker) for this shell."
            ));
        }
        None
    }

    fn environment(&self) -> Vec<(String, String)> {
        let mut env: Vec<(String, String)> = self
            .env_allowlist
            .iter()
            .filter_map(|k| std::env::var(k).ok().map(|v| (k.clone(), v)))
            .collect();
        for (k, v) in &self.extra_env {
            env.retain(|(existing, _)| existing != k);
            env.push((k.clone(), v.clone()));
        }
        env
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ShellArgs {
    command: String,
    cwd: Option<String>,
    timeout_secs: Option<u64>,
}

#[async_trait]
impl Tool for Shell {
    /// The loop must allow at least the shell's own maximum plus time to
    /// kill the process group and collect output.
    fn timeout(&self) -> Option<Duration> {
        Some(self.max_timeout + Duration::from_secs(10))
    }

    fn spec(&self) -> ToolSpec {
        let containment = if self.backend.is_contained() {
            "Writes outside the workspace are blocked"
        } else {
            "Commands run directly on the host"
        };
        let network = if self.allow_network == Some(true) || !self.backend.enforces_network_off() {
            "network available"
        } else {
            "no network access"
        };
        ToolSpec {
            name: "shell".into(),
            description: format!(
                "Run a non-interactive command with `sh -c` in the workspace (backend: {}). \
                 {containment}; {network}. stdin is closed, so do not run commands that wait \
                 for input or open editors/pagers. Returns combined stdout+stderr (long output \
                 keeps the start and end) and the exit code; a non-zero exit is reported as an \
                 error. Default timeout {}s, maximum {}s. Use read_file/grep/glob/edit_file \
                 instead of cat/grep/find/sed for files.",
                self.backend.name(),
                self.default_timeout.as_secs(),
                self.max_timeout.as_secs()
            ),
            parameters: json!({
                "type": "object",
                "properties": {
                    "command": {"type": "string", "description": "The command line to run."},
                    "cwd": {"type": "string", "description": "Working directory, relative to the workspace root. Default: the root."},
                    "timeout_secs": {"type": "integer", "minimum": 1, "maximum": self.max_timeout.as_secs(), "description": "Kill the command after this many seconds."}
                },
                "required": ["command"],
                "additionalProperties": false
            }),
        }
    }

    fn annotations(&self) -> ToolAnnotations {
        ToolAnnotations::DESTRUCTIVE
    }

    fn validate(&self, arguments: &Value) -> Result<(), String> {
        match arguments.get("command").and_then(Value::as_str) {
            Some(c) if !c.trim().is_empty() => Ok(()),
            Some(_) => Err("`command` must not be empty".into()),
            None => Err("`command` is required and must be a string".into()),
        }
    }

    fn access(&self, arguments: &Value) -> AccessManifest {
        AccessManifest {
            commands: arguments
                .get("command")
                .and_then(Value::as_str)
                .map(|c| vec![c.to_string()])
                .unwrap_or_default(),
            ..Default::default()
        }
    }

    async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult {
        if let Err(e) = self.validate(&arguments) {
            return Ok(fail(e));
        }
        if let Some(refusal) = self.unenforceable() {
            return Ok(fail(refusal));
        }
        let args: ShellArgs = match parse_args("shell", arguments) {
            Ok(a) => a,
            Err(e) => return Ok(fail(e)),
        };
        let cwd = match args.cwd.as_deref().filter(|c| !c.trim().is_empty()) {
            Some(c) => match self.workspace.resolve(c) {
                Ok(p) if p.is_dir() => p,
                Ok(p) => {
                    return Ok(fail(format!(
                        "cwd `{}` is not an existing directory",
                        self.workspace.display(&p)
                    )));
                }
                Err(e) => return Ok(fail(e.to_string())),
            },
            None => self.workspace.root().to_path_buf(),
        };
        let timeout = args
            .timeout_secs
            .map(Duration::from_secs)
            .unwrap_or(self.default_timeout)
            .clamp(Duration::from_secs(1), self.max_timeout);

        let spec = SandboxCommand {
            command: args.command,
            cwd: cwd.clone(),
            workspace_root: self.workspace.root().to_path_buf(),
            env: self.environment(),
            timeout,
            max_output_bytes: self.max_output_bytes,
            allow_network: self.allow_network.unwrap_or(false),
            deny_read: self.deny_read.clone(),
            cancel: ctx.cancel.clone(),
        };
        let out = match self.backend.run(&spec).await {
            Ok(o) => o,
            Err(e) => return Ok(fail(e.to_string())),
        };

        let mut content = out.output.clone();
        if content.trim().is_empty() {
            content = "(no output)".into();
        }
        if !content.ends_with('\n') {
            content.push('\n');
        }
        let status_line = if out.timed_out {
            format!(
                "[timed out after {}s; process killed. Use a longer timeout_secs or run less at once.]",
                timeout.as_secs()
            )
        } else if out.cancelled {
            "[cancelled; process killed]".to_string()
        } else {
            match out.exit_code {
                Some(code) => format!("[exit code: {code}]"),
                None => "[terminated by a signal]".to_string(),
            }
        };
        content.push_str(&status_line);
        let details = json!({
            "exit_code": out.exit_code,
            "timed_out": out.timed_out,
            "cancelled": out.cancelled,
            "duration_ms": out.duration.as_millis() as u64,
            "output_bytes": out.output_bytes,
            "truncated": out.truncated,
            "backend": self.backend.name(),
            "cwd": self.workspace.display(&cwd),
        });
        let output = if out.exit_code == Some(0) {
            ToolOutput::text(content)
        } else {
            ToolOutput::error(content)
        };
        Ok(output.with_details(details))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::exec::LocalSandbox;
    use crate::testutil::{ScopedVar, ctx, ws};

    fn shell(ws: &Workspace) -> Shell {
        Shell::new(ws.clone(), Arc::new(LocalSandbox))
    }

    #[tokio::test]
    async fn reports_exit_codes() {
        let (_d, ws) = ws();
        let tool = shell(&ws);
        let out = tool
            .call(json!({"command": "echo hello; echo oops >&2"}), &ctx())
            .await
            .unwrap();
        assert!(!out.is_error, "{}", out.content);
        assert!(out.content.contains("hello") && out.content.contains("oops"));
        assert!(out.content.ends_with("[exit code: 0]"));
        assert_eq!(out.details["exit_code"], 0);
        assert_eq!(out.details["backend"], "local");

        let out = tool
            .call(json!({"command": "echo failing; exit 3"}), &ctx())
            .await
            .unwrap();
        assert!(out.is_error);
        assert_eq!(out.details["exit_code"], 3);
        assert!(out.content.contains("[exit code: 3]"));
    }

    #[tokio::test]
    async fn runs_in_cwd_and_refuses_escapes() {
        let (_d, ws) = ws();
        std::fs::create_dir(ws.root().join("sub")).unwrap();
        let tool = shell(&ws);
        let out = tool
            .call(json!({"command": "pwd", "cwd": "sub"}), &ctx())
            .await
            .unwrap();
        assert!(
            out.content
                .trim_end()
                .contains(&ws.root().join("sub").display().to_string())
        );
        let out = tool
            .call(json!({"command": "pwd", "cwd": "../"}), &ctx())
            .await
            .unwrap();
        assert!(out.is_error && out.content.contains("outside the workspace"));
        let out = tool
            .call(json!({"command": "pwd", "cwd": "missing"}), &ctx())
            .await
            .unwrap();
        assert!(out.is_error && out.content.contains("not an existing directory"));
    }

    #[tokio::test]
    async fn times_out_and_kills() {
        let (_d, ws) = ws();
        let tool = shell(&ws);
        let started = std::time::Instant::now();
        let out = tool
            .call(
                json!({"command": "echo start; sleep 30; echo never", "timeout_secs": 1}),
                &ctx(),
            )
            .await
            .unwrap();
        assert!(started.elapsed() < Duration::from_secs(10));
        assert!(out.is_error);
        assert_eq!(out.details["timed_out"], true);
        assert!(out.content.contains("start") && !out.content.contains("never"));
        assert!(out.content.contains("timed out after 1s"));
    }

    #[tokio::test]
    async fn caps_output_head_and_tail() {
        let (_d, ws) = ws();
        let tool = shell(&ws).max_output_bytes(1000);
        let out = tool
            .call(
                json!({"command": "echo FIRST; i=0; while [ $i -lt 5000 ]; do echo line$i; i=$((i+1)); done; echo LAST"}),
                &ctx(),
            )
            .await
            .unwrap();
        assert!(!out.is_error);
        assert!(out.content.starts_with("FIRST\n"));
        assert!(out.content.contains("LAST\n[exit code: 0]"));
        assert!(out.content.contains("bytes of output omitted"));
        assert!(out.content.len() < 1200, "{}", out.content.len());
        assert_eq!(out.details["truncated"], true);
    }

    #[tokio::test]
    async fn environment_is_allowlisted() {
        let (_d, ws) = ws();
        let _secret = ScopedVar::set("AIDAEMON_TOOLS_TEST_SECRET", "synthetic-secret");
        let tool = shell(&ws).env("GREETING", "hi");
        let out = tool
            .call(
                json!({"command": "echo \"[$AIDAEMON_TOOLS_TEST_SECRET][$GREETING]\""}),
                &ctx(),
            )
            .await
            .unwrap();
        assert!(out.content.contains("[][hi]"), "{}", out.content);
    }

    #[tokio::test]
    async fn restrictions_the_backend_cannot_enforce_refuse_the_command() {
        let (dir, ws) = ws();
        let local = Arc::new(crate::exec::LocalSandbox);
        let secrets = tempfile::tempdir().unwrap();
        std::fs::write(secrets.path().join("credentials"), "synthetic-secret").unwrap();
        let cat = json!({"command": format!(
            "cat {}/credentials; touch ran", secrets.path().display()
        )});

        let shell = Shell::new(ws.clone(), local.clone()).deny_read([secrets.path()]);
        let out = shell.call(cat.clone(), &ctx()).await.unwrap();
        assert!(out.is_error, "{}", out.content);
        assert!(out.content.contains("cannot enforce"), "{}", out.content);
        assert!(!out.content.contains("synthetic-secret"), "{}", out.content);
        assert!(!dir.path().join("ran").exists(), "the command must not run");

        let shell = Shell::new(ws.clone(), local.clone()).allow_network(false);
        let out = shell
            .call(json!({"command": "touch ran"}), &ctx())
            .await
            .unwrap();
        assert!(out.is_error, "{}", out.content);
        assert!(out.content.contains("network"), "{}", out.content);
        assert!(!dir.path().join("ran").exists(), "the command must not run");

        // Unrestricted, the host backend runs and says the network is on.
        let shell = Shell::new(ws, local);
        assert!(shell.spec().description.contains("network available"));
        let out = shell
            .call(json!({"command": "touch ran"}), &ctx())
            .await
            .unwrap();
        assert!(!out.is_error, "{}", out.content);
        assert!(dir.path().join("ran").exists());
    }

    #[test]
    fn declares_destructive_and_command() {
        let (_d, ws) = ws();
        let tool = shell(&ws);
        assert!(tool.annotations().destructive);
        assert_eq!(
            tool.access(&json!({"command": "ls -la"})).commands,
            vec!["ls -la"]
        );
        assert!(tool.validate(&json!({"command": "  "})).is_err());
        assert_eq!(tool.spec().parameters["additionalProperties"], json!(false));
    }
}