strands/sandbox/base.rs
1//! The [`Sandbox`] trait and its [`ExecuteOptions`].
2
3use std::sync::Arc;
4use std::time::Duration;
5
6use async_trait::async_trait;
7use futures::StreamExt;
8
9use crate::cancel::CancelSignal;
10use crate::error::{Error, Result};
11use crate::models::BoxStream;
12use crate::sandbox::types::{ExecutionResult, ExecutionStreamItem, FileInfo};
13use crate::tools::Tool;
14
15/// The stream returned by [`Sandbox::execute_streaming`] and
16/// [`Sandbox::execute_code_streaming`]: output chunks followed by one final
17/// [`ExecutionResult`], or an error.
18pub type ExecutionStream = BoxStream<'static, Result<ExecutionStreamItem>>;
19
20/// Options for command and code execution (`ExecuteOptions`).
21///
22/// ```
23/// use std::time::Duration;
24///
25/// use strands::sandbox::ExecuteOptions;
26///
27/// let options = ExecuteOptions::builder()
28/// .timeout(Duration::from_secs(30))
29/// .cwd("/tmp")
30/// .env([("GREETING", "hi")])
31/// .build();
32/// assert_eq!(options.env.unwrap(), [("GREETING".to_owned(), "hi".to_owned())]);
33/// ```
34#[derive(Debug, Clone, Default, bon::Builder)]
35pub struct ExecuteOptions {
36 /// Maximum execution time. `None` means no timeout. When it elapses the process is killed and
37 /// execution fails with [`SandboxTimeoutError`](crate::SandboxTimeoutError).
38 pub timeout: Option<Duration>,
39 /// Working directory for execution. `None` means the sandbox default.
40 #[builder(into)]
41 pub cwd: Option<String>,
42 /// Cancels execution: the process is killed when the signal fires and execution fails with
43 /// [`SandboxAbortError`](crate::SandboxAbortError).
44 pub signal: Option<CancelSignal>,
45 /// Environment variables to set for this command, in order; for a repeated name the last
46 /// value applies. The built-in sandboxes always apply them; a custom [`Sandbox`] must apply
47 /// them itself or they have no effect.
48 #[builder(with = |env: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>| {
49 env.into_iter().map(|(key, value)| (key.into(), value.into())).collect()
50 })]
51 pub env: Option<Vec<(String, String)>>,
52}
53
54/// An execution environment: where tools run commands and code and read and write files
55/// (`Sandbox`).
56///
57/// Several tools share one sandbox, so they see the same working directory and filesystem. The
58/// streaming methods are the primitives; [`execute`](Sandbox::execute) and
59/// [`execute_code`](Sandbox::execute_code) consume them and return the final result.
60///
61/// Implement [`PosixShellSandbox`](crate::sandbox::PosixShellSandbox) instead when the
62/// environment only offers a POSIX shell: it supplies everything except
63/// `execute_streaming`.
64///
65/// ```
66/// use futures::stream;
67/// use strands::sandbox::{ExecuteOptions, ExecutionResult, ExecutionStream, FileInfo, Sandbox};
68/// use strands::{Error, Result, async_trait};
69///
70/// struct Echo;
71///
72/// #[async_trait]
73/// impl Sandbox for Echo {
74/// fn execute_streaming(&self, command: &str, _options: ExecuteOptions) -> ExecutionStream {
75/// let result = ExecutionResult::new(0, format!("{command}\n"), "");
76/// Box::pin(stream::iter([Ok(result.into())]))
77/// }
78///
79/// fn execute_code_streaming(&self, code: &str, _language: &str, options: ExecuteOptions) -> ExecutionStream {
80/// self.execute_streaming(code, options)
81/// }
82///
83/// async fn read_file(&self, path: &str) -> Result<Vec<u8>> {
84/// Err(strands::SandboxPathNotFoundError::new(path).into())
85/// }
86///
87/// async fn write_file(&self, _path: &str, _content: &[u8]) -> Result<()> {
88/// Err(Error::other("read-only"))
89/// }
90///
91/// async fn remove_file(&self, _path: &str) -> Result<()> {
92/// Err(Error::other("read-only"))
93/// }
94///
95/// async fn list_files(&self, _path: &str) -> Result<Vec<FileInfo>> {
96/// Ok(Vec::new())
97/// }
98/// }
99///
100/// # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
101/// let result = Echo.execute("hello", ExecuteOptions::default()).await?;
102/// assert_eq!(result.stdout, "hello\n");
103/// # Ok::<_, Error>(())
104/// # }).unwrap();
105/// ```
106#[async_trait]
107pub trait Sandbox: Send + Sync + 'static {
108 /// Runs a shell command, streaming its output.
109 ///
110 /// Yields a [`StreamChunk`](crate::sandbox::StreamChunk) for each piece of stdout and
111 /// stderr as it arrives, then one [`ExecutionResult`] with the exit code and the complete
112 /// output. A non-zero exit code is a result, not an error.
113 ///
114 /// # Errors
115 ///
116 /// The stream ends with [`SandboxTimeoutError`](crate::SandboxTimeoutError) when
117 /// `options.timeout` elapses, [`SandboxAbortError`](crate::SandboxAbortError) when
118 /// `options.signal` fires, and another error when the command cannot be started or an
119 /// environment variable name is invalid.
120 fn execute_streaming(&self, command: &str, options: ExecuteOptions) -> ExecutionStream;
121
122 /// Runs source code through a language interpreter such as `python3` or `node`, streaming
123 /// its output.
124 ///
125 /// # Errors
126 ///
127 /// As [`execute_streaming`](Sandbox::execute_streaming); the stream also fails when
128 /// `language` does not match [`LANGUAGE_PATTERN`](crate::sandbox::LANGUAGE_PATTERN). A
129 /// missing interpreter is a result with exit code 127.
130 fn execute_code_streaming(&self, code: &str, language: &str, options: ExecuteOptions) -> ExecutionStream;
131
132 /// Reads a file as raw bytes. See [`read_text`](Sandbox::read_text) for text.
133 ///
134 /// # Errors
135 ///
136 /// [`SandboxPathNotFoundError`](crate::SandboxPathNotFoundError) when the path does not
137 /// exist, [`SandboxIsADirectoryError`](crate::SandboxIsADirectoryError) when it is a
138 /// directory, [`SandboxPermissionError`](crate::SandboxPermissionError) when it cannot be
139 /// read, and another error for any other failure.
140 async fn read_file(&self, path: &str) -> Result<Vec<u8>>;
141
142 /// Writes raw bytes to a file, creating missing parent directories.
143 ///
144 /// # Errors
145 ///
146 /// When the file cannot be written.
147 async fn write_file(&self, path: &str, content: &[u8]) -> Result<()>;
148
149 /// Removes a file.
150 ///
151 /// # Errors
152 ///
153 /// When the file does not exist or cannot be removed.
154 async fn remove_file(&self, path: &str) -> Result<()>;
155
156 /// Lists a directory.
157 ///
158 /// # Errors
159 ///
160 /// [`SandboxPathNotFoundError`](crate::SandboxPathNotFoundError) when the directory does not
161 /// exist or a path component is a file, and another error for any other failure.
162 async fn list_files(&self, path: &str) -> Result<Vec<FileInfo>>;
163
164 /// Tools this sandbox vends to an agent. The agent registers them at
165 /// initialization, skipping any whose name the user already registered. None by default.
166 fn get_tools(&self) -> Vec<Arc<dyn Tool>> {
167 Vec::new()
168 }
169
170 /// Runs a shell command and returns its result (`execute`), consuming
171 /// [`execute_streaming`](Sandbox::execute_streaming).
172 ///
173 /// # Errors
174 ///
175 /// As [`execute_streaming`](Sandbox::execute_streaming), and when the stream ends without a
176 /// result.
177 async fn execute(&self, command: &str, options: ExecuteOptions) -> Result<ExecutionResult> {
178 final_result(self.execute_streaming(command, options), "execute_streaming").await
179 }
180
181 /// Runs source code through an interpreter and returns its result,
182 /// consuming [`execute_code_streaming`](Sandbox::execute_code_streaming).
183 ///
184 /// # Errors
185 ///
186 /// As [`execute_code_streaming`](Sandbox::execute_code_streaming), and when the stream ends
187 /// without a result.
188 async fn execute_code(&self, code: &str, language: &str, options: ExecuteOptions) -> Result<ExecutionResult> {
189 final_result(
190 self.execute_code_streaming(code, language, options),
191 "execute_code_streaming",
192 )
193 .await
194 }
195
196 /// Reads a file as UTF-8 text, replacing invalid sequences with U+FFFD and
197 /// dropping a leading byte order mark.
198 ///
199 /// # Errors
200 ///
201 /// As [`read_file`](Sandbox::read_file).
202 async fn read_text(&self, path: &str) -> Result<String> {
203 Ok(decode_text(&self.read_file(path).await?))
204 }
205
206 /// Writes text to a file as UTF-8.
207 ///
208 /// # Errors
209 ///
210 /// As [`write_file`](Sandbox::write_file).
211 async fn write_text(&self, path: &str, content: &str) -> Result<()> {
212 self.write_file(path, content.as_bytes()).await
213 }
214}
215
216/// What the builder's `sandbox(..)` setter takes: a sandbox by value, an `Arc` of one, or an
217/// `Arc<dyn Sandbox>` (kept as is, so the agent's [`sandbox`](crate::Agent::sandbox) is the
218/// same instance).
219pub trait IntoSandbox {
220 /// The sandbox, shared.
221 fn into_sandbox(self) -> Arc<dyn Sandbox>;
222}
223
224impl<S: Sandbox> IntoSandbox for S {
225 fn into_sandbox(self) -> Arc<dyn Sandbox> {
226 Arc::new(self)
227 }
228}
229
230impl<S: Sandbox> IntoSandbox for Arc<S> {
231 fn into_sandbox(self) -> Arc<dyn Sandbox> {
232 self
233 }
234}
235
236impl IntoSandbox for Arc<dyn Sandbox> {
237 fn into_sandbox(self) -> Arc<dyn Sandbox> {
238 self
239 }
240}
241
242/// Drains an execution stream up to its result.
243pub(crate) async fn final_result(mut stream: ExecutionStream, method: &str) -> Result<ExecutionResult> {
244 while let Some(item) = stream.next().await {
245 if let ExecutionStreamItem::ExecutionResult(result) = item? {
246 return Ok(result);
247 }
248 }
249 Err(Error::other(format!("{method}() did not yield an ExecutionResult")))
250}
251
252fn decode_text(bytes: &[u8]) -> String {
253 let bytes = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);
254 String::from_utf8_lossy(bytes).into_owned()
255}
256
257#[cfg(test)]
258mod tests {
259 use futures::stream;
260
261 use super::*;
262 use crate::sandbox::types::{StreamChunk, StreamType};
263
264 struct Scripted(Vec<ExecutionStreamItem>);
265
266 #[async_trait]
267 impl Sandbox for Scripted {
268 fn execute_streaming(&self, _command: &str, _options: ExecuteOptions) -> ExecutionStream {
269 Box::pin(stream::iter(self.0.clone().into_iter().map(Ok)))
270 }
271
272 fn execute_code_streaming(&self, code: &str, _language: &str, options: ExecuteOptions) -> ExecutionStream {
273 self.execute_streaming(code, options)
274 }
275
276 async fn read_file(&self, _path: &str) -> Result<Vec<u8>> {
277 Ok(b"\xEF\xBB\xBFcaf\xC3\xA9 \xFF".to_vec())
278 }
279
280 async fn write_file(&self, _path: &str, _content: &[u8]) -> Result<()> {
281 Ok(())
282 }
283
284 async fn remove_file(&self, _path: &str) -> Result<()> {
285 Ok(())
286 }
287
288 async fn list_files(&self, _path: &str) -> Result<Vec<FileInfo>> {
289 Ok(Vec::new())
290 }
291 }
292
293 #[tokio::test]
294 async fn execute_returns_the_final_result_after_the_chunks() {
295 let sandbox = Scripted(vec![
296 StreamChunk::new("hi\n", StreamType::Stdout).into(),
297 ExecutionResult::new(0, "hi\n", "").into(),
298 ]);
299 let result = sandbox.execute("echo hi", ExecuteOptions::default()).await.unwrap();
300 assert_eq!(result, ExecutionResult::new(0, "hi\n", ""));
301 let code = sandbox
302 .execute_code("x", "sh", ExecuteOptions::default())
303 .await
304 .unwrap();
305 assert_eq!(code.exit_code, 0);
306 }
307
308 #[tokio::test]
309 async fn execute_fails_when_the_stream_ends_without_a_result() {
310 let sandbox = Scripted(vec![StreamChunk::new("hi", StreamType::Stdout).into()]);
311 let error = sandbox.execute("echo hi", ExecuteOptions::default()).await.unwrap_err();
312 assert_eq!(
313 error.to_string(),
314 "execute_streaming() did not yield an ExecutionResult"
315 );
316 let error = sandbox
317 .execute_code("x", "sh", ExecuteOptions::default())
318 .await
319 .unwrap_err();
320 assert_eq!(
321 error.to_string(),
322 "execute_code_streaming() did not yield an ExecutionResult"
323 );
324 }
325
326 #[tokio::test]
327 async fn read_text_decodes_like_text_decoder() {
328 let text = Scripted(Vec::new()).read_text("any").await.unwrap();
329 assert_eq!(text, "café \u{FFFD}");
330 }
331
332 #[test]
333 fn get_tools_is_empty_by_default() {
334 assert!(Scripted(Vec::new()).get_tools().is_empty());
335 }
336
337 #[test]
338 fn options_builder_keeps_env_order() {
339 let options = ExecuteOptions::builder()
340 .env([("FOO".to_owned(), "1".to_owned()), ("BAR".to_owned(), "2".to_owned())])
341 .build();
342 let keys: Vec<_> = options.env.unwrap().into_iter().map(|(key, _)| key).collect();
343 assert_eq!(keys, ["FOO", "BAR"]);
344 }
345}