Skip to main content

vtcode_bash_runner/
pipe.rs

1//! Async pipe-based process spawning with unified handle interface.
2//!
3//! This module provides helpers for spawning non-interactive processes using
4//! regular pipes for stdin/stdout/stderr, with proper process group management
5//! for reliable cleanup.
6//!
7//! Inspired by codex-rs/utils/pty pipe spawning patterns.
8
9use hashbrown::HashMap;
10use std::io::{self, ErrorKind};
11use std::path::Path;
12use std::process::Stdio;
13use std::sync::Arc;
14use std::sync::Mutex as StdMutex;
15use std::sync::atomic::AtomicBool;
16
17use anyhow::{Context, Result};
18use bytes::Bytes;
19use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt, BufReader};
20use tokio::process::Command;
21use tokio::sync::{broadcast, mpsc, oneshot};
22use tokio::task::JoinHandle;
23
24use crate::process::{ChildTerminator, ProcessHandle, SpawnedProcess};
25use crate::process_group;
26
27/// Terminator for pipe-based child processes.
28struct PipeChildTerminator {
29    #[cfg(windows)]
30    pid: u32,
31    #[cfg(unix)]
32    process_group_id: u32,
33}
34
35impl ChildTerminator for PipeChildTerminator {
36    fn kill(&mut self) -> io::Result<()> {
37        #[cfg(unix)]
38        {
39            process_group::kill_process_group(self.process_group_id)
40        }
41
42        #[cfg(windows)]
43        {
44            process_group::kill_process(self.pid)
45        }
46
47        #[cfg(not(any(unix, windows)))]
48        {
49            Ok(())
50        }
51    }
52}
53
54/// Read from an async reader and send chunks to a broadcast channel.
55async fn read_output_stream<R>(mut reader: R, output_tx: broadcast::Sender<Bytes>)
56where
57    R: AsyncRead + Unpin,
58{
59    let mut buf = vec![0u8; 8_192];
60    loop {
61        match reader.read(&mut buf).await {
62            Ok(0) => break,
63            Ok(n) => {
64                let _ = output_tx.send(Bytes::copy_from_slice(&buf[..n]));
65            }
66            Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
67            Err(_) => break,
68        }
69    }
70}
71
72/// Stdin mode for pipe-based processes.
73#[derive(Clone, Copy)]
74pub enum PipeStdinMode {
75    /// Stdin is available as a pipe.
76    Piped,
77    /// Stdin is connected to /dev/null (immediate EOF).
78    Null,
79}
80
81/// Options for spawning a pipe-based process.
82#[derive(Clone)]
83pub struct PipeSpawnOptions {
84    /// The program to execute.
85    pub program: String,
86    /// Arguments to pass to the program.
87    pub args: Vec<String>,
88    /// Working directory for the process.
89    pub cwd: std::path::PathBuf,
90    /// Environment variables (if None, inherits from parent).
91    pub env: Option<HashMap<String, String>>,
92    /// Override for `argv[0]` (Unix only).
93    pub arg0: Option<String>,
94    /// Stdin mode.
95    pub stdin_mode: PipeStdinMode,
96}
97
98impl PipeSpawnOptions {
99    /// Create new spawn options with default settings.
100    pub fn new(program: impl Into<String>, cwd: impl Into<std::path::PathBuf>) -> Self {
101        Self {
102            program: program.into(),
103            args: Vec::new(),
104            cwd: cwd.into(),
105            env: None,
106            arg0: None,
107            stdin_mode: PipeStdinMode::Piped,
108        }
109    }
110
111    /// Add arguments.
112    pub fn args(mut self, args: impl IntoIterator<Item = impl Into<String>>) -> Self {
113        self.args = args.into_iter().map(Into::into).collect();
114        self
115    }
116
117    /// Set environment variables.
118    pub fn env(mut self, env: HashMap<String, String>) -> Self {
119        self.env = Some(env);
120        self
121    }
122
123    /// Set arg0 override (Unix only).
124    pub fn arg0(mut self, arg0: impl Into<String>) -> Self {
125        self.arg0 = Some(arg0.into());
126        self
127    }
128
129    /// Set stdin mode.
130    pub fn stdin_mode(mut self, mode: PipeStdinMode) -> Self {
131        self.stdin_mode = mode;
132        self
133    }
134}
135
136/// Spawn a process using regular pipes, with configurable options.
137async fn spawn_process_internal(opts: PipeSpawnOptions) -> Result<SpawnedProcess> {
138    if opts.program.is_empty() {
139        anyhow::bail!("missing program for pipe spawn");
140    }
141
142    let mut command = Command::new(&opts.program);
143
144    #[cfg(unix)]
145    if let Some(ref arg0) = opts.arg0 {
146        command.arg0(arg0);
147    }
148
149    #[cfg(unix)]
150    {
151        command.process_group(0);
152    }
153
154    #[cfg(not(unix))]
155    let _ = &opts.arg0;
156
157    command.current_dir(&opts.cwd);
158
159    // Handle environment
160    if let Some(ref env) = opts.env {
161        command.env_clear();
162        for (key, value) in env {
163            command.env(key, value);
164        }
165    }
166
167    for arg in &opts.args {
168        command.arg(arg);
169    }
170
171    match opts.stdin_mode {
172        PipeStdinMode::Piped => {
173            command.stdin(Stdio::piped());
174        }
175        PipeStdinMode::Null => {
176            command.stdin(Stdio::null());
177        }
178    }
179    command.stdout(Stdio::piped());
180    command.stderr(Stdio::piped());
181
182    let mut child = command.spawn().context("failed to spawn pipe process")?;
183    let pid = child.id().ok_or_else(|| io::Error::other("missing child pid"))?;
184
185    #[cfg(unix)]
186    let process_group_id = pid;
187
188    let stdin = child.stdin.take();
189    let stdout = child.stdout.take();
190    let stderr = child.stderr.take();
191
192    let (writer_tx, mut writer_rx) = mpsc::channel::<Vec<u8>>(128);
193    let (output_tx, _) = broadcast::channel::<Bytes>(256);
194    let initial_output_rx = output_tx.subscribe();
195
196    // Spawn writer task
197    let writer_handle = if let Some(stdin) = stdin {
198        let writer = Arc::new(tokio::sync::Mutex::new(stdin));
199        tokio::spawn(async move {
200            while let Some(bytes) = writer_rx.recv().await {
201                let mut guard = writer.lock().await;
202                let _ = guard.write_all(&bytes).await;
203                let _ = guard.flush().await;
204            }
205        })
206    } else {
207        drop(writer_rx);
208        tokio::spawn(async {})
209    };
210
211    // Spawn reader tasks for stdout and stderr
212    let stdout_handle = stdout.map(|stdout| {
213        let output_tx = output_tx.clone();
214        tokio::spawn(async move {
215            read_output_stream(BufReader::new(stdout), output_tx).await;
216        })
217    });
218
219    let stderr_handle = stderr.map(|stderr| {
220        let output_tx = output_tx.clone();
221        tokio::spawn(async move {
222            read_output_stream(BufReader::new(stderr), output_tx).await;
223        })
224    });
225
226    let mut reader_abort_handles = Vec::new();
227    if let Some(ref handle) = stdout_handle {
228        reader_abort_handles.push(handle.abort_handle());
229    }
230    if let Some(ref handle) = stderr_handle {
231        reader_abort_handles.push(handle.abort_handle());
232    }
233
234    let reader_handle = tokio::spawn(async move {
235        if let Some(handle) = stdout_handle {
236            let _ = handle.await;
237        }
238        if let Some(handle) = stderr_handle {
239            let _ = handle.await;
240        }
241    });
242
243    // Spawn wait task
244    let (exit_tx, exit_rx) = oneshot::channel::<i32>();
245    let exit_status = Arc::new(AtomicBool::new(false));
246    let wait_exit_status = Arc::clone(&exit_status);
247    let exit_code = Arc::new(StdMutex::new(None));
248    let wait_exit_code = Arc::clone(&exit_code);
249
250    let wait_handle: JoinHandle<()> = tokio::spawn(async move {
251        let code = match child.wait().await {
252            Ok(status) => status.code().unwrap_or(-1),
253            Err(_) => -1,
254        };
255        wait_exit_status.store(true, std::sync::atomic::Ordering::SeqCst);
256        if let Ok(mut guard) = wait_exit_code.lock() {
257            *guard = Some(code);
258        }
259        let _ = exit_tx.send(code);
260    });
261
262    let (handle, output_rx) = ProcessHandle::new(
263        writer_tx,
264        output_tx,
265        initial_output_rx,
266        Box::new(PipeChildTerminator {
267            #[cfg(windows)]
268            pid,
269            #[cfg(unix)]
270            process_group_id,
271        }),
272        reader_handle,
273        reader_abort_handles,
274        writer_handle,
275        wait_handle,
276        exit_status,
277        exit_code,
278        None,
279    );
280
281    Ok(SpawnedProcess { session: handle, output_rx, exit_rx })
282}
283
284/// Spawn a process using regular pipes (no PTY), returning handles for stdin, output, and exit.
285///
286/// # Example
287/// ```ignore
288/// use vtcode_bash_runner::pipe::spawn_process;
289/// use hashbrown::HashMap;
290/// use std::path::Path;
291///
292/// let env: HashMap<String, String> = std::env::vars().collect();
293/// let spawned = spawn_process("echo", &["hello".into()], Path::new("."), &env, &None).await?;
294/// let output_rx = spawned.output_rx;
295/// let exit_code = spawned.exit_rx.await?;
296/// ```
297pub async fn spawn_process(
298    program: &str,
299    args: &[String],
300    cwd: &Path,
301    env: &HashMap<String, String>,
302    arg0: &Option<String>,
303) -> Result<SpawnedProcess> {
304    let opts = PipeSpawnOptions {
305        program: program.to_string(),
306        args: args.to_vec(),
307        cwd: cwd.to_path_buf(),
308        env: Some(env.clone()),
309        arg0: arg0.clone(),
310        stdin_mode: PipeStdinMode::Piped,
311    };
312    spawn_process_internal(opts).await
313}
314
315/// Spawn a process using regular pipes, but close stdin immediately.
316///
317/// This is useful for commands that should see EOF on stdin immediately.
318pub async fn spawn_process_no_stdin(
319    program: &str,
320    args: &[String],
321    cwd: &Path,
322    env: &HashMap<String, String>,
323    arg0: &Option<String>,
324) -> Result<SpawnedProcess> {
325    let opts = PipeSpawnOptions {
326        program: program.to_string(),
327        args: args.to_vec(),
328        cwd: cwd.to_path_buf(),
329        env: Some(env.clone()),
330        arg0: arg0.clone(),
331        stdin_mode: PipeStdinMode::Null,
332    };
333    spawn_process_internal(opts).await
334}
335
336/// Spawn a process with full options control.
337pub async fn spawn_process_with_options(opts: PipeSpawnOptions) -> Result<SpawnedProcess> {
338    spawn_process_internal(opts).await
339}
340
341#[cfg(test)]
342mod tests {
343    use super::*;
344
345    fn find_echo_command() -> Option<(String, Vec<String>)> {
346        #[cfg(windows)]
347        {
348            Some(("cmd.exe".to_string(), vec!["/C".to_string(), "echo".to_string()]))
349        }
350        #[cfg(not(windows))]
351        {
352            Some(("echo".to_string(), vec![]))
353        }
354    }
355
356    #[tokio::test]
357    async fn test_spawn_process_echo() -> Result<()> {
358        let Some((program, mut base_args)) = find_echo_command() else {
359            return Ok(());
360        };
361
362        base_args.push("hello".to_string());
363
364        let env: HashMap<String, String> = std::env::vars().collect();
365        let spawned = spawn_process(&program, &base_args, Path::new("."), &env, &None).await?;
366
367        let exit_code = spawned.exit_rx.await.unwrap_or(-1);
368        assert_eq!(exit_code, 0);
369
370        Ok(())
371    }
372
373    #[tokio::test]
374    async fn test_spawn_options_builder() {
375        let opts = PipeSpawnOptions::new("echo", ".")
376            .args(["hello", "world"])
377            .stdin_mode(PipeStdinMode::Null);
378
379        assert_eq!(opts.program, "echo");
380        assert_eq!(opts.args, vec!["hello", "world"]);
381        assert!(matches!(opts.stdin_mode, PipeStdinMode::Null));
382    }
383}