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