1use 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
24pub(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 BashTimeoutError
33);
34
35tool_error!(
36 BashSessionError
39);
40
41#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
43#[non_exhaustive]
44pub struct BashOutput {
45 pub output: String,
47 pub error: String,
49}
50
51struct 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
103struct 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 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
159async 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#[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#[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;