1use crate::streaming::parse_json_records;
5use crate::tools::shell::{
6 build_command_head, escape_arg, escape_single_quotes, lookup_model_alias,
7};
8use serde_json::Value;
9use std::collections::HashMap;
10
11pub const READ_ONLY_PERMISSION: &str = r#"{"edit":"deny","bash":"deny","task":"deny"}"#;
13
14pub fn get_model_map() -> HashMap<&'static str, &'static str> {
16 let mut map = HashMap::new();
17 map.insert("formal-ai", "formalai/formal-ai");
19 map.insert("formalai/formal-ai", "formalai/formal-ai");
20 map.insert("gpt4", "openai/gpt-4");
21 map.insert("gpt4o", "openai/gpt-4o");
22 map.insert("big-pickle", "opencode/big-pickle");
23 map.insert("nemotron-3-ultra-free", "opencode/nemotron-3-ultra-free");
24 map.insert(
25 "nemotron-3.5-lightning-free",
26 "opencode/nemotron-3.5-lightning-free",
27 );
28 map.insert("ling-3.1-flash-free", "opencode/ling-3.1-flash-free");
29 map.insert("mimo-v2.6-flash-free", "opencode/mimo-v2.6-flash-free");
30 map.insert("step-5-preview-free", "opencode/step-5-preview-free");
31 map.insert("exo-free", "opencode/exo-free");
32 map.insert("opus", "anthropic/claude-opus-5-5");
33 map.insert("sonnet", "anthropic/claude-sonnet-5-5");
34 map.insert("haiku", "anthropic/claude-haiku-5-5");
35 map.insert("fable", "anthropic/claude-fable-5-1");
36 map.insert("claude", "anthropic/claude-sonnet-5-5");
37 map.insert("gemini", "google/gemini-3.1-pro-preview");
38 map.insert("grok", "opencode/grok-code");
39 map.insert("grok-code", "opencode/grok-code");
40 map.insert("grok-code-fast-1", "opencode/grok-code");
41 map
42}
43
44pub fn map_model_to_id(model: &str) -> String {
52 lookup_model_alias(&get_model_map(), model).unwrap_or_else(|| model.to_string())
53}
54
55#[derive(Debug, Clone, Default)]
57pub struct OpencodeBuildOptions {
58 pub prompt: Option<String>,
59 pub prompt_file: Option<String>,
60 pub system_prompt: Option<String>,
61 pub model: Option<String>,
62 pub json: bool,
63 pub resume: Option<String>,
64 pub read_only: bool,
65 pub executable: Option<String>,
66 pub extra_env: Vec<(String, String)>,
67 pub unset_env: Vec<String>,
69 pub extra_args: Vec<String>,
70}
71
72pub fn build_args(options: &OpencodeBuildOptions) -> Vec<String> {
80 let mut args = vec!["run".to_string()];
81
82 if let Some(ref model) = options.model {
83 let mapped_model = map_model_to_id(model);
84 args.push("--model".to_string());
85 args.push(mapped_model);
86 }
87
88 if options.json {
90 args.push("--format".to_string());
91 args.push("json".to_string());
92 }
93
94 if let Some(ref resume) = options.resume {
95 args.push("--session".to_string());
96 args.push(resume.clone());
97 }
98
99 args.extend(options.extra_args.clone());
100
101 args
102}
103
104pub fn build_command(options: &OpencodeBuildOptions) -> String {
113 let args = build_args(options);
114 let args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
115
116 let combined_prompt = match (&options.system_prompt, &options.prompt) {
118 (Some(sys), Some(prompt)) => format!("{}\n\n{}", sys, prompt),
119 (Some(sys), None) => sys.clone(),
120 (None, Some(prompt)) => prompt.clone(),
121 (None, None) => String::new(),
122 };
123
124 let input_command = options.prompt_file.as_ref().map_or_else(
126 || format!("printf '%s' '{}'", escape_single_quotes(&combined_prompt)),
127 |prompt_file| format!("cat {}", escape_arg(prompt_file)),
128 );
129 let executable = options.executable.as_deref().unwrap_or("opencode");
130 let mut extra_env = Vec::new();
131 if options.read_only {
132 extra_env.push((
133 "OPENCODE_PERMISSION".to_string(),
134 READ_ONLY_PERMISSION.to_string(),
135 ));
136 }
137 extra_env.extend(options.extra_env.clone());
138
139 format!(
140 "{} | {} {}",
141 input_command,
142 build_command_head(executable, &options.unset_env, &extra_env, &[]),
143 args_str.join(" ")
144 )
145 .trim()
146 .to_string()
147}
148
149pub fn parse_output(output: &str) -> Vec<Value> {
158 parse_json_records(output)
159}
160
161pub fn extract_session_id(output: &str) -> Option<String> {
169 let messages = parse_output(output);
170
171 for msg in messages {
172 if let Some(session_id) = msg
173 .get("session_id")
174 .or_else(|| msg.get("sessionID"))
175 .and_then(|v| v.as_str())
176 {
177 return Some(session_id.to_string());
178 }
179 }
180
181 None
182}
183
184pub type OpencodeUsage = super::agent::AgentUsage;
186
187pub fn extract_usage(output: &str) -> OpencodeUsage {
195 let mut result = super::agent::extract_usage(output);
196 for event in parse_output(output) {
197 if let Some(record) = event.get("usage") {
198 result.input_tokens += super::usage::count(record, super::usage::INPUT);
199 result.output_tokens += super::usage::count(record, super::usage::OUTPUT);
200 }
201 }
202 result
203}
204
205#[derive(Debug, Clone)]
207pub struct OpencodeTool {
208 pub name: &'static str,
209 pub display_name: &'static str,
210 pub executable: &'static str,
211 pub supports_json_output: bool,
212 pub supports_json_input: bool,
213 pub supports_system_prompt: bool,
214 pub supports_resume: bool,
215 pub supports_read_only: bool,
216 pub supports_ask: bool,
217 pub default_model: &'static str,
218}
219
220impl Default for OpencodeTool {
221 fn default() -> Self {
222 Self {
223 name: "opencode",
224 display_name: "OpenCode CLI",
225 executable: "opencode",
226 supports_json_output: true,
227 supports_json_input: false, supports_system_prompt: false, supports_resume: true,
230 supports_read_only: true, supports_ask: false, default_model: "big-pickle",
233 }
234 }
235}
236
237