1use hashbrown::HashMap;
2use std::ffi::OsString;
3use std::path::PathBuf;
4use std::pin::Pin;
5use std::time::{Duration, Instant};
6
7use anyhow::{Context, Result, anyhow};
8use std::process::{ExitStatus, Stdio};
9use tokio::io::AsyncReadExt;
10use tokio::process::{Child, Command};
11use tokio::time::{Sleep, sleep, timeout};
12use tokio_util::sync::{CancellationToken, WaitForCancellationFutureOwned};
13
14use crate::telemetry::perf;
15use crate::utils::gatekeeper;
16
17const DEFAULT_CAPTURE_LIMIT: usize = 256 * 1024; const POST_KILL_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);
32
33#[derive(Debug, Clone)]
35pub struct StreamCaptureConfig {
36 pub capture: bool,
38 pub max_bytes: usize,
40}
41
42impl Default for StreamCaptureConfig {
43 fn default() -> Self {
44 Self { capture: true, max_bytes: DEFAULT_CAPTURE_LIMIT }
45 }
46}
47
48#[derive(Debug, Clone, Default)]
50pub struct ProcessOptions {
51 pub program: String,
53 pub args: Vec<String>,
55 pub env: HashMap<OsString, OsString>,
57 pub current_dir: Option<PathBuf>,
59 pub timeout: Option<Duration>,
61 pub cancellation_token: Option<CancellationToken>,
63 pub stdout: StreamCaptureConfig,
65 pub stderr: StreamCaptureConfig,
67}
68
69#[derive(Debug)]
71pub struct ProcessOutput {
72 pub exit_status: ExitStatus,
74 pub stdout: Vec<u8>,
76 pub stderr: Vec<u8>,
78 pub timed_out: bool,
80 pub cancelled: bool,
82 pub duration: Duration,
84}
85
86pub struct AsyncProcessRunner;
88
89impl AsyncProcessRunner {
90 pub async fn run(options: ProcessOptions) -> Result<ProcessOutput> {
98 if options.program.is_empty() {
99 return Err(anyhow!("program cannot be empty"));
100 }
101
102 let mut tags = HashMap::new();
103 tags.insert("subsystem".to_string(), "async_command".to_string());
104 tags.insert("program".to_string(), options.program.clone());
105 perf::record_value("vtcode.perf.spawn_count", 1.0, tags);
106
107 gatekeeper::check_quarantine_for_program(&options.program);
108
109 let start = Instant::now();
110 let mut command = Command::new(&options.program);
111 command.args(&options.args);
112 if let Some(dir) = &options.current_dir {
113 command.current_dir(dir);
114 }
115 if !options.env.is_empty() {
116 command.envs(&options.env);
117 }
118 #[cfg(unix)]
121 command.process_group(0);
122 command.stdout(Stdio::piped());
123 command.stderr(Stdio::piped());
124
125 let mut child = command
126 .spawn()
127 .with_context(|| format!("failed to spawn '{}' with args {:?}", options.program, options.args))?;
128
129 let child_pid = child.id();
130 let stdout_handle = child.stdout.take();
131 let stderr_handle = child.stderr.take();
132
133 let mut stdout_future = Box::pin(read_stream(stdout_handle, options.stdout));
134 let mut stderr_future = Box::pin(read_stream(stderr_handle, options.stderr));
135 let mut timeout_future = options.timeout.map(|dur| Box::pin(sleep(dur)) as Pin<Box<Sleep>>);
136 let mut cancellation_future = options
137 .cancellation_token
138 .as_ref()
139 .map(|token| Box::pin(token.clone().cancelled_owned()) as Pin<Box<WaitForCancellationFutureOwned>>);
140
141 #[derive(Clone, Copy, PartialEq, Eq)]
142 enum Completion {
143 Finished,
144 TimedOut,
145 Cancelled,
146 }
147
148 let mut exit_status: Option<ExitStatus> = None;
149 let mut stdout_result: Option<Result<Vec<u8>>> = None;
150 let mut stderr_result: Option<Result<Vec<u8>>> = None;
151
152 let completion = loop {
153 tokio::select! {
154 res = child.wait(), if exit_status.is_none() => {
155 exit_status = Some(res?);
156 }
158 res = &mut stdout_future, if stdout_result.is_none() => {
159 stdout_result = Some(res);
160 }
161 res = &mut stderr_future, if stderr_result.is_none() => {
162 stderr_result = Some(res);
163 }
164 _ = async {
165 if let Some(fut) = timeout_future.as_mut() {
166 fut.as_mut().await;
167 } else {
168 futures::future::pending::<()>().await;
169 }
170 }, if timeout_future.is_some() => {
171 break Completion::TimedOut;
172 }
173 _ = async {
174 if let Some(fut) = cancellation_future.as_mut() {
175 fut.as_mut().await;
176 } else {
177 futures::future::pending::<()>().await;
178 }
179 }, if cancellation_future.is_some() => {
180 break Completion::Cancelled;
181 }
182 }
183
184 if exit_status.is_some() && stdout_result.is_some() && stderr_result.is_some() {
186 break Completion::Finished;
187 }
188 };
189
190 let bounded_drain = matches!(completion, Completion::TimedOut | Completion::Cancelled);
196
197 let (timed_out, cancelled, status) = match completion {
198 Completion::Finished => {
199 let status = match exit_status {
200 Some(status) => status,
201 None => child.wait().await?,
202 };
203 (false, false, status)
204 }
205 Completion::TimedOut => {
206 if exit_status.is_none() {
210 kill_child_process_group(child_pid, &mut child)
211 .await
212 .with_context(|| format!("failed to kill timed-out process '{}'", options.program))?;
213 }
214 let status = match exit_status {
215 Some(status) => status,
216 None => match timeout(POST_KILL_DRAIN_TIMEOUT, child.wait()).await {
217 Ok(res) => res?,
218 Err(_) => {
219 return Err(anyhow!(
220 "process timed out and was killed, but could not be reaped within {POST_KILL_DRAIN_TIMEOUT:?}"
221 ));
222 }
223 },
224 };
225 (true, false, status)
226 }
227 Completion::Cancelled => {
228 if exit_status.is_none() {
230 kill_child_process_group(child_pid, &mut child)
231 .await
232 .with_context(|| format!("failed to kill cancelled process '{}'", options.program))?;
233 }
234 let status = match exit_status {
235 Some(status) => status,
236 None => match timeout(POST_KILL_DRAIN_TIMEOUT, child.wait()).await {
237 Ok(res) => res?,
238 Err(_) => {
239 return Err(anyhow!(
240 "process was cancelled and killed, but could not be reaped within {POST_KILL_DRAIN_TIMEOUT:?}"
241 ));
242 }
243 },
244 };
245 (false, true, status)
246 }
247 };
248
249 let stdout = match stdout_result {
254 Some(Ok(data)) => data,
255 Some(Err(e)) => return Err(e),
256 None if bounded_drain => match timeout(POST_KILL_DRAIN_TIMEOUT, stdout_future.as_mut()).await {
257 Ok(res) => res?,
258 Err(_) => Vec::new(),
259 },
260 None => stdout_future.await?,
261 };
262 let stderr = match stderr_result {
263 Some(Ok(data)) => data,
264 Some(Err(e)) => return Err(e),
265 None if bounded_drain => match timeout(POST_KILL_DRAIN_TIMEOUT, stderr_future.as_mut()).await {
266 Ok(res) => res?,
267 Err(_) => Vec::new(),
268 },
269 None => stderr_future.await?,
270 };
271
272 Ok(ProcessOutput {
273 exit_status: status,
274 stdout,
275 stderr,
276 timed_out,
277 cancelled,
278 duration: start.elapsed(),
279 })
280 }
281}
282
283async fn read_stream<R>(reader: Option<R>, config: StreamCaptureConfig) -> Result<Vec<u8>>
284where
285 R: tokio::io::AsyncRead + Unpin,
286{
287 if !config.capture {
288 return Ok(Vec::new());
289 }
290
291 let mut reader = match reader {
292 Some(r) => r,
293 None => return Ok(Vec::new()),
294 };
295
296 let mut output = Vec::new();
297 let reserve_cap = config.max_bytes.min(DEFAULT_CAPTURE_LIMIT);
302 if reserve_cap > 0 {
303 output.reserve(reserve_cap);
304 }
305
306 let mut buffer = [0u8; 4096];
307 loop {
308 let read = reader.read(&mut buffer).await?;
309 if read == 0 {
310 break;
311 }
312 let remaining = config.max_bytes.saturating_sub(output.len());
313 if remaining > 0 {
314 let to_copy = remaining.min(read);
315 output.extend_from_slice(&buffer[..to_copy]);
316 }
317 }
318
319 Ok(output)
320}
321
322async fn kill_child_process_group(child_pid: Option<u32>, child: &mut Child) -> Result<()> {
330 #[cfg(unix)]
331 if let Some(pid) = child_pid {
332 return vtcode_bash_runner::process_group::kill_process_group_by_pid(pid)
333 .context("failed to kill process group");
334 }
335 let _ = child_pid;
336 child.kill().await.context("failed to kill child process")
337}
338
339#[cfg(test)]
340mod tests {
341 use super::*;
342
343 #[tokio::test]
348 async fn run_returns_promptly_after_timeout_kill() {
349 let options = ProcessOptions {
350 program: "sleep".to_string(),
351 args: vec!["30".to_string()],
352 timeout: Some(Duration::from_millis(100)),
353 ..Default::default()
354 };
355
356 let outcome = timeout(Duration::from_secs(10), AsyncProcessRunner::run(options))
357 .await
358 .expect("run() must return well within the outer bound instead of hanging")
359 .expect("timed-out run should still yield a ProcessOutput, not an error");
360
361 assert!(outcome.timed_out, "expected timed_out to be true");
362 assert!(!outcome.cancelled, "cancelled must remain false on timeout");
363 }
364
365 #[tokio::test]
369 async fn run_returns_promptly_after_cancellation_kill() {
370 let token = CancellationToken::new();
371 let cancel_token = token.clone();
372 tokio::spawn(async move {
373 sleep(Duration::from_millis(100)).await;
374 cancel_token.cancel();
375 });
376
377 let options = ProcessOptions {
378 program: "sleep".to_string(),
379 args: vec!["30".to_string()],
380 cancellation_token: Some(token),
381 ..Default::default()
382 };
383
384 let outcome = timeout(Duration::from_secs(10), AsyncProcessRunner::run(options))
385 .await
386 .expect("run() must return well within the outer bound instead of hanging")
387 .expect("cancelled run should still yield a ProcessOutput, not an error");
388
389 assert!(outcome.cancelled, "expected cancelled to be true");
390 assert!(!outcome.timed_out, "timed_out must remain false on cancellation");
391 }
392
393 #[tokio::test]
400 async fn run_bounds_drain_when_grandchild_holds_pipe_open() {
401 let options = ProcessOptions {
402 program: "sh".to_string(),
403 args: vec![
404 "-c".to_string(),
405 "sleep 30 & exit 0".to_string(),
409 ],
410 timeout: Some(Duration::from_millis(100)),
411 ..Default::default()
412 };
413
414 let outcome = timeout(Duration::from_secs(10), AsyncProcessRunner::run(options))
415 .await
416 .expect("run() must return well within the outer bound instead of hanging")
417 .expect("run should still yield a ProcessOutput even with a surviving grandchild");
418
419 assert!(outcome.timed_out, "expected timed_out to be true");
420 }
421}