use std::process::Stdio;
use std::sync::Arc;
use std::time::{Duration, Instant};
use adk_core::{Result, Tool, ToolContext};
#[cfg(windows)]
use adk_sandbox::process_tree::{ContainedChild, ContainedProcess, JobObject};
use async_trait::async_trait;
use serde_json::{Value, json};
use tokio::io::{AsyncRead, AsyncReadExt};
use tokio::sync::Notify;
use tokio::task::JoinHandle;
use crate::error::DevToolError;
use crate::launcher::{CommandLauncher, HostLauncher};
use crate::tools::output::{Collector, OutputStore, Stream};
use crate::tools::read::require_str;
use crate::workspace::Workspace;
const KILL_GRACE: Duration = Duration::from_secs(1);
const PROGRESS_LINE_MAX: usize = 8192;
pub struct BashTool {
workspace: Workspace,
launcher: Arc<dyn CommandLauncher>,
output_store: Option<Arc<dyn OutputStore>>,
}
impl BashTool {
pub fn new(workspace: Workspace) -> Self {
Self { workspace, launcher: Arc::new(HostLauncher), output_store: None }
}
#[must_use]
pub fn with_launcher(mut self, launcher: Arc<dyn CommandLauncher>) -> Self {
self.launcher = launcher;
self
}
#[must_use]
pub fn with_output_store(mut self, store: Arc<dyn OutputStore>) -> Self {
self.output_store = Some(store);
self
}
pub async fn spawn(&self, ctx: Arc<dyn ToolContext>, command: &str) -> Result<RunningCommand> {
if !self.workspace.bash_allowed() {
return Err(DevToolError::BashDisabled.into());
}
let kill_group_on_exit = self.workspace.kills_bash_group_on_exit();
let (child, group, stdout, stderr) = self.start(&ctx, command, kill_group_on_exit).await?;
let pid = child.id();
tracing::debug!(
bash.isolation = self.launcher.isolation(),
process.pid = pid,
"started bash command"
);
let output = Arc::new(Collector::new(
self.output_store.clone(),
ctx.clone(),
command,
self.workspace.max_output(),
));
let pumps = [(stdout, Stream::Stdout), (stderr, Stream::Stderr)]
.into_iter()
.filter_map(|(pipe, stream)| {
pipe.map(|pipe| tokio::spawn(pump(pipe, stream, output.clone(), ctx.clone())))
})
.collect();
let kill = Arc::new(Notify::new());
#[cfg(windows)]
let job = group.job.clone();
let done = tokio::spawn(supervise(child, group, kill_group_on_exit, pumps, kill.clone()));
Ok(RunningCommand {
command: command.to_string(),
pid,
output,
kill,
done,
exit: None,
started: Instant::now(),
#[cfg(windows)]
job,
})
}
async fn start(
&self,
ctx: &Arc<dyn ToolContext>,
script: &str,
kill_group_on_exit: bool,
) -> Result<(Running, ProcessGroupGuard, Option<Pipe>, Option<Pipe>)> {
#[cfg(windows)]
{
let (launcher, ws, script, call) =
(self.launcher.clone(), self.workspace.clone(), script.to_string(), ctx.clone());
let contained = tokio::task::spawn_blocking(move || {
launcher.spawn_contained(&ws, &script, &[], call.as_ref())
})
.await
.map_err(|error| {
DevToolError::Other(format!("the command could not be started: {error}"))
})?;
if let Some(contained) = contained {
let ContainedChild { job, process, stdin, stdout, stderr, .. } = contained?;
drop(stdin);
let pipe =
|file: std::fs::File| -> Pipe { Box::new(tokio::fs::File::from_std(file)) };
return Ok((
Running::Contained(process),
ProcessGroupGuard {
_launch: None,
job: Some(Arc::new(job)),
keep_on_exit: !kill_group_on_exit,
},
stdout.map(pipe),
stderr.map(pipe),
));
}
}
self.spawn_process(script, ctx.as_ref(), kill_group_on_exit)
}
}
#[async_trait]
impl Tool for BashTool {
fn name(&self) -> &str {
"bash"
}
fn description(&self) -> &str {
if self.workspace.kills_bash_group_on_exit() {
"Run a shell command in the workspace root and return stdout, stderr, and the \
exit code. Streams output incrementally for live UI display. Has a timeout. \
Standard input is empty, and background processes the command starts are \
stopped when it exits."
} else {
"Run a shell command in the workspace root and return stdout, stderr, and the \
exit code. Streams output incrementally for live UI display. Has a timeout. \
Standard input is empty."
}
}
fn parameters_schema(&self) -> Option<Value> {
Some(json!({
"type": "object",
"properties": {
"command": { "type": "string", "description": "The shell command to run." },
"timeout_secs": { "type": "integer", "description": "Optional timeout in seconds. Defaults to, and cannot exceed, the workspace limit." }
},
"required": ["command"]
}))
}
fn egress(&self, _args: &Value) -> adk_core::egress::ToolEgress {
self.launcher.egress()
}
async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
if !self.workspace.bash_allowed() {
return Err(DevToolError::BashDisabled.into());
}
let command = require_str(&args, "command")?;
let limit = self.workspace.bash_timeout_value();
let timeout = args
.get("timeout_secs")
.and_then(Value::as_u64)
.map_or(limit, |requested| Duration::from_secs(requested).min(limit));
let mut running = self.spawn(ctx.clone(), &command).await?;
match tokio::time::timeout(timeout, running.wait()).await {
Ok(Ok(exit_code)) => Ok(running.result(exit_code)),
Ok(Err(error)) => Err(error),
Err(_) => {
running.kill_and_wait().await;
ctx.emit_progress("stderr", &format!("\n[timeout after {}s]\n", timeout.as_secs()))
.await;
Err(DevToolError::Timeout(timeout).into())
}
}
}
}
pub struct RunningCommand {
command: String,
pid: Option<u32>,
output: Arc<Collector>,
kill: Arc<Notify>,
done: JoinHandle<std::io::Result<Option<i32>>>,
exit: Option<Option<i32>>,
started: Instant,
#[cfg(windows)]
job: Option<Arc<JobObject>>,
}
impl std::fmt::Debug for RunningCommand {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RunningCommand")
.field("command", &self.command)
.field("pid", &self.pid)
.field("exit", &self.exit)
.finish_non_exhaustive()
}
}
impl RunningCommand {
pub fn command(&self) -> &str {
&self.command
}
pub fn pid(&self) -> Option<u32> {
self.pid
}
pub fn elapsed(&self) -> Duration {
self.started.elapsed()
}
pub async fn wait(&mut self) -> Result<Option<i32>> {
if let Some(exit) = self.exit {
return Ok(exit);
}
let exit = match (&mut self.done).await {
Ok(Ok(exit)) => exit,
Ok(Err(error)) => return Err(DevToolError::from(error).into()),
Err(error) => {
return Err(DevToolError::Other(format!(
"the command's supervision ended unexpectedly: {error}"
))
.into());
}
};
self.exit = Some(exit);
Ok(exit)
}
pub fn is_finished(&self) -> bool {
self.exit.is_some() || self.done.is_finished()
}
pub fn kill(&self) {
self.kill.notify_one();
}
pub async fn kill_and_wait(&mut self) {
self.kill();
let _ = tokio::time::timeout(KILL_GRACE * 2, self.wait()).await;
}
pub fn output_bytes(&self) -> u64 {
self.output.total()
}
pub fn last_line(&self) -> Option<String> {
self.output.last_line()
}
pub fn keep_output(&self) -> std::io::Result<String> {
self.output.keep()
}
pub fn result(&self, exit_code: Option<i32>) -> Value {
let rendered = self.output.render();
let mut result = json!({
"command": self.command,
"exit_code": exit_code,
"stdout": rendered.stdout,
"stderr": rendered.stderr,
"truncated": rendered.truncated,
});
if let Some(id) = rendered.output_id {
result["output_id"] = Value::String(id);
}
result
}
}
impl Drop for RunningCommand {
fn drop(&mut self) {
if self.exit.is_none() {
self.kill.notify_one();
#[cfg(windows)]
if !self.done.is_finished()
&& let Some(job) = &self.job
{
note_termination(job.terminate_and_wait(JobObject::TERMINATION_WAIT));
}
}
}
}
async fn supervise(
mut child: Running,
mut group: ProcessGroupGuard,
kill_group_on_exit: bool,
pumps: Vec<JoinHandle<()>>,
kill: Arc<Notify>,
) -> std::io::Result<Option<i32>> {
let mut killed = false;
if kill_group_on_exit {
#[cfg(unix)]
let exited = wait_for_exit(child.id());
#[cfg(windows)]
let exited = async { child.wait().await.is_ok() };
#[cfg(not(any(unix, windows)))]
let exited = async { false };
tokio::select! {
shell_exited = exited => {
if shell_exited {
group.kill().await;
}
}
() = kill.notified() => killed = true,
}
}
let aborts: Vec<_> = pumps.iter().map(JoinHandle::abort_handle).collect();
let output_ended = async {
for pump in pumps {
let _ = pump.await;
}
};
tokio::pin!(output_ended);
if !killed {
tokio::select! {
() = &mut output_ended => {}
() = kill.notified() => killed = true,
}
}
if killed {
group.kill().await;
child.start_kill();
if tokio::time::timeout(KILL_GRACE, &mut output_ended).await.is_err() {
for abort in aborts {
abort.abort();
}
}
}
let exit_code = child.wait().await?;
group.disarm();
Ok(exit_code)
}
impl BashTool {
fn spawn_process(
&self,
script: &str,
ctx: &dyn ToolContext,
kill_group_on_exit: bool,
) -> Result<(Running, ProcessGroupGuard, Option<Pipe>, Option<Pipe>)> {
let (mut cmd, launch) = self.launcher.guarded_command(&self.workspace, script, ctx)?;
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
#[cfg(unix)]
{
unsafe {
cmd.pre_exec(|| {
if libc::setsid() == -1 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
}
#[cfg(windows)]
cmd.creation_flags(adk_sandbox::process_tree::CREATE_SUSPENDED);
let mut child = cmd.spawn().map_err(DevToolError::from)?;
#[cfg(unix)]
let group = ProcessGroupGuard { pid: child.id(), _launch: launch };
#[cfg(windows)]
let group = ProcessGroupGuard {
_launch: launch,
job: Some(Arc::new(contain(&child).map_err(|error| {
DevToolError::Other(format!(
"the command could not be placed in a Job Object, which stops the \
processes it starts, so it was not run: {error}"
))
})?)),
keep_on_exit: !kill_group_on_exit,
};
#[cfg(not(any(unix, windows)))]
let group = ProcessGroupGuard { _launch: launch };
#[cfg(not(windows))]
let _ = kill_group_on_exit;
let stdout = child.stdout.take().map(|pipe| Box::new(pipe) as Pipe);
let stderr = child.stderr.take().map(|pipe| Box::new(pipe) as Pipe);
Ok((Running::Spawned(Box::new(child)), group, stdout, stderr))
}
}
type Pipe = Box<dyn AsyncRead + Send + Unpin>;
enum Running {
Spawned(Box<tokio::process::Child>),
#[cfg(windows)]
Contained(ContainedProcess),
}
impl Running {
fn id(&self) -> Option<u32> {
match self {
Self::Spawned(child) => child.id(),
#[cfg(windows)]
Self::Contained(process) => Some(process.id()),
}
}
async fn wait(&mut self) -> std::io::Result<Option<i32>> {
match self {
Self::Spawned(child) => child.wait().await.map(|status| status.code()),
#[cfg(windows)]
Self::Contained(process) => process.wait().await.map(Some),
}
}
fn start_kill(&mut self) {
match self {
Self::Spawned(child) => {
let _ = child.start_kill();
}
#[cfg(windows)]
Self::Contained(_) => {}
}
}
}
struct ProcessGroupGuard {
_launch: Option<crate::LaunchGuard>,
#[cfg(unix)]
pid: Option<u32>,
#[cfg(windows)]
job: Option<Arc<JobObject>>,
#[cfg(windows)]
keep_on_exit: bool,
}
impl ProcessGroupGuard {
fn signal(&self) {
#[cfg(unix)]
if let Some(pid) = self.pid {
unsafe {
libc::killpg(pid as libc::pid_t, libc::SIGKILL);
}
}
}
async fn kill(&self) {
self.signal();
#[cfg(windows)]
if let Some(job) = &self.job {
note_termination(job.terminate_and_wait_async(JobObject::TERMINATION_WAIT).await);
}
}
fn disarm(&mut self) {
#[cfg(unix)]
{
self.pid = None;
}
#[cfg(windows)]
if let Some(job) = self.job.take()
&& self.keep_on_exit
&& let Err(error) = job.kill_on_close(false)
{
tracing::warn!(
error = %error,
"background processes of the bash command were not kept"
);
}
}
}
impl Drop for ProcessGroupGuard {
fn drop(&mut self) {
self.signal();
#[cfg(windows)]
if let Some(job) = &self.job {
note_termination(job.terminate_and_wait(JobObject::TERMINATION_WAIT));
}
}
}
#[cfg(windows)]
fn note_termination(result: std::io::Result<bool>) {
match result {
Ok(true) => {}
Ok(false) => tracing::warn!(
wait = ?JobObject::TERMINATION_WAIT,
"a process of the bash command had not exited when the call ended"
),
Err(error) => {
tracing::warn!(error = %error, "could not wait for the bash command's processes to exit")
}
}
}
#[cfg(windows)]
fn contain(child: &tokio::process::Child) -> std::io::Result<JobObject> {
let pid = child
.id()
.ok_or_else(|| std::io::Error::other("the command exited before it was started"))?;
JobObject::contain_suspended(pid)
}
#[cfg(unix)]
async fn wait_for_exit(pid: Option<u32>) -> bool {
let Some(pid) = pid else { return false };
let waited = tokio::task::spawn_blocking(move || {
loop {
let status = unsafe {
let mut info: libc::siginfo_t = std::mem::zeroed();
libc::waitid(
libc::P_PID,
pid as libc::id_t,
&mut info,
libc::WEXITED | libc::WNOWAIT,
)
};
if status == 0 {
return true;
}
if std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted {
return false;
}
}
})
.await;
waited.unwrap_or_else(|error| {
tracing::debug!(error = %error, "waiting for the bash command to exit failed");
false
})
}
async fn pump(mut pipe: Pipe, stream: Stream, output: Arc<Collector>, ctx: Arc<dyn ToolContext>) {
let mut chunk = [0u8; 8192];
let mut line = Vec::new();
loop {
let read = match pipe.read(&mut chunk).await {
Ok(0) | Err(_) => break,
Ok(read) => read,
};
output.push(stream, &chunk[..read]);
line.extend_from_slice(&chunk[..read]);
let end = match line.iter().rposition(|&byte| byte == b'\n') {
Some(newline) => newline + 1,
None if line.len() > PROGRESS_LINE_MAX => line.len(),
None => continue,
};
let rest = line.split_off(end);
ctx.emit_progress(stream.name(), &String::from_utf8_lossy(&line)).await;
line = rest;
}
if !line.is_empty() {
ctx.emit_progress(stream.name(), &String::from_utf8_lossy(&line)).await;
}
}