Skip to main content

agent_commander/
executor.rs

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