1use std::path::Path;
9use std::time::Duration;
10
11use rinne_core::worker::{
12 AuthMode, Capability, LatencyProfile, McpServerSpec, QuotaModel, Transport, Usage,
13 WorkerDescriptor, WorkerEvent, WorkerFamily,
14};
15use rinne_core::Result;
16
17use super::claude_code::last_json_object;
18use super::common::{HarnessAdapter, ParsedHarness, Provision};
19use super::mcp_util;
20use crate::transport::subprocess::SubprocessOutput;
21
22pub fn worker() -> HarnessAdapter {
23 HarnessAdapter {
24 descriptor: descriptor(),
25 program: "opencode".to_string(),
26 build_args,
27 plan_args: Some(plan_args),
28 interactive_args: Some(interactive_args),
30 parse,
31 line_mapper,
32 prompt_via_stdin: false,
33 default_timeout: Duration::from_secs(600),
34 provisioner: Some(provision),
35 }
36}
37
38fn descriptor() -> WorkerDescriptor {
39 WorkerDescriptor {
40 name: "opencode".to_string(),
41 family: WorkerFamily::Harness,
42 capabilities: vec![
43 Capability::CodeEdit,
44 Capability::RepoAware,
45 Capability::Reasoning,
46 Capability::Writing,
47 Capability::ToolRun,
48 Capability::CodeReview,
49 ],
50 auth_mode: AuthMode::Subscription,
53 quota: QuotaModel {
54 capacity: 150_000.0,
55 refill_per_minute: 15_000.0,
56 },
57 latency: LatencyProfile::Medium,
58 transport: Transport::SubprocessJson,
59 models: Vec::new(),
60 }
61}
62
63fn build_args(prompt: &str, model: Option<&str>) -> Vec<String> {
64 let mut args = vec![
65 "run".into(),
66 prompt.into(),
67 "--format".into(),
68 "json".into(),
69 ];
70 if let Some(m) = model {
71 args.push("--model".into());
73 args.push(m.into());
74 }
75 args
76}
77
78fn plan_args(prompt: &str, model: Option<&str>) -> Vec<String> {
80 let mut args = vec!["run".into(), prompt.into()];
81 if let Some(m) = model {
82 args.push("--model".into());
83 args.push(m.into());
84 }
85 args
86}
87
88fn interactive_args(prompt: &str, model: Option<&str>) -> Vec<String> {
90 let mut args = Vec::new();
91 if let Some(m) = model {
92 args.push("--model".into());
93 args.push(m.into());
94 }
95 args.push(prompt.into());
96 args
97}
98
99fn parse(out: &SubprocessOutput) -> ParsedHarness {
100 if let Some(value) = last_json_object(&out.stdout) {
102 return parse_value(&value, out);
103 }
104
105 let mut result = String::new();
107 let mut session_id = None;
108 let mut usage = Usage::default();
109 let mut is_error = false;
110 let mut saw = false;
111
112 for line in out.stdout.lines() {
113 let line = line.trim();
114 if !line.starts_with('{') {
115 continue;
116 }
117 let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
118 continue;
119 };
120 saw = true;
121 let ty = v.get("type").and_then(|t| t.as_str()).unwrap_or("");
122 match ty {
123 "text" | "message" | "assistant" | "result" => {
124 let t = text_from(&v).or_else(|| {
125 v.get("data")
126 .and_then(|d| d.as_str())
127 .map(|s| s.to_string())
128 });
129 if let Some(t) = t {
130 if ty == "text" {
131 result.push_str(&t);
132 } else {
133 result = t;
134 }
135 }
136 }
137 "error" => {
138 is_error = true;
139 if let Some(t) = text_from(&v) {
140 result = t;
141 }
142 }
143 "done" | "end" | "complete" => {
144 session_id = v
145 .get("sessionID")
146 .or_else(|| v.get("session_id"))
147 .or_else(|| v.get("sessionId"))
148 .and_then(|s| s.as_str())
149 .map(String::from)
150 .or(session_id);
151 if let Some(u) = v.get("usage") {
152 fill_usage(&mut usage, u);
153 }
154 }
155 _ => {
156 if let Some(t) = text_from(&v) {
157 if t.len() > result.len() {
158 result = t;
159 }
160 }
161 }
162 }
163 if let Some(u) = v.get("usage") {
164 fill_usage(&mut usage, u);
165 }
166 session_id = v
167 .get("session_id")
168 .or_else(|| v.get("sessionID"))
169 .and_then(|s| s.as_str())
170 .map(String::from)
171 .or(session_id);
172 }
173
174 if !result.trim().is_empty() {
175 return ParsedHarness {
176 result: result.trim().to_string(),
177 session_id,
178 usage,
179 is_error,
180 };
181 }
182 if saw {
183 return ParsedHarness::raw(&out.stdout);
184 }
185 ParsedHarness::raw(&out.stdout)
186}
187
188fn parse_value(value: &serde_json::Value, out: &SubprocessOutput) -> ParsedHarness {
189 let result = text_from(value).unwrap_or_else(|| out.stdout.trim().to_string());
190
191 let session_id = value
192 .get("session_id")
193 .or_else(|| value.get("sessionID"))
194 .or_else(|| value.get("sessionId"))
195 .and_then(|v| v.as_str())
196 .map(|s| s.to_string());
197
198 let mut usage = Usage::default();
199 if let Some(u) = value.get("usage") {
200 fill_usage(&mut usage, u);
201 }
202
203 let is_error = value
204 .get("error")
205 .map(|e| !e.is_null())
206 .or_else(|| value.get("is_error").and_then(|b| b.as_bool()))
207 .or_else(|| value.get("ok").and_then(|b| b.as_bool().map(|ok| !ok)))
208 .unwrap_or(false);
209
210 ParsedHarness {
211 result,
212 session_id,
213 usage,
214 is_error,
215 }
216}
217
218fn text_from(v: &serde_json::Value) -> Option<String> {
219 const KEYS: &[&str] = &[
220 "result", "text", "message", "content", "output", "response", "data",
221 ];
222 for k in KEYS {
223 if let Some(s) = v.get(*k).and_then(|x| x.as_str()) {
224 let t = s.trim();
225 if !t.is_empty() {
226 return Some(t.to_string());
227 }
228 }
229 }
230 if let Some(arr) = v.get("content").and_then(|c| c.as_array()) {
231 let mut acc = String::new();
232 for block in arr {
233 if let Some(t) = block.get("text").and_then(|t| t.as_str()) {
234 acc.push_str(t);
235 } else if let Some(t) = block.as_str() {
236 acc.push_str(t);
237 }
238 }
239 if !acc.trim().is_empty() {
240 return Some(acc);
241 }
242 }
243 None
244}
245
246fn fill_usage(usage: &mut Usage, u: &serde_json::Value) {
247 if let Some(n) = u
248 .get("input_tokens")
249 .or_else(|| u.get("prompt_tokens"))
250 .or_else(|| u.get("input"))
251 .and_then(|x| x.as_u64())
252 {
253 usage.prompt_tokens = n;
254 }
255 if let Some(n) = u
256 .get("output_tokens")
257 .or_else(|| u.get("completion_tokens"))
258 .or_else(|| u.get("output"))
259 .and_then(|x| x.as_u64())
260 {
261 usage.completion_tokens = n;
262 }
263}
264
265fn line_mapper(line: &str) -> Vec<WorkerEvent> {
266 let t = line.trim();
267 if t.is_empty() {
268 return Vec::new();
269 }
270 if t.starts_with('{') {
271 if let Ok(v) = serde_json::from_str::<serde_json::Value>(t) {
272 return map_json(&v);
273 }
274 }
275 let lower = t.to_ascii_lowercase();
277 if lower.contains("read ") || lower.contains("reading ") {
278 return vec![WorkerEvent::Reading(t.to_string())];
279 }
280 if lower.contains("write ") || lower.contains("edit ") || lower.contains("wrote ") {
281 return vec![WorkerEvent::Editing(t.to_string())];
282 }
283 vec![WorkerEvent::Raw(t.to_string())]
284}
285
286fn map_json(v: &serde_json::Value) -> Vec<WorkerEvent> {
287 let ty = v.get("type").and_then(|t| t.as_str()).unwrap_or("");
288 match ty {
289 "text" | "token" => text_from(v)
290 .or_else(|| v.get("data").and_then(|d| d.as_str()).map(String::from))
291 .map(|t| vec![WorkerEvent::Token(t)])
292 .unwrap_or_default(),
293 "message" | "assistant" | "result" => text_from(v)
294 .map(|t| vec![WorkerEvent::Message(t)])
295 .unwrap_or_default(),
296 "thinking" | "thought" | "reasoning" => text_from(v)
297 .or_else(|| v.get("data").and_then(|d| d.as_str()).map(String::from))
298 .map(|t| vec![WorkerEvent::Thinking(t)])
299 .unwrap_or_default(),
300 "tool" | "tool_use" | "tool_call" => {
301 let name = v
302 .get("name")
303 .or_else(|| v.get("tool"))
304 .and_then(|n| n.as_str())
305 .unwrap_or("tool");
306 let input = v.get("input").cloned().unwrap_or(serde_json::Value::Null);
307 vec![tool_event(name, &input)]
308 }
309 "file" | "read" => {
310 let p = v
311 .get("path")
312 .or_else(|| v.get("file"))
313 .and_then(|p| p.as_str())
314 .unwrap_or("file");
315 vec![WorkerEvent::Reading(p.into())]
316 }
317 "write" | "edit" => {
318 let p = v
319 .get("path")
320 .or_else(|| v.get("file"))
321 .and_then(|p| p.as_str())
322 .unwrap_or("file");
323 vec![WorkerEvent::Editing(format!("editing {p}"))]
324 }
325 "error" => text_from(v)
326 .map(|t| vec![WorkerEvent::Message(format!("error: {t}"))])
327 .unwrap_or_default(),
328 _ => Vec::new(),
329 }
330}
331
332fn tool_event(name: &str, input: &serde_json::Value) -> WorkerEvent {
333 let s = |k: &str| {
334 input
335 .get(k)
336 .and_then(|v| v.as_str())
337 .unwrap_or("")
338 .to_string()
339 };
340 let path = {
341 let p = s("path");
342 if p.is_empty() {
343 s("file_path")
344 } else {
345 p
346 }
347 };
348 match name {
349 "Read" | "read" => WorkerEvent::Reading(path),
350 "Write" | "write" => WorkerEvent::Editing(format!("writing {path}")),
351 "Edit" | "edit" => WorkerEvent::Editing(format!("editing {path}")),
352 "Bash" | "bash" | "shell" => {
353 let cmd = s("command");
354 WorkerEvent::ToolUse(if cmd.is_empty() { name.into() } else { cmd })
355 }
356 other => WorkerEvent::ToolUse(other.to_string()),
357 }
358}
359
360fn provision(servers: &[McpServerSpec], scratch: &Path) -> Result<Provision> {
361 mcp_util::provision_opencode_style(servers, scratch)
362}
363
364#[cfg(test)]
365mod tests {
366 use super::*;
367 use rinne_core::worker::ExecStatus;
368
369 fn out(stdout: &str) -> SubprocessOutput {
370 SubprocessOutput {
371 stdout: stdout.into(),
372 stderr: String::new(),
373 exit_code: Some(0),
374 status: ExecStatus::Success,
375 wall_ms: 5,
376 }
377 }
378
379 #[test]
380 fn parses_result_object() {
381 let json = r#"{"result":"all green","sessionID":"oc1","usage":{"input_tokens":3,"output_tokens":2}}"#;
382 let p = parse(&out(json));
383 assert_eq!(p.result, "all green");
384 assert_eq!(p.session_id.as_deref(), Some("oc1"));
385 assert_eq!(p.usage.prompt_tokens, 3);
386 assert_eq!(p.usage.completion_tokens, 2);
387 }
388
389 #[test]
390 fn parses_ndjson_text_stream() {
391 let stdout = r#"
392{"type":"text","data":"Hello "}
393{"type":"text","data":"world"}
394{"type":"done","session_id":"s2"}
395"#;
396 let p = parse(&out(stdout));
397 assert!(p.result.contains("Hello"), "got {:?}", p.result);
398 assert!(p.result.contains("world"), "got {:?}", p.result);
399 assert_eq!(p.session_id.as_deref(), Some("s2"));
400 }
401
402 #[test]
403 fn line_mapper_tool() {
404 let evs = line_mapper(r#"{"type":"tool","name":"Read","input":{"path":"a.rs"}}"#);
405 assert!(matches!(evs.first(), Some(WorkerEvent::Reading(_))));
406 }
407}