1use 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
12pub const READ_ONLY_PERMISSION: &str = r#"{"edit":"deny","bash":"deny","task":"deny"}"#;
14
15pub fn get_model_map() -> HashMap<&'static str, &'static str> {
17 let mut map = HashMap::new();
18 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
45pub 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#[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 pub unset_env: Vec<String>,
70 pub extra_args: Vec<String>,
71 pub launch: LaunchOptions,
73}
74
75pub fn build_args(options: &OpencodeBuildOptions) -> Vec<String> {
83 let mut args = vec!["run".to_string()];
84 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 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
115pub 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 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 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 extra_env.extend(options.extra_env.clone());
149
150 format!(
151 "{} | {} {}",
152 input_command,
153 build_command_head(executable, &options.unset_env, &extra_env, &[]),
154 args_str.join(" ")
155 )
156 .trim()
157 .to_string()
158}
159
160pub fn parse_output(output: &str) -> Vec<Value> {
169 parse_json_records(output)
170}
171
172pub fn extract_session_id(output: &str) -> Option<String> {
180 let messages = parse_output(output);
181
182 for msg in messages {
183 if let Some(session_id) = msg
184 .get("session_id")
185 .or_else(|| msg.get("sessionID"))
186 .and_then(|v| v.as_str())
187 {
188 return Some(session_id.to_string());
189 }
190 }
191
192 None
193}
194
195pub type OpencodeUsage = super::agent::AgentUsage;
197
198pub fn extract_usage(output: &str) -> OpencodeUsage {
206 let mut result = super::agent::extract_usage(output);
207 for event in parse_output(output) {
208 if let Some(record) = event.get("usage") {
209 result.input_tokens += super::usage::count(record, super::usage::INPUT);
210 result.output_tokens += super::usage::count(record, super::usage::OUTPUT);
211 }
212 }
213 result
214}
215
216#[derive(Debug, Clone)]
218pub struct OpencodeTool {
219 pub name: &'static str,
220 pub display_name: &'static str,
221 pub executable: &'static str,
222 pub supports_json_output: bool,
223 pub supports_json_input: bool,
224 pub supports_system_prompt: bool,
225 pub supports_resume: bool,
226 pub supports_read_only: bool,
227 pub supports_ask: bool,
228 pub default_model: &'static str,
229}
230
231impl Default for OpencodeTool {
232 fn default() -> Self {
233 Self {
234 name: "opencode",
235 display_name: "OpenCode CLI",
236 executable: "opencode",
237 supports_json_output: true,
238 supports_json_input: false, supports_system_prompt: false, supports_resume: true,
241 supports_read_only: true, supports_ask: false, default_model: "big-pickle",
244 }
245 }
246}
247
248