adk_devtools/tools/bash.rs
1//! `bash` — run a shell command inside the workspace.
2//!
3//! Executes host-local (`sh -c`) by default, with the working directory pinned to
4//! the workspace root and a timeout. A [`CommandLauncher`] can build the process
5//! instead, for example to run the script under an OS sandbox. Streams
6//! stdout/stderr incrementally via [`ToolContext::emit_progress`] for UI
7//! implementations that display live terminal output.
8//!
9//! The command runs with standard input at end of file, in a new session with no
10//! controlling terminal, and its process group is killed when the shell exits, on a
11//! timeout and when the call is cancelled. On Windows the command runs in a Job Object,
12//! and the job's processes are killed at the same points (spec 3.2 §10 W1).
13//!
14//! A result carries at most [`INLINE_OUTPUT_CHARS`](crate::INLINE_OUTPUT_CHARS) of output; an [`OutputStore`] keeps
15//! the whole of a longer one (spec 3.1 §7.33 fix 8). [`BashTool::spawn`] starts a command
16//! and returns a [`RunningCommand`] at once (spec 3.1 §10 D10).
17//!
18//! **Not** strongly isolated with the default [`HostLauncher`]; production
19//! deployments should run behind a sandboxing launcher or a containerized
20//! `CodeExecutor` (see the coding-agent design, §9).
21//! Mutating use requires [`Workspace::bash_allowed`].
22
23use std::process::Stdio;
24use std::sync::Arc;
25use std::time::{Duration, Instant};
26
27use adk_core::{Result, Tool, ToolContext};
28#[cfg(windows)]
29use adk_sandbox::process_tree::{ContainedChild, ContainedProcess, JobObject};
30use async_trait::async_trait;
31use serde_json::{Value, json};
32use tokio::io::{AsyncRead, AsyncReadExt};
33use tokio::sync::Notify;
34use tokio::task::JoinHandle;
35
36use crate::error::DevToolError;
37use crate::launcher::{CommandLauncher, HostLauncher};
38use crate::tools::output::{Collector, OutputStore, Stream};
39use crate::tools::read::require_str;
40use crate::workspace::Workspace;
41
42/// How long a killed command's output is still read: a process that left the group can
43/// hold a pipe open, and its output is not waited for.
44const KILL_GRACE: Duration = Duration::from_secs(1);
45
46/// The longest partial line held back from progress before it is forwarded anyway.
47const PROGRESS_LINE_MAX: usize = 8192;
48
49/// Runs a shell command in the workspace root with a timeout.
50///
51/// Streams stdout and stderr line-by-line via [`ToolContext::emit_progress`]
52/// so UI layers can display live terminal output. The result carries at most
53/// [`INLINE_OUTPUT_CHARS`](crate::INLINE_OUTPUT_CHARS) of output, stdout and stderr together: a longer stream keeps
54/// its first third and last two thirds of its share around a marker naming the bytes left
55/// out (spec 3.1 §7.33 fix 8). With an [`OutputStore`]
56/// ([`with_output_store`](Self::with_output_store)) the whole output, up to
57/// [`Workspace::max_output`] bytes, goes to a file the marker and the result's `output_id`
58/// name. Memory stays bounded either way.
59///
60/// The command reads end of file from standard input and starts in a new session,
61/// so it has no controlling terminal and leads its own process group. When the
62/// shell exits, the rest of the group — anything it started in the background —
63/// is killed, unless [`Workspace::bash_kill_group_on_exit`] turns that off. A
64/// timeout or a cancelled call (dropping its future) kills the whole group too.
65/// A process that starts its own session or group escapes the kill.
66///
67/// On Windows the command starts suspended and runs only once it is in a Job Object, so
68/// every process it starts belongs to the job and none can leave it. The job's processes
69/// are killed where Unix kills the group, and when the agent process exits during the
70/// call (spec 3.2 §10 W1).
71///
72/// The process comes from a [`CommandLauncher`]: [`HostLauncher`] by default,
73/// another one through [`with_launcher`](Self::with_launcher).
74pub struct BashTool {
75 workspace: Workspace,
76 launcher: Arc<dyn CommandLauncher>,
77 output_store: Option<Arc<dyn OutputStore>>,
78}
79
80impl BashTool {
81 /// Create a `bash` tool bound to `workspace`, running commands with [`HostLauncher`].
82 pub fn new(workspace: Workspace) -> Self {
83 Self { workspace, launcher: Arc::new(HostLauncher), output_store: None }
84 }
85
86 /// Build each command with `launcher` instead of [`HostLauncher`].
87 ///
88 /// The timeout ceiling, output cap, streaming, standard input, session and
89 /// process-group kill stay with the tool. Implements spec 3.1 §10 D1.
90 ///
91 /// # Example
92 ///
93 /// ```rust
94 /// use std::sync::Arc;
95 ///
96 /// use adk_devtools::{BashTool, HostLauncher, Workspace};
97 ///
98 /// let workspace = Workspace::new("./my-repo").allow_bash(true);
99 /// let bash = BashTool::new(workspace).with_launcher(Arc::new(HostLauncher));
100 /// # let _ = bash;
101 /// ```
102 #[must_use]
103 pub fn with_launcher(mut self, launcher: Arc<dyn CommandLauncher>) -> Self {
104 self.launcher = launcher;
105 self
106 }
107
108 /// Keep the whole output of a command whose result is cut in a file from `store`,
109 /// named by the result's `output_id` (spec 3.1 §7.33 fix 8). The file holds at most
110 /// [`Workspace::max_output`] bytes.
111 ///
112 /// # Example
113 ///
114 /// ```rust
115 /// use std::sync::Arc;
116 ///
117 /// use adk_core::ToolContext;
118 /// use adk_devtools::{BashTool, OutputFile, OutputStore, Workspace};
119 ///
120 /// struct Temp;
121 ///
122 /// impl OutputStore for Temp {
123 /// fn create(&self, ctx: &dyn ToolContext, _command: &str) -> std::io::Result<OutputFile> {
124 /// let id = ctx.function_call_id().to_string();
125 /// let path = std::env::temp_dir().join(format!("{id}.log"));
126 /// let file = std::fs::File::create(&path)?;
127 /// Ok(OutputFile { id, path, file })
128 /// }
129 /// }
130 ///
131 /// let bash = BashTool::new(Workspace::new(".").allow_bash(true))
132 /// .with_output_store(Arc::new(Temp));
133 /// # let _ = bash;
134 /// ```
135 #[must_use]
136 pub fn with_output_store(mut self, store: Arc<dyn OutputStore>) -> Self {
137 self.output_store = Some(store);
138 self
139 }
140
141 /// Starts `command` and returns at once (spec 3.1 §10 D10).
142 ///
143 /// The command runs as [`execute`](Tool::execute) runs it — the same launcher,
144 /// environment, standard input, session and process group — with no timeout: the
145 /// caller decides when to [`kill`](RunningCommand::kill) it. Its output streams
146 /// through `ctx` while `ctx` listens and is kept as `execute` keeps it;
147 /// [`RunningCommand::keep_output`] sends all of it to a file. Dropping the
148 /// [`RunningCommand`] kills the command's processes.
149 ///
150 /// # Errors
151 ///
152 /// Returns `BashDisabled` when the workspace does not allow `bash`, or the error that
153 /// kept the command from starting.
154 ///
155 /// # Example
156 ///
157 /// ```rust,ignore
158 /// let mut running = bash.spawn(ctx, "cargo build").await?;
159 /// let exit_code = running.wait().await?;
160 /// let result = running.result(exit_code);
161 /// ```
162 pub async fn spawn(&self, ctx: Arc<dyn ToolContext>, command: &str) -> Result<RunningCommand> {
163 if !self.workspace.bash_allowed() {
164 return Err(DevToolError::BashDisabled.into());
165 }
166 let kill_group_on_exit = self.workspace.kills_bash_group_on_exit();
167 let (child, group, stdout, stderr) = self.start(&ctx, command, kill_group_on_exit).await?;
168 let pid = child.id();
169 tracing::debug!(
170 bash.isolation = self.launcher.isolation(),
171 process.pid = pid,
172 "started bash command"
173 );
174 let output = Arc::new(Collector::new(
175 self.output_store.clone(),
176 ctx.clone(),
177 command,
178 self.workspace.max_output(),
179 ));
180 let pumps = [(stdout, Stream::Stdout), (stderr, Stream::Stderr)]
181 .into_iter()
182 .filter_map(|(pipe, stream)| {
183 pipe.map(|pipe| tokio::spawn(pump(pipe, stream, output.clone(), ctx.clone())))
184 })
185 .collect();
186 let kill = Arc::new(Notify::new());
187 #[cfg(windows)]
188 let job = group.job.clone();
189 let done = tokio::spawn(supervise(child, group, kill_group_on_exit, pumps, kill.clone()));
190 Ok(RunningCommand {
191 command: command.to_string(),
192 pid,
193 output,
194 kill,
195 done,
196 exit: None,
197 started: Instant::now(),
198 #[cfg(windows)]
199 job,
200 })
201 }
202
203 /// Starts the process for `script`: the launcher's own on Windows when it contains one
204 /// (spec 3.2 §10 W5), else the one [`spawn_process`](Self::spawn_process) builds.
205 async fn start(
206 &self,
207 ctx: &Arc<dyn ToolContext>,
208 script: &str,
209 kill_group_on_exit: bool,
210 ) -> Result<(Running, ProcessGroupGuard, Option<Pipe>, Option<Pipe>)> {
211 // A launcher may start a confined process itself (spec 3.2 §10 W5); starting one
212 // can take long, so it runs on the blocking pool.
213 #[cfg(windows)]
214 {
215 let (launcher, ws, script, call) =
216 (self.launcher.clone(), self.workspace.clone(), script.to_string(), ctx.clone());
217 let contained = tokio::task::spawn_blocking(move || {
218 launcher.spawn_contained(&ws, &script, &[], call.as_ref())
219 })
220 .await
221 .map_err(|error| {
222 DevToolError::Other(format!("the command could not be started: {error}"))
223 })?;
224 if let Some(contained) = contained {
225 let ContainedChild { job, process, stdin, stdout, stderr, .. } = contained?;
226 // Standard input reads end of file, as `Stdio::null()` gives a spawned one.
227 drop(stdin);
228 let pipe =
229 |file: std::fs::File| -> Pipe { Box::new(tokio::fs::File::from_std(file)) };
230 return Ok((
231 Running::Contained(process),
232 ProcessGroupGuard {
233 _launch: None,
234 job: Some(Arc::new(job)),
235 keep_on_exit: !kill_group_on_exit,
236 },
237 stdout.map(pipe),
238 stderr.map(pipe),
239 ));
240 }
241 }
242 self.spawn_process(script, ctx.as_ref(), kill_group_on_exit)
243 }
244}
245
246#[async_trait]
247impl Tool for BashTool {
248 fn name(&self) -> &str {
249 "bash"
250 }
251
252 fn description(&self) -> &str {
253 if self.workspace.kills_bash_group_on_exit() {
254 "Run a shell command in the workspace root and return stdout, stderr, and the \
255 exit code. Streams output incrementally for live UI display. Has a timeout. \
256 Standard input is empty, and background processes the command starts are \
257 stopped when it exits."
258 } else {
259 "Run a shell command in the workspace root and return stdout, stderr, and the \
260 exit code. Streams output incrementally for live UI display. Has a timeout. \
261 Standard input is empty."
262 }
263 }
264
265 fn parameters_schema(&self) -> Option<Value> {
266 Some(json!({
267 "type": "object",
268 "properties": {
269 "command": { "type": "string", "description": "The shell command to run." },
270 "timeout_secs": { "type": "integer", "description": "Optional timeout in seconds. Defaults to, and cannot exceed, the workspace limit." }
271 },
272 "required": ["command"]
273 }))
274 }
275
276 /// What the launcher's commands reach on the network ([`CommandLauncher::egress`]).
277 fn egress(&self, _args: &Value) -> adk_core::egress::ToolEgress {
278 self.launcher.egress()
279 }
280
281 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
282 if !self.workspace.bash_allowed() {
283 return Err(DevToolError::BashDisabled.into());
284 }
285 let command = require_str(&args, "command")?;
286 // The operator's timeout is a ceiling: a model may ask for less time, never more.
287 let limit = self.workspace.bash_timeout_value();
288 let timeout = args
289 .get("timeout_secs")
290 .and_then(Value::as_u64)
291 .map_or(limit, |requested| Duration::from_secs(requested).min(limit));
292
293 let mut running = self.spawn(ctx.clone(), &command).await?;
294 match tokio::time::timeout(timeout, running.wait()).await {
295 Ok(Ok(exit_code)) => Ok(running.result(exit_code)),
296 Ok(Err(error)) => Err(error),
297 Err(_) => {
298 running.kill_and_wait().await;
299 ctx.emit_progress("stderr", &format!("\n[timeout after {}s]\n", timeout.as_secs()))
300 .await;
301 Err(DevToolError::Timeout(timeout).into())
302 }
303 }
304 }
305}
306
307/// A command [`BashTool::spawn`] started (spec 3.1 §10 D10).
308///
309/// [`wait`](Self::wait) for it to exit, then read its [`result`](Self::result); or
310/// [`kill`](Self::kill) it. Dropping it kills the command's processes, so a caller that
311/// keeps a command running — a background shell — keeps this value.
312pub struct RunningCommand {
313 command: String,
314 pid: Option<u32>,
315 output: Arc<Collector>,
316 kill: Arc<Notify>,
317 done: JoinHandle<std::io::Result<Option<i32>>>,
318 /// The exit code once [`wait`](Self::wait) has seen it.
319 exit: Option<Option<i32>>,
320 started: Instant,
321 /// The command's Job Object, shared with its supervising task.
322 #[cfg(windows)]
323 job: Option<Arc<JobObject>>,
324}
325
326impl std::fmt::Debug for RunningCommand {
327 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
328 f.debug_struct("RunningCommand")
329 .field("command", &self.command)
330 .field("pid", &self.pid)
331 .field("exit", &self.exit)
332 .finish_non_exhaustive()
333 }
334}
335
336impl RunningCommand {
337 /// The command as it was started.
338 pub fn command(&self) -> &str {
339 &self.command
340 }
341
342 /// The process id of the shell, which leads the command's process group on Unix; `None`
343 /// when the platform gave none.
344 pub fn pid(&self) -> Option<u32> {
345 self.pid
346 }
347
348 /// How long the command has run.
349 pub fn elapsed(&self) -> Duration {
350 self.started.elapsed()
351 }
352
353 /// Waits for the command to exit and its output to end; its exit code, `None` when a
354 /// signal ended it. Cancel-safe: a `wait` dropped before it returns can be called again.
355 ///
356 /// # Errors
357 ///
358 /// Returns the error from waiting on the process.
359 pub async fn wait(&mut self) -> Result<Option<i32>> {
360 if let Some(exit) = self.exit {
361 return Ok(exit);
362 }
363 let exit = match (&mut self.done).await {
364 Ok(Ok(exit)) => exit,
365 Ok(Err(error)) => return Err(DevToolError::from(error).into()),
366 Err(error) => {
367 return Err(DevToolError::Other(format!(
368 "the command's supervision ended unexpectedly: {error}"
369 ))
370 .into());
371 }
372 };
373 self.exit = Some(exit);
374 Ok(exit)
375 }
376
377 /// Whether the command has exited and been waited for.
378 pub fn is_finished(&self) -> bool {
379 self.exit.is_some() || self.done.is_finished()
380 }
381
382 /// Kills the command's processes; [`wait`](Self::wait) returns soon after.
383 pub fn kill(&self) {
384 self.kill.notify_one();
385 }
386
387 /// Kills the command's processes and waits, briefly, for them to be reaped.
388 pub async fn kill_and_wait(&mut self) {
389 self.kill();
390 let _ = tokio::time::timeout(KILL_GRACE * 2, self.wait()).await;
391 }
392
393 /// Bytes the command has written to stdout and stderr so far.
394 pub fn output_bytes(&self) -> u64 {
395 self.output.total()
396 }
397
398 /// The last line the command has written, at most 200 characters.
399 pub fn last_line(&self) -> Option<String> {
400 self.output.last_line()
401 }
402
403 /// Sends the command's output to a file from the output store, from its first byte and
404 /// whatever the result needs, and returns the file's id.
405 ///
406 /// # Errors
407 ///
408 /// Returns an error when the tool has no output store or the store cannot create the
409 /// file.
410 pub fn keep_output(&self) -> std::io::Result<String> {
411 self.output.keep()
412 }
413
414 /// The result of the call: `{ command, exit_code, stdout, stderr, truncated }`, plus
415 /// `output_id` when the output was cut and an output store keeps the whole of it.
416 pub fn result(&self, exit_code: Option<i32>) -> Value {
417 let rendered = self.output.render();
418 let mut result = json!({
419 "command": self.command,
420 "exit_code": exit_code,
421 "stdout": rendered.stdout,
422 "stderr": rendered.stderr,
423 "truncated": rendered.truncated,
424 });
425 if let Some(id) = rendered.output_id {
426 result["output_id"] = Value::String(id);
427 }
428 result
429 }
430}
431
432impl Drop for RunningCommand {
433 fn drop(&mut self) {
434 if self.exit.is_none() {
435 self.kill.notify_one();
436 // The supervising task may not run again before the caller blocks or the
437 // runtime stops, so a dropped call ends its job here, waiting as the guard does.
438 #[cfg(windows)]
439 if !self.done.is_finished()
440 && let Some(job) = &self.job
441 {
442 note_termination(job.terminate_and_wait(JobObject::TERMINATION_WAIT));
443 }
444 }
445 }
446}
447
448/// Supervises one command: kills the rest of its group once the shell exits, waits for
449/// its output to end, and reaps it; or kills it on request. Returns the exit code.
450async fn supervise(
451 mut child: Running,
452 mut group: ProcessGroupGuard,
453 kill_group_on_exit: bool,
454 pumps: Vec<JoinHandle<()>>,
455 kill: Arc<Notify>,
456) -> std::io::Result<Option<i32>> {
457 let mut killed = false;
458 if kill_group_on_exit {
459 // The shell has exited but is not reaped, so its pid, which is the group id,
460 // cannot be reused while the rest of the group is killed. That also closes the
461 // output pipes a background process holds open.
462 #[cfg(unix)]
463 let exited = wait_for_exit(child.id());
464 // The job, not the pid, names the processes, so the shell can be reaped.
465 #[cfg(windows)]
466 let exited = async { child.wait().await.is_ok() };
467 #[cfg(not(any(unix, windows)))]
468 let exited = async { false };
469 tokio::select! {
470 shell_exited = exited => {
471 if shell_exited {
472 group.kill().await;
473 }
474 }
475 () = kill.notified() => killed = true,
476 }
477 }
478 let aborts: Vec<_> = pumps.iter().map(JoinHandle::abort_handle).collect();
479 let output_ended = async {
480 for pump in pumps {
481 let _ = pump.await;
482 }
483 };
484 tokio::pin!(output_ended);
485 if !killed {
486 tokio::select! {
487 () = &mut output_ended => {}
488 () = kill.notified() => killed = true,
489 }
490 }
491 if killed {
492 group.kill().await;
493 // Also signal the child directly, which is all that is available elsewhere.
494 child.start_kill();
495 if tokio::time::timeout(KILL_GRACE, &mut output_ended).await.is_err() {
496 for abort in aborts {
497 abort.abort();
498 }
499 }
500 }
501 let exit_code = child.wait().await?;
502 // The child is reaped, so its pid may be reused and must not be signalled.
503 group.disarm();
504 Ok(exit_code)
505}
506
507impl BashTool {
508 /// Spawns the launcher's command for `script`: standard input at end of file, output
509 /// piped, in a new session on Unix and in a Job Object on Windows.
510 fn spawn_process(
511 &self,
512 script: &str,
513 ctx: &dyn ToolContext,
514 kill_group_on_exit: bool,
515 ) -> Result<(Running, ProcessGroupGuard, Option<Pipe>, Option<Pipe>)> {
516 let (mut cmd, launch) = self.launcher.guarded_command(&self.workspace, script, ctx)?;
517 cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
518
519 // A new session detaches the command from any controlling terminal, so it cannot
520 // read from or inject input into the agent's terminal, and makes it the leader of
521 // its own process group, so a timeout, a cancelled call or the shell's exit can
522 // terminate its descendants.
523 #[cfg(unix)]
524 {
525 // SAFETY: the closure runs in the forked child before `exec` and calls only
526 // `setsid`, which is async-signal-safe and touches no memory of the parent.
527 unsafe {
528 cmd.pre_exec(|| {
529 if libc::setsid() == -1 {
530 return Err(std::io::Error::last_os_error());
531 }
532 Ok(())
533 });
534 }
535 }
536
537 // The command runs only once it is in the job, so nothing it starts is outside it.
538 #[cfg(windows)]
539 cmd.creation_flags(adk_sandbox::process_tree::CREATE_SUSPENDED);
540
541 let mut child = cmd.spawn().map_err(DevToolError::from)?;
542 #[cfg(unix)]
543 let group = ProcessGroupGuard { pid: child.id(), _launch: launch };
544 // On failure the suspended child is dropped, and `kill_on_drop` ends it.
545 #[cfg(windows)]
546 let group = ProcessGroupGuard {
547 _launch: launch,
548 job: Some(Arc::new(contain(&child).map_err(|error| {
549 DevToolError::Other(format!(
550 "the command could not be placed in a Job Object, which stops the \
551 processes it starts, so it was not run: {error}"
552 ))
553 })?)),
554 keep_on_exit: !kill_group_on_exit,
555 };
556 #[cfg(not(any(unix, windows)))]
557 let group = ProcessGroupGuard { _launch: launch };
558 // Only a Windows job is told whether to keep background processes.
559 #[cfg(not(windows))]
560 let _ = kill_group_on_exit;
561 let stdout = child.stdout.take().map(|pipe| Box::new(pipe) as Pipe);
562 let stderr = child.stderr.take().map(|pipe| Box::new(pipe) as Pipe);
563 Ok((Running::Spawned(Box::new(child)), group, stdout, stderr))
564 }
565}
566
567/// One end of a command's output.
568type Pipe = Box<dyn AsyncRead + Send + Unpin>;
569
570/// The process a call runs: the one `BashTool` spawned, or on Windows one its launcher
571/// started in a Job Object (spec 3.2 §10 W5).
572enum Running {
573 Spawned(Box<tokio::process::Child>),
574 #[cfg(windows)]
575 Contained(ContainedProcess),
576}
577
578impl Running {
579 fn id(&self) -> Option<u32> {
580 match self {
581 Self::Spawned(child) => child.id(),
582 #[cfg(windows)]
583 Self::Contained(process) => Some(process.id()),
584 }
585 }
586
587 /// Waits for the process to exit; its exit code when it has one.
588 async fn wait(&mut self) -> std::io::Result<Option<i32>> {
589 match self {
590 Self::Spawned(child) => child.wait().await.map(|status| status.code()),
591 #[cfg(windows)]
592 Self::Contained(process) => process.wait().await.map(Some),
593 }
594 }
595
596 /// Signals a spawned process directly; a contained one ends with its job.
597 fn start_kill(&mut self) {
598 match self {
599 Self::Spawned(child) => {
600 let _ = child.start_kill();
601 }
602 #[cfg(windows)]
603 Self::Contained(_) => {}
604 }
605 }
606}
607
608/// Kills the command's whole process group, including when dropped.
609///
610/// The child leads its own session and process group, so signalling the group
611/// reaches grandchildren too. `kill_on_drop` reaches only the direct child, which
612/// left descendants — a spawned server, a background build — running after a timeout
613/// or a cancelled call. The guard is disarmed once the child is reaped, because its
614/// pid may then be reused.
615///
616/// On Windows the guard holds the command's Job Object instead, which also kills its
617/// processes when the agent process exits, since the job closes with it (spec 3.2 §10
618/// W1).
619struct ProcessGroupGuard {
620 /// What the launcher keeps alive until the process ends ([`CommandLauncher::guarded_command`]).
621 _launch: Option<crate::LaunchGuard>,
622 #[cfg(unix)]
623 pid: Option<u32>,
624 #[cfg(windows)]
625 job: Option<Arc<JobObject>>,
626 /// Whether the job's processes keep running once the call ends normally.
627 #[cfg(windows)]
628 keep_on_exit: bool,
629}
630
631impl ProcessGroupGuard {
632 /// Signals the Unix process group; a Windows job is ended by `kill` or the drop.
633 fn signal(&self) {
634 #[cfg(unix)]
635 if let Some(pid) = self.pid {
636 // SAFETY: `killpg` takes a process-group id and a signal, and cannot violate
637 // memory safety. A failure means the group already exited.
638 unsafe {
639 libc::killpg(pid as libc::pid_t, libc::SIGKILL);
640 }
641 }
642 }
643
644 /// Kills the command's processes. On Windows it returns once the job's processes have
645 /// exited, for at most `JobObject::TERMINATION_WAIT`, since a process the job ended can
646 /// still complete a write it had in flight.
647 async fn kill(&self) {
648 self.signal();
649 #[cfg(windows)]
650 if let Some(job) = &self.job {
651 note_termination(job.terminate_and_wait_async(JobObject::TERMINATION_WAIT).await);
652 }
653 }
654
655 fn disarm(&mut self) {
656 #[cfg(unix)]
657 {
658 self.pid = None;
659 }
660 // The guard's handle closes here; the job's last one kills what is left in it
661 // unless the workspace keeps background processes.
662 #[cfg(windows)]
663 if let Some(job) = self.job.take()
664 && self.keep_on_exit
665 && let Err(error) = job.kill_on_close(false)
666 {
667 tracing::warn!(
668 error = %error,
669 "background processes of the bash command were not kept"
670 );
671 }
672 }
673}
674
675impl Drop for ProcessGroupGuard {
676 fn drop(&mut self) {
677 self.signal();
678 // A dropped call, such as a cancelled run's, waits briefly for its processes too.
679 #[cfg(windows)]
680 if let Some(job) = &self.job {
681 note_termination(job.terminate_and_wait(JobObject::TERMINATION_WAIT));
682 }
683 }
684}
685
686/// Logs a job whose processes had not all exited when the wait ended.
687#[cfg(windows)]
688fn note_termination(result: std::io::Result<bool>) {
689 match result {
690 Ok(true) => {}
691 Ok(false) => tracing::warn!(
692 wait = ?JobObject::TERMINATION_WAIT,
693 "a process of the bash command had not exited when the call ended"
694 ),
695 Err(error) => {
696 tracing::warn!(error = %error, "could not wait for the bash command's processes to exit")
697 }
698 }
699}
700
701/// Places the suspended `child` in a Job Object, then lets it run (spec 3.2 §10 W1).
702#[cfg(windows)]
703fn contain(child: &tokio::process::Child) -> std::io::Result<JobObject> {
704 let pid = child
705 .id()
706 .ok_or_else(|| std::io::Error::other("the command exited before it was started"))?;
707 JobObject::contain_suspended(pid)
708}
709
710/// Waits until the child `pid` has exited, without reaping it.
711///
712/// Returns `true` once the child is a zombie: `waitid` with `WNOWAIT` leaves it
713/// unreaped, so its pid stays reserved until `Child::wait` reaps it. The wait blocks,
714/// so it runs on the blocking pool.
715#[cfg(unix)]
716async fn wait_for_exit(pid: Option<u32>) -> bool {
717 let Some(pid) = pid else { return false };
718 let waited = tokio::task::spawn_blocking(move || {
719 loop {
720 // SAFETY: `info` is a zeroed, writable `siginfo_t` that outlives the call,
721 // and `waitid` writes only into it.
722 let status = unsafe {
723 let mut info: libc::siginfo_t = std::mem::zeroed();
724 libc::waitid(
725 libc::P_PID,
726 pid as libc::id_t,
727 &mut info,
728 libc::WEXITED | libc::WNOWAIT,
729 )
730 };
731 if status == 0 {
732 return true;
733 }
734 if std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted {
735 return false;
736 }
737 }
738 })
739 .await;
740 waited.unwrap_or_else(|error| {
741 tracing::debug!(error = %error, "waiting for the bash command to exit failed");
742 false
743 })
744}
745
746/// Reads one output stream to its end into `output`, forwarding complete lines as
747/// progress through `ctx` (spec 3.1 §10 D10).
748///
749/// Every byte is read, so a writer never blocks on a full pipe; `output` keeps the start
750/// and end in memory and the rest in its file, if any.
751async fn pump(mut pipe: Pipe, stream: Stream, output: Arc<Collector>, ctx: Arc<dyn ToolContext>) {
752 let mut chunk = [0u8; 8192];
753 // Output read but not yet forwarded: the partial line after the last newline.
754 let mut line = Vec::new();
755 loop {
756 let read = match pipe.read(&mut chunk).await {
757 Ok(0) | Err(_) => break,
758 Ok(read) => read,
759 };
760 output.push(stream, &chunk[..read]);
761 line.extend_from_slice(&chunk[..read]);
762 let end = match line.iter().rposition(|&byte| byte == b'\n') {
763 Some(newline) => newline + 1,
764 None if line.len() > PROGRESS_LINE_MAX => line.len(),
765 None => continue,
766 };
767 let rest = line.split_off(end);
768 ctx.emit_progress(stream.name(), &String::from_utf8_lossy(&line)).await;
769 line = rest;
770 }
771 if !line.is_empty() {
772 ctx.emit_progress(stream.name(), &String::from_utf8_lossy(&line)).await;
773 }
774}