Skip to main content

borg/harness/
opencode.rs

1//! opencode 1.x and 2.x: the TS plugin `adapters/opencode/borg.ts`, compiled in and copied to
2//! `~/.config/opencode/plugins/borg.ts` (`$OPENCODE_CONFIG_DIR`, `$XDG_CONFIG_HOME/opencode`). The plugin
3//! translates both ways, sends opencode's pid, emulates the stop's second round and sets its budget.
4
5use std::ffi::OsStr;
6use std::path::{Path, PathBuf};
7use std::time::{Duration, Instant};
8
9use serde_json::Value;
10
11use crate::runner;
12
13use super::{Caps, DroneWake, Harness, Probe, Run, SubAgent, Transcript, Wiring};
14
15pub const ADAPTER: &str = include_str!("../../assets/adapters/opencode/borg.ts");
16
17pub struct Opencode;
18
19impl Harness for Opencode {
20    fn name(&self) -> &'static str {
21        "opencode"
22    }
23
24    fn caps(&self) -> Caps {
25        Caps {
26            prompt_context: true,
27            tool_context: true,
28            // The channels exist (borg.ts); turning these on waits for an evaluation.
29            early_delivery: false,
30            question_dialog: false,
31            transcript: Transcript::None,
32            deny_capture: true,
33            sends_pid: true,
34            // The adapter names the stop's budget itself (`BORG_STOP_BUDGET_MS`).
35            stop_budget: None,
36            session_env: None,
37            pid_env: Some("OPENCODE_PID"),
38            drone_wake: DroneWake::Plugin,
39        }
40    }
41
42    fn wiring(&self) -> Wiring {
43        Wiring::AdapterFile { source: ADAPTER }
44    }
45
46    fn target(&self, home: &Path, var: &dyn Fn(&str) -> Option<PathBuf>) -> PathBuf {
47        let dir = var("OPENCODE_CONFIG_DIR").or_else(|| var("XDG_CONFIG_HOME").map(|x| x.join("opencode")));
48        dir.unwrap_or_else(|| home.join(".config/opencode")).join("plugins/borg.ts")
49    }
50
51    fn probe(&self) -> Probe {
52        Probe { cli: "opencode", tested: " (adapter tested with 1.18.32, 1.19.0, 2.0.23 and 2.0.29)" }
53    }
54
55    /// Each session's subagents, through opencode's CLI (read-only, as `borg assimilate` reads it), and
56    /// only where opencode keeps data under `home` (`$XDG_DATA_HOME/opencode`, else
57    /// `home/.local/share/opencode`). Every session: 1.x only (2.x has no query that lists them).
58    fn sub_runs(&self, home: &Path, session: Option<&str>, since: Option<i64>) -> Vec<Run> {
59        let data = std::env::var_os("XDG_DATA_HOME").filter(|v| !v.is_empty()).map_or_else(|| home.join(".local/share"), PathBuf::from);
60        if !data.join("opencode").is_dir() {
61            return Vec::new();
62        }
63        let here = std::env::current_dir().unwrap_or_else(|_| std::env::temp_dir());
64        session_runs(session, since, &|id, dir| export(id, dir.unwrap_or(&here)), &db)
65    }
66}
67
68// ---------------------------------------------------------------- the CLI
69
70/// How long one opencode CLI call (the query, a listing, one export) may take.
71const CLI_CAP: Duration = Duration::from_secs(30);
72
73/// `opencode <args>` in `dir`, the `opencode` on `path` (None: this process's PATH), capped like a
74/// model call (a hung CLI never stalls the run). PWD names the dir too: opencode takes the project
75/// from it, not from the process cwd. 2.x (`v2`) gets a model call's env (`runner::standalone_env`):
76/// its private server would otherwise load every plugin and the project's own config in the
77/// engineer's repos. The output goes to a file in a private scratch dir: opencode exits before a
78/// full pipe drains, so a large export read through a pipe arrives cut off (seen on 1.19 at 72 KiB),
79/// while a file gets all of it. Here, beside the harness, so `borg assimilate` and the subagent reader
80/// share it without harness/ depending on assimilate.rs (arch.sh M5).
81pub(crate) fn cli(v2: bool, path: Option<&OsStr>, args: &[String], dir: &Path) -> Option<Vec<u8>> {
82    let scratch = runner::Scratch::new("opencode-out")?;
83    let out = scratch.0.join("out.json");
84    let mut cmd = std::process::Command::new("sh");
85    cmd.args(["-c", r#"umask 077; out="$1"; shift; exec opencode "$@" > "$out""#, "sh"]).arg(&out).args(args);
86    cmd.current_dir(dir).env("PWD", dir).env("OPENCODE_DISABLE_AUTOUPDATE", "1");
87    if v2 {
88        let empty = scratch.0.join("config");
89        std::fs::create_dir(&empty).ok()?;
90        runner::standalone_env(&mut cmd, Some(&empty), runner::engineers_config());
91    }
92    if let Some(p) = path {
93        cmd.env("PATH", p);
94    }
95    runner::run_capped(cmd, None, CLI_CAP)?;
96    std::fs::read(&out).ok()
97}
98
99/// The arguments that export session `id` (2.x always `--standalone`: a private server).
100pub(crate) fn export_args(v2: bool, id: &str) -> Vec<String> {
101    let head: &[&str] = if v2 { &["session", "export", "--standalone"] } else { &["export", "--pure"] };
102    head.iter().map(|a| a.to_string()).chain(std::iter::once(id.to_string())).collect()
103}
104
105/// One session's export through this machine's opencode CLI, run in `dir`.
106fn export(id: &str, dir: &Path) -> Option<Value> {
107    let v2 = runner::opencode() == runner::Opencode::V2;
108    cli(v2, None, &export_args(v2, id), dir).and_then(|o| serde_json::from_slice(&o).ok())
109}
110
111/// The rows of a read-only query of opencode 1.x's database; None on 2.x, which has no such query,
112/// or when the call fails.
113fn db(sql: &str) -> Option<Vec<Value>> {
114    if runner::opencode() == runner::Opencode::V2 {
115        return None;
116    }
117    let args: Vec<String> = ["db", "--pure", "--format", "json", sql].iter().map(|a| a.to_string()).collect();
118    cli(false, None, &args, &std::env::temp_dir()).and_then(|o| serde_json::from_slice(&o).ok())
119}
120
121// ---------------------------------------------------------------- subagents
122
123/// Exports a session by id, in the directory given (else wherever it runs).
124pub type Export<'a> = &'a dyn Fn(&str, Option<&Path>) -> Option<Value>;
125/// Runs a read-only query of opencode 1.x's database (None: no such query).
126pub type Query<'a> = &'a dyn Fn(&str) -> Option<Vec<Value>>;
127
128/// A guard, not a tuning knob: at most this many children of one session are exported, the rest read
129/// from the parent's copy of their final text.
130pub const CHILDREN: usize = 20;
131/// All of one session's exports stop after this long; the remaining children are read from the parent.
132const SESSION_BUDGET: Duration = Duration::from_secs(120);
133
134/// An opencode session id (`ses_` and alphanumerics), the only thing passed to its CLI.
135fn session_id(s: &str) -> bool {
136    s.starts_with("ses_") && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
137}
138
139/// One run per main session that started subagents, oldest first: `session` (a `ses_…` id) only, else
140/// every parent of a subagent session since `since` (1.x's query). A subagent is a child session; the
141/// parent's task tool call (1.x `task`, 2.x `subagent`) names it (`metadata.sessionId`/`sessionID`)
142/// with its description, agent and prompt, and holds its final text. Its export gives its cwd and
143/// work. opencode has no structured output: `output` stays None.
144pub fn session_runs(session: Option<&str>, since: Option<i64>, export: Export, query: Query) -> Vec<Run> {
145    let roots: Vec<String> = match session {
146        Some(s) if session_id(s) => vec![s.to_string()],
147        Some(_) => Vec::new(),
148        None => {
149            let since = since.map(|ms| format!(" AND time_created >= {ms}")).unwrap_or_default();
150            let sql = format!("SELECT parent_id AS id, MIN(time_created) AS t FROM session WHERE parent_id IS NOT NULL{since} GROUP BY parent_id ORDER BY t");
151            query(&sql).unwrap_or_default().iter().filter_map(|r| r["id"].as_str().filter(|s| session_id(s)).map(String::from)).collect()
152        }
153    };
154    let mut runs: Vec<Run> = roots
155        .iter()
156        .filter_map(|id| {
157            let until = Instant::now() + SESSION_BUDGET;
158            run_of(&export(id, None)?, export, until)
159        })
160        .collect();
161    runs.sort_by_key(|r| r.started);
162    runs
163}
164
165/// A message's parts: 1.x `parts`, 2.x `content`.
166fn parts(m: &Value) -> impl Iterator<Item = &Value> {
167    m["parts"].as_array().or(m["content"].as_array()).into_iter().flatten()
168}
169
170fn assistant(m: &Value) -> bool {
171    m["info"]["role"] == "assistant" || m["type"] == "assistant"
172}
173
174fn text(v: &Value) -> String {
175    match v {
176        Value::String(s) => s.clone(),
177        Value::Array(bs) => bs.iter().filter_map(|b| b["text"].as_str()).collect::<Vec<_>>().join("\n"),
178        _ => String::new(),
179    }
180}
181
182/// The run of `root`'s children: each exported while the id is valid, fewer than `CHILDREN` were and
183/// `until` has not passed; else read from the parent's copy of its final text.
184fn run_of(root: &Value, export: Export, until: Instant) -> Option<Run> {
185    let info = &root["info"];
186    let dir = info["directory"].as_str().or(info["location"]["directory"].as_str()).unwrap_or_default();
187    let mut agents = Vec::new();
188    let mut exported = 0;
189    for m in root["messages"].as_array().into_iter().flatten() {
190        let at = m["info"]["time"]["created"].as_i64().or(m["time"]["created"].as_i64()).unwrap_or(0);
191        for p in parts(m).filter(|p| p["type"] == "tool") {
192            let state = &p["state"];
193            let Some(child) = state["metadata"]["sessionId"].as_str().or(state["metadata"]["sessionID"].as_str()) else { continue };
194            let input = &state["input"];
195            let s = |k: &str| input[k].as_str().unwrap_or_default().to_string();
196            let started = state["time"]["start"].as_i64().or(p["time"]["created"].as_i64()).unwrap_or(at);
197            let mut a = SubAgent {
198                label: s("description"),
199                kind: input["subagent_type"].as_str().map_or_else(|| s("agent"), String::from),
200                started,
201                prompt: s("prompt"),
202                cwd: dir.to_string(),
203                ..Default::default()
204            };
205            let read = session_id(child) && exported < CHILDREN && Instant::now() < until;
206            exported += usize::from(read);
207            match read.then(|| export(child, (!dir.is_empty()).then_some(Path::new(dir)))).flatten() {
208                Some(c) => from_export(&mut a, &c),
209                // Without its export (or not read), its final text as the parent saw it.
210                None => {
211                    a.work = state["output"].as_str().map_or_else(|| text(&state["content"]), String::from);
212                    a.final_text = a.work.clone();
213                }
214            }
215            agents.push(a);
216        }
217    }
218    if agents.is_empty() {
219        return None;
220    }
221    agents.sort_by_key(|a| a.started);
222    let id = info["id"].as_str().unwrap_or_default().to_string();
223    let started = info["time"]["created"].as_i64().unwrap_or(agents[0].started);
224    Some(Run { session: id.clone(), id, name: info["title"].as_str().unwrap_or_default().to_string(), started, agents, loose: false })
225}
226
227/// A child's work from its export `c`: its cwd when the export names one, and its assistant parts.
228fn from_export(a: &mut SubAgent, c: &Value) {
229    let ci = &c["info"];
230    if let Some(d) = ci["directory"].as_str().or(ci["location"]["directory"].as_str()) {
231        a.cwd = d.to_string();
232    }
233    for p in c["messages"].as_array().into_iter().flatten().filter(|m| assistant(m)).flat_map(parts) {
234        match p["type"].as_str() {
235            Some("tool") => a.called(&p["state"]["input"]),
236            Some("text") => a.said(p["text"].as_str().unwrap_or_default()),
237            _ => {}
238        }
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245    use serde_json::json;
246    use std::cell::RefCell;
247
248    /// A parent with one task call per child id, each with its final text.
249    fn parent(children: &[String]) -> Value {
250        let parts: Vec<Value> = children
251            .iter()
252            .map(|c| json!({"type": "tool", "state": {"input": {"description": c}, "metadata": {"sessionId": c}, "output": format!("parent's copy of {c}")}}))
253            .collect();
254        json!({"info": {"id": "ses_root", "directory": "/w/app"}, "messages": [{"info": {"role": "assistant"}, "parts": parts}]})
255    }
256
257    fn child(id: &str) -> Value {
258        json!({"info": {"directory": "/w/app"}, "messages": [{"info": {"role": "assistant"}, "parts": [{"type": "text", "text": format!("export of {id}")}]}]})
259    }
260
261    #[test]
262    fn only_valid_ids_are_exported_and_at_most_children_of_them() {
263        let asked = RefCell::new(Vec::new());
264        let export = |id: &str, _: Option<&Path>| {
265            asked.borrow_mut().push(id.to_string());
266            Some(child(id))
267        };
268        let mut ids: Vec<String> = (0..CHILDREN + 5).map(|i| format!("ses_c{i}")).collect();
269        ids.insert(0, "--help".into());
270        ids.insert(1, "ses_../x".into());
271        let run = run_of(&parent(&ids), &export, Instant::now() + SESSION_BUDGET).unwrap();
272        let asked = asked.into_inner();
273        assert_eq!(asked.len(), CHILDREN, "{asked:?}");
274        assert!(asked.iter().all(|id| session_id(id)), "{asked:?}");
275        let works: Vec<&str> = run.agents.iter().map(|a| a.work.trim()).collect();
276        assert_eq!((works[0], works[1], works[2]), ("parent's copy of --help", "parent's copy of ses_../x", "export of ses_c0"));
277        assert_eq!(works.last().copied(), Some(format!("parent's copy of ses_c{}", CHILDREN + 4).as_str()));
278    }
279
280    #[test]
281    fn past_the_sessions_deadline_children_are_read_from_the_parent() {
282        let export = |_: &str, _: Option<&Path>| -> Option<Value> { panic!("no export after the deadline") };
283        let run = run_of(&parent(&["ses_c0".into()]), &export, Instant::now()).unwrap();
284        assert_eq!(run.agents[0].work, "parent's copy of ses_c0");
285    }
286}