1use super::usage::{self, count};
5use crate::streaming::parse_json_records;
6use crate::tools::shell::{build_command_head, escape_arg, lookup_model_alias};
7use serde_json::Value;
8use std::collections::HashMap;
9
10pub fn get_model_map() -> HashMap<&'static str, &'static str> {
12 let mut map = HashMap::new();
13 map.insert("formal-ai", "formal-ai");
15 map.insert("formalai/formal-ai", "formal-ai");
16 map.insert("auto", "auto");
17 map.insert("pro", "pro");
18 map.insert("flash", "flash");
19 map.insert("flash-lite", "flash-lite");
20 map.insert("gemini", "flash");
21 map.insert("lite", "flash-lite");
22 map.insert("gemini-pro", "pro");
23 map.insert("gemini-flash", "flash");
24 map.insert("gemini-flash-lite", "flash-lite");
25 map.insert("3.1-pro", "gemini-3.1-pro-preview");
26 map.insert("3-pro", "gemini-3-pro-preview");
27 map.insert("2.5-pro", "gemini-2.5-pro");
28 map.insert("3.8-flash", "gemini-3.8-flash");
29 map.insert("3.5-flash", "gemini-3.5-flash");
30 map.insert("3-flash", "gemini-3-flash-preview");
31 map.insert("3.5-flash-lite", "gemini-3.5-flash-lite");
32 map.insert("3.1-flash-lite", "gemini-3.1-flash-lite");
33 map.insert("gemini-3.1-pro-preview", "gemini-3.1-pro-preview");
34 map.insert("gemini-3-pro-preview", "gemini-3-pro-preview");
35 map.insert("gemini-3.8-flash", "gemini-3.8-flash");
36 map.insert("gemini-3.5-flash", "gemini-3.5-flash");
37 map.insert("gemini-3-flash-preview", "gemini-3-flash-preview");
38 map.insert("gemini-3-flash", "gemini-3-flash");
39 map.insert("gemini-3.5-flash-lite", "gemini-3.5-flash-lite");
40 map.insert("gemini-3.1-flash-lite", "gemini-3.1-flash-lite");
41 map.insert("gemini-2.5-pro", "gemini-2.5-pro");
42 map.insert("gemma-4-31b-it", "gemma-4-31b-it");
43 map.insert("gemma-4-26b-a4b-it", "gemma-4-26b-a4b-it");
44 map.insert("2.5-flash", "gemini-2.5-flash");
45 map.insert("2.5-lite", "gemini-2.5-flash-lite");
46 map.insert("gemini-2.5-flash", "gemini-2.5-flash");
47 map.insert("gemini-2.5-flash-lite", "gemini-2.5-flash-lite");
48 map
49}
50
51pub fn map_model_to_id(model: &str) -> String {
59 lookup_model_alias(&get_model_map(), model).unwrap_or_else(|| model.to_string())
60}
61
62#[derive(Debug, Clone, Default)]
64pub struct GeminiBuildOptions {
65 pub prompt: Option<String>,
66 pub prompt_file: Option<String>,
67 pub system_prompt: Option<String>,
68 pub model: Option<String>,
69 pub resume: Option<String>,
70 pub json: bool,
71 pub yolo: bool,
72 pub read_only: bool,
73 pub sandbox: bool,
74 pub debug: bool,
75 pub checkpointing: bool,
76 pub interactive: bool,
77 pub executable: Option<String>,
78 pub extra_env: Vec<(String, String)>,
79 pub unset_env: Vec<String>,
81 pub extra_args: Vec<String>,
82 pub skip_default_safety_flags: bool,
83}
84
85impl GeminiBuildOptions {
86 pub fn new() -> Self {
88 Self {
89 yolo: true,
90 ..Default::default()
91 }
92 }
93}
94
95pub fn build_args(options: &GeminiBuildOptions) -> Vec<String> {
103 let mut args = Vec::new();
104 if let Some(resume) = &options.resume {
105 args.extend(["--resume".into(), resume.clone()]);
106 }
107
108 if let Some(ref model) = options.model {
109 let mapped_model = map_model_to_id(model);
110 args.push("-m".to_string());
111 args.push(mapped_model);
112 }
113
114 if options.read_only {
115 args.push("--approval-mode".to_string());
116 args.push("plan".to_string());
117 } else if options.yolo && !options.skip_default_safety_flags {
118 args.push("--yolo".to_string());
120 }
121
122 if options.sandbox {
124 args.push("--sandbox".to_string());
125 }
126
127 if options.debug {
129 args.push("-d".to_string());
130 }
131
132 if options.checkpointing {
134 args.push("--checkpointing".to_string());
135 }
136
137 if options.json {
139 args.push("--output-format".to_string());
140 args.push("stream-json".to_string());
141 }
142
143 if let Some(ref prompt) = options.prompt {
145 if options.interactive {
146 args.push("-i".to_string());
147 } else {
148 args.push("-p".to_string());
149 }
150 args.push(prompt.clone());
151 }
152
153 args.extend(options.extra_args.clone());
154
155 args
156}
157
158pub fn build_command(options: &GeminiBuildOptions) -> String {
166 let combined_prompt = if options.prompt_file.is_some() {
169 None
170 } else {
171 match (&options.system_prompt, &options.prompt) {
172 (Some(sys), Some(prompt)) => Some(format!("{}\n\n{}", sys, prompt)),
173 (Some(sys), None) => Some(sys.clone()),
174 (None, Some(prompt)) => Some(prompt.clone()),
175 (None, None) => None,
176 }
177 };
178
179 let modified_options = GeminiBuildOptions {
180 prompt: combined_prompt,
181 system_prompt: None,
182 ..options.clone()
183 };
184
185 let args = build_args(&modified_options);
186 let args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
187 let executable = options.executable.as_deref().unwrap_or("gemini");
188 let command = format!(
189 "{} {}",
190 build_command_head(executable, &options.unset_env, &options.extra_env, &[]),
191 args_str.join(" ")
192 )
193 .trim()
194 .to_string();
195
196 if let Some(prompt_file) = &options.prompt_file {
197 return format!("cat {} | {}", escape_arg(prompt_file), command);
198 }
199
200 command
201}
202
203pub fn parse_output(output: &str) -> Vec<Value> {
212 parse_json_records(output)
215}
216
217pub fn extract_session_id(output: &str) -> Option<String> {
225 let messages = parse_output(output);
226
227 for msg in messages {
228 if let Some(session_id) = msg.get("session_id").and_then(|v| v.as_str()) {
229 return Some(session_id.to_string());
230 }
231 if let Some(conv_id) = msg.get("conversation_id").and_then(|v| v.as_str()) {
233 return Some(conv_id.to_string());
234 }
235 }
236
237 None
238}
239
240#[derive(Debug, Clone, Default, serde::Serialize)]
242#[serde(rename_all = "camelCase")]
243pub struct GeminiUsage {
244 pub input_tokens: u64,
245 pub output_tokens: u64,
246 pub total_tokens: u64,
247 pub cache_read_tokens: u64,
248 pub reasoning_tokens: u64,
249 pub cache_creation_tokens: u64,
250}
251
252pub fn extract_usage(output: &str) -> GeminiUsage {
260 let messages = parse_output(output);
261 let mut result = GeminiUsage::default();
262 for record in usage::records("gemini", &messages) {
263 result.input_tokens += count(record, usage::INPUT);
264 result.output_tokens += count(record, usage::OUTPUT);
265 result.cache_read_tokens += count(record, usage::CACHE_READ);
266 result.reasoning_tokens += count(record, usage::REASONING);
267 result.cache_creation_tokens += count(record, usage::CACHE_WRITE);
268 result.total_tokens += count(record, usage::TOTAL);
269 }
270 if result.total_tokens == 0 {
271 result.total_tokens = result.input_tokens + result.output_tokens;
272 }
273 result
274}
275
276#[derive(Debug, Clone, Default)]
278pub struct GeminiErrorResult {
279 pub has_error: bool,
280 pub error_type: Option<String>,
281 pub message: Option<String>,
282}
283
284pub fn detect_errors(output: &str) -> GeminiErrorResult {
292 let messages = parse_output(output);
293
294 for msg in messages {
295 let is_error =
297 msg.get("type").and_then(|v| v.as_str()) == Some("error") || msg.get("error").is_some();
298
299 if is_error {
300 let error_type = msg
301 .get("type")
302 .and_then(|v| v.as_str())
303 .map(|s| s.to_string())
304 .or_else(|| Some("error".to_string()));
305
306 let message = msg
307 .get("message")
308 .and_then(|v| v.as_str())
309 .map(|s| s.to_string())
310 .or_else(|| {
311 msg.get("error")
312 .and_then(|v| v.as_str())
313 .map(|s| s.to_string())
314 })
315 .or_else(|| Some("Unknown error".to_string()));
316
317 return GeminiErrorResult {
318 has_error: true,
319 error_type,
320 message,
321 };
322 }
323 }
324
325 GeminiErrorResult::default()
326}
327
328#[derive(Debug, Clone)]
330pub struct GeminiTool {
331 pub name: &'static str,
332 pub display_name: &'static str,
333 pub executable: &'static str,
334 pub supports_json_output: bool,
335 pub supports_json_input: bool,
336 pub supports_system_prompt: bool,
337 pub supports_resume: bool,
338 pub supports_yolo: bool,
339 pub supports_sandbox: bool,
340 pub supports_checkpointing: bool,
341 pub supports_debug: bool,
342 pub supports_read_only: bool,
343 pub supports_ask: bool,
344 pub default_model: &'static str,
345}
346
347impl Default for GeminiTool {
348 fn default() -> Self {
349 Self {
350 name: "gemini",
351 display_name: "Gemini CLI",
352 executable: "gemini",
353 supports_json_output: true,
354 supports_json_input: false, supports_system_prompt: false, supports_resume: true, supports_yolo: true, supports_sandbox: true, supports_checkpointing: true, supports_debug: true, supports_read_only: true, supports_ask: false, default_model: "flash",
364 }
365 }
366}
367
368