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