Skip to main content

agent_commander/
executor.rs

1//! Execute commands while continuously draining both process pipes.
2use std::{io, process::Stdio};
3use tokio::{
4    io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
5    process::{Child, Command},
6    task::JoinHandle,
7};
8
9/// Command execution result.
10#[derive(Debug, Clone, Default)]
11pub struct ExecutionResult {
12    pub exit_code: i32,
13    pub stdout: String,
14    pub stderr: String,
15    pub command: String,
16}
17
18async fn drain<R: AsyncRead + Unpin>(
19    mut pipe: R,
20    attached: bool,
21    stderr: bool,
22) -> io::Result<String> {
23    let mut bytes = Vec::new();
24    let mut chunk = [0; 8192];
25    loop {
26        let count = pipe.read(&mut chunk).await?;
27        if count == 0 {
28            break;
29        }
30        bytes.extend_from_slice(&chunk[..count]);
31        if attached {
32            if stderr {
33                tokio::io::stderr().write_all(&chunk[..count]).await?;
34            } else {
35                tokio::io::stdout().write_all(&chunk[..count]).await?;
36            }
37        }
38    }
39    Ok(String::from_utf8_lossy(&bytes).into_owned())
40}
41
42/// Execute a command, or return the command without spawning in dry-run mode.
43pub async fn execute_command(
44    command: &str,
45    dry_run: bool,
46    attached: bool,
47) -> io::Result<ExecutionResult> {
48    if dry_run {
49        println!("Dry run - command that would be executed:\n{}", command);
50        return Ok(ExecutionResult {
51            command: command.into(),
52            ..Default::default()
53        });
54    }
55    let mut handle = start_command(command, attached).await?;
56    let exit_code = handle.wait_for_exit().await?;
57    let (stdout, stderr, _) = handle.get_output();
58    Ok(ExecutionResult {
59        exit_code,
60        stdout: stdout.into(),
61        stderr: stderr.into(),
62        command: command.into(),
63    })
64}
65
66/// Non-blocking process handle. Pipe readers run immediately after spawning.
67pub struct ProcessHandle {
68    pub command: String,
69    child: Child,
70    readers: Option<(
71        JoinHandle<io::Result<String>>,
72        JoinHandle<io::Result<String>>,
73    )>,
74    stdout: String,
75    stderr: String,
76    exit_code: Option<i32>,
77}
78impl ProcessHandle {
79    /// Wait for process completion and all output, preserving exact bytes as UTF-8.
80    pub async fn wait_for_exit(&mut self) -> io::Result<i32> {
81        if let Some(code) = self.exit_code {
82            return Ok(code);
83        }
84        let status = self.child.wait().await?;
85        if let Some((stdout, stderr)) = self.readers.take() {
86            let (out, err) = tokio::join!(stdout, stderr);
87            self.stdout = out.map_err(io::Error::other)??;
88            self.stderr = err.map_err(io::Error::other)??;
89        }
90        let code = status.code().unwrap_or(1);
91        self.exit_code = Some(code);
92        Ok(code)
93    }
94    /// Terminate the running command and its Unix process group.
95    pub async fn terminate(&mut self) -> io::Result<()> {
96        if self.exit_code.is_some() || self.child.try_wait()?.is_some() {
97            return Ok(());
98        }
99        #[cfg(unix)]
100        if let Some(id) = self.child.id() {
101            // bash's kill builtin is available wherever our executor is supported.
102            let output = Command::new("bash")
103                .arg("-c")
104                .arg(format!("kill -TERM -- -{}", id))
105                .output()
106                .await?;
107            if std::env::var_os("AGENT_COMMANDER_DEBUG").is_some() {
108                eprintln!(
109                    "Cancel process group {id}: {} {}",
110                    output.status,
111                    String::from_utf8_lossy(&output.stderr)
112                );
113            }
114            if !output.status.success() && self.child.try_wait()?.is_none() {
115                return Err(io::Error::other(
116                    String::from_utf8_lossy(&output.stderr).into_owned(),
117                ));
118            }
119        }
120        #[cfg(not(unix))]
121        self.child.start_kill()?;
122        Ok(())
123    }
124
125    /// Get collected output after waiting for completion.
126    pub fn get_output(&self) -> (&str, &str, Option<i32>) {
127        (&self.stdout, &self.stderr, self.exit_code)
128    }
129    /// Check whether completion has been collected.
130    pub fn has_exited(&self) -> bool {
131        self.exit_code.is_some()
132    }
133}
134
135/// Start a command and drain stdout/stderr concurrently, with optional console output.
136pub async fn start_command(command: &str, attached: bool) -> io::Result<ProcessHandle> {
137    let mut command_builder = Command::new("bash");
138    #[cfg(unix)]
139    {
140        use std::os::unix::process::CommandExt;
141        command_builder.as_std_mut().process_group(0);
142    }
143    let mut child = command_builder
144        .arg("-c")
145        .arg(command)
146        .stdout(Stdio::piped())
147        .stderr(Stdio::piped())
148        .stdin(Stdio::null())
149        .kill_on_drop(true)
150        .spawn()?;
151    let stdout = child.stdout.take().expect("piped stdout");
152    let stderr = child.stderr.take().expect("piped stderr");
153    Ok(ProcessHandle {
154        command: command.into(),
155        child,
156        readers: Some((
157            tokio::spawn(drain(stdout, attached, false)),
158            tokio::spawn(drain(stderr, attached, true)),
159        )),
160        stdout: String::new(),
161        stderr: String::new(),
162        exit_code: None,
163    })
164}
165
166/// Start a detached command with all standard streams disconnected.
167pub async fn execute_detached(command: &str) -> io::Result<Option<u32>> {
168    let child = Command::new("bash")
169        .arg("-c")
170        .arg(command)
171        .stdout(Stdio::null())
172        .stderr(Stdio::null())
173        .stdin(Stdio::null())
174        .spawn()?;
175    Ok(child.id())
176}
177/// Signal cleanup callback.
178pub type CleanupFn = Box<dyn Fn() + Send + Sync>;
179
180/// Register a Ctrl+C cleanup callback in the current Tokio runtime.
181/// Calling the returned function unregisters it without running cleanup.
182pub fn setup_signal_handler<F>(cleanup_fn: F) -> impl Fn()
183where
184    F: Fn() + Send + Sync + 'static,
185{
186    let task = tokio::runtime::Handle::try_current().ok().map(|runtime| {
187        runtime.spawn(async move {
188            if tokio::signal::ctrl_c().await.is_ok() {
189                cleanup_fn();
190            }
191        })
192    });
193    move || {
194        if let Some(task) = &task {
195            task.abort();
196        }
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    #[tokio::test]
205    async fn test_execute_command_dry_run() {
206        let result = execute_command("echo hello", true, false).await.unwrap();
207        assert_eq!(result.exit_code, 0);
208        assert_eq!(result.command, "echo hello");
209    }
210
211    #[tokio::test]
212    #[cfg(not(target_os = "windows"))]
213    async fn test_execute_command_real() {
214        let result = execute_command("echo hello", false, false).await.unwrap();
215        assert_eq!(result.exit_code, 0);
216        assert!(result.stdout.contains("hello"));
217    }
218
219    #[tokio::test]
220    #[cfg(not(target_os = "windows"))]
221    async fn test_start_command_and_wait() {
222        let mut handle = start_command("echo hello", false).await.unwrap();
223        let exit_code = handle.wait_for_exit().await.unwrap();
224        assert_eq!(exit_code, 0);
225
226        let (stdout, _, _) = handle.get_output();
227        assert!(stdout.contains("hello"));
228    }
229
230    #[tokio::test]
231    #[cfg(not(target_os = "windows"))]
232    async fn test_execute_detached() {
233        let pid = execute_detached("sleep 0.1").await.unwrap();
234        assert!(pid.is_some());
235    }
236}