strands/vended_tools/
shell.rs1use 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
22pub 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
32#[non_exhaustive]
33pub struct ShellOutput {
34 pub output: String,
36 pub error: String,
38 pub exit_code: i32,
40}
41
42impl ShellOutput {
43 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#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
58#[error("{message}")]
59#[non_exhaustive]
60pub struct ShellTimeoutError {
61 message: String,
62 pub partial: Option<ShellOutput>,
64}
65
66impl ShellTimeoutError {
67 pub const NAME: &'static str = "ShellTimeoutError";
69
70 pub fn new(message: impl Into<String>, partial: Option<ShellOutput>) -> Self {
72 Self {
73 message: message.into(),
74 partial,
75 }
76 }
77
78 #[must_use]
80 pub fn message(&self) -> &str {
81 &self.message
82 }
83}
84
85tool_error!(
86 ShellExecutionError
88);
89
90#[derive(Clone, Default, bon::Builder)]
92#[builder(on(String, into))]
93pub struct MakeShellOptions {
94 pub sandbox: Option<Arc<dyn Sandbox>>,
97 pub name: Option<String>,
99 pub description: Option<String>,
101 pub input_schema: Option<JsonSchema>,
103 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
134pub 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 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;