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