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