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, read-only provider. Its stderr is deliberately not copied to reports.
26/// Limits bound this direct child and its stdout, not arbitrary descendants.
27pub fn resolve(spec: &CommandSpec, limits: ResolverLimits) -> Result<AttachmentResolution> {
28    serde_json::from_slice(&output(spec, limits)?).context("invalid attachment resolution")
29}
30
31pub fn output(spec: &CommandSpec, limits: ResolverLimits) -> Result<Vec<u8>> {
32    spec.validate()?;
33    if limits.timeout.is_zero() || limits.output_bytes == 0 {
34        bail!("resolver limits must be nonzero");
35    }
36    let mut command = Command::new(&spec.program);
37    command
38        .args(&spec.args)
39        .stdin(Stdio::null())
40        .stdout(Stdio::piped())
41        .stderr(Stdio::null());
42    if let Some(cwd) = &spec.cwd {
43        command.current_dir(cwd);
44    }
45    let mut child = command.spawn().context("could not start resolver")?;
46    let stdout = child.stdout.take().context("resolver stdout unavailable")?;
47    let (send, receive) = mpsc::channel();
48    thread::spawn(move || {
49        let mut bytes = Vec::new();
50        let result = stdout
51            .take(limits.output_bytes.saturating_add(1) as u64)
52            .read_to_end(&mut bytes)
53            .map(|_| bytes);
54        let _ = send.send(result);
55    });
56    let deadline = Instant::now() + limits.timeout;
57    let status = loop {
58        if let Some(status) = child.try_wait()? {
59            break status;
60        }
61        if Instant::now() >= deadline {
62            let _ = child.kill();
63            let _ = child.wait();
64            bail!("resolver timed out");
65        }
66        thread::sleep(Duration::from_millis(10));
67    };
68    let bytes = receive
69        .recv_timeout(deadline.saturating_duration_since(Instant::now()))
70        .context("resolver output did not close before timeout")??;
71    if bytes.len() > limits.output_bytes {
72        bail!("resolver output exceeds limit");
73    }
74    if !status.success() {
75        bail!("resolver exited unsuccessfully");
76    }
77    Ok(bytes)
78}