Skip to main content

agent_ssh/
resolver.rs

1use crate::attachment::{AttachmentResolution, CommandSpec};
2use anyhow::{Context, Result, bail};
3use std::{
4    io::Read,
5    process::{Command, Stdio},
6    sync::mpsc,
7    thread,
8    time::{Duration, Instant},
9};
10
11#[derive(Clone, Copy, Debug)]
12pub struct ResolverLimits {
13    pub timeout: Duration,
14    pub output_bytes: usize,
15}
16impl Default for ResolverLimits {
17    fn default() -> Self {
18        Self {
19            timeout: Duration::from_secs(10),
20            output_bytes: 1024 * 1024,
21        }
22    }
23}
24
25/// Run a trusted subprocess. Its stderr is deliberately not copied to reports.
26/// Callers own effect semantics: a timeout cannot undo dispatched mutations.
27/// Limits bound this direct child and its stdout, not arbitrary descendants.
28pub fn resolve(spec: &CommandSpec, limits: ResolverLimits) -> Result<AttachmentResolution> {
29    serde_json::from_slice(&output(spec, limits)?).context("invalid attachment resolution")
30}
31
32pub fn output(spec: &CommandSpec, limits: ResolverLimits) -> Result<Vec<u8>> {
33    spec.validate()?;
34    if limits.timeout.is_zero() || limits.output_bytes == 0 {
35        bail!("resolver limits must be nonzero");
36    }
37    let mut command = Command::new(&spec.program);
38    command
39        .args(&spec.args)
40        .stdin(Stdio::null())
41        .stdout(Stdio::piped())
42        .stderr(Stdio::null());
43    if let Some(cwd) = &spec.cwd {
44        command.current_dir(cwd);
45    }
46    let mut child = command.spawn().context("could not start resolver")?;
47    let stdout = child.stdout.take().context("resolver stdout unavailable")?;
48    let (send, receive) = mpsc::channel();
49    thread::spawn(move || {
50        let mut bytes = Vec::new();
51        let result = stdout
52            .take(limits.output_bytes.saturating_add(1) as u64)
53            .read_to_end(&mut bytes)
54            .map(|_| bytes);
55        let _ = send.send(result);
56    });
57    let deadline = Instant::now() + limits.timeout;
58    let status = loop {
59        if let Some(status) = child.try_wait()? {
60            break status;
61        }
62        if Instant::now() >= deadline {
63            let _ = child.kill();
64            let _ = child.wait();
65            bail!("resolver timed out");
66        }
67        thread::sleep(Duration::from_millis(10));
68    };
69    let bytes = receive
70        .recv_timeout(deadline.saturating_duration_since(Instant::now()))
71        .context("resolver output did not close before timeout")??;
72    if bytes.len() > limits.output_bytes {
73        bail!("resolver output exceeds limit");
74    }
75    if !status.success() {
76        bail!("resolver exited unsuccessfully");
77    }
78    Ok(bytes)
79}