Skip to main content

aidaemon_tools/
shell.rs

1//! `shell`: run a command through a [`Sandbox`].
2
3use std::sync::Arc;
4use std::time::Duration;
5
6use async_trait::async_trait;
7use serde::Deserialize;
8use serde_json::{Value, json};
9
10use aidaemon_core::{
11    AccessManifest, Tool, ToolAnnotations, ToolContext, ToolOutput, ToolResult, ToolSpec,
12};
13
14use crate::exec::{Sandbox, SandboxCommand, best_available_sandbox};
15use crate::util::{fail, parse_args};
16use crate::workspace::Workspace;
17
18/// Host variables passed through by default.
19pub const DEFAULT_ENV_ALLOWLIST: &[&str] = &[
20    "PATH", "HOME", "USER", "LOGNAME", "LANG", "LC_ALL", "LC_CTYPE", "TERM", "TZ", "TMPDIR",
21];
22
23/// Run shell commands in the workspace.
24///
25/// The tool is annotated destructive. It contains no approval logic: put an
26/// approval [`aidaemon_core::Hook`] in front of it, and pick a contained
27/// backend to limit what an approved command can reach.
28///
29/// Note that the agent's `Limits::tool_timeout` (120 s by default) also
30/// bounds each call; raise it if you raise `max_timeout`.
31#[derive(Clone)]
32pub struct Shell {
33    workspace: Workspace,
34    backend: Arc<dyn Sandbox>,
35    env_allowlist: Vec<String>,
36    extra_env: Vec<(String, String)>,
37    default_timeout: Duration,
38    max_timeout: Duration,
39    max_output_bytes: usize,
40    /// `None`: the backend's default (off where it can cut the network).
41    allow_network: Option<bool>,
42    deny_read: Vec<std::path::PathBuf>,
43}
44
45impl std::fmt::Debug for Shell {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        f.debug_struct("Shell")
48            .field("workspace", &self.workspace)
49            .field("backend", &self.backend.name())
50            .field("allow_network", &self.allow_network)
51            .finish_non_exhaustive()
52    }
53}
54
55impl Shell {
56    pub fn new(workspace: Workspace, backend: Arc<dyn Sandbox>) -> Self {
57        Self {
58            workspace,
59            backend,
60            env_allowlist: DEFAULT_ENV_ALLOWLIST
61                .iter()
62                .map(|s| s.to_string())
63                .collect(),
64            extra_env: Vec::new(),
65            default_timeout: Duration::from_secs(60),
66            max_timeout: Duration::from_secs(110),
67            max_output_bytes: 20_000,
68            allow_network: None,
69            deny_read: Vec::new(),
70        }
71    }
72
73    /// Shell with [`best_available_sandbox`]: bubblewrap on Linux and
74    /// seatbelt on macOS when available, overridable with
75    /// [`crate::SANDBOX_ENV`]; uncontained (with a one-time warning) when no
76    /// OS sandbox is available.
77    pub fn sandboxed(workspace: Workspace) -> Self {
78        Self::new(workspace, best_available_sandbox())
79    }
80
81    /// Replace the list of host environment variables passed through.
82    pub fn env_allowlist(mut self, names: impl IntoIterator<Item = impl Into<String>>) -> Self {
83        self.env_allowlist = names.into_iter().map(Into::into).collect();
84        self
85    }
86
87    /// Set a fixed variable for every command (overrides the host value).
88    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
89        self.extra_env.push((key.into(), value.into()));
90        self
91    }
92
93    pub fn timeouts(mut self, default: Duration, max: Duration) -> Self {
94        self.max_timeout = max.max(Duration::from_secs(1));
95        self.default_timeout = default.min(self.max_timeout);
96        self
97    }
98
99    pub fn max_output_bytes(mut self, bytes: usize) -> Self {
100        self.max_output_bytes = bytes.max(64);
101        self
102    }
103
104    /// Let commands use the network, or not. Unset, a backend that can cut
105    /// the network ([`Sandbox::enforces_network_off`]) does, and one that
106    /// cannot (`LocalSandbox`) leaves it on and says so in the tool's
107    /// description. Set to `false`, commands are refused on a backend that
108    /// cannot enforce it, rather than run with the network on.
109    pub fn allow_network(mut self, allow: bool) -> Self {
110        self.allow_network = Some(allow);
111        self
112    }
113
114    /// Host paths commands must not read, for example credential
115    /// directories (on top of the backend's own defaults; see
116    /// [`SandboxCommand::deny_read`]). On a backend that cannot enforce it
117    /// ([`Sandbox::enforces_deny_read`], for example `LocalSandbox`), every
118    /// command is refused rather than run with the paths readable.
119    pub fn deny_read(
120        mut self,
121        paths: impl IntoIterator<Item = impl Into<std::path::PathBuf>>,
122    ) -> Self {
123        self.deny_read.extend(paths.into_iter().map(Into::into));
124        self
125    }
126
127    pub fn backend(&self) -> &Arc<dyn Sandbox> {
128        &self.backend
129    }
130
131    /// Why no command may run: a restriction this shell was configured
132    /// with that its backend cannot enforce. Fails closed instead of
133    /// running the command without it.
134    fn unenforceable(&self) -> Option<String> {
135        let backend = self.backend.name();
136        if !self.deny_read.is_empty() && !self.backend.enforces_deny_read() {
137            let paths = self
138                .deny_read
139                .iter()
140                .map(|p| format!("`{}`", p.display()))
141                .collect::<Vec<_>>()
142                .join(", ");
143            return Some(format!(
144                "refused: this shell must keep commands from reading {paths}, but its \
145                 `{backend}` backend cannot enforce that, so the command was not run. Use a \
146                 contained backend (bubblewrap, seatbelt or docker) for this shell."
147            ));
148        }
149        if self.allow_network == Some(false) && !self.backend.enforces_network_off() {
150            return Some(format!(
151                "refused: this shell must run commands without network access, but its \
152                 `{backend}` backend cannot cut the network, so the command was not run. Use a \
153                 contained backend (bubblewrap, seatbelt or docker) for this shell."
154            ));
155        }
156        None
157    }
158
159    fn environment(&self) -> Vec<(String, String)> {
160        let mut env: Vec<(String, String)> = self
161            .env_allowlist
162            .iter()
163            .filter_map(|k| std::env::var(k).ok().map(|v| (k.clone(), v)))
164            .collect();
165        for (k, v) in &self.extra_env {
166            env.retain(|(existing, _)| existing != k);
167            env.push((k.clone(), v.clone()));
168        }
169        env
170    }
171}
172
173#[derive(Deserialize)]
174#[serde(deny_unknown_fields)]
175struct ShellArgs {
176    command: String,
177    cwd: Option<String>,
178    timeout_secs: Option<u64>,
179}
180
181#[async_trait]
182impl Tool for Shell {
183    /// The loop must allow at least the shell's own maximum plus time to
184    /// kill the process group and collect output.
185    fn timeout(&self) -> Option<Duration> {
186        Some(self.max_timeout + Duration::from_secs(10))
187    }
188
189    fn spec(&self) -> ToolSpec {
190        let containment = if self.backend.is_contained() {
191            "Writes outside the workspace are blocked"
192        } else {
193            "Commands run directly on the host"
194        };
195        let network = if self.allow_network == Some(true) || !self.backend.enforces_network_off() {
196            "network available"
197        } else {
198            "no network access"
199        };
200        ToolSpec {
201            name: "shell".into(),
202            description: format!(
203                "Run a non-interactive command with `sh -c` in the workspace (backend: {}). \
204                 {containment}; {network}. stdin is closed, so do not run commands that wait \
205                 for input or open editors/pagers. Returns combined stdout+stderr (long output \
206                 keeps the start and end) and the exit code; a non-zero exit is reported as an \
207                 error. Default timeout {}s, maximum {}s. Use read_file/grep/glob/edit_file \
208                 instead of cat/grep/find/sed for files.",
209                self.backend.name(),
210                self.default_timeout.as_secs(),
211                self.max_timeout.as_secs()
212            ),
213            parameters: json!({
214                "type": "object",
215                "properties": {
216                    "command": {"type": "string", "description": "The command line to run."},
217                    "cwd": {"type": "string", "description": "Working directory, relative to the workspace root. Default: the root."},
218                    "timeout_secs": {"type": "integer", "minimum": 1, "maximum": self.max_timeout.as_secs(), "description": "Kill the command after this many seconds."}
219                },
220                "required": ["command"],
221                "additionalProperties": false
222            }),
223        }
224    }
225
226    fn annotations(&self) -> ToolAnnotations {
227        ToolAnnotations::DESTRUCTIVE
228    }
229
230    fn validate(&self, arguments: &Value) -> Result<(), String> {
231        match arguments.get("command").and_then(Value::as_str) {
232            Some(c) if !c.trim().is_empty() => Ok(()),
233            Some(_) => Err("`command` must not be empty".into()),
234            None => Err("`command` is required and must be a string".into()),
235        }
236    }
237
238    fn access(&self, arguments: &Value) -> AccessManifest {
239        AccessManifest {
240            commands: arguments
241                .get("command")
242                .and_then(Value::as_str)
243                .map(|c| vec![c.to_string()])
244                .unwrap_or_default(),
245            ..Default::default()
246        }
247    }
248
249    async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult {
250        if let Err(e) = self.validate(&arguments) {
251            return Ok(fail(e));
252        }
253        if let Some(refusal) = self.unenforceable() {
254            return Ok(fail(refusal));
255        }
256        let args: ShellArgs = match parse_args("shell", arguments) {
257            Ok(a) => a,
258            Err(e) => return Ok(fail(e)),
259        };
260        let cwd = match args.cwd.as_deref().filter(|c| !c.trim().is_empty()) {
261            Some(c) => match self.workspace.resolve(c) {
262                Ok(p) if p.is_dir() => p,
263                Ok(p) => {
264                    return Ok(fail(format!(
265                        "cwd `{}` is not an existing directory",
266                        self.workspace.display(&p)
267                    )));
268                }
269                Err(e) => return Ok(fail(e.to_string())),
270            },
271            None => self.workspace.root().to_path_buf(),
272        };
273        let timeout = args
274            .timeout_secs
275            .map(Duration::from_secs)
276            .unwrap_or(self.default_timeout)
277            .clamp(Duration::from_secs(1), self.max_timeout);
278
279        let spec = SandboxCommand {
280            command: args.command,
281            cwd: cwd.clone(),
282            workspace_root: self.workspace.root().to_path_buf(),
283            env: self.environment(),
284            timeout,
285            max_output_bytes: self.max_output_bytes,
286            allow_network: self.allow_network.unwrap_or(false),
287            deny_read: self.deny_read.clone(),
288            cancel: ctx.cancel.clone(),
289        };
290        let out = match self.backend.run(&spec).await {
291            Ok(o) => o,
292            Err(e) => return Ok(fail(e.to_string())),
293        };
294
295        let mut content = out.output.clone();
296        if content.trim().is_empty() {
297            content = "(no output)".into();
298        }
299        if !content.ends_with('\n') {
300            content.push('\n');
301        }
302        let status_line = if out.timed_out {
303            format!(
304                "[timed out after {}s; process killed. Use a longer timeout_secs or run less at once.]",
305                timeout.as_secs()
306            )
307        } else if out.cancelled {
308            "[cancelled; process killed]".to_string()
309        } else {
310            match out.exit_code {
311                Some(code) => format!("[exit code: {code}]"),
312                None => "[terminated by a signal]".to_string(),
313            }
314        };
315        content.push_str(&status_line);
316        let details = json!({
317            "exit_code": out.exit_code,
318            "timed_out": out.timed_out,
319            "cancelled": out.cancelled,
320            "duration_ms": out.duration.as_millis() as u64,
321            "output_bytes": out.output_bytes,
322            "truncated": out.truncated,
323            "backend": self.backend.name(),
324            "cwd": self.workspace.display(&cwd),
325        });
326        let output = if out.exit_code == Some(0) {
327            ToolOutput::text(content)
328        } else {
329            ToolOutput::error(content)
330        };
331        Ok(output.with_details(details))
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338    use crate::exec::LocalSandbox;
339    use crate::testutil::{ScopedVar, ctx, ws};
340
341    fn shell(ws: &Workspace) -> Shell {
342        Shell::new(ws.clone(), Arc::new(LocalSandbox))
343    }
344
345    #[tokio::test]
346    async fn reports_exit_codes() {
347        let (_d, ws) = ws();
348        let tool = shell(&ws);
349        let out = tool
350            .call(json!({"command": "echo hello; echo oops >&2"}), &ctx())
351            .await
352            .unwrap();
353        assert!(!out.is_error, "{}", out.content);
354        assert!(out.content.contains("hello") && out.content.contains("oops"));
355        assert!(out.content.ends_with("[exit code: 0]"));
356        assert_eq!(out.details["exit_code"], 0);
357        assert_eq!(out.details["backend"], "local");
358
359        let out = tool
360            .call(json!({"command": "echo failing; exit 3"}), &ctx())
361            .await
362            .unwrap();
363        assert!(out.is_error);
364        assert_eq!(out.details["exit_code"], 3);
365        assert!(out.content.contains("[exit code: 3]"));
366    }
367
368    #[tokio::test]
369    async fn runs_in_cwd_and_refuses_escapes() {
370        let (_d, ws) = ws();
371        std::fs::create_dir(ws.root().join("sub")).unwrap();
372        let tool = shell(&ws);
373        let out = tool
374            .call(json!({"command": "pwd", "cwd": "sub"}), &ctx())
375            .await
376            .unwrap();
377        assert!(
378            out.content
379                .trim_end()
380                .contains(&ws.root().join("sub").display().to_string())
381        );
382        let out = tool
383            .call(json!({"command": "pwd", "cwd": "../"}), &ctx())
384            .await
385            .unwrap();
386        assert!(out.is_error && out.content.contains("outside the workspace"));
387        let out = tool
388            .call(json!({"command": "pwd", "cwd": "missing"}), &ctx())
389            .await
390            .unwrap();
391        assert!(out.is_error && out.content.contains("not an existing directory"));
392    }
393
394    #[tokio::test]
395    async fn times_out_and_kills() {
396        let (_d, ws) = ws();
397        let tool = shell(&ws);
398        let started = std::time::Instant::now();
399        let out = tool
400            .call(
401                json!({"command": "echo start; sleep 30; echo never", "timeout_secs": 1}),
402                &ctx(),
403            )
404            .await
405            .unwrap();
406        assert!(started.elapsed() < Duration::from_secs(10));
407        assert!(out.is_error);
408        assert_eq!(out.details["timed_out"], true);
409        assert!(out.content.contains("start") && !out.content.contains("never"));
410        assert!(out.content.contains("timed out after 1s"));
411    }
412
413    #[tokio::test]
414    async fn caps_output_head_and_tail() {
415        let (_d, ws) = ws();
416        let tool = shell(&ws).max_output_bytes(1000);
417        let out = tool
418            .call(
419                json!({"command": "echo FIRST; i=0; while [ $i -lt 5000 ]; do echo line$i; i=$((i+1)); done; echo LAST"}),
420                &ctx(),
421            )
422            .await
423            .unwrap();
424        assert!(!out.is_error);
425        assert!(out.content.starts_with("FIRST\n"));
426        assert!(out.content.contains("LAST\n[exit code: 0]"));
427        assert!(out.content.contains("bytes of output omitted"));
428        assert!(out.content.len() < 1200, "{}", out.content.len());
429        assert_eq!(out.details["truncated"], true);
430    }
431
432    #[tokio::test]
433    async fn environment_is_allowlisted() {
434        let (_d, ws) = ws();
435        let _secret = ScopedVar::set("AIDAEMON_TOOLS_TEST_SECRET", "synthetic-secret");
436        let tool = shell(&ws).env("GREETING", "hi");
437        let out = tool
438            .call(
439                json!({"command": "echo \"[$AIDAEMON_TOOLS_TEST_SECRET][$GREETING]\""}),
440                &ctx(),
441            )
442            .await
443            .unwrap();
444        assert!(out.content.contains("[][hi]"), "{}", out.content);
445    }
446
447    #[tokio::test]
448    async fn restrictions_the_backend_cannot_enforce_refuse_the_command() {
449        let (dir, ws) = ws();
450        let local = Arc::new(crate::exec::LocalSandbox);
451        let secrets = tempfile::tempdir().unwrap();
452        std::fs::write(secrets.path().join("credentials"), "synthetic-secret").unwrap();
453        let cat = json!({"command": format!(
454            "cat {}/credentials; touch ran", secrets.path().display()
455        )});
456
457        let shell = Shell::new(ws.clone(), local.clone()).deny_read([secrets.path()]);
458        let out = shell.call(cat.clone(), &ctx()).await.unwrap();
459        assert!(out.is_error, "{}", out.content);
460        assert!(out.content.contains("cannot enforce"), "{}", out.content);
461        assert!(!out.content.contains("synthetic-secret"), "{}", out.content);
462        assert!(!dir.path().join("ran").exists(), "the command must not run");
463
464        let shell = Shell::new(ws.clone(), local.clone()).allow_network(false);
465        let out = shell
466            .call(json!({"command": "touch ran"}), &ctx())
467            .await
468            .unwrap();
469        assert!(out.is_error, "{}", out.content);
470        assert!(out.content.contains("network"), "{}", out.content);
471        assert!(!dir.path().join("ran").exists(), "the command must not run");
472
473        // Unrestricted, the host backend runs and says the network is on.
474        let shell = Shell::new(ws, local);
475        assert!(shell.spec().description.contains("network available"));
476        let out = shell
477            .call(json!({"command": "touch ran"}), &ctx())
478            .await
479            .unwrap();
480        assert!(!out.is_error, "{}", out.content);
481        assert!(dir.path().join("ran").exists());
482    }
483
484    #[test]
485    fn declares_destructive_and_command() {
486        let (_d, ws) = ws();
487        let tool = shell(&ws);
488        assert!(tool.annotations().destructive);
489        assert_eq!(
490            tool.access(&json!({"command": "ls -la"})).commands,
491            vec!["ls -la"]
492        );
493        assert!(tool.validate(&json!({"command": "  "})).is_err());
494        assert_eq!(tool.spec().parameters["additionalProperties"], json!(false));
495    }
496}