Skip to main content

strands/vended_tools/
bash.rs

1//! The host `bash` tool: a persistent bash process per agent, so variables and the working
2//! directory carry over between calls.
3//!
4//! The process runs on the host, not in the agent's sandbox, and has no isolation. The
5//! sandbox-routed, stateless shell is [`shell`](super::shell).
6
7use std::process::Stdio;
8use std::sync::{Arc, Mutex, PoisonError, RwLock, Weak};
9
10use serde::Serialize;
11use serde_json::json;
12use tokio::io::{AsyncReadExt, AsyncWriteExt};
13use tokio::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command};
14
15use super::input::InputReader;
16use super::{js_number_text, seconds, tool_error};
17use crate::sandbox::process_group::{self, ProcessGroup};
18use crate::tools::{FunctionTool, ToolError};
19use crate::types::{JsonObject, JsonSchema, JsonValue};
20
21const DEFAULT_TIMEOUT: f64 = 120.0;
22const READ_BUFFER_SIZE: usize = 8192;
23
24/// The description of the `bash` tool shown to the model.
25pub(crate) const BASH_DESCRIPTION: &str = concat!(
26    "Executes bash shell commands in a persistent session. Supports execute and restart modes. ",
27    "Commands persist state (variables, directory) within the session."
28);
29
30tool_error!(
31    /// A bash command exceeded its timeout (`BashTimeoutError`); the session is stopped.
32    BashTimeoutError
33);
34
35tool_error!(
36    /// The bash session failed (`BashSessionError`), for example the process exited during a
37    /// command. The next call starts a new session.
38    BashSessionError
39);
40
41/// What a bash command wrote (`BashOutput`), each stream trimmed.
42#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
43#[non_exhaustive]
44pub struct BashOutput {
45    /// Standard output.
46    pub output: String,
47    /// Standard error; empty when there was none.
48    pub error: String,
49}
50
51/// A running bash process. Dropping it kills the process and its process group, so every way a
52/// call can end without a complete exchange (error, timeout, a dropped future) also ends the
53/// session: a later call never reads the output of an earlier command.
54struct Process {
55    child: Child,
56    group: ProcessGroup,
57    stdin: ChildStdin,
58    stdout: ChildStdout,
59    stderr: ChildStderr,
60}
61
62impl Process {
63    fn spawn() -> Result<Self, BashSessionError> {
64        let cwd = std::env::current_dir()
65            .map_err(|error| BashSessionError::new(format!("Failed to start bash session: {error}")))?;
66        let mut command = Command::new("bash");
67        let mut child = process_group::isolate(&mut command)
68            .current_dir(cwd)
69            .env("PS1", "")
70            .env("PS2", "")
71            .stdin(Stdio::piped())
72            .stdout(Stdio::piped())
73            .stderr(Stdio::piped())
74            .kill_on_drop(true)
75            .spawn()
76            .map_err(|error| BashSessionError::new(format!("Failed to start bash session: {error}")))?;
77        let group = ProcessGroup::of(&child);
78        let (Some(stdin), Some(stdout), Some(stderr)) = (child.stdin.take(), child.stdout.take(), child.stderr.take())
79        else {
80            group.kill(&mut child);
81            return Err(BashSessionError::new("Failed to create bash process streams"));
82        };
83        Ok(Self {
84            child,
85            group,
86            stdin,
87            stdout,
88            stderr,
89        })
90    }
91
92    fn is_running(&mut self) -> bool {
93        self.child.try_wait().ok().flatten().is_none()
94    }
95}
96
97impl Drop for Process {
98    fn drop(&mut self) {
99        self.group.kill(&mut self.child);
100    }
101}
102
103/// One agent's bash process, started on first use (`BashSession`).
104struct BashSession {
105    timeout: f64,
106    sentinel: String,
107    process: Option<Process>,
108}
109
110impl BashSession {
111    fn new(timeout: f64) -> Self {
112        Self {
113            timeout,
114            sentinel: format!("__BASH_DONE_{}__", uuid::Uuid::new_v4().simple()),
115            process: None,
116        }
117    }
118
119    /// Takes the running process, or starts one. The caller puts it back only after a complete
120    /// exchange.
121    fn take_process(&mut self) -> Result<Process, BashSessionError> {
122        if let Some(mut process) = self.process.take()
123            && process.is_running()
124        {
125            return Ok(process);
126        }
127        Process::spawn()
128    }
129
130    fn stop(&mut self) {
131        self.process = None;
132    }
133
134    async fn run(&mut self, command: &str, timeout: Option<f64>) -> Result<BashOutput, ToolError> {
135        let effective = timeout.unwrap_or(self.timeout);
136        let sentinel = self.sentinel.clone();
137        let mut process = self.take_process()?;
138        let outcome = match seconds(effective) {
139            Some(limit) => tokio::time::timeout(limit, exchange(&mut process, command, &sentinel))
140                .await
141                .ok(),
142            None => Some(exchange(&mut process, command, &sentinel).await),
143        };
144        match outcome {
145            Some(Ok(output)) => {
146                self.process = Some(process);
147                Ok(output)
148            }
149            Some(Err(error)) => Err(error.into()),
150            None => Err(BashTimeoutError::new(format!(
151                "Command timed out after {} seconds",
152                js_number_text(effective)
153            ))
154            .into()),
155        }
156    }
157}
158
159/// Sends `command` followed by a sentinel on both streams, and reads until both sentinels
160/// arrive, so all of the command's output belongs to this call.
161async fn exchange(process: &mut Process, command: &str, sentinel: &str) -> Result<BashOutput, BashSessionError> {
162    let script = format!("{command}\necho \"{sentinel}\" >&2\necho \"{sentinel}\"\n");
163    if let Err(error) = process.stdin.write_all(script.as_bytes()).await {
164        return Err(BashSessionError::new(format!("Failed to write command: {error}")));
165    }
166    let mut stdout = Vec::new();
167    let mut stderr = Vec::new();
168    let mut out_buf = vec![0_u8; READ_BUFFER_SIZE];
169    let mut err_buf = vec![0_u8; READ_BUFFER_SIZE];
170    let marker = sentinel.as_bytes();
171    while !contains(&stdout, marker) || !contains(&stderr, marker) {
172        let read = tokio::select! {
173            read = process.stdout.read(&mut out_buf), if !contains(&stdout, marker) => read.map(|n| (n, true)),
174            read = process.stderr.read(&mut err_buf), if !contains(&stderr, marker) => read.map(|n| (n, false)),
175        };
176        match read {
177            Ok((0, _)) | Err(_) => {
178                let code = process
179                    .child
180                    .wait()
181                    .await
182                    .ok()
183                    .and_then(|status| status.code())
184                    .map_or_else(|| "unknown".to_owned(), |code| code.to_string());
185                return Err(BashSessionError::new(format!(
186                    "Bash process exited unexpectedly with code {code}"
187                )));
188            }
189            Ok((n, true)) => stdout.extend_from_slice(&out_buf[..n]),
190            Ok((n, false)) => stderr.extend_from_slice(&err_buf[..n]),
191        }
192    }
193    Ok(BashOutput {
194        output: strip(&stdout, sentinel),
195        error: strip(&stderr, sentinel),
196    })
197}
198
199fn contains(haystack: &[u8], needle: &[u8]) -> bool {
200    haystack.windows(needle.len()).any(|window| window == needle)
201}
202
203fn strip(bytes: &[u8], sentinel: &str) -> String {
204    String::from_utf8_lossy(bytes)
205        .replacen(sentinel, "", 1)
206        .trim()
207        .to_owned()
208}
209
210type AgentKey = Weak<RwLock<JsonObject>>;
211type SharedSession = Arc<tokio::sync::Mutex<BashSession>>;
212
213/// The sessions of the agents that called one `bash` tool, keyed by their app state so a
214/// dropped agent's process is stopped on the next call.
215#[derive(Default)]
216struct Sessions(Mutex<Vec<(AgentKey, SharedSession)>>);
217
218impl Sessions {
219    fn with<T>(&self, f: impl FnOnce(&mut Vec<(AgentKey, SharedSession)>) -> T) -> T {
220        let mut sessions = self.0.lock().unwrap_or_else(PoisonError::into_inner);
221        sessions.retain(|(agent, _)| agent.strong_count() > 0);
222        f(&mut sessions)
223    }
224
225    fn get(&self, key: &AgentKey) -> Option<SharedSession> {
226        self.with(|sessions| {
227            sessions
228                .iter()
229                .find(|(agent, _)| Weak::ptr_eq(agent, key))
230                .map(|(_, session)| session.clone())
231        })
232    }
233
234    fn get_or_create(&self, key: &AgentKey, timeout: f64) -> SharedSession {
235        self.with(|sessions| {
236            if let Some((_, session)) = sessions.iter().find(|(agent, _)| Weak::ptr_eq(agent, key)) {
237                return session.clone();
238            }
239            let session = Arc::new(tokio::sync::Mutex::new(BashSession::new(timeout)));
240            sessions.push((key.clone(), session.clone()));
241            session
242        })
243    }
244
245    fn replace(&self, key: &AgentKey) -> Option<SharedSession> {
246        self.with(|sessions| {
247            let previous = sessions
248                .iter()
249                .position(|(agent, _)| Weak::ptr_eq(agent, key))
250                .map(|index| sessions.remove(index).1);
251            let session = Arc::new(tokio::sync::Mutex::new(BashSession::new(DEFAULT_TIMEOUT)));
252            sessions.push((key.clone(), session));
253            previous
254        })
255    }
256}
257
258fn input_schema() -> JsonSchema {
259    json!({
260        "type": "object",
261        "properties": {
262            "mode": {
263                "type": "string",
264                "enum": ["execute", "restart"],
265                "description": "Operation mode: \"execute\" to run a command, \"restart\" to restart the session"
266            },
267            "command": {
268                "description": "The bash command to execute (required when mode is \"execute\")",
269                "type": "string"
270            },
271            "timeout": {
272                "description": "Timeout in seconds (default: 120, applies only to execute mode)",
273                "type": "number",
274                "exclusiveMinimum": 0
275            }
276        },
277        "required": ["mode"],
278        "additionalProperties": false
279    })
280}
281
282/// Creates the `bash` tool (`bash`): `mode: "execute"` runs `command` in the calling agent's
283/// session and returns a [`BashOutput`] as JSON; `mode: "restart"` replaces the session.
284///
285/// Each agent has its own session, created on first use with `timeout` (120 seconds when
286/// absent) as its default. A timeout fails with a [`BashTimeoutError`] and stops the session;
287/// the process exiting fails with a [`BashSessionError`]. Either way the next call starts a new
288/// process. Sessions end when their agent is dropped and when the tool is dropped.
289///
290/// ```
291/// let agent = strands::Agent::builder().tools([strands::vended_tools::bash::bash()]).printer(false).build()?;
292/// assert!(agent.tool_registry().get("bash").is_some());
293/// # Ok::<(), strands::Error>(())
294/// ```
295#[must_use]
296pub fn bash() -> FunctionTool {
297    let sessions = Arc::new(Sessions::default());
298    FunctionTool::builder("bash", BASH_DESCRIPTION)
299        .input_schema(input_schema())
300        .callback(move |input, context| {
301            let sessions = sessions.clone();
302            let key = context.agent().app_state().downgrade();
303            async move { run(&sessions, &key, &input).await }
304        })
305}
306
307async fn run(sessions: &Sessions, key: &AgentKey, input: &JsonValue) -> Result<JsonValue, ToolError> {
308    let mut reader = InputReader::new(input);
309    let mode = reader.one_of("mode", &["execute", "restart"]);
310    let command = reader.optional_string("command");
311    let timeout = reader.optional_positive("timeout", |_| "Too small: expected number to be >0".to_owned());
312    reader.finish()?;
313    if mode == Some("restart") {
314        if let Some(previous) = sessions.replace(key) {
315            previous.lock().await.stop();
316        }
317        return Ok("Bash session restarted".into());
318    }
319    let Some(command) = command.filter(|command| !command.is_empty()) else {
320        return Err(ToolError::msg("command is required when mode is \"execute\""));
321    };
322    let session = match sessions.get(key) {
323        Some(session) => session,
324        None => sessions.get_or_create(key, timeout.unwrap_or(DEFAULT_TIMEOUT)),
325    };
326    let output = session.lock().await.run(command, timeout).await?;
327    Ok(serde_json::to_value(output)?)
328}
329
330#[cfg(test)]
331mod tests;