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, 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}
217impl ProcessHandle {
218    /// Bound the wait for open pipes after the wrapper exits; `None` waits
219    /// until every holder closes them.
220    #[must_use]
221    pub const fn with_pipe_drain(mut self, pipe_drain: Option<Duration>) -> Self {
222        self.pipe_drain = pipe_drain;
223        self
224    }
225
226    /// Process id of the wrapper shell, which also leads the process group.
227    pub const fn pid(&self) -> Option<u32> {
228        self.pid
229    }
230
231    /// Wait for process completion and all output, preserving exact bytes as UTF-8.
232    pub async fn wait_for_exit(&mut self) -> io::Result<i32> {
233        if let Some(code) = self.exit_code {
234            return Ok(code);
235        }
236        let status = self.child.wait().await?;
237        if let Some((stdout, stderr)) = self.readers.take() {
238            let mut readers = [Some(stdout), Some(stderr)];
239            let deadline = self.pipe_drain.map(|limit| Instant::now() + limit);
240            if !join_readers(&mut readers, deadline).await? {
241                // A grandchild still holds the pipes: stop the group, then
242                // keep what was read.
243                #[cfg(unix)]
244                if let Some(pid) = self.pid {
245                    if is_process_group_alive(pid).await {
246                        let _ = kill_group(pid, "KILL").await;
247                    }
248                }
249                let grace = Some(Instant::now() + Duration::from_millis(500));
250                if !join_readers(&mut readers, grace).await? {
251                    for reader in readers.iter().flatten() {
252                        reader.abort();
253                    }
254                }
255            }
256        }
257        self.stdout = read_buffer(&self.stdout_buffer);
258        self.stderr = read_buffer(&self.stderr_buffer);
259        let (code, signal) = normalize_exit(status);
260        self.exit_code = Some(code);
261        self.signal = signal;
262        Ok(code)
263    }
264
265    /// Terminate the command and its Unix process group with `SIGTERM`,
266    /// escalating to `SIGKILL` after [`DEFAULT_KILL_AFTER`].
267    pub async fn terminate(&mut self) -> io::Result<()> {
268        self.terminate_with("SIGTERM", Some(DEFAULT_KILL_AFTER))
269            .await
270            .map(|_| ())
271    }
272
273    /// Send `signal` to the process group while any member is alive, even
274    /// after the wrapper shell exited. Unless the signal is `SIGKILL`,
275    /// `kill_after` sends `SIGKILL` to a group that is still alive then.
276    ///
277    /// Returns whether a signal was sent.
278    pub async fn terminate_with(
279        &mut self,
280        signal: &str,
281        kill_after: Option<Duration>,
282    ) -> io::Result<bool> {
283        #[cfg(unix)]
284        {
285            let Some(pid) = self.pid else {
286                return Ok(false);
287            };
288            if !is_process_group_alive(pid).await {
289                return Ok(false);
290            }
291            let output = kill_group(pid, signal).await?;
292            if std::env::var_os("AGENT_COMMANDER_DEBUG").is_some() {
293                eprintln!(
294                    "Cancel process group {pid}: {} {}",
295                    output.status,
296                    String::from_utf8_lossy(&output.stderr)
297                );
298            }
299            if !output.status.success() && is_process_group_alive(pid).await {
300                return Err(io::Error::other(
301                    String::from_utf8_lossy(&output.stderr).into_owned(),
302                ));
303            }
304            let is_kill = matches!(signal.trim_start_matches("SIG"), "KILL" | "9");
305            if let (Some(delay), false) = (kill_after, is_kill) {
306                tokio::spawn(async move {
307                    tokio::time::sleep(delay).await;
308                    if is_process_group_alive(pid).await {
309                        let _ = kill_group(pid, "KILL").await;
310                    }
311                });
312            }
313            Ok(true)
314        }
315        #[cfg(not(unix))]
316        {
317            let _ = (signal, kill_after);
318            if self.exit_code.is_some() || self.child.try_wait()?.is_some() {
319                return Ok(false);
320            }
321            self.child.start_kill()?;
322            Ok(true)
323        }
324    }
325
326    /// Get collected output after waiting for completion.
327    pub fn get_output(&self) -> (&str, &str, Option<i32>) {
328        (&self.stdout, &self.stderr, self.exit_code)
329    }
330    /// Stdout read so far, also while the process runs.
331    pub fn peek_stdout(&self) -> String {
332        read_buffer(&self.stdout_buffer)
333    }
334    /// Signal that ended the process, after waiting for completion.
335    pub const fn signal(&self) -> Option<&'static str> {
336        self.signal
337    }
338    /// Whether the wrapper process has exited, without waiting for it.
339    pub fn try_wait(&mut self) -> io::Result<bool> {
340        Ok(self.exit_code.is_some() || self.child.try_wait()?.is_some())
341    }
342    /// Check whether completion has been collected.
343    pub const fn has_exited(&self) -> bool {
344        self.exit_code.is_some()
345    }
346}
347
348/// Start a command and drain stdout/stderr concurrently, with optional console output.
349pub async fn start_command(command: &str, attached: bool) -> io::Result<ProcessHandle> {
350    let mut command_builder = Command::new("bash");
351    #[cfg(unix)]
352    {
353        use std::os::unix::process::CommandExt;
354        command_builder.as_std_mut().process_group(0);
355    }
356    let mut child = command_builder
357        .arg("-c")
358        .arg(command)
359        .stdout(Stdio::piped())
360        .stderr(Stdio::piped())
361        .stdin(Stdio::null())
362        .kill_on_drop(true)
363        .spawn()?;
364    let stdout = child.stdout.take().expect("piped stdout");
365    let stderr = child.stderr.take().expect("piped stderr");
366    let stdout_buffer = Buffer::default();
367    let stderr_buffer = Buffer::default();
368    Ok(ProcessHandle {
369        command: command.into(),
370        pid: child.id(),
371        child,
372        readers: Some((
373            tokio::spawn(drain(stdout, Arc::clone(&stdout_buffer), attached, false)),
374            tokio::spawn(drain(stderr, Arc::clone(&stderr_buffer), attached, true)),
375        )),
376        stdout_buffer,
377        stderr_buffer,
378        pipe_drain: Some(DEFAULT_PIPE_DRAIN),
379        stdout: String::new(),
380        stderr: String::new(),
381        exit_code: None,
382        signal: None,
383    })
384}
385
386/// Start a detached command with all standard streams disconnected, in its
387/// own process group (JS `spawn(..., { detached: true })`).
388pub async fn execute_detached(command: &str) -> io::Result<Option<u32>> {
389    let mut command_builder = Command::new("bash");
390    #[cfg(unix)]
391    {
392        use std::os::unix::process::CommandExt;
393        command_builder.as_std_mut().process_group(0);
394    }
395    let child = command_builder
396        .arg("-c")
397        .arg(command)
398        .stdout(Stdio::null())
399        .stderr(Stdio::null())
400        .stdin(Stdio::null())
401        .spawn()?;
402    Ok(child.id())
403}
404/// Signal cleanup callback.
405pub type CleanupFn = Box<dyn Fn() + Send + Sync>;
406
407/// Register a Ctrl+C cleanup callback in the current Tokio runtime.
408/// Calling the returned function unregisters it without running cleanup.
409pub fn setup_signal_handler<F>(cleanup_fn: F) -> impl Fn()
410where
411    F: Fn() + Send + Sync + 'static,
412{
413    let task = tokio::runtime::Handle::try_current().ok().map(|runtime| {
414        runtime.spawn(async move {
415            if tokio::signal::ctrl_c().await.is_ok() {
416                cleanup_fn();
417            }
418        })
419    });
420    move || {
421        if let Some(task) = &task {
422            task.abort();
423        }
424    }
425}
426
427#[cfg(test)]
428mod tests {
429    use super::*;
430
431    #[tokio::test]
432    async fn test_execute_command_dry_run() {
433        let result = execute_command("echo hello", true, false).await.unwrap();
434        assert_eq!(result.exit_code, 0);
435        assert_eq!(result.command, "echo hello");
436    }
437
438    #[tokio::test]
439    #[cfg(not(target_os = "windows"))]
440    async fn test_execute_command_real() {
441        let result = execute_command("echo hello", false, false).await.unwrap();
442        assert_eq!(result.exit_code, 0);
443        assert!(result.stdout.contains("hello"));
444    }
445
446    #[tokio::test]
447    #[cfg(not(target_os = "windows"))]
448    async fn test_start_command_and_wait() {
449        let mut handle = start_command("echo hello", false).await.unwrap();
450        let exit_code = handle.wait_for_exit().await.unwrap();
451        assert_eq!(exit_code, 0);
452
453        let (stdout, _, _) = handle.get_output();
454        assert!(stdout.contains("hello"));
455    }
456
457    #[tokio::test]
458    #[cfg(not(target_os = "windows"))]
459    async fn test_execute_detached() {
460        let pid = execute_detached("sleep 0.1").await.unwrap();
461        assert!(pid.is_some());
462    }
463
464    #[tokio::test]
465    #[cfg(unix)]
466    async fn test_execute_detached_leads_its_own_process_group() {
467        // Like JS `spawn(..., { detached: true })`: Ctrl+C to the caller's
468        // group must not reach the background agent.
469        let pid = execute_detached("sleep 1").await.unwrap().unwrap();
470        let output = tokio::process::Command::new("ps")
471            .args(["-o", "pgid=", "-p", &pid.to_string()])
472            .output()
473            .await
474            .unwrap();
475        assert_eq!(
476            String::from_utf8_lossy(&output.stdout).trim(),
477            pid.to_string()
478        );
479    }
480}