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
//! OpenAI-compatible API worker adapter (`CONTEXT.md` §8, §16).
//!
//! A raw model on the user's own key. Unlike a harness, it sees only what is
//! sent, so the context assembler inlines file *contents* here, not paths
//! (`CONTEXT.md` §8 behavioral split, §12). Always metered (`CONTEXT.md` §9).

use std::sync::Arc;
use std::time::Instant;

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

use rinne_core::worker::{
    emit, AuthMode, Capability, EventSink, ExecStatus, ExecuteRequest, ExecuteResult,
    LatencyProfile, QuotaModel, ToolExecutor, Transport, Usage, Worker, WorkerDescriptor,
    WorkerEvent, WorkerFamily,
};
use rinne_core::{Result, RinneError};

use crate::adapters::common::render_symbol_map;
use crate::transport::http::{ChatMessage, ChatRequest, ChatTurn, OpenAiClient};

/// An API worker backed by an OpenAI-compatible endpoint, with an optional pool
/// of keys it rotates across when one is rate-limited (`CONTEXT.md` §13).
pub struct OpenAiWorker {
    descriptor: WorkerDescriptor,
    base_url: String,
    /// Key pool; rotated on rate-limit. The user's own keys, never pooled across
    /// users (`CONTEXT.md` §4).
    keys: Vec<String>,
    /// Default model when a node doesn't pin one.
    default_model: String,
    system_prompt: String,
    /// Provider-specific params merged into each request.
    extra_body: Option<serde_json::Value>,
    /// Executes MCP tool calls for the host agentic loop (`MCP_SKILLS.md` §6).
    /// `None` means no tools are wired; the worker then always runs the plain
    /// streaming path regardless of a node's `tools`.
    tool_executor: Option<Arc<dyn ToolExecutor>>,
}

impl OpenAiWorker {
    /// Build an API worker.
    ///
    /// `name` is the Rinne worker name (e.g. `openrouter`, `deepseek`).
    /// `base_url` includes the version (e.g. `https://api.openai.com/v1`).
    /// `keys` is the user's key pool (rotated on rate-limit). `models` is the
    /// ladder cheap→strong; the first is the default. The per-node model
    /// (conductor's choice or a cascade escalation) overrides the default.
    pub fn new(
        name: &str,
        base_url: &str,
        keys: Vec<String>,
        models: Vec<String>,
        capabilities: Vec<Capability>,
        extra_body: Option<serde_json::Value>,
    ) -> Self {
        let default_model = models.first().cloned().unwrap_or_else(|| "gpt-4o-mini".to_string());
        Self {
            extra_body,
            tool_executor: None,
            descriptor: WorkerDescriptor {
                name: name.to_string(),
                family: WorkerFamily::Api,
                capabilities,
                auth_mode: AuthMode::ApiKey,
                quota: QuotaModel::unlimited(),
                latency: LatencyProfile::Fast,
                transport: Transport::Http,
                models,
            },
            base_url: base_url.to_string(),
            keys: if keys.is_empty() { vec![String::new()] } else { keys },
            default_model,
            system_prompt: "You are a focused worker inside an orchestration system. \
                Follow the instruction precisely and return only the requested result."
                .to_string(),
        }
    }

    /// Wire an MCP tool executor so nodes that attach `tools` get the host
    /// agentic loop (`MCP_SKILLS.md` §6). Without one the worker ignores tools.
    pub fn with_tool_executor(mut self, executor: Arc<dyn ToolExecutor>) -> Self {
        self.tool_executor = Some(executor);
        self
    }
}

/// Whether an error looks like a rate-limit/quota condition worth rotating keys.
fn is_rate_limited(err: &rinne_core::RinneError) -> bool {
    let s = err.to_string().to_lowercase();
    s.contains("429") || s.contains("rate limit") || s.contains("quota") || s.contains("too many requests")
}

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

    /// An API worker serves MCP tools when a tool executor is wired (the host
    /// agentic loop, `MCP_SKILLS.md` §6).
    fn serves_mcp_tools(&self) -> bool {
        self.tool_executor.is_some()
    }

    async fn execute(
        &self,
        request: ExecuteRequest,
        events: EventSink,
        cancel: CancellationToken,
    ) -> Result<ExecuteResult> {
        let started = Instant::now();

        // The per-node model (conductor's tier choice or a cascade escalation)
        // wins; otherwise the worker's default model.
        let model = request
            .constraints
            .model
            .clone()
            .unwrap_or_else(|| self.default_model.clone());

        // Host path: a node that attaches tools, with an executor wired, runs the
        // agentic loop instead of a single streamed completion (`MCP_SKILLS.md` §6).
        if !request.tools.is_empty() {
            if let Some(executor) = self.tool_executor.clone() {
                return self
                    .run_tool_loop(&request, model, executor, &events, &cancel)
                    .await;
            }
        }

        let user = compose_message(&request);
        let chat = ChatRequest {
            model,
            messages: vec![
                ChatMessage::system(self.system_prompt.clone()),
                ChatMessage::user(user),
            ],
            temperature: None,
            extra: self.extra_body.clone(),
        };

        // Try keys in order, rotating to the next on a rate-limit/quota error.
        let mut last_err = None;
        let mut resp = None;
        for (i, key) in self.keys.iter().enumerate() {
            let client = OpenAiClient::new(&self.base_url, Some(key.clone()));
            match client.chat_stream(&chat, &events, &cancel).await {
                Ok(r) => {
                    resp = Some(r);
                    break;
                }
                Err(e) => {
                    let rotate = is_rate_limited(&e) && i + 1 < self.keys.len();
                    if rotate {
                        rinne_core::worker::emit(
                            &events,
                            rinne_core::worker::WorkerEvent::Message(format!(
                                "key {} rate-limited — rotating to key {}",
                                i + 1,
                                i + 2
                            )),
                        );
                        last_err = Some(e);
                        continue;
                    }
                    return Err(e);
                }
            }
        }
        let resp = match resp {
            Some(r) => r,
            None => return Err(last_err.unwrap_or_else(|| {
                rinne_core::RinneError::Worker("no API key available".into())
            })),
        };

        let status = if cancel.is_cancelled() {
            ExecStatus::Cancelled
        } else {
            ExecStatus::Success
        };

        let mut usage = resp.usage;
        usage.wall_ms = started.elapsed().as_millis() as u64;

        Ok(ExecuteResult {
            result: resp.content.clone(),
            file_diff: None,
            transcript: resp.content,
            status,
            usage,
            session_id: None,
        })
    }
}

/// The largest number of model↔tool round-trips before the loop gives up and
/// returns whatever it has. A backstop against a model that never stops calling.
const MAX_TOOL_ROUNDS: usize = 8;

impl OpenAiWorker {
    /// The host agentic loop: offer the node's tools, execute the model's tool
    /// calls against the live MCP pool, feed results back, repeat until the model
    /// answers in text or the round cap is hit (`MCP_SKILLS.md` §6).
    async fn run_tool_loop(
        &self,
        request: &ExecuteRequest,
        model: String,
        executor: Arc<dyn ToolExecutor>,
        events: &EventSink,
        cancel: &CancellationToken,
    ) -> Result<ExecuteResult> {
        let started = Instant::now();
        let mut messages = vec![
            ChatMessage::system(self.system_prompt.clone()),
            ChatMessage::user(compose_message(request)),
        ];
        let mut usage = Usage::default();
        let mut transcript = String::new();
        let mut answer = String::new();
        let mut answered = false;

        for _ in 0..MAX_TOOL_ROUNDS {
            if cancel.is_cancelled() {
                break;
            }
            let chat = ChatRequest {
                model: model.clone(),
                messages: messages.clone(),
                temperature: None,
                extra: self.extra_body.clone(),
            };
            let turn = self.chat_tools_rotating(&chat, &request.tools, events).await?;
            usage.prompt_tokens += turn.usage.prompt_tokens;
            usage.completion_tokens += turn.usage.completion_tokens;

            if turn.tool_calls.is_empty() {
                // The model answered — done.
                answer = turn.content;
                answered = true;
                if !answer.is_empty() {
                    emit(events, WorkerEvent::Token(answer.clone()));
                }
                transcript.push_str(&answer);
                break;
            }

            // Echo the assistant's tool calls, then run each and feed results back.
            messages.push(ChatMessage::assistant_tool_calls(turn.tool_calls.clone()));
            for call in &turn.tool_calls {
                emit(
                    events,
                    WorkerEvent::ToolUse(format!(
                        "{}({})",
                        call.function.name,
                        truncate(&call.function.arguments, 120)
                    )),
                );
                transcript.push_str(&format!(
                    "\n[tool] {} {}\n",
                    call.function.name, call.function.arguments
                ));
                // Empty args are valid (a no-arg tool); only non-empty garbage is
                // an error we hand back so the model can retry with valid JSON.
                let trimmed = call.function.arguments.trim();
                let result = if trimmed.is_empty() {
                    executor
                        .call(&call.function.name, serde_json::Value::Object(Default::default()))
                        .await
                        .unwrap_or_else(|e| format!("tool error: {e}"))
                } else {
                    match serde_json::from_str::<serde_json::Value>(trimmed) {
                        Ok(args) => executor
                            .call(&call.function.name, args)
                            .await
                            .unwrap_or_else(|e| format!("tool error: {e}")),
                        Err(e) => format!("tool error: arguments were not valid JSON ({e})"),
                    }
                };
                transcript.push_str(&format!("[result] {}\n", truncate(&result, 400)));
                messages.push(ChatMessage::tool_result(call.id.clone(), result));
            }
        }

        emit(events, WorkerEvent::Done);
        usage.wall_ms = started.elapsed().as_millis() as u64;
        // A loop that ran out of rounds still calling tools never converged —
        // fail it cleanly (the engine can loop back / replan) rather than report
        // an empty success that silently starves downstream nodes.
        let status = if cancel.is_cancelled() {
            ExecStatus::Cancelled
        } else if !answered {
            emit(
                events,
                WorkerEvent::Message(format!(
                    "tool loop hit the {MAX_TOOL_ROUNDS}-round limit without a final answer"
                )),
            );
            ExecStatus::Failed(format!(
                "model did not finish within {MAX_TOOL_ROUNDS} tool rounds"
            ))
        } else {
            ExecStatus::Success
        };
        Ok(ExecuteResult {
            result: answer,
            file_diff: None,
            transcript,
            status,
            usage,
            session_id: None,
        })
    }

    /// One non-streaming tool-aware completion, rotating keys on a rate-limit
    /// just like the streaming path.
    async fn chat_tools_rotating(
        &self,
        chat: &ChatRequest,
        tools: &[rinne_core::worker::ToolSpec],
        events: &EventSink,
    ) -> Result<ChatTurn> {
        let mut last_err = None;
        for (i, key) in self.keys.iter().enumerate() {
            let client = OpenAiClient::new(&self.base_url, Some(key.clone()));
            match client.chat_with_tools(chat, tools).await {
                Ok(turn) => return Ok(turn),
                Err(e) => {
                    if is_rate_limited(&e) && i + 1 < self.keys.len() {
                        emit(
                            events,
                            WorkerEvent::Message(format!(
                                "key {} rate-limited — rotating to key {}",
                                i + 1,
                                i + 2
                            )),
                        );
                        last_err = Some(e);
                        continue;
                    }
                    return Err(e);
                }
            }
        }
        Err(last_err.unwrap_or_else(|| RinneError::Worker("no API key available".into())))
    }
}

/// Shorten a string for an event line / transcript, marking elision.
fn truncate(s: &str, max: usize) -> String {
    let one_line = s.replace('\n', " ");
    if one_line.chars().count() > max {
        let kept: String = one_line.chars().take(max).collect();
        format!("{kept}…")
    } else {
        one_line
    }
}

/// Inline the full context an API worker needs: instruction, file contents,
/// prior context, critique, and steering.
fn compose_message(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);
    }

    for file in &request.context.inlined_files {
        out.push_str("\n\n## File: ");
        out.push_str(&file.path.display().to_string());
        out.push_str("\n```\n");
        out.push_str(&file.contents);
        out.push_str("\n```\n");
    }

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

    out
}

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

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

    #[test]
    fn symbol_map_is_rendered_into_api_message() {
        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("do the task");
        r.context.symbol_map = vec![nb];
        let msg = compose_message(&r);
        assert!(msg.contains("## Relevant code structure"), "section header missing");
        assert!(msg.contains("helper"), "definition name missing");
        assert!(msg.contains("m.rs:1"), "definition file:line missing");
        assert!(msg.contains("main"), "caller name missing");
    }
}