Skip to main content

rinne_workers/adapters/
common.rs

1//! Shared machinery for harness adapters (`CONTEXT.md` §8).
2//!
3//! A harness worker is an autonomous agent: it gets a chunky self-contained
4//! prompt and reads/edits the repo itself, so context is passed as a prompt plus
5//! *pinned file paths*, never inlined contents (`CONTEXT.md` §8 behavioral
6//! split, §12 context assembler).
7
8use std::time::Duration;
9
10use async_trait::async_trait;
11use tokio_util::sync::CancellationToken;
12
13use rinne_core::worker::{
14    emit, EventSink, ExecStatus, ExecuteRequest, ExecuteResult, Role, Usage, Worker,
15    WorkerDescriptor, WorkerEvent,
16};
17use rinne_core::Result;
18
19use crate::transport::subprocess::{self, LineMapper, SubprocessOutput, SubprocessSpec};
20
21/// What an adapter extracts from a harness CLI's raw output. Parsers should be
22/// defensive: on any doubt, fall back to the raw stdout as the result text so a
23/// schema change in a beta CLI degrades gracefully (`CONTEXT.md` §21).
24pub struct ParsedHarness {
25    pub result: String,
26    pub session_id: Option<String>,
27    pub usage: Usage,
28    /// The CLI signalled an error in its structured output, even if it exited 0.
29    pub is_error: bool,
30}
31
32impl ParsedHarness {
33    /// The trivial parse: use raw stdout, no session, no usage.
34    pub fn raw(stdout: &str) -> Self {
35        Self {
36            result: stdout.trim().to_string(),
37            session_id: None,
38            usage: Usage::default(),
39            is_error: false,
40        }
41    }
42}
43
44/// Build the argv for a harness invocation given the composed prompt and an
45/// optional model selection.
46pub type ArgsBuilder = fn(prompt: &str, model: Option<&str>) -> Vec<String>;
47
48/// Defensive parser for harnesses that emit a single JSON result object: probe
49/// common result fields, falling back to raw stdout on any surprise
50/// (`CONTEXT.md` §21). Suitable for not-yet-pinned beta CLIs.
51pub fn parse_generic_json(out: &SubprocessOutput) -> ParsedHarness {
52    let pick = |v: &serde_json::Value| {
53        v.get("result")
54            .or_else(|| v.get("text"))
55            .or_else(|| v.get("message"))
56            .or_else(|| v.get("content"))
57            .or_else(|| v.get("response"))
58            .and_then(|x| x.as_str())
59            .map(String::from)
60    };
61    for line in out.stdout.lines().rev() {
62        let line = line.trim();
63        if !line.starts_with('{') {
64            continue;
65        }
66        if let Ok(v) = serde_json::from_str::<serde_json::Value>(line) {
67            if let Some(result) = pick(&v) {
68                let session_id = v
69                    .get("session_id")
70                    .or_else(|| v.get("sessionId"))
71                    .and_then(|x| x.as_str())
72                    .map(String::from);
73                let is_error = v.get("is_error").and_then(|b| b.as_bool()).unwrap_or(false);
74                return ParsedHarness {
75                    result,
76                    session_id,
77                    usage: Usage::default(),
78                    is_error,
79                };
80            }
81        }
82    }
83    ParsedHarness::raw(&out.stdout)
84}
85
86/// The trivial parser: the captured stdout is the result (for CLIs that print
87/// plain text, e.g. Aider).
88pub fn parse_raw(out: &SubprocessOutput) -> ParsedHarness {
89    ParsedHarness::raw(&out.stdout)
90}
91/// Parse a harness CLI's captured output into normalized fields.
92pub type OutputParser = fn(out: &SubprocessOutput) -> ParsedHarness;
93
94/// A generic harness worker driven over the `subprocess-json` transport. Each
95/// concrete CLI supplies its program name, argv builder, output parser, and an
96/// optional line mapper for richer streaming.
97pub struct HarnessAdapter {
98    pub descriptor: WorkerDescriptor,
99    pub program: String,
100    pub build_args: ArgsBuilder,
101    /// Lean argv used when the harness runs as the **planner** (`Role::Planner`):
102    /// a plain-text completion, not the agentic/streaming work invocation. When
103    /// set, planning reads the full stdout as the answer (more robust across CLI
104    /// versions than parsing a streaming format). `None` → planning reuses
105    /// `build_args` and the normal parser unchanged.
106    pub plan_args: Option<ArgsBuilder>,
107    pub parse: OutputParser,
108    pub line_mapper: LineMapper,
109    /// Whether the prompt is piped via stdin (vs. passed as an argument).
110    pub prompt_via_stdin: bool,
111    pub default_timeout: Duration,
112}
113
114#[async_trait]
115impl Worker for HarnessAdapter {
116    fn descriptor(&self) -> &WorkerDescriptor {
117        &self.descriptor
118    }
119
120    async fn execute(
121        &self,
122        request: ExecuteRequest,
123        events: EventSink,
124        cancel: CancellationToken,
125    ) -> Result<ExecuteResult> {
126        let prompt = compose_prompt(&request);
127        let timeout = request
128            .constraints
129            .timeout_secs
130            .map(Duration::from_secs)
131            .unwrap_or(self.default_timeout);
132
133        let model = request.constraints.model.as_deref();
134        let has_lean = self.plan_args.is_some();
135        // The lean plain-text invocation: used for the planner role, and as an
136        // automatic fallback when the rich/streaming invocation fails with no
137        // output (e.g. a CLI version that rejects the streaming flags). Planning
138        // starts lean so a work flag can't make the planner exit non-zero.
139        let mut lean = matches!(request.role, Role::Planner) && has_lean;
140
141        // Retry transient failures (spawn errors, timeouts) once before giving
142        // up — beta CLIs are flaky (`CONTEXT.md` §21). A cancelled run is not
143        // retried.
144        const MAX_ATTEMPTS: u32 = 2;
145        let mut attempt = 0;
146        let out = loop {
147            attempt += 1;
148            let builder = if lean { self.plan_args.unwrap() } else { self.build_args };
149            let mapper = if lean { subprocess::raw_lines } else { self.line_mapper };
150            let (args, stdin) = if self.prompt_via_stdin {
151                (builder("", model), Some(prompt.clone()))
152            } else {
153                (builder(&prompt, model), None)
154            };
155            let spec = SubprocessSpec {
156                program: self.program.clone(),
157                args,
158                workspace: request.workspace.clone(),
159                stdin,
160                timeout: Some(timeout),
161            };
162            match subprocess::run(spec, &events, &cancel, mapper).await {
163                Ok(out) => {
164                    let timed_out = matches!(out.status, ExecStatus::TimedOut);
165                    if timed_out && attempt < MAX_ATTEMPTS && !cancel.is_cancelled() {
166                        emit(&events, WorkerEvent::Message(format!(
167                            "{} timed out — retrying ({attempt}/{MAX_ATTEMPTS})",
168                            self.program
169                        )));
170                        continue;
171                    }
172                    // Rich invocation failed with nothing usable on stdout, and a
173                    // lean plain invocation is available → fall back to it once.
174                    let empty_fail = !matches!(out.status, ExecStatus::Success)
175                        && out.stdout.trim().is_empty();
176                    if empty_fail && !lean && has_lean && !cancel.is_cancelled() {
177                        lean = true;
178                        emit(&events, WorkerEvent::Message(format!(
179                            "{} failed in streaming mode — retrying in plain mode",
180                            self.program
181                        )));
182                        continue;
183                    }
184                    break out;
185                }
186                Err(e) => {
187                    if attempt < MAX_ATTEMPTS && !cancel.is_cancelled() {
188                        emit(&events, WorkerEvent::Message(format!(
189                            "{} failed to start ({e}) — retrying ({attempt}/{MAX_ATTEMPTS})",
190                            self.program
191                        )));
192                        tokio::time::sleep(Duration::from_millis(500)).await;
193                        continue;
194                    }
195                    return Err(e);
196                }
197            }
198        };
199        // The lean invocation yields plain text (the answer / JSON DAG, possibly
200        // fenced); take full stdout and let the caller's tolerant parser read it.
201        let parsed = if lean {
202            ParsedHarness::raw(&out.stdout)
203        } else {
204            (self.parse)(&out)
205        };
206
207        // Reconcile the transport-level status with the parsed error flag.
208        let status = match out.status {
209            ExecStatus::Success if parsed.is_error => {
210                ExecStatus::Failed("worker reported an error".into())
211            }
212            other => other,
213        };
214
215        let mut usage = parsed.usage;
216        if usage.wall_ms == 0 {
217            usage.wall_ms = out.wall_ms;
218        }
219
220        Ok(ExecuteResult {
221            result: parsed.result,
222            // Diff capture from the workspace is handled by the dispatcher in
223            // Phase 3 (git-aware); adapters leave it None unless the CLI emits
224            // one directly.
225            file_diff: None,
226            transcript: if out.stderr.is_empty() {
227                out.stdout
228            } else {
229                format!("{}\n--- stderr ---\n{}", out.stdout, out.stderr)
230            },
231            status,
232            usage,
233            session_id: parsed.session_id,
234        })
235    }
236}
237
238/// Compose a harness prompt from the request: the instruction, any critique fed
239/// back on loop-back, ambient steering, and the pinned file paths the worker
240/// should read itself.
241pub fn compose_prompt(request: &ExecuteRequest) -> String {
242    let mut out = String::new();
243    out.push_str(&request.instruction);
244
245    if !request.context.prior_context.is_empty() {
246        out.push_str("\n\n## Context\n");
247        out.push_str(&request.context.prior_context);
248    }
249
250    if let Some(critique) = &request.context.critique {
251        out.push_str("\n\n## Address this feedback from the previous attempt\n");
252        out.push_str(critique);
253    }
254
255    if let Some(steer) = &request.constraints.steer {
256        out.push_str("\n\n## Steering\n");
257        out.push_str(steer);
258    }
259
260    if !request.context.pinned_paths.is_empty() {
261        out.push_str("\n\n## Relevant files (read these)\n");
262        for p in &request.context.pinned_paths {
263            out.push_str("- ");
264            out.push_str(&p.display().to_string());
265            out.push('\n');
266        }
267    }
268
269    out
270}