Skip to main content

agent_commander/tools/
opencode.rs

1//! OpenCode CLI tool configuration
2//! Based on hive-mind's opencode.lib.mjs implementation
3
4use crate::streaming::parse_json_records;
5use crate::tools::shell::{
6    build_command_head, escape_arg, escape_single_quotes, lookup_model_alias,
7};
8use serde_json::Value;
9use std::collections::HashMap;
10
11/// OpenCode permission policy used for read-only planning mode.
12pub const READ_ONLY_PERMISSION: &str = r#"{"edit":"deny","bash":"deny","task":"deny"}"#;
13
14/// Get the OpenCode model map
15pub fn get_model_map() -> HashMap<&'static str, &'static str> {
16    let mut map = HashMap::new();
17    // Pinned Hive Mind catalogue; generated by experiments/sync-model-catalog.py.
18    map.insert("formal-ai", "formalai/formal-ai");
19    map.insert("formalai/formal-ai", "formalai/formal-ai");
20    map.insert("gpt4", "openai/gpt-4");
21    map.insert("gpt4o", "openai/gpt-4o");
22    map.insert("big-pickle", "opencode/big-pickle");
23    map.insert("nemotron-3-ultra-free", "opencode/nemotron-3-ultra-free");
24    map.insert(
25        "nemotron-3.5-lightning-free",
26        "opencode/nemotron-3.5-lightning-free",
27    );
28    map.insert("ling-3.1-flash-free", "opencode/ling-3.1-flash-free");
29    map.insert("mimo-v2.6-flash-free", "opencode/mimo-v2.6-flash-free");
30    map.insert("step-5-preview-free", "opencode/step-5-preview-free");
31    map.insert("exo-free", "opencode/exo-free");
32    map.insert("opus", "anthropic/claude-opus-5-5");
33    map.insert("sonnet", "anthropic/claude-sonnet-5-5");
34    map.insert("haiku", "anthropic/claude-haiku-5-5");
35    map.insert("fable", "anthropic/claude-fable-5-1");
36    map.insert("claude", "anthropic/claude-sonnet-5-5");
37    map.insert("gemini", "google/gemini-3.1-pro-preview");
38    map.insert("grok", "opencode/grok-code");
39    map.insert("grok-code", "opencode/grok-code");
40    map.insert("grok-code-fast-1", "opencode/grok-code");
41    map
42}
43
44/// Map model alias to full model ID
45///
46/// # Arguments
47/// * `model` - Model alias or full ID
48///
49/// # Returns
50/// Full model ID
51pub fn map_model_to_id(model: &str) -> String {
52    lookup_model_alias(&get_model_map(), model).unwrap_or_else(|| model.to_string())
53}
54
55/// OpenCode command build options
56#[derive(Debug, Clone, Default)]
57pub struct OpencodeBuildOptions {
58    pub prompt: Option<String>,
59    pub prompt_file: Option<String>,
60    pub system_prompt: Option<String>,
61    pub model: Option<String>,
62    pub json: bool,
63    pub resume: Option<String>,
64    pub read_only: bool,
65    pub executable: Option<String>,
66    pub extra_env: Vec<(String, String)>,
67    /// Variables removed from the inherited environment (`env -u`)
68    pub unset_env: Vec<String>,
69    pub extra_args: Vec<String>,
70}
71
72/// Build command line arguments for OpenCode
73///
74/// # Arguments
75/// * `options` - Build options
76///
77/// # Returns
78/// Vector of CLI arguments
79pub fn build_args(options: &OpencodeBuildOptions) -> Vec<String> {
80    let mut args = vec!["run".to_string()];
81
82    if let Some(ref model) = options.model {
83        let mapped_model = map_model_to_id(model);
84        args.push("--model".to_string());
85        args.push(mapped_model);
86    }
87
88    // Default to json=true like JavaScript version
89    if options.json {
90        args.push("--format".to_string());
91        args.push("json".to_string());
92    }
93
94    if let Some(ref resume) = options.resume {
95        args.push("--session".to_string());
96        args.push(resume.clone());
97    }
98
99    args.extend(options.extra_args.clone());
100
101    args
102}
103
104/// Build complete command string for OpenCode
105/// OpenCode uses stdin for prompt input
106///
107/// # Arguments
108/// * `options` - Build options
109///
110/// # Returns
111/// Complete command string
112pub fn build_command(options: &OpencodeBuildOptions) -> String {
113    let args = build_args(options);
114    let args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
115
116    // OpenCode expects prompt via stdin, combine system and user prompts
117    let combined_prompt = match (&options.system_prompt, &options.prompt) {
118        (Some(sys), Some(prompt)) => format!("{}\n\n{}", sys, prompt),
119        (Some(sys), None) => sys.clone(),
120        (None, Some(prompt)) => prompt.clone(),
121        (None, None) => String::new(),
122    };
123
124    // Build command with stdin piping
125    let input_command = options.prompt_file.as_ref().map_or_else(
126        || format!("printf '%s' '{}'", escape_single_quotes(&combined_prompt)),
127        |prompt_file| format!("cat {}", escape_arg(prompt_file)),
128    );
129    let executable = options.executable.as_deref().unwrap_or("opencode");
130    let mut extra_env = Vec::new();
131    if options.read_only {
132        extra_env.push((
133            "OPENCODE_PERMISSION".to_string(),
134            READ_ONLY_PERMISSION.to_string(),
135        ));
136    }
137    extra_env.extend(options.extra_env.clone());
138
139    format!(
140        "{} | {} {}",
141        input_command,
142        build_command_head(executable, &options.unset_env, &extra_env, &[]),
143        args_str.join(" ")
144    )
145    .trim()
146    .to_string()
147}
148
149/// Parse JSON messages from OpenCode output
150/// OpenCode outputs NDJSON format
151///
152/// # Arguments
153/// * `output` - Raw output string
154///
155/// # Returns
156/// Vector of parsed JSON messages
157pub fn parse_output(output: &str) -> Vec<Value> {
158    parse_json_records(output)
159}
160
161/// Extract session ID from OpenCode output
162///
163/// # Arguments
164/// * `output` - Raw output string
165///
166/// # Returns
167/// Session ID or None
168pub fn extract_session_id(output: &str) -> Option<String> {
169    let messages = parse_output(output);
170
171    for msg in messages {
172        if let Some(session_id) = msg
173            .get("session_id")
174            .or_else(|| msg.get("sessionID"))
175            .and_then(|v| v.as_str())
176        {
177            return Some(session_id.to_string());
178        }
179    }
180
181    None
182}
183
184/// Usage statistics
185pub type OpencodeUsage = super::agent::AgentUsage;
186
187/// Extract usage statistics from OpenCode output
188///
189/// # Arguments
190/// * `output` - Raw output string
191///
192/// # Returns
193/// Usage statistics
194pub fn extract_usage(output: &str) -> OpencodeUsage {
195    let mut result = super::agent::extract_usage(output);
196    for event in parse_output(output) {
197        if let Some(record) = event.get("usage") {
198            result.input_tokens += super::usage::count(record, super::usage::INPUT);
199            result.output_tokens += super::usage::count(record, super::usage::OUTPUT);
200        }
201    }
202    result
203}
204
205/// OpenCode tool configuration
206#[derive(Debug, Clone)]
207pub struct OpencodeTool {
208    pub name: &'static str,
209    pub display_name: &'static str,
210    pub executable: &'static str,
211    pub supports_json_output: bool,
212    pub supports_json_input: bool,
213    pub supports_system_prompt: bool,
214    pub supports_resume: bool,
215    pub supports_read_only: bool,
216    pub supports_ask: bool,
217    pub default_model: &'static str,
218}
219
220impl Default for OpencodeTool {
221    fn default() -> Self {
222        Self {
223            name: "opencode",
224            display_name: "OpenCode CLI",
225            executable: "opencode",
226            supports_json_output: true,
227            supports_json_input: false, // OpenCode reads plaintext prompts via stdin
228            supports_system_prompt: false, // System prompt is combined with user prompt
229            supports_resume: true,
230            supports_read_only: true, // Supports OPENCODE_PERMISSION
231            supports_ask: false, // OPENCODE_PERMISSION is env-based policy, not a relayable JSON approval stream
232            default_model: "big-pickle",
233        }
234    }
235}
236
237// Tests are in rust/tests/opencode_tests.rs