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;
15
16use anyhow::{Context, Result};
17use bytes::{Bytes, BytesMut};
18use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt, BufReader};
19use tokio::process::Command;
20use tokio::sync::{broadcast, mpsc, oneshot};
21use tokio::task::JoinHandle;
22
23use crate::process::{ChildTerminator, ProcessExitState, ProcessHandle, SpawnedProcess};
24use crate::process_group;
25
26/// Terminator for pipe-based child processes.
27struct PipeChildTerminator {
28    #[cfg(windows)]
29    pid: u32,
30    #[cfg(unix)]
31    process_group_id: u32,
32}
33
34impl ChildTerminator for PipeChildTerminator {
35    fn kill(&mut self) -> io::Result<()> {
36        #[cfg(unix)]
37        {
38            process_group::kill_process_group(self.process_group_id)
39        }
40
41        #[cfg(windows)]
42        {
43            process_group::kill_process(self.pid)
44        }
45
46        #[cfg(not(any(unix, windows)))]
47        {
48            Ok(())
49        }
50    }
51}
52
53const RELIABLE_OUTPUT_CHANNEL_CAPACITY: usize = 128;
54
55/// Read from an async reader and send chunks to both compatibility and
56/// optional lossless output channels. The compatibility broadcast is always
57/// independent: callers that only use the legacy receiver must never be able
58/// to stop the child-process pipe from being drained.
59async fn read_output_stream<R>(
60    mut reader: R,
61    output_tx: broadcast::Sender<Bytes>,
62    mut reliable_output_tx: Option<mpsc::Sender<Bytes>>,
63) where
64    R: AsyncRead + Unpin,
65{
66    // Read directly into a BytesMut so each chunk can be frozen without a
67    // separate Vec-to-Bytes copy.
68    let mut buf = BytesMut::with_capacity(65_536);
69    loop {
70        buf.clear();
71        match reader.read_buf(&mut buf).await {
72            Ok(0) => break,
73            Ok(n) => {
74                let chunk = buf.split_to(n).freeze();
75                let _ = output_tx.send(chunk.clone());
76                if let Some(sender) = reliable_output_tx.as_ref().cloned()
77                    && sender.send(chunk).await.is_err()
78                {
79                    // A lossless consumer is optional. Once it goes away,
80                    // continue draining the child stream for compatibility
81                    // subscribers instead of deadlocking the child.
82                    reliable_output_tx = None;
83                }
84            }
85            Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
86            Err(_) => break,
87        }
88    }
89}
90
91/// Stdin mode for pipe-based processes.
92#[derive(Clone, Copy)]
93pub enum PipeStdinMode {
94    /// Stdin is available as a pipe.
95    Piped,
96    /// Stdin is connected to /dev/null (immediate EOF).
97    Null,
98}
99
100/// Options for spawning a pipe-based process.
101#[derive(Clone)]
102#[must_use = "spawn options must be passed to a spawn function"]
103pub struct PipeSpawnOptions {
104    /// The program to execute.
105    program: String,
106    /// Arguments to pass to the program.
107    args: Vec<String>,
108    /// Working directory for the process.
109    cwd: std::path::PathBuf,
110    /// Environment variables (if None, inherits from parent).
111    env: Option<HashMap<String, String>>,
112    /// Override for `argv[0]` (Unix only).
113    arg0: Option<String>,
114    /// Stdin mode.
115    stdin_mode: PipeStdinMode,
116    /// Enable the bounded lossless stream used by spoolers and
117    /// `wait_with_output`. Legacy callers should leave this disabled so an
118    /// unconsumed reliable receiver cannot apply backpressure.
119    lossless_output: bool,
120}
121
122impl PipeSpawnOptions {
123    /// Create new spawn options with default settings.
124    pub fn new(program: impl Into<String>, cwd: impl Into<std::path::PathBuf>) -> Self {
125        Self {
126            program: program.into(),
127            args: Vec::new(),
128            cwd: cwd.into(),
129            env: None,
130            arg0: None,
131            stdin_mode: PipeStdinMode::Piped,
132            lossless_output: false,
133        }
134    }
135
136    /// Add arguments.
137    pub fn args(mut self, args: impl IntoIterator<Item = impl Into<String>>) -> Self {
138        self.args = args.into_iter().map(Into::into).collect();
139        self
140    }
141
142    /// Set environment variables.
143    pub fn env(mut self, env: HashMap<String, String>) -> Self {
144        self.env = Some(env);
145        self
146    }
147
148    /// Set arg0 override (Unix only).
149    pub fn arg0(mut self, arg0: impl Into<String>) -> Self {
150        self.arg0 = Some(arg0.into());
151        self
152    }
153
154    /// Set stdin mode.
155    pub fn stdin_mode(mut self, mode: PipeStdinMode) -> Self {
156        self.stdin_mode = mode;
157        self
158    }
159
160    /// Enable the lossless output stream for a consumer that drains it.
161    pub fn lossless_output(mut self, enabled: bool) -> Self {
162        self.lossless_output = enabled;
163        self
164    }
165}
166
167/// Spawn a process using regular pipes, with configurable options.
168async fn spawn_process_internal(opts: PipeSpawnOptions) -> Result<SpawnedProcess> {
169    if opts.program.is_empty() {
170        anyhow::bail!("missing program for pipe spawn");
171    }
172
173    #[cfg(unix)]
174    let owned = crate::process_owner::OwnedCommand::from_environment(
175        opts.program.as_ref(),
176        opts.args.iter(),
177        opts.arg0.as_deref().map(std::ffi::OsStr::new),
178    )?;
179
180    #[cfg(unix)]
181    let mut command = match &owned {
182        Some(owned) => {
183            let mut command = Command::new(&owned.executable);
184            command.args(&owned.arguments);
185            command
186        }
187        None => Command::new(&opts.program),
188    };
189    #[cfg(not(unix))]
190    let mut command = Command::new(&opts.program);
191
192    #[cfg(unix)]
193    if owned.is_none()
194        && let Some(ref arg0) = opts.arg0
195    {
196        command.arg0(arg0);
197    }
198
199    #[cfg(unix)]
200    #[expect(
201        unsafe_code,
202        reason = "detach_from_tty only calls setsid/setpgid via safe nix wrappers to detach the child from the controlling terminal; it is a pure process-group operation with no undefined behavior"
203    )]
204    // SAFETY: `pre_exec` runs the closure in the forked child before `exec`,
205    // so only async-signal-safe operations are permitted. `detach_from_tty`
206    // calls `setsid()` (falling back to `setpgid(0, 0)` on EPERM) through safe
207    // `nix` wrappers — both are async-signal-safe POSIX calls that perform no
208    // allocation, no locking, and no mutable aliasing of process memory.
209    unsafe {
210        command.pre_exec(process_group::detach_from_tty);
211    }
212
213    #[cfg(not(unix))]
214    let _ = &opts.arg0;
215
216    command.current_dir(&opts.cwd);
217
218    // Handle environment
219    if let Some(ref env) = opts.env {
220        command.env_clear();
221        for (key, value) in env {
222            command.env(key, value);
223        }
224    }
225
226    #[cfg(unix)]
227    if let Some(owned) = &owned {
228        // Environment filtering remains authoritative; add only this private
229        // lifetime endpoint after applying the admitted command's environment.
230        command.env(crate::process_owner::OWNER_SOCKET_ENV, &owned.owner_socket);
231    } else {
232        command.args(&opts.args);
233    }
234    #[cfg(not(unix))]
235    command.args(&opts.args);
236
237    match opts.stdin_mode {
238        PipeStdinMode::Piped => {
239            command.stdin(Stdio::piped());
240        }
241        PipeStdinMode::Null => {
242            command.stdin(Stdio::null());
243        }
244    }
245    command.stdout(Stdio::piped());
246    command.stderr(Stdio::piped());
247
248    let mut child = command.spawn().context("failed to spawn pipe process")?;
249    let pid = child.id().ok_or_else(|| io::Error::other("missing child pid"))?;
250
251    #[cfg(unix)]
252    let process_group_id = pid;
253
254    let stdin = child.stdin.take();
255    let stdout = child.stdout.take();
256    let stderr = child.stderr.take();
257
258    let (writer_tx, mut writer_rx) = mpsc::channel::<Vec<u8>>(128);
259    let (output_tx, _) = broadcast::channel::<Bytes>(256);
260    let initial_output_rx = output_tx.subscribe();
261    let (reliable_output_tx, reliable_output_rx) = mpsc::channel::<Bytes>(RELIABLE_OUTPUT_CHANNEL_CAPACITY);
262    let reliable_output_enabled = opts.lossless_output;
263
264    // Spawn writer task
265    let writer_handle = if let Some(stdin) = stdin {
266        let writer = Arc::new(tokio::sync::Mutex::new(stdin));
267        tokio::spawn(async move {
268            while let Some(bytes) = writer_rx.recv().await {
269                let mut guard = writer.lock().await;
270                let _ = guard.write_all(&bytes).await;
271                let _ = guard.flush().await;
272            }
273        })
274    } else {
275        drop(writer_rx);
276        tokio::spawn(async {})
277    };
278
279    // Spawn reader tasks for stdout and stderr
280    let stdout_handle = stdout.map(|stdout| {
281        let output_tx = output_tx.clone();
282        let reliable_output_tx = opts.lossless_output.then(|| reliable_output_tx.clone());
283        tokio::spawn(async move {
284            read_output_stream(BufReader::new(stdout), output_tx, reliable_output_tx).await;
285        })
286    });
287
288    let stderr_handle = stderr.map(|stderr| {
289        let output_tx = output_tx.clone();
290        let reliable_output_tx = opts.lossless_output.then(|| reliable_output_tx.clone());
291        tokio::spawn(async move {
292            read_output_stream(BufReader::new(stderr), output_tx, reliable_output_tx).await;
293        })
294    });
295    drop(reliable_output_tx);
296
297    let mut reader_abort_handles = Vec::new();
298    if let Some(ref handle) = stdout_handle {
299        reader_abort_handles.push(handle.abort_handle());
300    }
301    if let Some(ref handle) = stderr_handle {
302        reader_abort_handles.push(handle.abort_handle());
303    }
304
305    let reader_handle = tokio::spawn(async move {
306        if let Some(handle) = stdout_handle {
307            let _ = handle.await;
308        }
309        if let Some(handle) = stderr_handle {
310            let _ = handle.await;
311        }
312    });
313
314    // Spawn wait task
315    let (exit_tx, exit_rx) = oneshot::channel::<i32>();
316    // One lock, one published snapshot: a reader that sees `has_exited()` is
317    // guaranteed to see the matching `exit_code()` on its next read.
318    let exit_state = Arc::new(StdMutex::new(ProcessExitState::default()));
319    let wait_exit_state = Arc::clone(&exit_state);
320
321    let wait_handle: JoinHandle<()> = tokio::spawn(async move {
322        let (code, observed) = match child.wait().await {
323            Ok(status) => (status.code().unwrap_or(-1), true),
324            Err(_) => (-1, false),
325        };
326        ProcessExitState::publish(&wait_exit_state, observed, code);
327        let _ = exit_tx.send(code);
328    });
329
330    let (handle, output_rx) = ProcessHandle::new(
331        writer_tx,
332        output_tx,
333        initial_output_rx,
334        Box::new(PipeChildTerminator {
335            #[cfg(windows)]
336            pid,
337            #[cfg(unix)]
338            process_group_id,
339        }),
340        reader_handle,
341        reader_abort_handles,
342        writer_handle,
343        wait_handle,
344        exit_state,
345        None,
346    );
347
348    Ok(SpawnedProcess {
349        session: handle,
350        process_id: pid,
351        output_rx,
352        reliable_output_rx,
353        reliable_output_enabled,
354        exit_rx,
355    })
356}
357
358/// Spawn a process using regular pipes (no PTY), returning handles for stdin, output, and exit.
359///
360/// Copies the borrowed arguments, environment, and optional `arg0` into owned
361/// spawn options. `arg0` overrides Unix `argv[0]`; other platforms ignore it.
362///
363/// # Errors
364/// Returns launch or pipe setup failures with process context.
365///
366/// # Example
367/// ```ignore
368/// use vtcode_bash_runner::pipe::spawn_process;
369/// use hashbrown::HashMap;
370/// use std::path::Path;
371///
372/// let env: HashMap<String, String> = std::env::vars().collect();
373/// let spawned = spawn_process("echo", &["hello".into()], Path::new("."), &env, None).await?;
374/// let output_rx = spawned.output_rx;
375/// let exit_code = spawned.exit_rx.await?;
376/// ```
377pub async fn spawn_process(
378    program: &str,
379    args: &[String],
380    cwd: &Path,
381    env: &HashMap<String, String>,
382    arg0: Option<&str>,
383) -> Result<SpawnedProcess> {
384    let opts = PipeSpawnOptions {
385        program: program.to_string(),
386        args: args.to_vec(),
387        cwd: cwd.to_path_buf(),
388        env: Some(env.clone()),
389        arg0: arg0.map(str::to_owned),
390        stdin_mode: PipeStdinMode::Piped,
391        lossless_output: false,
392    };
393    spawn_process_internal(opts).await
394}
395
396/// Spawn a process using regular pipes, but close stdin immediately.
397///
398/// This is useful for commands that should see EOF on stdin immediately.
399/// Borrowed inputs and Unix `arg0` have the same semantics as [`spawn_process`].
400///
401/// # Errors
402/// Returns launch or pipe setup failures with process context.
403pub async fn spawn_process_no_stdin(
404    program: &str,
405    args: &[String],
406    cwd: &Path,
407    env: &HashMap<String, String>,
408    arg0: Option<&str>,
409) -> Result<SpawnedProcess> {
410    let opts = PipeSpawnOptions {
411        program: program.to_string(),
412        args: args.to_vec(),
413        cwd: cwd.to_path_buf(),
414        env: Some(env.clone()),
415        arg0: arg0.map(str::to_owned),
416        stdin_mode: PipeStdinMode::Null,
417        lossless_output: false,
418    };
419    spawn_process_internal(opts).await
420}
421
422/// Spawn a process with full options control.
423pub async fn spawn_process_with_options(opts: PipeSpawnOptions) -> Result<SpawnedProcess> {
424    spawn_process_internal(opts).await
425}
426
427#[cfg(test)]
428mod tests {
429    use super::*;
430    use assert_fs::TempDir;
431
432    fn find_echo_command() -> Option<(String, Vec<String>)> {
433        #[cfg(windows)]
434        {
435            Some(("cmd.exe".to_string(), vec!["/C".to_string(), "echo".to_string()]))
436        }
437        #[cfg(not(windows))]
438        {
439            Some(("echo".to_string(), vec![]))
440        }
441    }
442
443    #[tokio::test]
444    async fn test_spawn_process_echo() -> Result<()> {
445        let Some((program, mut base_args)) = find_echo_command() else {
446            return Ok(());
447        };
448
449        base_args.push("hello".to_string());
450
451        let env: HashMap<String, String> = std::env::vars().collect();
452        let spawned = spawn_process(&program, &base_args, Path::new("."), &env, None).await?;
453
454        let exit_code = spawned.exit_rx.await.unwrap_or(-1);
455        assert_eq!(exit_code, 0);
456        assert!(spawned.session.has_observed_exit(), "successful wait records the direct-child exit");
457
458        Ok(())
459    }
460
461    /// Mirrors the exec-session consumer: gate on `has_exited()`, then read
462    /// `exit_code()`. With the former three-field publication there was a
463    /// window where the first was true and the second still `None`, so a
464    /// just-finished session could be reported as "still running".
465    #[tokio::test]
466    async fn exit_code_is_present_as_soon_as_has_exited_flips() -> Result<()> {
467        let Some((program, mut base_args)) = find_echo_command() else {
468            return Ok(());
469        };
470        base_args.push("hello".to_string());
471
472        let env: HashMap<String, String> = std::env::vars().collect();
473        let spawned = spawn_process(&program, &base_args, Path::new("."), &env, None).await?;
474
475        while !spawned.session.has_exited() {
476            tokio::time::sleep(std::time::Duration::from_millis(1)).await;
477        }
478        assert_eq!(spawned.session.exit_code(), Some(0));
479        assert_eq!(spawned.exit_rx.await.unwrap_or(-1), 0);
480        Ok(())
481    }
482
483    #[tokio::test]
484    async fn test_spawn_options_builder() {
485        let opts = PipeSpawnOptions::new("echo", ".")
486            .args(["hello", "world"])
487            .stdin_mode(PipeStdinMode::Null);
488
489        assert_eq!(opts.program, "echo");
490        assert_eq!(opts.args, vec!["hello", "world"]);
491        assert!(matches!(opts.stdin_mode, PipeStdinMode::Null));
492    }
493
494    #[cfg(unix)]
495    #[tokio::test]
496    async fn test_spawn_process_detaches_from_tty() {
497        let dir = TempDir::new().expect("tempdir");
498        let env: HashMap<String, String> = HashMap::new();
499
500        let spawned = spawn_process("sh", &["-c".into(), "echo ok".into()], dir.path(), &env, None)
501            .await
502            .expect("spawn");
503
504        let exit_code = spawned.exit_rx.await.unwrap_or(-1);
505        assert_eq!(exit_code, 0);
506    }
507}