use anyhow::Result;
use std::process::{Command, Stdio};
const CLAUDE_NESTING_ENV_VARS: &[&str] = &["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT"];
pub async fn execute_command(
cmd: &str,
args: &[&str],
input: &str,
timeout: u64,
) -> Result<String> {
let mut command = tokio::process::Command::new(cmd);
command.args(args);
command.stdin(Stdio::piped());
command.stdout(Stdio::piped());
command.stderr(Stdio::piped());
for var in CLAUDE_NESTING_ENV_VARS {
command.env_remove(var);
}
#[cfg(unix)]
unsafe {
command.pre_exec(|| {
libc::setsid();
Ok(())
});
}
let mut child = command.spawn()?;
let pid = child.id();
let mut stdin = child
.stdin
.take()
.ok_or_else(|| anyhow::anyhow!("Failed to open command stdin"))?;
let input = input.as_bytes().to_vec();
let execution = async move {
use tokio::io::AsyncWriteExt;
let write_input = async move {
stdin.write_all(&input).await?;
stdin.shutdown().await
};
let ((), output) = tokio::try_join!(write_input, child.wait_with_output())?;
Ok::<std::process::Output, std::io::Error>(output)
};
let timeout_duration = std::time::Duration::from_secs(timeout);
tokio::select! {
result = execution => {
match result {
Ok(output) => {
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
if output.status.success() {
Ok(stdout)
} else {
Err(anyhow::anyhow!("Command failed: {}", stderr))
}
}
Err(e) => Err(e.into()),
}
}
_ = tokio::time::sleep(timeout_duration) => {
if let Some(child_pid) = pid {
#[cfg(unix)]
{
let pgid = -(child_pid as i32);
unsafe {
libc::kill(pgid, libc::SIGTERM);
std::thread::sleep(std::time::Duration::from_millis(100));
libc::kill(pgid, libc::SIGKILL);
}
}
#[cfg(windows)]
{
let _ = child_pid;
}
}
Err(anyhow::anyhow!("Command timed out after {} seconds", timeout))
}
}
}
pub fn command_exists(cmd: &str) -> bool {
Command::new("which")
.arg(cmd)
.output()
.ok()
.is_some_and(|o| o.status.success())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_execute_command_basic() {
let result = execute_command("echo", &["hello world"], "", 5).await;
assert!(result.is_ok());
assert_eq!(result.unwrap().trim(), "hello world");
}
#[tokio::test]
async fn test_execute_command_timeout() {
let result = execute_command("sleep", &["30"], "", 1).await;
assert!(result.is_err());
let err = result.unwrap_err().to_string();
assert!(
err.contains("timed out"),
"expected timeout error, got: {err}"
);
}
#[tokio::test]
async fn test_claude_env_vars_not_inherited() {
std::env::set_var("CLAUDECODE", "1");
std::env::set_var("CLAUDE_CODE_ENTRYPOINT", "cli");
let result = execute_command("env", &[], "", 5).await;
assert!(result.is_ok());
let output = result.unwrap();
for line in output.lines() {
assert!(
!line.starts_with("CLAUDECODE="),
"CLAUDECODE should be stripped from child env"
);
assert!(
!line.starts_with("CLAUDE_CODE_ENTRYPOINT="),
"CLAUDE_CODE_ENTRYPOINT should be stripped from child env"
);
}
std::env::remove_var("CLAUDECODE");
std::env::remove_var("CLAUDE_CODE_ENTRYPOINT");
}
}