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, None)
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, None)
382}
383
384/// Like [`start_command`], with an explicit child environment that replaces
385/// the inherited one (issue #60: values stay off the command line).
386pub async fn start_command_with_env(
387    command: &str,
388    attached: bool,
389    pipe_stdin: bool,
390    env: &[(String, String)],
391) -> io::Result<ProcessHandle> {
392    spawn_command(command, attached, pipe_stdin, Some(env))
393}
394
395fn apply_env(command_builder: &mut Command, env: Option<&[(String, String)]>) {
396    if let Some(env) = env {
397        command_builder.env_clear();
398        command_builder.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())));
399    }
400}
401
402fn spawn_command(
403    command: &str,
404    attached: bool,
405    pipe_stdin: bool,
406    env: Option<&[(String, String)]>,
407) -> io::Result<ProcessHandle> {
408    let mut command_builder = Command::new("bash");
409    apply_env(&mut command_builder, env);
410    #[cfg(unix)]
411    {
412        use std::os::unix::process::CommandExt;
413        command_builder.as_std_mut().process_group(0);
414    }
415    let mut child = command_builder
416        .arg("-c")
417        .arg(command)
418        .stdout(Stdio::piped())
419        .stderr(Stdio::piped())
420        .stdin(if pipe_stdin {
421            Stdio::piped()
422        } else {
423            Stdio::null()
424        })
425        .kill_on_drop(true)
426        .spawn()?;
427    let stdin = child.stdin.take();
428    let stdout = child.stdout.take().expect("piped stdout");
429    let stderr = child.stderr.take().expect("piped stderr");
430    let stdout_buffer = Buffer::default();
431    let stderr_buffer = Buffer::default();
432    Ok(ProcessHandle {
433        command: command.into(),
434        pid: child.id(),
435        child,
436        readers: Some((
437            tokio::spawn(drain(stdout, Arc::clone(&stdout_buffer), attached, false)),
438            tokio::spawn(drain(stderr, Arc::clone(&stderr_buffer), attached, true)),
439        )),
440        stdout_buffer,
441        stderr_buffer,
442        pipe_drain: Some(DEFAULT_PIPE_DRAIN),
443        stdout: String::new(),
444        stderr: String::new(),
445        exit_code: None,
446        signal: None,
447        stdin,
448    })
449}
450
451/// Start a detached command with all standard streams disconnected, in its
452/// own process group (JS `spawn(..., { detached: true })`).
453pub async fn execute_detached(command: &str) -> io::Result<Option<u32>> {
454    execute_detached_with_env(command, None).await
455}
456
457/// Like [`execute_detached`], with an optional explicit child environment.
458pub async fn execute_detached_with_env(
459    command: &str,
460    env: Option<&[(String, String)]>,
461) -> io::Result<Option<u32>> {
462    let mut command_builder = Command::new("bash");
463    apply_env(&mut command_builder, env);
464    #[cfg(unix)]
465    {
466        use std::os::unix::process::CommandExt;
467        command_builder.as_std_mut().process_group(0);
468    }
469    let child = command_builder
470        .arg("-c")
471        .arg(command)
472        .stdout(Stdio::null())
473        .stderr(Stdio::null())
474        .stdin(Stdio::null())
475        .spawn()?;
476    Ok(child.id())
477}
478/// Signal cleanup callback.
479pub type CleanupFn = Box<dyn Fn() + Send + Sync>;
480
481/// Register a Ctrl+C cleanup callback in the current Tokio runtime.
482/// Calling the returned function unregisters it without running cleanup.
483pub fn setup_signal_handler<F>(cleanup_fn: F) -> impl Fn()
484where
485    F: Fn() + Send + Sync + 'static,
486{
487    let task = tokio::runtime::Handle::try_current().ok().map(|runtime| {
488        runtime.spawn(async move {
489            if tokio::signal::ctrl_c().await.is_ok() {
490                cleanup_fn();
491            }
492        })
493    });
494    move || {
495        if let Some(task) = &task {
496            task.abort();
497        }
498    }
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504
505    #[tokio::test]
506    async fn test_execute_command_dry_run() {
507        let result = execute_command("echo hello", true, false).await.unwrap();
508        assert_eq!(result.exit_code, 0);
509        assert_eq!(result.command, "echo hello");
510    }
511
512    #[tokio::test]
513    #[cfg(not(target_os = "windows"))]
514    async fn test_execute_command_real() {
515        let result = execute_command("echo hello", false, false).await.unwrap();
516        assert_eq!(result.exit_code, 0);
517        assert!(result.stdout.contains("hello"));
518    }
519
520    #[tokio::test]
521    #[cfg(not(target_os = "windows"))]
522    async fn test_start_command_and_wait() {
523        let mut handle = start_command("echo hello", false).await.unwrap();
524        let exit_code = handle.wait_for_exit().await.unwrap();
525        assert_eq!(exit_code, 0);
526
527        let (stdout, _, _) = handle.get_output();
528        assert!(stdout.contains("hello"));
529    }
530
531    #[tokio::test]
532    #[cfg(not(target_os = "windows"))]
533    async fn test_execute_detached() {
534        let pid = execute_detached("sleep 0.1").await.unwrap();
535        assert!(pid.is_some());
536    }
537
538    #[tokio::test]
539    #[cfg(unix)]
540    async fn test_execute_detached_leads_its_own_process_group() {
541        // Like JS `spawn(..., { detached: true })`: Ctrl+C to the caller's
542        // group must not reach the background agent.
543        let pid = execute_detached("sleep 1").await.unwrap().unwrap();
544        let output = tokio::process::Command::new("ps")
545            .args(["-o", "pgid=", "-p", &pid.to_string()])
546            .output()
547            .await
548            .unwrap();
549        assert_eq!(
550            String::from_utf8_lossy(&output.stdout).trim(),
551            pid.to_string()
552        );
553    }
554}