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