1use super::usage::{self, count};
5use crate::streaming::parse_ndjson;
6use crate::tools::shell::{build_command_head, escape_arg};
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("gemini", "gemini-2.5-flash");
18 map.insert("flash", "gemini-2.5-flash");
19 map.insert("2.5-flash", "gemini-2.5-flash");
20 map.insert("pro", "gemini-2.5-pro");
21 map.insert("2.5-pro", "gemini-2.5-pro");
22 map.insert("lite", "gemini-2.5-flash-lite");
23 map.insert("2.5-lite", "gemini-2.5-flash-lite");
24 map.insert("flash-lite", "gemini-2.5-flash-lite");
25 map.insert("3-flash", "gemini-3-flash-preview");
26 map.insert("3-pro", "gemini-3-pro-preview");
27 map.insert("gemini-flash", "gemini-2.5-flash");
28 map.insert("gemini-pro", "gemini-2.5-pro");
29 map.insert("gemini-2.5-flash", "gemini-2.5-flash");
30 map.insert("gemini-2.5-pro", "gemini-2.5-pro");
31 map.insert("gemini-2.5-flash-lite", "gemini-2.5-flash-lite");
32 map.insert("gemini-3-flash-preview", "gemini-3-flash-preview");
33 map.insert("gemini-3-pro-preview", "gemini-3-pro-preview");
34 map
35}
36
37pub fn map_model_to_id(model: &str) -> String {
45 let model_map = get_model_map();
46 model_map
47 .get(model)
48 .map(|s| s.to_string())
49 .unwrap_or_else(|| model.to_string())
50}
51
52#[derive(Debug, Clone, Default)]
54pub struct GeminiBuildOptions {
55 pub prompt: Option<String>,
56 pub prompt_file: Option<String>,
57 pub system_prompt: Option<String>,
58 pub model: Option<String>,
59 pub resume: Option<String>,
60 pub json: bool,
61 pub yolo: bool,
62 pub read_only: bool,
63 pub sandbox: bool,
64 pub debug: bool,
65 pub checkpointing: bool,
66 pub interactive: bool,
67 pub executable: Option<String>,
68 pub extra_env: Vec<(String, String)>,
69 pub extra_args: Vec<String>,
70 pub skip_default_safety_flags: bool,
71}
72
73impl GeminiBuildOptions {
74 pub fn new() -> Self {
76 Self {
77 yolo: true,
78 ..Default::default()
79 }
80 }
81}
82
83pub fn build_args(options: &GeminiBuildOptions) -> Vec<String> {
91 let mut args = Vec::new();
92 if let Some(resume) = &options.resume {
93 args.extend(["--resume".into(), resume.clone()]);
94 }
95
96 if let Some(ref model) = options.model {
97 let mapped_model = map_model_to_id(model);
98 args.push("-m".to_string());
99 args.push(mapped_model);
100 }
101
102 if options.read_only {
103 args.push("--approval-mode".to_string());
104 args.push("plan".to_string());
105 } else if options.yolo && !options.skip_default_safety_flags {
106 args.push("--yolo".to_string());
108 }
109
110 if options.sandbox {
112 args.push("--sandbox".to_string());
113 }
114
115 if options.debug {
117 args.push("-d".to_string());
118 }
119
120 if options.checkpointing {
122 args.push("--checkpointing".to_string());
123 }
124
125 if options.json {
127 args.push("--output-format".to_string());
128 args.push("stream-json".to_string());
129 }
130
131 if let Some(ref prompt) = options.prompt {
133 if options.interactive {
134 args.push("-i".to_string());
135 } else {
136 args.push("-p".to_string());
137 }
138 args.push(prompt.clone());
139 }
140
141 args.extend(options.extra_args.clone());
142
143 args
144}
145
146pub fn build_command(options: &GeminiBuildOptions) -> String {
154 let combined_prompt = if options.prompt_file.is_some() {
157 None
158 } else {
159 match (&options.system_prompt, &options.prompt) {
160 (Some(sys), Some(prompt)) => Some(format!("{}\n\n{}", sys, prompt)),
161 (Some(sys), None) => Some(sys.clone()),
162 (None, Some(prompt)) => Some(prompt.clone()),
163 (None, None) => None,
164 }
165 };
166
167 let modified_options = GeminiBuildOptions {
168 prompt: combined_prompt,
169 system_prompt: None,
170 ..options.clone()
171 };
172
173 let args = build_args(&modified_options);
174 let args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
175 let executable = options.executable.as_deref().unwrap_or("gemini");
176 let command = format!(
177 "{} {}",
178 build_command_head(executable, &options.extra_env, &[]),
179 args_str.join(" ")
180 )
181 .trim()
182 .to_string();
183
184 if let Some(prompt_file) = &options.prompt_file {
185 return format!("cat {} | {}", escape_arg(prompt_file), command);
186 }
187
188 command
189}
190
191pub fn parse_output(output: &str) -> Vec<Value> {
200 if let Ok(message) = serde_json::from_str::<Value>(output) {
202 if message.is_object() {
203 return vec![message];
204 }
205 }
206 parse_ndjson(output)
207}
208
209pub fn extract_session_id(output: &str) -> Option<String> {
217 let messages = parse_output(output);
218
219 for msg in messages {
220 if let Some(session_id) = msg.get("session_id").and_then(|v| v.as_str()) {
221 return Some(session_id.to_string());
222 }
223 if let Some(conv_id) = msg.get("conversation_id").and_then(|v| v.as_str()) {
225 return Some(conv_id.to_string());
226 }
227 }
228
229 None
230}
231
232#[derive(Debug, Clone, Default, serde::Serialize)]
234#[serde(rename_all = "camelCase")]
235pub struct GeminiUsage {
236 pub input_tokens: u64,
237 pub output_tokens: u64,
238 pub total_tokens: u64,
239 pub cache_read_tokens: u64,
240 pub reasoning_tokens: u64,
241 pub cache_creation_tokens: u64,
242}
243
244pub fn extract_usage(output: &str) -> GeminiUsage {
252 let messages = parse_output(output);
253 let mut result = GeminiUsage::default();
254 for record in usage::records("gemini", &messages) {
255 result.input_tokens += count(record, usage::INPUT);
256 result.output_tokens += count(record, usage::OUTPUT);
257 result.cache_read_tokens += count(record, usage::CACHE_READ);
258 result.reasoning_tokens += count(record, usage::REASONING);
259 result.cache_creation_tokens += count(record, usage::CACHE_WRITE);
260 result.total_tokens += count(record, usage::TOTAL);
261 }
262 if result.total_tokens == 0 {
263 result.total_tokens = result.input_tokens + result.output_tokens;
264 }
265 result
266}
267
268#[derive(Debug, Clone, Default)]
270pub struct GeminiErrorResult {
271 pub has_error: bool,
272 pub error_type: Option<String>,
273 pub message: Option<String>,
274}
275
276pub fn detect_errors(output: &str) -> GeminiErrorResult {
284 let messages = parse_output(output);
285
286 for msg in messages {
287 let is_error =
289 msg.get("type").and_then(|v| v.as_str()) == Some("error") || msg.get("error").is_some();
290
291 if is_error {
292 let error_type = msg
293 .get("type")
294 .and_then(|v| v.as_str())
295 .map(|s| s.to_string())
296 .or_else(|| Some("error".to_string()));
297
298 let message = msg
299 .get("message")
300 .and_then(|v| v.as_str())
301 .map(|s| s.to_string())
302 .or_else(|| {
303 msg.get("error")
304 .and_then(|v| v.as_str())
305 .map(|s| s.to_string())
306 })
307 .or_else(|| Some("Unknown error".to_string()));
308
309 return GeminiErrorResult {
310 has_error: true,
311 error_type,
312 message,
313 };
314 }
315 }
316
317 GeminiErrorResult::default()
318}
319
320#[derive(Debug, Clone)]
322pub struct GeminiTool {
323 pub name: &'static str,
324 pub display_name: &'static str,
325 pub executable: &'static str,
326 pub supports_json_output: bool,
327 pub supports_json_input: bool,
328 pub supports_system_prompt: bool,
329 pub supports_resume: bool,
330 pub supports_yolo: bool,
331 pub supports_sandbox: bool,
332 pub supports_checkpointing: bool,
333 pub supports_debug: bool,
334 pub supports_read_only: bool,
335 pub supports_ask: bool,
336 pub default_model: &'static str,
337}
338
339impl Default for GeminiTool {
340 fn default() -> Self {
341 Self {
342 name: "gemini",
343 display_name: "Gemini CLI",
344 executable: "gemini",
345 supports_json_output: true,
346 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",
356 }
357 }
358}
359
360