rinne_workers/adapters/
common.rs1use 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
21pub struct ParsedHarness {
25 pub result: String,
26 pub session_id: Option<String>,
27 pub usage: Usage,
28 pub is_error: bool,
30}
31
32impl ParsedHarness {
33 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
44pub type ArgsBuilder = fn(prompt: &str, model: Option<&str>) -> Vec<String>;
47
48pub 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
86pub fn parse_raw(out: &SubprocessOutput) -> ParsedHarness {
89 ParsedHarness::raw(&out.stdout)
90}
91pub type OutputParser = fn(out: &SubprocessOutput) -> ParsedHarness;
93
94pub struct HarnessAdapter {
98 pub descriptor: WorkerDescriptor,
99 pub program: String,
100 pub build_args: ArgsBuilder,
101 pub plan_args: Option<ArgsBuilder>,
107 pub parse: OutputParser,
108 pub line_mapper: LineMapper,
109 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 let mut lean = matches!(request.role, Role::Planner) && has_lean;
140
141 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 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 let parsed = if lean {
202 ParsedHarness::raw(&out.stdout)
203 } else {
204 (self.parse)(&out)
205 };
206
207 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 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
238pub 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}