Skip to main content

rigspark_runtime/
opencode.rs

1use crate::harness::{ChatHarness, DeltaSink, HarnessError, HarnessRequest};
2use serde_json::{Value, json};
3use std::{collections::BTreeMap, path::PathBuf, process::Stdio, time::Duration};
4use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
5use tokio_util::sync::CancellationToken;
6pub struct LaunchSpec {
7    pub args: Vec<String>,
8    pub config: String,
9}
10pub fn launch_spec(input: &HarnessRequest, unrestricted: bool) -> Result<LaunchSpec, HarnessError> {
11    input.validate()?;
12    let raw = rigspark_core::reports::strip_control(&input.model)
13        .trim()
14        .to_owned();
15    if raw.is_empty() {
16        return Err(HarnessError::Invalid);
17    }
18    let model = if raw.contains('/') {
19        raw
20    } else {
21        format!("ollama/{raw}")
22    };
23    let (provider, name) = model.split_once('/').ok_or(HarnessError::Invalid)?;
24    if provider.is_empty() || name.is_empty() {
25        return Err(HarnessError::Invalid);
26    }
27    let prompt = input
28        .messages
29        .iter()
30        .map(|message| {
31            format!(
32                "[{}]\n{}",
33                message.role,
34                rigspark_core::reports::strip_control(&message.content)
35            )
36        })
37        .collect::<Vec<_>>()
38        .join("\n\n");
39    if prompt.len() > 1048576 {
40        return Err(HarnessError::Limit);
41    }
42    let permission = if unrestricted { "allow" } else { "deny" };
43    let mut config = json!({"autoupdate":unrestricted,"share":if unrestricted{"auto"}else{"disabled"},"snapshot":unrestricted,"permission":permission,"agent":{"rigspark-chat":{"description":if unrestricted{"Chat invoked by rigspark (unrestricted)"}else{"Text-only chat invoked by rigspark"},"mode":"primary","permission":permission}}});
44    if provider == "ollama" {
45        config["provider"] = json!({"ollama":{"npm":"@ai-sdk/openai-compatible","name":"Ollama (local)","options":{"baseURL":"http://127.0.0.1:11434/v1"},"models":{name:{"name":name}}}});
46    }
47    Ok(LaunchSpec {
48        args: vec![
49            "run".into(),
50            prompt,
51            "--model".into(),
52            model,
53            "--agent".into(),
54            "rigspark-chat".into(),
55            "--format".into(),
56            "json".into(),
57        ],
58        config: config.to_string(),
59    })
60}
61pub fn parse_event(raw: &str) -> Result<String, HarnessError> {
62    if raw.trim().is_empty() {
63        return Ok(String::new());
64    }
65    if raw.len() > 1048576 {
66        return Err(HarnessError::Limit);
67    }
68    let event: Value = serde_json::from_str(raw).map_err(|_| HarnessError::Response)?;
69    if !event["timestamp"].as_f64().is_some_and(f64::is_finite)
70        || !event["sessionID"]
71            .as_str()
72            .is_some_and(|id| !id.is_empty() && id.len() <= 1024)
73    {
74        return Err(HarnessError::Response);
75    }
76    let part = &event["part"];
77    match event["type"].as_str() {
78        Some("text") if part["type"] == "text" => part["text"]
79            .as_str()
80            .map(rigspark_core::reports::strip_control)
81            .ok_or(HarnessError::Response),
82        Some("error") => Err(HarnessError::Response),
83        Some("step_start" | "step_finish" | "reasoning" | "tool_use") => {
84            if !part["type"]
85                .as_str()
86                .is_some_and(|kind| !kind.is_empty() && kind.len() <= 100)
87            {
88                return Err(HarnessError::Response);
89            }
90            let capped = |value: &str, maximum: usize| {
91                rigspark_core::reports::strip_control(value)
92                    .chars()
93                    .take(maximum)
94                    .collect::<String>()
95            };
96            if event["type"] == "reasoning" {
97                let text = capped(part["text"].as_str().unwrap_or(""), 400);
98                return Ok(if text.is_empty() {
99                    String::new()
100                } else {
101                    format!("\n\n> \u{1f4ad} {text}\n")
102                });
103            }
104            if event["type"] == "tool_use" {
105                let tool = part["tool"].as_str().unwrap_or("tool");
106                let state = &part["state"];
107                let input = &state["input"];
108                let target = [
109                    &state["title"],
110                    &input["filePath"],
111                    &input["command"],
112                    &input["pattern"],
113                ]
114                .into_iter()
115                .filter_map(Value::as_str)
116                .find(|text| !text.is_empty())
117                .unwrap_or("");
118                let target = capped(target, 160);
119                let output = capped(state["output"].as_str().unwrap_or(""), 400);
120                return Ok(format!(
121                    "\n\n> \u{1f527} `{}`{}{}\n",
122                    capped(tool, 100),
123                    if target.is_empty() {
124                        String::new()
125                    } else {
126                        format!(" \u{b7} {target}")
127                    },
128                    if output.is_empty() {
129                        String::new()
130                    } else {
131                        format!("\n\n```\n{output}\n```")
132                    }
133                ));
134            }
135            Ok(String::new())
136        }
137        _ => Err(HarnessError::Response),
138    }
139}
140#[async_trait::async_trait]
141pub trait OpenCodeRunner: Send + Sync {
142    async fn available(&self) -> bool {
143        true
144    }
145    async fn run(
146        &self,
147        spec: &LaunchSpec,
148        cancel: &CancellationToken,
149        sink: &mut DeltaSink<'_>,
150    ) -> Result<(), HarnessError>;
151}
152pub struct NativeOpenCodeRunner {
153    pub binary: PathBuf,
154    pub env: BTreeMap<String, String>,
155}
156#[async_trait::async_trait]
157impl OpenCodeRunner for NativeOpenCodeRunner {
158    async fn available(&self) -> bool {
159        self.binary.is_absolute() && self.binary.is_file()
160    }
161    async fn run(
162        &self,
163        spec: &LaunchSpec,
164        cancel: &CancellationToken,
165        sink: &mut DeltaSink<'_>,
166    ) -> Result<(), HarnessError> {
167        if cancel.is_cancelled() {
168            return Err(HarnessError::Cancelled);
169        }
170        if !self.binary.is_absolute() {
171            return Err(HarnessError::Invalid);
172        }
173        let mut child = tokio::process::Command::new(&self.binary)
174            .args(&spec.args)
175            .env_clear()
176            .envs(&self.env)
177            .env("OPENCODE_CONFIG_CONTENT", &spec.config)
178            .stdin(Stdio::null())
179            .stdout(Stdio::piped())
180            .stderr(Stdio::piped())
181            .kill_on_drop(true)
182            .spawn()
183            .map_err(|_| HarnessError::Unavailable)?;
184        let stdout = child.stdout.take().ok_or(HarnessError::Transport)?;
185        let stderr = child.stderr.take().ok_or(HarnessError::Transport)?;
186        let total = std::sync::atomic::AtomicUsize::new(0);
187        let output = async {
188            let secrets = self
189                .env
190                .iter()
191                .filter(|(name, _)| {
192                    let name = name.to_ascii_lowercase();
193                    ["key", "token", "secret", "password", "credential"]
194                        .iter()
195                        .any(|word| name.contains(word))
196                })
197                .map(|(_, value)| value.clone());
198            let mut redactor = crate::redaction::StreamRedactor::new(secrets);
199            let mut reader = BufReader::new(stdout);
200            loop {
201                let mut line = Vec::new();
202                let count = (&mut reader)
203                    .take(1048577)
204                    .read_until(b'\n', &mut line)
205                    .await
206                    .map_err(|_| HarnessError::Transport)?;
207                if count == 0 {
208                    break;
209                }
210                if count > 1048576
211                    || total.fetch_add(count, std::sync::atomic::Ordering::Relaxed) + count
212                        > 16 * 1024 * 1024
213                {
214                    return Err(HarnessError::Limit);
215                }
216                let text = redactor.push(&parse_event(
217                    std::str::from_utf8(&line).map_err(|_| HarnessError::Response)?,
218                )?);
219                if !text.is_empty() {
220                    sink(&text)?;
221                }
222            }
223            let tail = redactor.finish();
224            if !tail.is_empty() {
225                sink(&tail)?;
226            }
227            Ok::<_, HarnessError>(())
228        };
229        let errors = async {
230            let mut reader = stderr;
231            let mut buffer = [0u8; 8192];
232            loop {
233                let count = reader
234                    .read(&mut buffer)
235                    .await
236                    .map_err(|_| HarnessError::Transport)?;
237                if count == 0 {
238                    break;
239                }
240                if total.fetch_add(count, std::sync::atomic::Ordering::Relaxed) + count
241                    > 16 * 1024 * 1024
242                {
243                    return Err(HarnessError::Limit);
244                }
245            }
246            Ok::<_, HarnessError>(())
247        };
248        let operation = async {
249            tokio::try_join!(output, errors)?;
250            if !child
251                .wait()
252                .await
253                .map_err(|_| HarnessError::Transport)?
254                .success()
255            {
256                return Err(HarnessError::Transport);
257            }
258            Ok(())
259        };
260        let result = tokio::select! {biased;_=cancel.cancelled()=>Err(HarnessError::Cancelled),result=tokio::time::timeout(Duration::from_secs(300),operation)=>result.map_err(|_|HarnessError::Timeout).and_then(|result|result)};
261        if result.is_err() {
262            let _ = tokio::time::timeout(Duration::from_secs(5), child.kill()).await;
263        }
264        result
265    }
266}
267pub struct OpenCodeHarness<'runtime> {
268    pub runner: &'runtime dyn OpenCodeRunner,
269    pub unrestricted: bool,
270}
271#[async_trait::async_trait]
272impl ChatHarness for OpenCodeHarness<'_> {
273    fn name(&self) -> &'static str {
274        "opencode"
275    }
276    async fn available(&self) -> bool {
277        self.runner.available().await
278    }
279    async fn chat(
280        &self,
281        input: &HarnessRequest,
282        cancel: &CancellationToken,
283        sink: &mut DeltaSink<'_>,
284    ) -> Result<String, HarnessError> {
285        let spec = launch_spec(input, self.unrestricted)?;
286        let mut text = String::new();
287        self.runner
288            .run(&spec, cancel, &mut |chunk| {
289                if text.len() + chunk.len() > 16 * 1024 * 1024 {
290                    return Err(HarnessError::Limit);
291                }
292                sink(chunk)?;
293                text.push_str(chunk);
294                Ok(())
295            })
296            .await?;
297        Ok(text)
298    }
299}