rinne-workers 0.1.8

Worker adapters (harness subprocess + OpenAI-compatible HTTP) and transports for Rinne, the local AI orchestration tool.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Shared machinery for harness adapters (`CONTEXT.md` §8).
//!
//! A harness worker is an autonomous agent: it gets a chunky self-contained
//! prompt and reads/edits the repo itself, so context is passed as a prompt plus
//! *pinned file paths*, never inlined contents (`CONTEXT.md` §8 behavioral
//! split, §12 context assembler).

use std::path::{Path, PathBuf};
use std::time::Duration;

use async_trait::async_trait;
use tokio_util::sync::CancellationToken;

use rinne_core::worker::{
    emit, EventSink, ExecStatus, ExecuteRequest, ExecuteResult, McpServerSpec, Role, Usage, Worker,
    WorkerDescriptor, WorkerEvent,
};
use rinne_core::Result;

use crate::transport::subprocess::{self, LineMapper, SubprocessOutput, SubprocessSpec};

/// How a harness invocation is augmented to use a set of MCP servers — the
/// provision path (`MCP_SKILLS.md` §6). A provisioner writes whatever config the
/// CLI needs and returns the extra argv, the subprocess environment (carrying
/// secret tokens, kept out of the file via `${VAR}` expansion), and a file to
/// clean up afterward.
pub struct Provision {
    pub args: Vec<String>,
    pub env: Vec<(String, String)>,
    pub cleanup: Option<PathBuf>,
}

/// Builds the MCP provisioning for a harness given the node's servers and a
/// scratch directory to write any config file into.
pub type McpProvisioner = fn(servers: &[McpServerSpec], scratch: &Path) -> Result<Provision>;

/// What an adapter extracts from a harness CLI's raw output. Parsers should be
/// defensive: on any doubt, fall back to the raw stdout as the result text so a
/// schema change in a beta CLI degrades gracefully (`CONTEXT.md` §21).
pub struct ParsedHarness {
    pub result: String,
    pub session_id: Option<String>,
    pub usage: Usage,
    /// The CLI signalled an error in its structured output, even if it exited 0.
    pub is_error: bool,
}

impl ParsedHarness {
    /// The trivial parse: use raw stdout, no session, no usage.
    pub fn raw(stdout: &str) -> Self {
        Self {
            result: stdout.trim().to_string(),
            session_id: None,
            usage: Usage::default(),
            is_error: false,
        }
    }
}

/// Build the argv for a harness invocation given the composed prompt and an
/// optional model selection.
pub type ArgsBuilder = fn(prompt: &str, model: Option<&str>) -> Vec<String>;

/// Defensive parser for harnesses that emit a single JSON result object: probe
/// common result fields, falling back to raw stdout on any surprise
/// (`CONTEXT.md` §21). Suitable for not-yet-pinned beta CLIs.
pub fn parse_generic_json(out: &SubprocessOutput) -> ParsedHarness {
    let pick = |v: &serde_json::Value| {
        v.get("result")
            .or_else(|| v.get("text"))
            .or_else(|| v.get("message"))
            .or_else(|| v.get("content"))
            .or_else(|| v.get("response"))
            .and_then(|x| x.as_str())
            .map(String::from)
    };
    for line in out.stdout.lines().rev() {
        let line = line.trim();
        if !line.starts_with('{') {
            continue;
        }
        if let Ok(v) = serde_json::from_str::<serde_json::Value>(line) {
            if let Some(result) = pick(&v) {
                let session_id = v
                    .get("session_id")
                    .or_else(|| v.get("sessionId"))
                    .and_then(|x| x.as_str())
                    .map(String::from);
                let is_error = v.get("is_error").and_then(|b| b.as_bool()).unwrap_or(false);
                return ParsedHarness {
                    result,
                    session_id,
                    usage: Usage::default(),
                    is_error,
                };
            }
        }
    }
    ParsedHarness::raw(&out.stdout)
}

/// The trivial parser: the captured stdout is the result (for CLIs that print
/// plain text, e.g. Aider).
pub fn parse_raw(out: &SubprocessOutput) -> ParsedHarness {
    ParsedHarness::raw(&out.stdout)
}
/// Parse a harness CLI's captured output into normalized fields.
pub type OutputParser = fn(out: &SubprocessOutput) -> ParsedHarness;

/// A generic harness worker driven over the `subprocess-json` transport. Each
/// concrete CLI supplies its program name, argv builder, output parser, and an
/// optional line mapper for richer streaming.
pub struct HarnessAdapter {
    pub descriptor: WorkerDescriptor,
    pub program: String,
    pub build_args: ArgsBuilder,
    /// Lean argv used when the harness runs as the **planner** (`Role::Planner`):
    /// a plain-text completion, not the agentic/streaming work invocation. When
    /// set, planning reads the full stdout as the answer (more robust across CLI
    /// versions than parsing a streaming format). `None` → planning reuses
    /// `build_args` and the normal parser unchanged.
    pub plan_args: Option<ArgsBuilder>,
    pub parse: OutputParser,
    pub line_mapper: LineMapper,
    /// Whether the prompt is piped via stdin (vs. passed as an argument).
    pub prompt_via_stdin: bool,
    pub default_timeout: Duration,
    /// How this harness is told to use a node's MCP servers (`MCP_SKILLS.md` §6).
    /// `None` means the harness has no MCP provisioning wired: a node's tools are
    /// simply unavailable to it (the node still runs), so the conductor should
    /// prefer an API worker for tool-heavy nodes on such a harness.
    pub provisioner: Option<McpProvisioner>,
}

impl HarnessAdapter {
    /// Replace the static model ladder with a live (or config-merged) list.
    pub fn with_models(mut self, models: Vec<String>) -> Self {
        self.descriptor.models = models;
        self
    }

    /// Ensure `model` is on the ladder (appended as frontier if missing). Used
    /// so a user pin / `[models].by_worker` entry is never dropped as "unknown".
    pub fn ensure_model(mut self, model: &str) -> Self {
        let model = model.trim();
        if model.is_empty() {
            return self;
        }
        if !self.descriptor.models.iter().any(|m| m == model) {
            self.descriptor.models.push(model.to_string());
        }
        self
    }
}

#[async_trait]
impl Worker for HarnessAdapter {
    fn descriptor(&self) -> &WorkerDescriptor {
        &self.descriptor
    }

    /// A harness serves MCP tools when it has a provisioner wired (the provision
    /// path, `MCP_SKILLS.md` §6).
    fn serves_mcp_tools(&self) -> bool {
        self.provisioner.is_some()
    }

    async fn execute(
        &self,
        request: ExecuteRequest,
        events: EventSink,
        cancel: CancellationToken,
    ) -> Result<ExecuteResult> {
        let prompt = compose_prompt(&request);
        let timeout = request
            .constraints
            .timeout_secs
            .map(Duration::from_secs)
            .unwrap_or(self.default_timeout);

        let model = request.constraints.model.as_deref();
        let has_lean = self.plan_args.is_some();
        // The lean plain-text invocation: used for the planner role, and as an
        // automatic fallback when the rich/streaming invocation fails with no
        // output (e.g. a CLI version that rejects the streaming flags). Planning
        // starts lean so a work flag can't make the planner exit non-zero.
        let mut lean = matches!(request.role, Role::Planner) && has_lean;

        // Provision the node's MCP servers into this harness once, up front
        // (`MCP_SKILLS.md` §6). A provisioner failure is non-fatal: narrate it and
        // run without the tools rather than failing the node.
        let provision = self.provision(&request, &events);

        // Retry transient failures (spawn errors, timeouts) once before giving
        // up — beta CLIs are flaky (`CONTEXT.md` §21). A cancelled run is not
        // retried.
        const MAX_ATTEMPTS: u32 = 2;
        let mut attempt = 0;
        let out = loop {
            attempt += 1;
            let builder = if lean { self.plan_args.unwrap() } else { self.build_args };
            let mapper = if lean { subprocess::raw_lines } else { self.line_mapper };
            let (mut args, stdin) = if self.prompt_via_stdin {
                (builder("", model), Some(prompt.clone()))
            } else {
                (builder(&prompt, model), None)
            };
            // Append the MCP flags on the rich work invocation (not the lean
            // planner path, which neither needs tools nor accepts the flags).
            if !lean {
                args.extend(provision.args.iter().cloned());
            }
            let spec = SubprocessSpec {
                program: self.program.clone(),
                args,
                workspace: request.workspace.clone(),
                stdin,
                timeout: Some(timeout),
                env: provision.env.clone(),
            };
            match subprocess::run(spec, &events, &cancel, mapper).await {
                Ok(out) => {
                    let timed_out = matches!(out.status, ExecStatus::TimedOut);
                    if timed_out && attempt < MAX_ATTEMPTS && !cancel.is_cancelled() {
                        emit(&events, WorkerEvent::Message(format!(
                            "{} timed out — retrying ({attempt}/{MAX_ATTEMPTS})",
                            self.program
                        )));
                        continue;
                    }
                    // Rich invocation failed with nothing usable on stdout, and a
                    // lean plain invocation is available → fall back to it once.
                    let empty_fail = !matches!(out.status, ExecStatus::Success)
                        && out.stdout.trim().is_empty();
                    if empty_fail && !lean && has_lean && !cancel.is_cancelled() {
                        lean = true;
                        emit(&events, WorkerEvent::Message(format!(
                            "{} failed in streaming mode — retrying in plain mode",
                            self.program
                        )));
                        continue;
                    }
                    break out;
                }
                Err(e) => {
                    if attempt < MAX_ATTEMPTS && !cancel.is_cancelled() {
                        emit(&events, WorkerEvent::Message(format!(
                            "{} failed to start ({e}) — retrying ({attempt}/{MAX_ATTEMPTS})",
                            self.program
                        )));
                        tokio::time::sleep(Duration::from_millis(500)).await;
                        continue;
                    }
                    return Err(e);
                }
            }
        };
        // Best-effort cleanup of the provisioned config file (it holds no secret,
        // but leaving scratch around is untidy).
        if let Some(path) = &provision.cleanup {
            let _ = std::fs::remove_file(path);
        }
        // The lean invocation yields plain text (the answer / JSON DAG, possibly
        // fenced); take full stdout and let the caller's tolerant parser read it.
        let parsed = if lean {
            ParsedHarness::raw(&out.stdout)
        } else {
            (self.parse)(&out)
        };

        // Reconcile the transport-level status with the parsed error flag.
        let status = match out.status {
            ExecStatus::Success if parsed.is_error => {
                ExecStatus::Failed("worker reported an error".into())
            }
            other => other,
        };

        let mut usage = parsed.usage;
        if usage.wall_ms == 0 {
            usage.wall_ms = out.wall_ms;
        }
        // Many harness CLIs (Grok streaming-json, Aider, …) never report token
        // counts. Fill zeros from the prompt + result so status / ledger / UI
        // show consumption instead of a permanent `0 tok`.
        usage.fill_estimates(&prompt, &parsed.result);

        Ok(ExecuteResult {
            result: parsed.result,
            // Diff capture from the workspace is handled by the dispatcher in
            // Phase 3 (git-aware); adapters leave it None unless the CLI emits
            // one directly.
            file_diff: None,
            transcript: if out.stderr.is_empty() {
                out.stdout
            } else {
                format!("{}\n--- stderr ---\n{}", out.stdout, out.stderr)
            },
            status,
            usage,
            session_id: parsed.session_id,
        })
    }
}

impl HarnessAdapter {
    /// Run this harness's provisioner over a node's MCP servers, narrating the
    /// outcome. Returns an empty provision (no args/env) when the node attaches
    /// no servers, the harness has no provisioner, or provisioning fails.
    fn provision(&self, request: &ExecuteRequest, events: &EventSink) -> Provision {
        let empty = Provision {
            args: Vec::new(),
            env: Vec::new(),
            cleanup: None,
        };
        if request.mcp_servers.is_empty() {
            return empty;
        }
        let Some(provisioner) = self.provisioner else {
            emit(
                events,
                WorkerEvent::Message(format!(
                    "{} has no MCP provisioning — running without {} tool server(s)",
                    self.program,
                    request.mcp_servers.len()
                )),
            );
            return empty;
        };
        let scratch = request
            .workspace
            .join(rinne_core::BLACKBOARD_DIR)
            .join("mcp");
        match provisioner(&request.mcp_servers, &scratch) {
            Ok(p) => {
                let names: Vec<&str> = request.mcp_servers.iter().map(|s| s.name.as_str()).collect();
                emit(
                    events,
                    WorkerEvent::Message(format!("provisioned MCP: {}", names.join(", "))),
                );
                p
            }
            Err(e) => {
                emit(
                    events,
                    WorkerEvent::Message(format!("MCP provisioning failed ({e}) — running without tools")),
                );
                empty
            }
        }
    }
}

/// Render the symbol map neighborhoods into a `## Relevant code structure` section.
/// Returns an empty string when the slice is empty so callers can push it unconditionally.
pub(crate) fn render_symbol_map(neighborhoods: &[rinne_types::graph::Neighborhood]) -> String {
    if neighborhoods.is_empty() {
        return String::new();
    }
    let mut s = String::from("\n\n## Relevant code structure\n");
    for nb in neighborhoods {
        let def = &nb.definition;
        s.push_str(&format!("{} ({}:{})\n", def.name, def.file, def.line));
        if !nb.callers.is_empty() {
            let names: Vec<&str> = nb.callers.iter().map(|r| r.name.as_str()).collect();
            s.push_str(&format!("  called by: {}\n", names.join(", ")));
        }
        if !nb.callees.is_empty() {
            let names: Vec<&str> = nb.callees.iter().map(|r| r.name.as_str()).collect();
            s.push_str(&format!("  calls: {}\n", names.join(", ")));
        }
    }
    s
}

/// Compose a harness prompt from the request: the instruction, any critique fed
/// back on loop-back, ambient steering, and the pinned file paths the worker
/// should read itself.
pub fn compose_prompt(request: &ExecuteRequest) -> String {
    let mut out = String::new();
    out.push_str(&request.instruction);

    if !request.context.skill_text.is_empty() {
        out.push_str("\n\n");
        out.push_str(&request.context.skill_text);
    }

    if !request.context.prior_context.is_empty() {
        out.push_str("\n\n## Context\n");
        out.push_str(&request.context.prior_context);
    }

    if let Some(critique) = &request.context.critique {
        out.push_str("\n\n## Address this feedback from the previous attempt\n");
        out.push_str(critique);
    }

    if let Some(steer) = &request.constraints.steer {
        out.push_str("\n\n## Steering\n");
        out.push_str(steer);
    }

    if !request.context.pinned_paths.is_empty() {
        out.push_str("\n\n## Relevant files (read these)\n");
        for p in &request.context.pinned_paths {
            out.push_str("- ");
            out.push_str(&p.display().to_string());
            out.push('\n');
        }
    }

    out.push_str(&render_symbol_map(&request.context.symbol_map));

    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use rinne_core::worker::{ContextPacket, Constraints};
    use std::path::PathBuf;

    fn req(skill_text: &str) -> ExecuteRequest {
        ExecuteRequest {
            role: Role::Generator,
            instruction: "do the task".into(),
            context: ContextPacket {
                skill_text: skill_text.into(),
                ..Default::default()
            },
            workspace: PathBuf::from("/tmp"),
            constraints: Constraints::default(),
            tools: Vec::new(),
            mcp_servers: Vec::new(),
        }
    }

    #[test]
    fn symbol_map_is_rendered_into_harness_prompt() {
        use rinne_types::graph::{Neighborhood, SymbolRef};
        let nb = Neighborhood {
            definition: SymbolRef { name: "helper".into(), file: "m.rs".into(), line: 1 },
            callers: vec![SymbolRef { name: "main".into(), file: "main.rs".into(), line: 5 }],
            callees: vec![],
            imports: vec![],
            stale: false,
        };
        let mut r = req("");
        r.context.symbol_map = vec![nb];
        let prompt = compose_prompt(&r);
        assert!(prompt.contains("## Relevant code structure"), "section header missing");
        assert!(prompt.contains("helper"), "definition name missing");
        assert!(prompt.contains("m.rs:1"), "definition file:line missing");
        assert!(prompt.contains("main"), "caller name missing");
    }

    #[test]
    fn skill_text_is_injected_after_instruction() {
        let prompt = compose_prompt(&req("## Skill: pdf-forms\nFlatten the form"));
        assert!(prompt.starts_with("do the task"));
        assert!(prompt.contains("## Skill: pdf-forms"));
        assert!(prompt.contains("Flatten the form"));
    }

    #[test]
    fn absent_skill_text_adds_nothing() {
        assert_eq!(compose_prompt(&req("")), "do the task");
    }

    fn harness(provisioner: Option<McpProvisioner>) -> HarnessAdapter {
        use rinne_core::worker::{
            AuthMode, Capability, LatencyProfile, QuotaModel, Transport, WorkerFamily,
        };
        HarnessAdapter {
            descriptor: WorkerDescriptor {
                name: "test".into(),
                family: WorkerFamily::Harness,
                capabilities: vec![Capability::CodeEdit],
                auth_mode: AuthMode::Subscription,
                quota: QuotaModel::unlimited(),
                latency: LatencyProfile::Medium,
                transport: Transport::SubprocessJson,
                models: vec![],
            },
            program: "test".into(),
            build_args: |_, _| vec![],
            plan_args: None,
            parse: parse_raw,
            line_mapper: crate::transport::subprocess::raw_lines,
            prompt_via_stdin: false,
            default_timeout: std::time::Duration::from_secs(1),
            provisioner,
        }
    }

    fn tool_request() -> ExecuteRequest {
        use rinne_core::worker::{McpServerSpec, McpTransportKind};
        let mut r = req("");
        r.mcp_servers = vec![McpServerSpec {
            name: "srv".into(),
            transport: McpTransportKind::Stdio,
            command: Some("cmd".into()),
            args: vec![],
            env: vec![],
            url: None,
            headers: vec![],
            token_env: None,
            token: None,
            auth: None,
            auth_header: None,
        }];
        r
    }

    #[test]
    fn provisioner_supplies_args_and_env_for_a_tool_node() {
        fn prov(_s: &[McpServerSpec], _p: &std::path::Path) -> Result<Provision> {
            Ok(Provision {
                args: vec!["--mcp-config".into(), "x.json".into()],
                env: vec![("TOKEN".into(), "secret".into())],
                cleanup: None,
            })
        }
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let p = harness(Some(prov)).provision(&tool_request(), &tx);
        assert_eq!(p.args, vec!["--mcp-config", "x.json"]);
        assert_eq!(p.env, vec![("TOKEN".to_string(), "secret".to_string())]);
    }

    #[test]
    fn no_provisioner_yields_empty_provision_and_narrates() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let p = harness(None).provision(&tool_request(), &tx);
        assert!(p.args.is_empty(), "no flags when the harness can't provision");
        assert!(p.env.is_empty());
        // The gap is surfaced, not silent.
        let mut narrated = false;
        while let Ok(ev) = rx.try_recv() {
            if let WorkerEvent::Message(m) = ev {
                if m.contains("no MCP provisioning") {
                    narrated = true;
                }
            }
        }
        assert!(narrated, "a missing provisioner should be narrated");
    }

    #[test]
    fn no_servers_means_no_provision_work() {
        fn prov(_s: &[McpServerSpec], _p: &std::path::Path) -> Result<Provision> {
            panic!("must not be called when the node attaches no servers");
        }
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let p = harness(Some(prov)).provision(&req(""), &tx); // req() has no mcp_servers
        assert!(p.args.is_empty());
    }
}