cascade-environment 0.1.0-alpha.2

Execution-environment detection and planning contracts for Cascade.
Documentation
//! Injectable process execution edge for read-only environment probes.

use std::ffi::OsString;
use std::process::Command;
use std::process::Stdio;
use std::thread;
use std::time::{Duration, Instant};

use cascade_core::{CascadeError, CascadeResult};

use crate::ProbeOutput;

/// Executes one program with already-separated arguments.
pub trait EnvironmentCommandRunner {
    fn run(&self, program: &str, args: &[OsString]) -> CascadeResult<ProbeOutput>;
}

/// Standard-library runner used by real host and WSL detection backends.
#[derive(Debug, Clone, Copy, Default)]
pub struct ProcessEnvironmentCommandRunner;

impl EnvironmentCommandRunner for ProcessEnvironmentCommandRunner {
    fn run(&self, program: &str, args: &[OsString]) -> CascadeResult<ProbeOutput> {
        let output = Command::new(program)
            .args(args)
            .output()
            .map_err(|error| CascadeError::new(format!("failed to run `{program}`: {error}")))?;

        Ok(ProbeOutput {
            stdout: decode_process_output(&output.stdout),
            stderr: decode_process_output(&output.stderr),
            exit_code: output.status.code(),
        })
    }
}

/// Interactive runner for approved installation commands.
///
/// Standard streams are inherited so package managers and `sudo` can prompt
/// the user. Read-only detection must continue using
/// [`ProcessEnvironmentCommandRunner`] so probe output remains inspectable.
#[derive(Debug, Clone, Copy, Default)]
pub struct InteractiveEnvironmentCommandRunner;

impl EnvironmentCommandRunner for InteractiveEnvironmentCommandRunner {
    fn run(&self, program: &str, args: &[OsString]) -> CascadeResult<ProbeOutput> {
        let status = Command::new(program)
            .args(args)
            .stdin(Stdio::inherit())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .status()
            .map_err(|error| CascadeError::new(format!("failed to run `{program}`: {error}")))?;
        Ok(ProbeOutput {
            stdout: String::new(),
            stderr: String::new(),
            exit_code: status.code(),
        })
    }
}

/// Non-interactive runner with a hard per-command deadline.
///
/// Output is discarded to avoid pipe backpressure from package managers. This
/// runner is intended for protocol automation where terminal prompts are
/// forbidden and a bounded failure is preferable to an indefinitely blocked
/// MCP request.
#[derive(Debug, Clone, Copy)]
pub struct BoundedEnvironmentCommandRunner {
    pub timeout: Duration,
}

impl Default for BoundedEnvironmentCommandRunner {
    fn default() -> Self {
        Self {
            timeout: Duration::from_secs(15 * 60),
        }
    }
}

impl EnvironmentCommandRunner for BoundedEnvironmentCommandRunner {
    fn run(&self, program: &str, args: &[OsString]) -> CascadeResult<ProbeOutput> {
        let mut child = Command::new(program)
            .args(args)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .map_err(|error| CascadeError::new(format!("failed to run `{program}`: {error}")))?;
        let started = Instant::now();
        loop {
            if let Some(status) = child.try_wait().map_err(|error| {
                CascadeError::new(format!("failed to inspect `{program}` status: {error}"))
            })? {
                return Ok(ProbeOutput {
                    stdout: String::new(),
                    stderr: String::new(),
                    exit_code: status.code(),
                });
            }
            if started.elapsed() >= self.timeout {
                let _ = child.kill();
                let _ = child.wait();
                return Err(CascadeError::new(format!(
                    "command `{program}` exceeded the {} second remediation timeout and was terminated",
                    self.timeout.as_secs()
                )));
            }
            thread::sleep(Duration::from_millis(100));
        }
    }
}

/// Decodes UTF-8 output and the NUL-interleaved UTF-16LE commonly emitted by WSL.
fn decode_process_output(bytes: &[u8]) -> String {
    if bytes.len() >= 2 && bytes.chunks_exact(2).any(|pair| pair[1] == 0) {
        let utf16 = bytes
            .chunks_exact(2)
            .map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
            .collect::<Vec<_>>();
        return String::from_utf16_lossy(&utf16);
    }
    String::from_utf8_lossy(bytes).into_owned()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn decodes_utf8_and_utf16le_probe_output() {
        assert_eq!(decode_process_output(b"Ubuntu\n"), "Ubuntu\n");
        let utf16 = "Ubuntu\r\n"
            .encode_utf16()
            .flat_map(u16::to_le_bytes)
            .collect::<Vec<_>>();
        assert_eq!(decode_process_output(&utf16), "Ubuntu\r\n");
    }
}