Skip to main content

agent_commander/
executor.rs

1//! Execute commands while continuously draining both process pipes.
2use std::{
3    io,
4    process::{ExitStatus, Stdio},
5    sync::{Arc, Mutex},
6    time::Duration,
7};
8use tokio::{
9    io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
10    process::{Child, ChildStdin, Command},
11    task::JoinHandle,
12    time::Instant,
13};
14
15/// Time a process group may keep running after `terminate` before `SIGKILL`.
16pub const DEFAULT_KILL_AFTER: Duration = Duration::from_secs(5);
17/// Time the pipes may stay open after the wrapper shell exited.
18///
19/// A grandchild that inherited stdout (`(sleep 600 &)`) otherwise holds
20/// `wait_for_exit` open forever (hive-mind#3015).
21pub const DEFAULT_PIPE_DRAIN: Duration = Duration::from_secs(5);
22
23/// Command execution result.
24#[derive(Debug, Clone, Default)]
25pub struct ExecutionResult {
26    pub exit_code: i32,
27    /// Signal that ended the process (`SIGKILL`), also inferred from 128 + N
28    pub signal: Option<String>,
29    pub stdout: String,
30    pub stderr: String,
31    pub command: String,
32}
33
34const SIGNALS: &[(i32, &str)] = &[
35    (1, "SIGHUP"),
36    (2, "SIGINT"),
37    (3, "SIGQUIT"),
38    (4, "SIGILL"),
39    (5, "SIGTRAP"),
40    (6, "SIGABRT"),
41    (8, "SIGFPE"),
42    (9, "SIGKILL"),
43    (11, "SIGSEGV"),
44    (13, "SIGPIPE"),
45    (14, "SIGALRM"),
46    (15, "SIGTERM"),
47    #[cfg(target_os = "linux")]
48    (7, "SIGBUS"),
49    #[cfg(target_os = "linux")]
50    (10, "SIGUSR1"),
51    #[cfg(target_os = "linux")]
52    (12, "SIGUSR2"),
53];
54
55/// Name of a signal number (`9` is `SIGKILL`).
56pub fn signal_name(number: i32) -> Option<&'static str> {
57    SIGNALS
58        .iter()
59        .find(|(value, _)| *value == number)
60        .map(|(_, name)| *name)
61}
62
63/// Signal named by a shell exit code of 128 + N (`137` is `SIGKILL`).
64pub fn signal_from_exit_code(exit_code: i32) -> Option<&'static str> {
65    if exit_code > 128 {
66        signal_name(exit_code - 128)
67    } else {
68        None
69    }
70}
71
72/// Exit code and signal of a status; a signal becomes 128 + N.
73pub fn normalize_exit(status: ExitStatus) -> (i32, Option<&'static str>) {
74    #[cfg(unix)]
75    {
76        use std::os::unix::process::ExitStatusExt;
77        if let Some(number) = status.signal() {
78            return (128 + number, signal_name(number));
79        }
80    }
81    let code = status.code().unwrap_or(1);
82    (code, signal_from_exit_code(code))
83}
84
85type Buffer = Arc<Mutex<Vec<u8>>>;
86type Reader = JoinHandle<io::Result<()>>;
87
88/// Join pipe readers until `deadline`; returns whether all finished. A
89/// finished reader is taken out, so it is never polled again.
90async fn join_readers(
91    readers: &mut [Option<Reader>],
92    deadline: Option<Instant>,
93) -> io::Result<bool> {
94    for slot in readers.iter_mut() {
95        let Some(reader) = slot.as_mut() else {
96            continue;
97        };
98        let joined = match deadline {
99            None => reader.await,
100            Some(deadline) => match tokio::time::timeout_at(deadline, reader).await {
101                Ok(joined) => joined,
102                Err(_) => return Ok(false),
103            },
104        };
105        *slot = None;
106        joined.map_err(io::Error::other)??;
107    }
108    Ok(true)
109}
110
111fn read_buffer(buffer: &Buffer) -> String {
112    let bytes = buffer.lock().unwrap_or_else(|e| e.into_inner());
113    String::from_utf8_lossy(&bytes).into_owned()
114}
115
116async fn drain<R: AsyncRead + Unpin>(
117    mut pipe: R,
118    buffer: Buffer,
119    attached: bool,
120    stderr: bool,
121) -> io::Result<()> {
122    let mut chunk = [0; 8192];
123    loop {
124        let count = pipe.read(&mut chunk).await?;
125        if count == 0 {
126            break;
127        }
128        buffer
129            .lock()
130            .unwrap_or_else(|e| e.into_inner())
131            .extend_from_slice(&chunk[..count]);
132        if attached {
133            if stderr {
134                tokio::io::stderr().write_all(&chunk[..count]).await?;
135            } else {
136                tokio::io::stdout().write_all(&chunk[..count]).await?;
137            }
138        }
139    }
140    Ok(())
141}
142
143/// Run `kill -<signal> -- -<pgid>`; `0` checks whether the group exists.
144#[cfg(unix)]
145async fn kill_group(pgid: u32, signal: &str) -> io::Result<std::process::Output> {
146    // bash's kill builtin is available wherever our executor is supported.
147    let signal = signal.trim_start_matches("SIG");
148    Command::new("bash")
149        .arg("-c")
150        .arg(format!("kill -{signal} -- -{pgid}"))
151        .stdin(Stdio::null())
152        .output()
153        .await
154}
155
156/// Whether any process in the group led by `pgid` is alive.
157///
158/// The wrapper shell can exit while the agent it started still runs in the
159/// same group (hive-mind#3015). A group the caller may not signal is alive.
160pub async fn is_process_group_alive(pgid: u32) -> bool {
161    #[cfg(unix)]
162    {
163        match kill_group(pgid, "0").await {
164            Ok(output) if output.status.success() => true,
165            Ok(output) => String::from_utf8_lossy(&output.stderr)
166                .to_lowercase()
167                .contains("not permitted"),
168            Err(_) => false,
169        }
170    }
171    #[cfg(not(unix))]
172    {
173        let _ = pgid;
174        false
175    }
176}
177
178/// Execute a command, or return the command without spawning in dry-run mode.
179pub async fn execute_command(
180    command: &str,
181    dry_run: bool,
182    attached: bool,
183) -> io::Result<ExecutionResult> {
184    if dry_run {
185        println!("Dry run - command that would be executed:\n{}", command);
186        return Ok(ExecutionResult {
187            command: command.into(),
188            ..Default::default()
189        });
190    }
191    let mut handle = start_command(command, attached).await?;
192    let exit_code = handle.wait_for_exit().await?;
193    let (stdout, stderr, _) = handle.get_output();
194    Ok(ExecutionResult {
195        exit_code,
196        signal: handle.signal().map(String::from),
197        stdout: stdout.into(),
198        stderr: stderr.into(),
199        command: command.into(),
200    })
201}
202
203/// Non-blocking process handle. Pipe readers run immediately after spawning.
204pub struct ProcessHandle {
205    pub command: String,
206    child: Child,
207    pid: Option<u32>,
208    readers: Option<(Reader, Reader)>,
209    stdout_buffer: Buffer,
210    stderr_buffer: Buffer,
211    pipe_drain: Option<Duration>,
212    stdout: String,
213    stderr: String,
214    exit_code: Option<i32>,
215    signal: Option<&'static str>,
216    stdin: Option<ChildStdin>,
217}
218impl ProcessHandle {
219    /// Bound the wait for open pipes after the wrapper exits; `None` waits
220    /// until every holder closes them.
221    #[must_use]
222    pub const fn with_pipe_drain(mut self, pipe_drain: Option<Duration>) -> Self {
223        self.pipe_drain = pipe_drain;
224        self
225    }
226
227    /// Process id of the wrapper shell, which also leads the process group.
228    pub const fn pid(&self) -> Option<u32> {
229        self.pid
230    }
231
232    /// Wait for process completion and all output, preserving exact bytes as UTF-8.
233    ///
234    /// Ends a piped stdin first: nothing can write while this borrows the
235    /// handle, and a tool reading stdin would otherwise never exit.
236    pub async fn wait_for_exit(&mut self) -> io::Result<i32> {
237        if let Some(code) = self.exit_code {
238            return Ok(code);
239        }
240        self.end_stdin();
241        let status = self.child.wait().await?;
242        if let Some((stdout, stderr)) = self.readers.take() {
243            let mut readers = [Some(stdout), Some(stderr)];
244            let deadline = self.pipe_drain.map(|limit| Instant::now() + limit);
245            if !join_readers(&mut readers, deadline).await? {
246                // A grandchild still holds the pipes: stop the group, then
247                // keep what was read.
248                #[cfg(unix)]
249                if let Some(pid) = self.pid {
250                    if is_process_group_alive(pid).await {
251                        let _ = kill_group(pid, "KILL").await;
252                    }
253                }
254                let grace = Some(Instant::now() + Duration::from_millis(500));
255                if !join_readers(&mut readers, grace).await? {
256                    for reader in readers.iter().flatten() {
257                        reader.abort();
258                    }
259                }
260            }
261        }
262        self.stdout = read_buffer(&self.stdout_buffer);
263        self.stderr = read_buffer(&self.stderr_buffer);
264        let (code, signal) = normalize_exit(status);
265        self.exit_code = Some(code);
266        self.signal = signal;
267        Ok(code)
268    }
269
270    /// Terminate the command and its Unix process group with `SIGTERM`,
271    /// escalating to `SIGKILL` after [`DEFAULT_KILL_AFTER`].
272    pub async fn terminate(&mut self) -> io::Result<()> {
273        self.terminate_with("SIGTERM", Some(DEFAULT_KILL_AFTER))
274            .await
275            .map(|_| ())
276    }
277
278    /// Send `signal` to the process group while any member is alive, even
279    /// after the wrapper shell exited. Unless the signal is `SIGKILL`,
280    /// `kill_after` sends `SIGKILL` to a group that is still alive then.
281    ///
282    /// Returns whether a signal was sent.
283    pub async fn terminate_with(
284        &mut self,
285        signal: &str,
286        kill_after: Option<Duration>,
287    ) -> io::Result<bool> {
288        #[cfg(unix)]
289        {
290            let Some(pid) = self.pid else {
291                return Ok(false);
292            };
293            if !is_process_group_alive(pid).await {
294                return Ok(false);
295            }
296            let output = kill_group(pid, signal).await?;
297            if std::env::var_os("AGENT_COMMANDER_DEBUG").is_some() {
298                eprintln!(
299                    "Cancel process group {pid}: {} {}",
300                    output.status,
301                    String::from_utf8_lossy(&output.stderr)
302                );
303            }
304            if !output.status.success() && is_process_group_alive(pid).await {
305                return Err(io::Error::other(
306                    String::from_utf8_lossy(&output.stderr).into_owned(),
307                ));
308            }
309            let is_kill = matches!(signal.trim_start_matches("SIG"), "KILL" | "9");
310            if let (Some(delay), false) = (kill_after, is_kill) {
311                tokio::spawn(async move {
312                    tokio::time::sleep(delay).await;
313                    if is_process_group_alive(pid).await {
314                        let _ = kill_group(pid, "KILL").await;
315                    }
316                });
317            }
318            Ok(true)
319        }
320        #[cfg(not(unix))]
321        {
322            let _ = (signal, kill_after);
323            if self.exit_code.is_some() || self.child.try_wait()?.is_some() {
324                return Ok(false);
325            }
326            self.child.start_kill()?;
327            Ok(true)
328        }
329    }
330
331    /// Get collected output after waiting for completion.
332    pub fn get_output(&self) -> (&str, &str, Option<i32>) {
333        (&self.stdout, &self.stderr, self.exit_code)
334    }
335    /// Stdout read so far, also while the process runs.
336    pub fn peek_stdout(&self) -> String {
337        read_buffer(&self.stdout_buffer)
338    }
339    /// Signal that ended the process, after waiting for completion.
340    pub const fn signal(&self) -> Option<&'static str> {
341        self.signal
342    }
343    /// Whether the wrapper process has exited, without waiting for it.
344    pub fn try_wait(&mut self) -> io::Result<bool> {
345        Ok(self.exit_code.is_some() || self.child.try_wait()?.is_some())
346    }
347    /// Check whether completion has been collected.
348    pub const fn has_exited(&self) -> bool {
349        self.exit_code.is_some()
350    }
351    /// Whether stdin is piped and still open (see [`start_command_with_stdin`]).
352    pub const fn has_stdin(&self) -> bool {
353        self.stdin.is_some()
354    }
355    /// Write to the piped stdin and flush.
356    ///
357    /// Fails when stdin was not piped, was ended, or the process exited
358    /// (`BrokenPipe`).
359    pub async fn write_stdin(&mut self, data: &str) -> io::Result<()> {
360        let stdin = self
361            .stdin
362            .as_mut()
363            .ok_or_else(|| io::Error::new(io::ErrorKind::BrokenPipe, "stdin is not open"))?;
364        stdin.write_all(data.as_bytes()).await?;
365        stdin.flush().await
366    }
367    /// Close the piped stdin (end of input). Returns whether it was open.
368    pub fn end_stdin(&mut self) -> bool {
369        self.stdin.take().is_some()
370    }
371}
372
373/// Start a command and drain stdout/stderr concurrently, with optional console output.
374pub async fn start_command(command: &str, attached: bool) -> io::Result<ProcessHandle> {
375    spawn_command(command, attached, false)
376}
377
378/// Like [`start_command`], with stdin piped for
379/// [`ProcessHandle::write_stdin`] (live input, stream-json frames).
380pub async fn start_command_with_stdin(command: &str, attached: bool) -> io::Result<ProcessHandle> {
381    spawn_command(command, attached, true)
382}
383
384fn spawn_command(command: &str, attached: bool, pipe_stdin: bool) -> io::Result<ProcessHandle> {
385    let mut command_builder = Command::new("bash");
386    #[cfg(unix)]
387    {
388        use std::os::unix::process::CommandExt;
389        command_builder.as_std_mut().process_group(0);
390    }
391    let mut child = command_builder
392        .arg("-c")
393        .arg(command)
394        .stdout(Stdio::piped())
395        .stderr(Stdio::piped())
396        .stdin(if pipe_stdin {
397            Stdio::piped()
398        } else {
399            Stdio::null()
400        })
401        .kill_on_drop(true)
402        .spawn()?;
403    let stdin = child.stdin.take();
404    let stdout = child.stdout.take().expect("piped stdout");
405    let stderr = child.stderr.take().expect("piped stderr");
406    let stdout_buffer = Buffer::default();
407    let stderr_buffer = Buffer::default();
408    Ok(ProcessHandle {
409        command: command.into(),
410        pid: child.id(),
411        child,
412        readers: Some((
413            tokio::spawn(drain(stdout, Arc::clone(&stdout_buffer), attached, false)),
414            tokio::spawn(drain(stderr, Arc::clone(&stderr_buffer), attached, true)),
415        )),
416        stdout_buffer,
417        stderr_buffer,
418        pipe_drain: Some(DEFAULT_PIPE_DRAIN),
419        stdout: String::new(),
420        stderr: String::new(),
421        exit_code: None,
422        signal: None,
423        stdin,
424    })
425}
426
427/// Start a detached command with all standard streams disconnected, in its
428/// own process group (JS `spawn(..., { detached: true })`).
429pub async fn execute_detached(command: &str) -> io::Result<Option<u32>> {
430    let mut command_builder = Command::new("bash");
431    #[cfg(unix)]
432    {
433        use std::os::unix::process::CommandExt;
434        command_builder.as_std_mut().process_group(0);
435    }
436    let child = command_builder
437        .arg("-c")
438        .arg(command)
439        .stdout(Stdio::null())
440        .stderr(Stdio::null())
441        .stdin(Stdio::null())
442        .spawn()?;
443    Ok(child.id())
444}
445/// Signal cleanup callback.
446pub type CleanupFn = Box<dyn Fn() + Send + Sync>;
447
448/// Register a Ctrl+C cleanup callback in the current Tokio runtime.
449/// Calling the returned function unregisters it without running cleanup.
450pub fn setup_signal_handler<F>(cleanup_fn: F) -> impl Fn()
451where
452    F: Fn() + Send + Sync + 'static,
453{
454    let task = tokio::runtime::Handle::try_current().ok().map(|runtime| {
455        runtime.spawn(async move {
456            if tokio::signal::ctrl_c().await.is_ok() {
457                cleanup_fn();
458            }
459        })
460    });
461    move || {
462        if let Some(task) = &task {
463            task.abort();
464        }
465    }
466}
467
468#[cfg(test)]
469mod tests {
470    use super::*;
471
472    #[tokio::test]
473    async fn test_execute_command_dry_run() {
474        let result = execute_command("echo hello", true, false).await.unwrap();
475        assert_eq!(result.exit_code, 0);
476        assert_eq!(result.command, "echo hello");
477    }
478
479    #[tokio::test]
480    #[cfg(not(target_os = "windows"))]
481    async fn test_execute_command_real() {
482        let result = execute_command("echo hello", false, false).await.unwrap();
483        assert_eq!(result.exit_code, 0);
484        assert!(result.stdout.contains("hello"));
485    }
486
487    #[tokio::test]
488    #[cfg(not(target_os = "windows"))]
489    async fn test_start_command_and_wait() {
490        let mut handle = start_command("echo hello", false).await.unwrap();
491        let exit_code = handle.wait_for_exit().await.unwrap();
492        assert_eq!(exit_code, 0);
493
494        let (stdout, _, _) = handle.get_output();
495        assert!(stdout.contains("hello"));
496    }
497
498    #[tokio::test]
499    #[cfg(not(target_os = "windows"))]
500    async fn test_execute_detached() {
501        let pid = execute_detached("sleep 0.1").await.unwrap();
502        assert!(pid.is_some());
503    }
504
505    #[tokio::test]
506    #[cfg(unix)]
507    async fn test_execute_detached_leads_its_own_process_group() {
508        // Like JS `spawn(..., { detached: true })`: Ctrl+C to the caller's
509        // group must not reach the background agent.
510        let pid = execute_detached("sleep 1").await.unwrap().unwrap();
511        let output = tokio::process::Command::new("ps")
512            .args(["-o", "pgid=", "-p", &pid.to_string()])
513            .output()
514            .await
515            .unwrap();
516        assert_eq!(
517            String::from_utf8_lossy(&output.stdout).trim(),
518            pid.to_string()
519        );
520    }
521}