Skip to main content

rinne_workers/transport/
subprocess.rs

1//! The `subprocess-json` transport (`CONTEXT.md` §8, §14).
2//!
3//! Spawns a harness CLI with piped stdio, streams its stdout lines to the event
4//! sink as they arrive, captures the full output for the adapter to parse, and
5//! enforces a timeout plus cancellation. Adapters build a [`SubprocessSpec`],
6//! call [`run`], then map the captured stdout into an `ExecuteResult`.
7
8use std::path::PathBuf;
9use std::process::Stdio;
10use std::time::{Duration, Instant};
11
12use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
13use tokio::process::Command;
14use tokio_util::sync::CancellationToken;
15
16use rinne_core::worker::{emit, EventSink, ExecStatus, WorkerEvent};
17use rinne_core::{Result, RinneError};
18
19/// Cap on captured stdout/stderr so a chatty or runaway CLI can't OOM Rinne. The
20/// subprocess boundary is exactly where a byte ceiling belongs; live events are
21/// still streamed past the cap, only the retained buffer is bounded.
22const MAX_CAPTURE_BYTES: usize = 8 * 1024 * 1024;
23
24/// How to invoke a subprocess worker.
25pub struct SubprocessSpec {
26    pub program: String,
27    pub args: Vec<String>,
28    /// Working directory — the repo the worker operates in.
29    pub workspace: PathBuf,
30    /// Optional text piped to the child's stdin (some CLIs take the prompt this
31    /// way); `None` closes stdin.
32    pub stdin: Option<String>,
33    /// Hard wall-clock timeout. Always set one for beta CLIs (`CONTEXT.md` §21).
34    pub timeout: Option<Duration>,
35    /// Extra environment variables set on the child, on top of the inherited
36    /// environment. Carries MCP provisioning tokens so they reach a harness's
37    /// servers without ever being written to a config file (`MCP_SKILLS.md` §6).
38    pub env: Vec<(String, String)>,
39}
40
41/// The captured result of a subprocess run.
42pub struct SubprocessOutput {
43    pub stdout: String,
44    pub stderr: String,
45    pub exit_code: Option<i32>,
46    pub status: ExecStatus,
47    pub wall_ms: u64,
48}
49
50/// Map a raw stdout line to zero or more streamed events. Adapters pass their
51/// own mapper to turn structured (e.g. NDJSON) output into rich live events; a
52/// single line may expand to several events (text + tool uses).
53pub type LineMapper = fn(&str) -> Vec<WorkerEvent>;
54
55/// Run a subprocess, streaming stdout lines via `mapper` and capturing output.
56pub async fn run(
57    spec: SubprocessSpec,
58    events: &EventSink,
59    cancel: &CancellationToken,
60    mapper: LineMapper,
61) -> Result<SubprocessOutput> {
62    let started = Instant::now();
63
64    let mut cmd = Command::new(&spec.program);
65    cmd.args(&spec.args)
66        .envs(spec.env.iter().map(|(k, v)| (k.clone(), v.clone())))
67        .current_dir(&spec.workspace)
68        .stdin(if spec.stdin.is_some() {
69            Stdio::piped()
70        } else {
71            Stdio::null()
72        })
73        .stdout(Stdio::piped())
74        .stderr(Stdio::piped())
75        .kill_on_drop(true);
76
77    let mut child = cmd
78        .spawn()
79        .map_err(|e| RinneError::Worker(format!("failed to spawn {}: {e}", spec.program)))?;
80
81    if let Some(input) = &spec.stdin {
82        if let Some(mut stdin) = child.stdin.take() {
83            stdin
84                .write_all(input.as_bytes())
85                .await
86                .map_err(|e| RinneError::Worker(format!("stdin write failed: {e}")))?;
87            // Drop closes the pipe so the child sees EOF.
88        }
89    }
90
91    let stdout = child
92        .stdout
93        .take()
94        .ok_or_else(|| RinneError::Worker("no stdout pipe".into()))?;
95    let stderr = child
96        .stderr
97        .take()
98        .ok_or_else(|| RinneError::Worker("no stderr pipe".into()))?;
99
100    // Drain stderr concurrently so a chatty child can't deadlock on a full pipe,
101    // bounded so it can't grow without limit.
102    let stderr_task = tokio::spawn(async move {
103        let mut buf = Vec::new();
104        let mut rdr = BufReader::new(stderr).take(MAX_CAPTURE_BYTES as u64);
105        let _ = rdr.read_to_end(&mut buf).await;
106        String::from_utf8_lossy(&buf).into_owned()
107    });
108
109    let mut lines = BufReader::new(stdout).lines();
110    let mut captured = String::new();
111    let mut truncated = false;
112
113    // A far-future deadline stands in when no timeout is configured, so the
114    // select arm is always well-formed.
115    let deadline = spec
116        .timeout
117        .map(|d| Instant::now() + d)
118        .unwrap_or_else(|| Instant::now() + Duration::from_secs(60 * 60 * 24 * 365));
119    let sleep = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline));
120    tokio::pin!(sleep);
121
122    let mut terminal: Option<ExecStatus> = None;
123
124    loop {
125        tokio::select! {
126            line = lines.next_line() => {
127                match line {
128                    Ok(Some(l)) => {
129                        // Always stream live events; only bound the retained buffer.
130                        if captured.len() < MAX_CAPTURE_BYTES {
131                            captured.push_str(&l);
132                            captured.push('\n');
133                        } else if !truncated {
134                            truncated = true;
135                            captured.push_str("\n…[output truncated]\n");
136                        }
137                        for ev in mapper(&l) {
138                            emit(events, ev);
139                        }
140                    }
141                    Ok(None) => break, // EOF: process closed stdout
142                    Err(e) => {
143                        terminal = Some(ExecStatus::Failed(format!("stdout read error: {e}")));
144                        break;
145                    }
146                }
147            }
148            _ = cancel.cancelled() => {
149                let _ = child.start_kill();
150                terminal = Some(ExecStatus::Cancelled);
151                break;
152            }
153            _ = &mut sleep => {
154                let _ = child.start_kill();
155                terminal = Some(ExecStatus::TimedOut);
156                break;
157            }
158        }
159    }
160
161    // Bound the reap: a child that closed stdout but won't exit (daemonized, or a
162    // grandchild holding the pipe) must not hang past a short grace period and
163    // defeat the timeout above. On expiry, kill and reap.
164    let wait_status = match tokio::time::timeout(Duration::from_secs(5), child.wait()).await {
165        Ok(r) => r.map_err(|e| RinneError::Worker(format!("wait failed: {e}")))?,
166        Err(_) => {
167            let _ = child.start_kill();
168            child
169                .wait()
170                .await
171                .map_err(|e| RinneError::Worker(format!("wait failed: {e}")))?
172        }
173    };
174    // The stderr drain finishes once the (now-dead) child's pipe hits EOF; bound
175    // it too so a lingering pipe can't stall the return.
176    let stderr_str = tokio::time::timeout(Duration::from_secs(2), stderr_task)
177        .await
178        .ok()
179        .and_then(|r| r.ok())
180        .unwrap_or_default();
181    let exit_code = wait_status.code();
182
183    let status = terminal.unwrap_or_else(|| {
184        if wait_status.success() {
185            ExecStatus::Success
186        } else {
187            let code = exit_code
188                .map(|c| c.to_string())
189                .unwrap_or_else(|| "signal".into());
190            ExecStatus::Failed(format!("exited {code}"))
191        }
192    });
193
194    emit(events, WorkerEvent::Done);
195
196    Ok(SubprocessOutput {
197        stdout: captured,
198        stderr: stderr_str,
199        exit_code,
200        status,
201        wall_ms: started.elapsed().as_millis() as u64,
202    })
203}
204
205/// The default line mapper: surface each non-empty line raw to the stream pane.
206pub fn raw_lines(line: &str) -> Vec<WorkerEvent> {
207    if line.trim().is_empty() {
208        Vec::new()
209    } else {
210        vec![WorkerEvent::Raw(line.to_string())]
211    }
212}