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::path::{Path, PathBuf};
9use std::time::Duration;
10
11use async_trait::async_trait;
12use tokio_util::sync::CancellationToken;
13
14use rinne_core::worker::{
15    emit, EventSink, ExecStatus, ExecuteRequest, ExecuteResult, McpServerSpec, Role, Usage, Worker,
16    WorkerDescriptor, WorkerEvent,
17};
18use rinne_core::Result;
19
20use crate::transport::subprocess::{self, LineMapper, SubprocessOutput, SubprocessSpec};
21
22/// How a harness invocation is augmented to use a set of MCP servers — the
23/// provision path (`MCP_SKILLS.md` §6). A provisioner writes whatever config the
24/// CLI needs and returns the extra argv, the subprocess environment (carrying
25/// secret tokens, kept out of the file via `${VAR}` expansion), and a file to
26/// clean up afterward.
27pub struct Provision {
28    pub args: Vec<String>,
29    pub env: Vec<(String, String)>,
30    pub cleanup: Option<PathBuf>,
31}
32
33/// Builds the MCP provisioning for a harness given the node's servers and a
34/// scratch directory to write any config file into.
35pub type McpProvisioner = fn(servers: &[McpServerSpec], scratch: &Path) -> Result<Provision>;
36
37/// What an adapter extracts from a harness CLI's raw output. Parsers should be
38/// defensive: on any doubt, fall back to the raw stdout as the result text so a
39/// schema change in a beta CLI degrades gracefully (`CONTEXT.md` §21).
40pub struct ParsedHarness {
41    pub result: String,
42    pub session_id: Option<String>,
43    pub usage: Usage,
44    /// The CLI signalled an error in its structured output, even if it exited 0.
45    pub is_error: bool,
46}
47
48impl ParsedHarness {
49    /// The trivial parse: use raw stdout, no session, no usage.
50    pub fn raw(stdout: &str) -> Self {
51        Self {
52            result: stdout.trim().to_string(),
53            session_id: None,
54            usage: Usage::default(),
55            is_error: false,
56        }
57    }
58}
59
60/// Build the argv for a harness invocation given the composed prompt and an
61/// optional model selection.
62pub type ArgsBuilder = fn(prompt: &str, model: Option<&str>) -> Vec<String>;
63
64/// Defensive parser for harnesses that emit a single JSON result object: probe
65/// common result fields, falling back to raw stdout on any surprise
66/// (`CONTEXT.md` §21). Suitable for not-yet-pinned beta CLIs.
67pub fn parse_generic_json(out: &SubprocessOutput) -> ParsedHarness {
68    let pick = |v: &serde_json::Value| {
69        v.get("result")
70            .or_else(|| v.get("text"))
71            .or_else(|| v.get("message"))
72            .or_else(|| v.get("content"))
73            .or_else(|| v.get("response"))
74            .and_then(|x| x.as_str())
75            .map(String::from)
76    };
77    for line in out.stdout.lines().rev() {
78        let line = line.trim();
79        if !line.starts_with('{') {
80            continue;
81        }
82        if let Ok(v) = serde_json::from_str::<serde_json::Value>(line) {
83            if let Some(result) = pick(&v) {
84                let session_id = v
85                    .get("session_id")
86                    .or_else(|| v.get("sessionId"))
87                    .and_then(|x| x.as_str())
88                    .map(String::from);
89                let is_error = v.get("is_error").and_then(|b| b.as_bool()).unwrap_or(false);
90                return ParsedHarness {
91                    result,
92                    session_id,
93                    usage: Usage::default(),
94                    is_error,
95                };
96            }
97        }
98    }
99    ParsedHarness::raw(&out.stdout)
100}
101
102/// The trivial parser: the captured stdout is the result (for CLIs that print
103/// plain text, e.g. Aider).
104pub fn parse_raw(out: &SubprocessOutput) -> ParsedHarness {
105    ParsedHarness::raw(&out.stdout)
106}
107/// Parse a harness CLI's captured output into normalized fields.
108pub type OutputParser = fn(out: &SubprocessOutput) -> ParsedHarness;
109
110/// A generic harness worker driven over the `subprocess-json` transport. Each
111/// concrete CLI supplies its program name, argv builder, output parser, and an
112/// optional line mapper for richer streaming.
113pub struct HarnessAdapter {
114    pub descriptor: WorkerDescriptor,
115    pub program: String,
116    pub build_args: ArgsBuilder,
117    /// Lean argv used when the harness runs as the **planner** (`Role::Planner`):
118    /// a plain-text completion, not the agentic/streaming work invocation. When
119    /// set, planning reads the full stdout as the answer (more robust across CLI
120    /// versions than parsing a streaming format). `None` → planning reuses
121    /// `build_args` and the normal parser unchanged.
122    pub plan_args: Option<ArgsBuilder>,
123    pub parse: OutputParser,
124    pub line_mapper: LineMapper,
125    /// Whether the prompt is piped via stdin (vs. passed as an argument).
126    pub prompt_via_stdin: bool,
127    pub default_timeout: Duration,
128    /// How this harness is told to use a node's MCP servers (`MCP_SKILLS.md` §6).
129    /// `None` means the harness has no MCP provisioning wired: a node's tools are
130    /// simply unavailable to it (the node still runs), so the conductor should
131    /// prefer an API worker for tool-heavy nodes on such a harness.
132    pub provisioner: Option<McpProvisioner>,
133}
134
135#[async_trait]
136impl Worker for HarnessAdapter {
137    fn descriptor(&self) -> &WorkerDescriptor {
138        &self.descriptor
139    }
140
141    /// A harness serves MCP tools when it has a provisioner wired (the provision
142    /// path, `MCP_SKILLS.md` §6).
143    fn serves_mcp_tools(&self) -> bool {
144        self.provisioner.is_some()
145    }
146
147    async fn execute(
148        &self,
149        request: ExecuteRequest,
150        events: EventSink,
151        cancel: CancellationToken,
152    ) -> Result<ExecuteResult> {
153        let prompt = compose_prompt(&request);
154        let timeout = request
155            .constraints
156            .timeout_secs
157            .map(Duration::from_secs)
158            .unwrap_or(self.default_timeout);
159
160        let model = request.constraints.model.as_deref();
161        let has_lean = self.plan_args.is_some();
162        // The lean plain-text invocation: used for the planner role, and as an
163        // automatic fallback when the rich/streaming invocation fails with no
164        // output (e.g. a CLI version that rejects the streaming flags). Planning
165        // starts lean so a work flag can't make the planner exit non-zero.
166        let mut lean = matches!(request.role, Role::Planner) && has_lean;
167
168        // Provision the node's MCP servers into this harness once, up front
169        // (`MCP_SKILLS.md` §6). A provisioner failure is non-fatal: narrate it and
170        // run without the tools rather than failing the node.
171        let provision = self.provision(&request, &events);
172
173        // Retry transient failures (spawn errors, timeouts) once before giving
174        // up — beta CLIs are flaky (`CONTEXT.md` §21). A cancelled run is not
175        // retried.
176        const MAX_ATTEMPTS: u32 = 2;
177        let mut attempt = 0;
178        let out = loop {
179            attempt += 1;
180            let builder = if lean { self.plan_args.unwrap() } else { self.build_args };
181            let mapper = if lean { subprocess::raw_lines } else { self.line_mapper };
182            let (mut args, stdin) = if self.prompt_via_stdin {
183                (builder("", model), Some(prompt.clone()))
184            } else {
185                (builder(&prompt, model), None)
186            };
187            // Append the MCP flags on the rich work invocation (not the lean
188            // planner path, which neither needs tools nor accepts the flags).
189            if !lean {
190                args.extend(provision.args.iter().cloned());
191            }
192            let spec = SubprocessSpec {
193                program: self.program.clone(),
194                args,
195                workspace: request.workspace.clone(),
196                stdin,
197                timeout: Some(timeout),
198                env: provision.env.clone(),
199            };
200            match subprocess::run(spec, &events, &cancel, mapper).await {
201                Ok(out) => {
202                    let timed_out = matches!(out.status, ExecStatus::TimedOut);
203                    if timed_out && attempt < MAX_ATTEMPTS && !cancel.is_cancelled() {
204                        emit(&events, WorkerEvent::Message(format!(
205                            "{} timed out — retrying ({attempt}/{MAX_ATTEMPTS})",
206                            self.program
207                        )));
208                        continue;
209                    }
210                    // Rich invocation failed with nothing usable on stdout, and a
211                    // lean plain invocation is available → fall back to it once.
212                    let empty_fail = !matches!(out.status, ExecStatus::Success)
213                        && out.stdout.trim().is_empty();
214                    if empty_fail && !lean && has_lean && !cancel.is_cancelled() {
215                        lean = true;
216                        emit(&events, WorkerEvent::Message(format!(
217                            "{} failed in streaming mode — retrying in plain mode",
218                            self.program
219                        )));
220                        continue;
221                    }
222                    break out;
223                }
224                Err(e) => {
225                    if attempt < MAX_ATTEMPTS && !cancel.is_cancelled() {
226                        emit(&events, WorkerEvent::Message(format!(
227                            "{} failed to start ({e}) — retrying ({attempt}/{MAX_ATTEMPTS})",
228                            self.program
229                        )));
230                        tokio::time::sleep(Duration::from_millis(500)).await;
231                        continue;
232                    }
233                    return Err(e);
234                }
235            }
236        };
237        // Best-effort cleanup of the provisioned config file (it holds no secret,
238        // but leaving scratch around is untidy).
239        if let Some(path) = &provision.cleanup {
240            let _ = std::fs::remove_file(path);
241        }
242        // The lean invocation yields plain text (the answer / JSON DAG, possibly
243        // fenced); take full stdout and let the caller's tolerant parser read it.
244        let parsed = if lean {
245            ParsedHarness::raw(&out.stdout)
246        } else {
247            (self.parse)(&out)
248        };
249
250        // Reconcile the transport-level status with the parsed error flag.
251        let status = match out.status {
252            ExecStatus::Success if parsed.is_error => {
253                ExecStatus::Failed("worker reported an error".into())
254            }
255            other => other,
256        };
257
258        let mut usage = parsed.usage;
259        if usage.wall_ms == 0 {
260            usage.wall_ms = out.wall_ms;
261        }
262
263        Ok(ExecuteResult {
264            result: parsed.result,
265            // Diff capture from the workspace is handled by the dispatcher in
266            // Phase 3 (git-aware); adapters leave it None unless the CLI emits
267            // one directly.
268            file_diff: None,
269            transcript: if out.stderr.is_empty() {
270                out.stdout
271            } else {
272                format!("{}\n--- stderr ---\n{}", out.stdout, out.stderr)
273            },
274            status,
275            usage,
276            session_id: parsed.session_id,
277        })
278    }
279}
280
281impl HarnessAdapter {
282    /// Run this harness's provisioner over a node's MCP servers, narrating the
283    /// outcome. Returns an empty provision (no args/env) when the node attaches
284    /// no servers, the harness has no provisioner, or provisioning fails.
285    fn provision(&self, request: &ExecuteRequest, events: &EventSink) -> Provision {
286        let empty = Provision {
287            args: Vec::new(),
288            env: Vec::new(),
289            cleanup: None,
290        };
291        if request.mcp_servers.is_empty() {
292            return empty;
293        }
294        let Some(provisioner) = self.provisioner else {
295            emit(
296                events,
297                WorkerEvent::Message(format!(
298                    "{} has no MCP provisioning — running without {} tool server(s)",
299                    self.program,
300                    request.mcp_servers.len()
301                )),
302            );
303            return empty;
304        };
305        let scratch = request
306            .workspace
307            .join(rinne_core::BLACKBOARD_DIR)
308            .join("mcp");
309        match provisioner(&request.mcp_servers, &scratch) {
310            Ok(p) => {
311                let names: Vec<&str> = request.mcp_servers.iter().map(|s| s.name.as_str()).collect();
312                emit(
313                    events,
314                    WorkerEvent::Message(format!("provisioned MCP: {}", names.join(", "))),
315                );
316                p
317            }
318            Err(e) => {
319                emit(
320                    events,
321                    WorkerEvent::Message(format!("MCP provisioning failed ({e}) — running without tools")),
322                );
323                empty
324            }
325        }
326    }
327}
328
329/// Compose a harness prompt from the request: the instruction, any critique fed
330/// back on loop-back, ambient steering, and the pinned file paths the worker
331/// should read itself.
332pub fn compose_prompt(request: &ExecuteRequest) -> String {
333    let mut out = String::new();
334    out.push_str(&request.instruction);
335
336    if !request.context.skill_text.is_empty() {
337        out.push_str("\n\n");
338        out.push_str(&request.context.skill_text);
339    }
340
341    if !request.context.prior_context.is_empty() {
342        out.push_str("\n\n## Context\n");
343        out.push_str(&request.context.prior_context);
344    }
345
346    if let Some(critique) = &request.context.critique {
347        out.push_str("\n\n## Address this feedback from the previous attempt\n");
348        out.push_str(critique);
349    }
350
351    if let Some(steer) = &request.constraints.steer {
352        out.push_str("\n\n## Steering\n");
353        out.push_str(steer);
354    }
355
356    if !request.context.pinned_paths.is_empty() {
357        out.push_str("\n\n## Relevant files (read these)\n");
358        for p in &request.context.pinned_paths {
359            out.push_str("- ");
360            out.push_str(&p.display().to_string());
361            out.push('\n');
362        }
363    }
364
365    out
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371    use rinne_core::worker::{ContextPacket, Constraints};
372    use std::path::PathBuf;
373
374    fn req(skill_text: &str) -> ExecuteRequest {
375        ExecuteRequest {
376            role: Role::Generator,
377            instruction: "do the task".into(),
378            context: ContextPacket {
379                skill_text: skill_text.into(),
380                ..Default::default()
381            },
382            workspace: PathBuf::from("/tmp"),
383            constraints: Constraints::default(),
384            tools: Vec::new(),
385            mcp_servers: Vec::new(),
386        }
387    }
388
389    #[test]
390    fn skill_text_is_injected_after_instruction() {
391        let prompt = compose_prompt(&req("## Skill: pdf-forms\nFlatten the form"));
392        assert!(prompt.starts_with("do the task"));
393        assert!(prompt.contains("## Skill: pdf-forms"));
394        assert!(prompt.contains("Flatten the form"));
395    }
396
397    #[test]
398    fn absent_skill_text_adds_nothing() {
399        assert_eq!(compose_prompt(&req("")), "do the task");
400    }
401
402    fn harness(provisioner: Option<McpProvisioner>) -> HarnessAdapter {
403        use rinne_core::worker::{
404            AuthMode, Capability, LatencyProfile, QuotaModel, Transport, WorkerFamily,
405        };
406        HarnessAdapter {
407            descriptor: WorkerDescriptor {
408                name: "test".into(),
409                family: WorkerFamily::Harness,
410                capabilities: vec![Capability::CodeEdit],
411                auth_mode: AuthMode::Subscription,
412                quota: QuotaModel::unlimited(),
413                latency: LatencyProfile::Medium,
414                transport: Transport::SubprocessJson,
415                models: vec![],
416            },
417            program: "test".into(),
418            build_args: |_, _| vec![],
419            plan_args: None,
420            parse: parse_raw,
421            line_mapper: crate::transport::subprocess::raw_lines,
422            prompt_via_stdin: false,
423            default_timeout: std::time::Duration::from_secs(1),
424            provisioner,
425        }
426    }
427
428    fn tool_request() -> ExecuteRequest {
429        use rinne_core::worker::{McpServerSpec, McpTransportKind};
430        let mut r = req("");
431        r.mcp_servers = vec![McpServerSpec {
432            name: "srv".into(),
433            transport: McpTransportKind::Stdio,
434            command: Some("cmd".into()),
435            args: vec![],
436            env: vec![],
437            url: None,
438            headers: vec![],
439            token_env: None,
440            token: None,
441            auth: None,
442            auth_header: None,
443        }];
444        r
445    }
446
447    #[test]
448    fn provisioner_supplies_args_and_env_for_a_tool_node() {
449        fn prov(_s: &[McpServerSpec], _p: &std::path::Path) -> Result<Provision> {
450            Ok(Provision {
451                args: vec!["--mcp-config".into(), "x.json".into()],
452                env: vec![("TOKEN".into(), "secret".into())],
453                cleanup: None,
454            })
455        }
456        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
457        let p = harness(Some(prov)).provision(&tool_request(), &tx);
458        assert_eq!(p.args, vec!["--mcp-config", "x.json"]);
459        assert_eq!(p.env, vec![("TOKEN".to_string(), "secret".to_string())]);
460    }
461
462    #[test]
463    fn no_provisioner_yields_empty_provision_and_narrates() {
464        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
465        let p = harness(None).provision(&tool_request(), &tx);
466        assert!(p.args.is_empty(), "no flags when the harness can't provision");
467        assert!(p.env.is_empty());
468        // The gap is surfaced, not silent.
469        let mut narrated = false;
470        while let Ok(ev) = rx.try_recv() {
471            if let WorkerEvent::Message(m) = ev {
472                if m.contains("no MCP provisioning") {
473                    narrated = true;
474                }
475            }
476        }
477        assert!(narrated, "a missing provisioner should be narrated");
478    }
479
480    #[test]
481    fn no_servers_means_no_provision_work() {
482        fn prov(_s: &[McpServerSpec], _p: &std::path::Path) -> Result<Provision> {
483            panic!("must not be called when the node attaches no servers");
484        }
485        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
486        let p = harness(Some(prov)).provision(&req(""), &tx); // req() has no mcp_servers
487        assert!(p.args.is_empty());
488    }
489}