Skip to main content

strands/vended_tools/
shell.rs

1//! The sandbox-routed `shell` tool.
2//!
3//! Each call runs in a fresh shell of the sandbox (`sh` locally and in containers, the login
4//! shell over SSH), so state such as variables and the working directory does not persist. The
5//! persistent host shell is [`bash`](super::bash).
6
7use std::sync::Arc;
8
9use serde::Serialize;
10use serde_json::json;
11
12use super::input::InputReader;
13use super::{js_number, resolve_sandbox, seconds, tool_error};
14use crate::cancel::CancelSignal;
15use crate::error::{Error, Result};
16use crate::sandbox::{ExecuteOptions, Sandbox};
17use crate::tools::{FunctionTool, ToolError};
18use crate::types::{JsonSchema, JsonValue};
19
20const DEFAULT_TIMEOUT: f64 = 120.0;
21
22/// The description of the `shell` tool shown to the model (`SANDBOX_SHELL_DESCRIPTION`).
23pub const SANDBOX_SHELL_DESCRIPTION: &str = concat!(
24    "Executes shell commands and returns output (stdout), error (stderr), and exit_code (non-zero means the ",
25    "command failed). Each call runs in a fresh shell; ",
26    "state such as variables and the working directory does not persist across calls."
27);
28
29/// What a shell command produced (`ShellOutput`): the tool's result, and the partial output of a
30/// timed-out command.
31#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
32#[non_exhaustive]
33pub struct ShellOutput {
34    /// Standard output.
35    pub output: String,
36    /// Standard error; empty when there was none.
37    pub error: String,
38    /// The exit code; non-zero means the command failed, and 124 that it timed out.
39    pub exit_code: i32,
40}
41
42impl ShellOutput {
43    /// Creates an output.
44    pub fn new(output: impl Into<String>, error: impl Into<String>, exit_code: i32) -> Self {
45        Self {
46            output: output.into(),
47            error: error.into(),
48            exit_code,
49        }
50    }
51}
52
53/// A shell command exceeded its timeout (`ShellTimeoutError`).
54///
55/// The message is the sandbox's timeout message followed by the partial output as JSON with exit
56/// code 124 (the `timeout(1)` convention), because the model sees only the message.
57#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
58#[error("{message}")]
59#[non_exhaustive]
60pub struct ShellTimeoutError {
61    message: String,
62    /// The output captured before the command was killed.
63    pub partial: Option<ShellOutput>,
64}
65
66impl ShellTimeoutError {
67    /// The error class name.
68    pub const NAME: &'static str = "ShellTimeoutError";
69
70    /// An error with `message` and the captured output.
71    pub fn new(message: impl Into<String>, partial: Option<ShellOutput>) -> Self {
72        Self {
73            message: message.into(),
74            partial,
75        }
76    }
77
78    /// What failed.
79    #[must_use]
80    pub fn message(&self) -> &str {
81        &self.message
82    }
83}
84
85tool_error!(
86    /// The sandbox failed to run a shell command (`ShellExecutionError`).
87    ShellExecutionError
88);
89
90/// Options for [`make_shell`] (`MakeShellOptions`).
91#[derive(Clone, Default, bon::Builder)]
92#[builder(on(String, into))]
93pub struct MakeShellOptions {
94    /// The sandbox to run in. `None` uses the calling agent's
95    /// [`sandbox`](crate::ToolAgent::sandbox).
96    pub sandbox: Option<Arc<dyn Sandbox>>,
97    /// The tool name; `shell` when absent.
98    pub name: Option<String>,
99    /// The tool description; [`SANDBOX_SHELL_DESCRIPTION`] when absent.
100    pub description: Option<String>,
101    /// The input schema shown to the model; the input is still read as `command` and `timeout`.
102    pub input_schema: Option<JsonSchema>,
103    /// The timeout in seconds when the model omits `timeout`; 120 when absent.
104    pub default_timeout: Option<f64>,
105}
106
107impl std::fmt::Debug for MakeShellOptions {
108    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
109        f.debug_struct("MakeShellOptions")
110            .field("sandbox", &self.sandbox.is_some())
111            .field("name", &self.name)
112            .field("default_timeout", &self.default_timeout)
113            .finish_non_exhaustive()
114    }
115}
116
117fn input_schema(default_timeout: f64) -> JsonSchema {
118    json!({
119        "type": "object",
120        "properties": {
121            "command": {"type": "string", "description": "The shell command to execute."},
122            "timeout": {
123                "default": js_number(default_timeout),
124                "description": "Optional per-execution timeout in seconds.",
125                "type": "number",
126                "exclusiveMinimum": 0
127            }
128        },
129        "required": ["command"],
130        "additionalProperties": false
131    })
132}
133
134/// Creates a sandbox shell tool: it runs `command` with the sandbox's
135/// [`execute`](Sandbox::execute) and returns a [`ShellOutput`] as JSON.
136///
137/// A non-zero exit code is a result; a timeout fails with a [`ShellTimeoutError`] that carries
138/// the partial output, cancellation of the call stops the command and fails with the sandbox's
139/// [`SandboxAbortError`](crate::SandboxAbortError) with the partial output appended to its
140/// message as JSON with exit code 130, and any other sandbox failure with a
141/// [`ShellExecutionError`].
142///
143/// ```
144/// use strands::vended_tools::shell::{MakeShellOptions, make_shell};
145///
146/// let shell = make_shell(MakeShellOptions::builder().default_timeout(30.0).build())?;
147/// let agent = strands::Agent::builder().tools([shell]).printer(false).build()?;
148/// assert!(agent.tool_registry().get("shell").is_some());
149/// # Ok::<(), strands::Error>(())
150/// ```
151///
152/// # Errors
153///
154/// When `default_timeout` is not a positive finite number.
155pub fn make_shell(options: MakeShellOptions) -> Result<FunctionTool> {
156    let default_timeout = options.default_timeout.unwrap_or(DEFAULT_TIMEOUT);
157    if !default_timeout.is_finite() || default_timeout <= 0.0 {
158        return Err(Error::other(format!(
159            "defaultTimeout must be a positive finite number, got {}",
160            super::js_number_text(default_timeout)
161        )));
162    }
163    let schema = options.input_schema.unwrap_or_else(|| input_schema(default_timeout));
164    let name = options.name.unwrap_or_else(|| "shell".to_owned());
165    let description = options
166        .description
167        .unwrap_or_else(|| SANDBOX_SHELL_DESCRIPTION.to_owned());
168    let bound = options.sandbox;
169    Ok(FunctionTool::builder(name, description)
170        .input_schema(schema)
171        .callback(move |input, context| {
172            let sandbox = resolve_sandbox(bound.as_ref(), &context);
173            let signal = context.cancel_signal().clone();
174            async move { run(sandbox.as_ref(), &input, default_timeout, signal).await }
175        }))
176}
177
178async fn run(
179    sandbox: &dyn Sandbox,
180    input: &JsonValue,
181    default_timeout: f64,
182    signal: CancelSignal,
183) -> std::result::Result<JsonValue, ToolError> {
184    let mut reader = InputReader::new(input);
185    let command = reader.string("command");
186    let timeout = reader.optional_positive("timeout", |_| "Too small: expected number to be >0".to_owned());
187    reader.finish()?;
188    let command = command.unwrap_or_default();
189    let options = ExecuteOptions {
190        timeout: seconds(timeout.unwrap_or(default_timeout)),
191        signal: Some(signal),
192        ..ExecuteOptions::default()
193    };
194    match sandbox.execute(command, options).await {
195        Ok(result) => Ok(serde_json::to_value(ShellOutput::new(
196            result.stdout,
197            result.stderr,
198            result.exit_code,
199        ))?),
200        Err(Error::SandboxTimeout(timeout)) => {
201            let partial = ShellOutput::new(timeout.stdout.clone(), timeout.stderr.clone(), 124);
202            let message = format!("{timeout}\n{}", serde_json::to_string(&partial)?);
203            Err(ToolError::new(ShellTimeoutError::new(message, Some(partial))))
204        }
205        // Not a shell failure: the abort itself, with the partial output and the interrupt
206        // convention's exit code 130 appended.
207        Err(Error::SandboxAbort(abort)) => {
208            let partial = ShellOutput::new(abort.stdout.clone(), abort.stderr.clone(), 130);
209            let detail = serde_json::to_string(&partial)?;
210            Err(Error::from(abort.with_detail(&detail)).into())
211        }
212        Err(error) => Err(ToolError::new(ShellExecutionError::new(error.to_string()))),
213    }
214}
215
216#[cfg(test)]
217mod tests;