1use 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
14pub const READ_ONLY_PERMISSION: &str = r#"{"edit":"deny","bash":"deny","task":"deny"}"#;
16
17pub fn get_model_map() -> HashMap<&'static str, &'static str> {
19 let mut map = HashMap::new();
20 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
47pub 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#[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 pub unset_env: Vec<String>,
72 pub extra_args: Vec<String>,
73 pub launch: LaunchOptions,
75}
76
77pub fn build_args(options: &OpencodeBuildOptions) -> Vec<String> {
85 let mut args = vec!["run".to_string()];
86 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 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
117pub 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 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 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
168pub fn parse_output(output: &str) -> Vec<Value> {
177 parse_json_records(output)
178}
179
180pub 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
203pub type OpencodeUsage = super::agent::AgentUsage;
205
206pub 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#[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, supports_system_prompt: false, supports_resume: true,
249 supports_read_only: true, supports_ask: false, default_model: "big-pickle",
252 }
253 }
254}
255
256