agent_commander/tools/
opencode.rs1use 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
9pub const READ_ONLY_PERMISSION: &str = r#"{"edit":"deny","bash":"deny","task":"deny"}"#;
11
12pub fn get_model_map() -> HashMap<&'static str, &'static str> {
14 let mut map = HashMap::new();
15 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
30pub 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#[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
60pub 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 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
92pub 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 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 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
137pub fn parse_output(output: &str) -> Vec<Value> {
146 parse_ndjson(output)
147}
148
149pub 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
172pub type OpencodeUsage = super::agent::AgentUsage;
174
175pub 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#[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, supports_system_prompt: false, supports_resume: true,
218 supports_read_only: true, supports_ask: false, default_model: "grok-code-fast-1",
221 }
222 }
223}
224
225