1use super::usage::{self, count};
5use crate::streaming::parse_json_records;
6use crate::tools::launch_options::{push_directories, LaunchOptions};
7use crate::tools::shell::{build_command_head, escape_arg, lookup_model_alias};
8use serde_json::Value;
9use std::collections::HashMap;
10
11pub fn get_model_map() -> HashMap<&'static str, &'static str> {
13 let mut map = HashMap::new();
14 map.insert("formal-ai", "formal-ai");
16 map.insert("formalai/formal-ai", "formal-ai");
17 map.insert("auto", "auto");
18 map.insert("pro", "pro");
19 map.insert("flash", "flash");
20 map.insert("flash-lite", "flash-lite");
21 map.insert("gemini", "flash");
22 map.insert("lite", "flash-lite");
23 map.insert("gemini-pro", "pro");
24 map.insert("gemini-flash", "flash");
25 map.insert("gemini-flash-lite", "flash-lite");
26 map.insert("3.1-pro", "gemini-3.1-pro-preview");
27 map.insert("3-pro", "gemini-3-pro-preview");
28 map.insert("2.5-pro", "gemini-2.5-pro");
29 map.insert("3.8-flash", "gemini-3.8-flash");
30 map.insert("3.5-flash", "gemini-3.5-flash");
31 map.insert("3-flash", "gemini-3-flash-preview");
32 map.insert("3.5-flash-lite", "gemini-3.5-flash-lite");
33 map.insert("3.1-flash-lite", "gemini-3.1-flash-lite");
34 map.insert("gemini-3.1-pro-preview", "gemini-3.1-pro-preview");
35 map.insert("gemini-3-pro-preview", "gemini-3-pro-preview");
36 map.insert("gemini-3.8-flash", "gemini-3.8-flash");
37 map.insert("gemini-3.5-flash", "gemini-3.5-flash");
38 map.insert("gemini-3-flash-preview", "gemini-3-flash-preview");
39 map.insert("gemini-3-flash", "gemini-3-flash");
40 map.insert("gemini-3.5-flash-lite", "gemini-3.5-flash-lite");
41 map.insert("gemini-3.1-flash-lite", "gemini-3.1-flash-lite");
42 map.insert("gemini-2.5-pro", "gemini-2.5-pro");
43 map.insert("gemma-4-31b-it", "gemma-4-31b-it");
44 map.insert("gemma-4-26b-a4b-it", "gemma-4-26b-a4b-it");
45 map.insert("2.5-flash", "gemini-2.5-flash");
46 map.insert("2.5-lite", "gemini-2.5-flash-lite");
47 map.insert("gemini-2.5-flash", "gemini-2.5-flash");
48 map.insert("gemini-2.5-flash-lite", "gemini-2.5-flash-lite");
49 map
50}
51
52pub fn map_model_to_id(model: &str) -> String {
60 lookup_model_alias(&get_model_map(), model).unwrap_or_else(|| model.to_string())
61}
62
63#[derive(Debug, Clone, Default)]
65pub struct GeminiBuildOptions {
66 pub prompt: Option<String>,
67 pub prompt_file: Option<String>,
68 pub system_prompt: Option<String>,
69 pub model: Option<String>,
70 pub resume: Option<String>,
71 pub json: bool,
72 pub yolo: bool,
73 pub read_only: bool,
74 pub sandbox: bool,
75 pub debug: bool,
76 pub checkpointing: bool,
77 pub interactive: bool,
78 pub executable: Option<String>,
79 pub extra_env: Vec<(String, String)>,
80 pub unset_env: Vec<String>,
82 pub extra_args: Vec<String>,
83 pub skip_default_safety_flags: bool,
84 pub launch: LaunchOptions,
86}
87
88impl GeminiBuildOptions {
89 pub fn new() -> Self {
91 Self {
92 yolo: true,
93 ..Default::default()
94 }
95 }
96}
97
98pub fn build_args(options: &GeminiBuildOptions) -> Vec<String> {
106 let mut args = Vec::new();
107 if let Some(resume) = &options.resume {
108 args.extend(["--resume".into(), resume.clone()]);
109 }
110
111 if let Some(ref model) = options.model {
112 let mapped_model = map_model_to_id(model);
113 args.push("-m".to_string());
114 args.push(mapped_model);
115 }
116
117 if options.read_only {
118 args.push("--approval-mode".to_string());
119 args.push("plan".to_string());
120 } else if options.yolo && !options.skip_default_safety_flags {
121 args.push("--yolo".to_string());
123 }
124
125 push_directories(
126 &mut args,
127 "--include-directories",
128 &options.launch.additional_directories,
129 );
130
131 if options.sandbox {
133 args.push("--sandbox".to_string());
134 }
135
136 if options.debug {
138 args.push("-d".to_string());
139 }
140
141 if options.checkpointing {
143 args.push("--checkpointing".to_string());
144 }
145
146 if options.json {
148 args.push("--output-format".to_string());
149 args.push("stream-json".to_string());
150 }
151
152 if let Some(ref prompt) = options.prompt {
154 if options.interactive {
155 args.push("-i".to_string());
156 } else {
157 args.push("-p".to_string());
158 }
159 args.push(prompt.clone());
160 }
161
162 args.extend(options.extra_args.clone());
163
164 args
165}
166
167pub fn build_command(options: &GeminiBuildOptions) -> String {
175 let combined_prompt = if options.prompt_file.is_some() {
178 None
179 } else {
180 match (&options.system_prompt, &options.prompt) {
181 (Some(sys), Some(prompt)) => Some(format!("{}\n\n{}", sys, prompt)),
182 (Some(sys), None) => Some(sys.clone()),
183 (None, Some(prompt)) => Some(prompt.clone()),
184 (None, None) => None,
185 }
186 };
187
188 let modified_options = GeminiBuildOptions {
189 prompt: combined_prompt,
190 system_prompt: None,
191 ..options.clone()
192 };
193
194 let args = build_args(&modified_options);
195 let args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
196 let executable = options.executable.as_deref().unwrap_or("gemini");
197 let command = format!(
198 "{} {}",
199 build_command_head(executable, &options.unset_env, &options.extra_env, &[]),
200 args_str.join(" ")
201 )
202 .trim()
203 .to_string();
204
205 if let Some(prompt_file) = &options.prompt_file {
206 return format!("cat {} | {}", escape_arg(prompt_file), command);
207 }
208
209 command
210}
211
212pub fn parse_output(output: &str) -> Vec<Value> {
221 parse_json_records(output)
224}
225
226pub fn extract_session_id(output: &str) -> Option<String> {
234 let messages = parse_output(output);
235
236 for msg in messages {
237 if let Some(session_id) = msg.get("session_id").and_then(|v| v.as_str()) {
238 return Some(session_id.to_string());
239 }
240 if let Some(conv_id) = msg.get("conversation_id").and_then(|v| v.as_str()) {
242 return Some(conv_id.to_string());
243 }
244 }
245
246 None
247}
248
249#[derive(Debug, Clone, Default, serde::Serialize)]
251#[serde(rename_all = "camelCase")]
252pub struct GeminiUsage {
253 pub input_tokens: u64,
254 pub output_tokens: u64,
255 pub total_tokens: u64,
256 pub cache_read_tokens: u64,
257 pub reasoning_tokens: u64,
258 pub cache_creation_tokens: u64,
259}
260
261pub fn extract_usage(output: &str) -> GeminiUsage {
269 let messages = parse_output(output);
270 let mut result = GeminiUsage::default();
271 for record in usage::records("gemini", &messages) {
272 result.input_tokens += count(record, usage::INPUT);
273 result.output_tokens += count(record, usage::OUTPUT);
274 result.cache_read_tokens += count(record, usage::CACHE_READ);
275 result.reasoning_tokens += count(record, usage::REASONING);
276 result.cache_creation_tokens += count(record, usage::CACHE_WRITE);
277 result.total_tokens += count(record, usage::TOTAL);
278 }
279 if result.total_tokens == 0 {
280 result.total_tokens = result.input_tokens + result.output_tokens;
281 }
282 result
283}
284
285#[derive(Debug, Clone, Default)]
287pub struct GeminiErrorResult {
288 pub has_error: bool,
289 pub error_type: Option<String>,
290 pub message: Option<String>,
291}
292
293pub fn detect_errors(output: &str) -> GeminiErrorResult {
301 let messages = parse_output(output);
302
303 for msg in messages {
304 let is_error =
306 msg.get("type").and_then(|v| v.as_str()) == Some("error") || msg.get("error").is_some();
307
308 if is_error {
309 let error_type = msg
310 .get("type")
311 .and_then(|v| v.as_str())
312 .map(|s| s.to_string())
313 .or_else(|| Some("error".to_string()));
314
315 let message = msg
316 .get("message")
317 .and_then(|v| v.as_str())
318 .map(|s| s.to_string())
319 .or_else(|| {
320 msg.get("error")
321 .and_then(|v| v.as_str())
322 .map(|s| s.to_string())
323 })
324 .or_else(|| Some("Unknown error".to_string()));
325
326 return GeminiErrorResult {
327 has_error: true,
328 error_type,
329 message,
330 };
331 }
332 }
333
334 GeminiErrorResult::default()
335}
336
337#[derive(Debug, Clone)]
339pub struct GeminiTool {
340 pub name: &'static str,
341 pub display_name: &'static str,
342 pub executable: &'static str,
343 pub supports_json_output: bool,
344 pub supports_json_input: bool,
345 pub supports_system_prompt: bool,
346 pub supports_resume: bool,
347 pub supports_yolo: bool,
348 pub supports_sandbox: bool,
349 pub supports_checkpointing: bool,
350 pub supports_debug: bool,
351 pub supports_read_only: bool,
352 pub supports_ask: bool,
353 pub default_model: &'static str,
354}
355
356impl Default for GeminiTool {
357 fn default() -> Self {
358 Self {
359 name: "gemini",
360 display_name: "Gemini CLI",
361 executable: "gemini",
362 supports_json_output: true,
363 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",
373 }
374 }
375}
376
377