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/// How to invoke a subprocess worker.
20pub struct SubprocessSpec {
21    pub program: String,
22    pub args: Vec<String>,
23    /// Working directory — the repo the worker operates in.
24    pub workspace: PathBuf,
25    /// Optional text piped to the child's stdin (some CLIs take the prompt this
26    /// way); `None` closes stdin.
27    pub stdin: Option<String>,
28    /// Hard wall-clock timeout. Always set one for beta CLIs (`CONTEXT.md` §21).
29    pub timeout: Option<Duration>,
30}
31
32/// The captured result of a subprocess run.
33pub struct SubprocessOutput {
34    pub stdout: String,
35    pub stderr: String,
36    pub exit_code: Option<i32>,
37    pub status: ExecStatus,
38    pub wall_ms: u64,
39}
40
41/// Map a raw stdout line to zero or more streamed events. Adapters pass their
42/// own mapper to turn structured (e.g. NDJSON) output into rich live events; a
43/// single line may expand to several events (text + tool uses).
44pub type LineMapper = fn(&str) -> Vec<WorkerEvent>;
45
46/// Run a subprocess, streaming stdout lines via `mapper` and capturing output.
47pub async fn run(
48    spec: SubprocessSpec,
49    events: &EventSink,
50    cancel: &CancellationToken,
51    mapper: LineMapper,
52) -> Result<SubprocessOutput> {
53    let started = Instant::now();
54
55    let mut cmd = Command::new(&spec.program);
56    cmd.args(&spec.args)
57        .current_dir(&spec.workspace)
58        .stdin(if spec.stdin.is_some() {
59            Stdio::piped()
60        } else {
61            Stdio::null()
62        })
63        .stdout(Stdio::piped())
64        .stderr(Stdio::piped())
65        .kill_on_drop(true);
66
67    let mut child = cmd
68        .spawn()
69        .map_err(|e| RinneError::Worker(format!("failed to spawn {}: {e}", spec.program)))?;
70
71    if let Some(input) = &spec.stdin {
72        if let Some(mut stdin) = child.stdin.take() {
73            stdin
74                .write_all(input.as_bytes())
75                .await
76                .map_err(|e| RinneError::Worker(format!("stdin write failed: {e}")))?;
77            // Drop closes the pipe so the child sees EOF.
78        }
79    }
80
81    let stdout = child
82        .stdout
83        .take()
84        .ok_or_else(|| RinneError::Worker("no stdout pipe".into()))?;
85    let stderr = child
86        .stderr
87        .take()
88        .ok_or_else(|| RinneError::Worker("no stderr pipe".into()))?;
89
90    // Drain stderr concurrently so a chatty child can't deadlock on a full pipe.
91    let stderr_task = tokio::spawn(async move {
92        let mut buf = String::new();
93        let mut rdr = BufReader::new(stderr);
94        let _ = rdr.read_to_string(&mut buf).await;
95        buf
96    });
97
98    let mut lines = BufReader::new(stdout).lines();
99    let mut captured = String::new();
100
101    // A far-future deadline stands in when no timeout is configured, so the
102    // select arm is always well-formed.
103    let deadline = spec
104        .timeout
105        .map(|d| Instant::now() + d)
106        .unwrap_or_else(|| Instant::now() + Duration::from_secs(60 * 60 * 24 * 365));
107    let sleep = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline));
108    tokio::pin!(sleep);
109
110    let mut terminal: Option<ExecStatus> = None;
111
112    loop {
113        tokio::select! {
114            line = lines.next_line() => {
115                match line {
116                    Ok(Some(l)) => {
117                        captured.push_str(&l);
118                        captured.push('\n');
119                        for ev in mapper(&l) {
120                            emit(events, ev);
121                        }
122                    }
123                    Ok(None) => break, // EOF: process closed stdout
124                    Err(e) => {
125                        terminal = Some(ExecStatus::Failed(format!("stdout read error: {e}")));
126                        break;
127                    }
128                }
129            }
130            _ = cancel.cancelled() => {
131                let _ = child.start_kill();
132                terminal = Some(ExecStatus::Cancelled);
133                break;
134            }
135            _ = &mut sleep => {
136                let _ = child.start_kill();
137                terminal = Some(ExecStatus::TimedOut);
138                break;
139            }
140        }
141    }
142
143    let wait_status = child
144        .wait()
145        .await
146        .map_err(|e| RinneError::Worker(format!("wait failed: {e}")))?;
147    let stderr_str = stderr_task.await.unwrap_or_default();
148    let exit_code = wait_status.code();
149
150    let status = terminal.unwrap_or_else(|| {
151        if wait_status.success() {
152            ExecStatus::Success
153        } else {
154            let code = exit_code
155                .map(|c| c.to_string())
156                .unwrap_or_else(|| "signal".into());
157            ExecStatus::Failed(format!("exited {code}"))
158        }
159    });
160
161    emit(events, WorkerEvent::Done);
162
163    Ok(SubprocessOutput {
164        stdout: captured,
165        stderr: stderr_str,
166        exit_code,
167        status,
168        wall_ms: started.elapsed().as_millis() as u64,
169    })
170}
171
172/// The default line mapper: surface each non-empty line raw to the stream pane.
173pub fn raw_lines(line: &str) -> Vec<WorkerEvent> {
174    if line.trim().is_empty() {
175        Vec::new()
176    } else {
177        vec![WorkerEvent::Raw(line.to_string())]
178    }
179}