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, Usage, Worker, WorkerDescriptor,
15    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    pub parse: OutputParser,
102    pub line_mapper: LineMapper,
103    /// Whether the prompt is piped via stdin (vs. passed as an argument).
104    pub prompt_via_stdin: bool,
105    pub default_timeout: Duration,
106}
107
108#[async_trait]
109impl Worker for HarnessAdapter {
110    fn descriptor(&self) -> &WorkerDescriptor {
111        &self.descriptor
112    }
113
114    async fn execute(
115        &self,
116        request: ExecuteRequest,
117        events: EventSink,
118        cancel: CancellationToken,
119    ) -> Result<ExecuteResult> {
120        let prompt = compose_prompt(&request);
121        let timeout = request
122            .constraints
123            .timeout_secs
124            .map(Duration::from_secs)
125            .unwrap_or(self.default_timeout);
126
127        let model = request.constraints.model.as_deref();
128        let (args, stdin) = if self.prompt_via_stdin {
129            ((self.build_args)("", model), Some(prompt))
130        } else {
131            ((self.build_args)(&prompt, model), None)
132        };
133
134        // Retry transient failures (spawn errors, timeouts) once before giving
135        // up — beta CLIs are flaky (`CONTEXT.md` §21). A cancelled run is not
136        // retried.
137        const MAX_ATTEMPTS: u32 = 2;
138        let mut attempt = 0;
139        let out = loop {
140            attempt += 1;
141            let spec = SubprocessSpec {
142                program: self.program.clone(),
143                args: args.clone(),
144                workspace: request.workspace.clone(),
145                stdin: stdin.clone(),
146                timeout: Some(timeout),
147            };
148            match subprocess::run(spec, &events, &cancel, self.line_mapper).await {
149                Ok(out) => {
150                    let timed_out = matches!(out.status, ExecStatus::TimedOut);
151                    if timed_out && attempt < MAX_ATTEMPTS && !cancel.is_cancelled() {
152                        emit(&events, WorkerEvent::Message(format!(
153                            "{} timed out — retrying ({attempt}/{MAX_ATTEMPTS})",
154                            self.program
155                        )));
156                        continue;
157                    }
158                    break out;
159                }
160                Err(e) => {
161                    if attempt < MAX_ATTEMPTS && !cancel.is_cancelled() {
162                        emit(&events, WorkerEvent::Message(format!(
163                            "{} failed to start ({e}) — retrying ({attempt}/{MAX_ATTEMPTS})",
164                            self.program
165                        )));
166                        tokio::time::sleep(Duration::from_millis(500)).await;
167                        continue;
168                    }
169                    return Err(e);
170                }
171            }
172        };
173        let parsed = (self.parse)(&out);
174
175        // Reconcile the transport-level status with the parsed error flag.
176        let status = match out.status {
177            ExecStatus::Success if parsed.is_error => {
178                ExecStatus::Failed("worker reported an error".into())
179            }
180            other => other,
181        };
182
183        let mut usage = parsed.usage;
184        if usage.wall_ms == 0 {
185            usage.wall_ms = out.wall_ms;
186        }
187
188        Ok(ExecuteResult {
189            result: parsed.result,
190            // Diff capture from the workspace is handled by the dispatcher in
191            // Phase 3 (git-aware); adapters leave it None unless the CLI emits
192            // one directly.
193            file_diff: None,
194            transcript: if out.stderr.is_empty() {
195                out.stdout
196            } else {
197                format!("{}\n--- stderr ---\n{}", out.stdout, out.stderr)
198            },
199            status,
200            usage,
201            session_id: parsed.session_id,
202        })
203    }
204}
205
206/// Compose a harness prompt from the request: the instruction, any critique fed
207/// back on loop-back, ambient steering, and the pinned file paths the worker
208/// should read itself.
209pub fn compose_prompt(request: &ExecuteRequest) -> String {
210    let mut out = String::new();
211    out.push_str(&request.instruction);
212
213    if !request.context.prior_context.is_empty() {
214        out.push_str("\n\n## Context\n");
215        out.push_str(&request.context.prior_context);
216    }
217
218    if let Some(critique) = &request.context.critique {
219        out.push_str("\n\n## Address this feedback from the previous attempt\n");
220        out.push_str(critique);
221    }
222
223    if let Some(steer) = &request.constraints.steer {
224        out.push_str("\n\n## Steering\n");
225        out.push_str(steer);
226    }
227
228    if !request.context.pinned_paths.is_empty() {
229        out.push_str("\n\n## Relevant files (read these)\n");
230        for p in &request.context.pinned_paths {
231            out.push_str("- ");
232            out.push_str(&p.display().to_string());
233            out.push('\n');
234        }
235    }
236
237    out
238}