agent-ssh 0.4.0

Arrange agent terminal layouts and reconnect through provider attachment plans
Documentation
use crate::attachment::{AttachmentResolution, CommandSpec};
use anyhow::{Context, Result, bail};
use std::{
    io::Read,
    process::{Command, Stdio},
    sync::mpsc,
    thread,
    time::{Duration, Instant},
};

#[derive(Clone, Copy, Debug)]
pub struct ResolverLimits {
    pub timeout: Duration,
    pub output_bytes: usize,
}
impl Default for ResolverLimits {
    fn default() -> Self {
        Self {
            timeout: Duration::from_secs(10),
            output_bytes: 1024 * 1024,
        }
    }
}

/// Run a trusted subprocess. Its stderr is deliberately not copied to reports.
/// Callers own effect semantics: a timeout cannot undo dispatched mutations.
/// Limits bound this direct child and its stdout, not arbitrary descendants.
pub fn resolve(spec: &CommandSpec, limits: ResolverLimits) -> Result<AttachmentResolution> {
    serde_json::from_slice(&output(spec, limits)?).context("invalid attachment resolution")
}

pub fn output(spec: &CommandSpec, limits: ResolverLimits) -> Result<Vec<u8>> {
    spec.validate()?;
    if limits.timeout.is_zero() || limits.output_bytes == 0 {
        bail!("resolver limits must be nonzero");
    }
    let mut command = Command::new(&spec.program);
    command
        .args(&spec.args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null());
    if let Some(cwd) = &spec.cwd {
        command.current_dir(cwd);
    }
    let mut child = command.spawn().context("could not start resolver")?;
    let stdout = child.stdout.take().context("resolver stdout unavailable")?;
    let (send, receive) = mpsc::channel();
    thread::spawn(move || {
        let mut bytes = Vec::new();
        let result = stdout
            .take(limits.output_bytes.saturating_add(1) as u64)
            .read_to_end(&mut bytes)
            .map(|_| bytes);
        let _ = send.send(result);
    });
    let deadline = Instant::now() + limits.timeout;
    let status = loop {
        if let Some(status) = child.try_wait()? {
            break status;
        }
        if Instant::now() >= deadline {
            let _ = child.kill();
            let _ = child.wait();
            bail!("resolver timed out");
        }
        thread::sleep(Duration::from_millis(10));
    };
    let bytes = receive
        .recv_timeout(deadline.saturating_duration_since(Instant::now()))
        .context("resolver output did not close before timeout")??;
    if bytes.len() > limits.output_bytes {
        bail!("resolver output exceeds limit");
    }
    if !status.success() {
        bail!("resolver exited unsuccessfully");
    }
    Ok(bytes)
}