Skip to main content

agent_commander/tools/
gemini.rs

1//! Gemini CLI tool configuration
2//! Based on Google's official gemini-cli: <https://github.com/google-gemini/gemini-cli>
3
4use 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
10/// Get the Gemini model map
11pub fn get_model_map() -> HashMap<&'static str, &'static str> {
12    let mut map = HashMap::new();
13    // Pinned Hive Mind catalogue; generated by experiments/sync-model-catalog.py.
14    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
51/// Map model alias to full model ID
52///
53/// # Arguments
54/// * `model` - Model alias or full ID
55///
56/// # Returns
57/// Full model ID
58pub 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/// Gemini command build options
63#[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    /// Variables removed from the inherited environment (`env -u`)
80    pub unset_env: Vec<String>,
81    pub extra_args: Vec<String>,
82    pub skip_default_safety_flags: bool,
83}
84
85impl GeminiBuildOptions {
86    /// Create new options with yolo enabled by default (for autonomous agent use)
87    pub fn new() -> Self {
88        Self {
89            yolo: true,
90            ..Default::default()
91        }
92    }
93}
94
95/// Build command line arguments for Gemini CLI
96///
97/// # Arguments
98/// * `options` - Build options
99///
100/// # Returns
101/// Vector of CLI arguments
102pub 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        // Enable yolo mode for autonomous execution (auto-approve all tool calls)
119        args.push("--yolo".to_string());
120    }
121
122    // Sandbox mode for secure execution
123    if options.sandbox {
124        args.push("--sandbox".to_string());
125    }
126
127    // Debug output
128    if options.debug {
129        args.push("-d".to_string());
130    }
131
132    // Checkpointing for file modifications
133    if options.checkpointing {
134        args.push("--checkpointing".to_string());
135    }
136
137    // JSON output mode - use stream-json for streaming events
138    if options.json {
139        args.push("--output-format".to_string());
140        args.push("stream-json".to_string());
141    }
142
143    // Add prompt for non-interactive mode
144    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
158/// Build complete command string for Gemini CLI
159///
160/// # Arguments
161/// * `options` - Build options
162///
163/// # Returns
164/// Complete command string
165pub fn build_command(options: &GeminiBuildOptions) -> String {
166    // Gemini CLI supports system prompt via GEMINI_SYSTEM_PROMPT env var
167    // or via .gemini/system.md file. For now, combine with user prompt.
168    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
203/// Parse JSON messages from Gemini CLI output
204/// Gemini CLI outputs NDJSON (newline-delimited JSON) in stream-json mode
205///
206/// # Arguments
207/// * `output` - Raw output string
208///
209/// # Returns
210/// Vector of parsed JSON messages
211pub fn parse_output(output: &str) -> Vec<Value> {
212    // Native single JSON output can be formatted across multiple lines; the
213    // record scanner handles it together with stream-json NDJSON.
214    parse_json_records(output)
215}
216
217/// Extract session ID from Gemini CLI output
218///
219/// # Arguments
220/// * `output` - Raw output string
221///
222/// # Returns
223/// Session ID or None
224pub 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        // Gemini might use different session identifier
232        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/// Usage statistics
241#[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
252/// Extract usage statistics from Gemini CLI output
253///
254/// # Arguments
255/// * `output` - Raw output string
256///
257/// # Returns
258/// Usage statistics
259pub 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/// Error detection result
277#[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
284/// Detect errors in Gemini CLI output
285///
286/// # Arguments
287/// * `output` - Raw output string
288///
289/// # Returns
290/// Error detection result
291pub fn detect_errors(output: &str) -> GeminiErrorResult {
292    let messages = parse_output(output);
293
294    for msg in messages {
295        // Check for explicit error message types
296        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/// Gemini CLI tool configuration
329#[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, // Gemini CLI uses -p flag for prompts, not stdin JSON
355            supports_system_prompt: false, // System prompt via env var or file, combined with user
356            supports_resume: true,      // Native --resume SESSION in headless mode
357            supports_yolo: true,        // Supports --yolo for autonomous execution
358            supports_sandbox: true,     // Supports --sandbox for secure execution
359            supports_checkpointing: true, // Supports --checkpointing
360            supports_debug: true,       // Supports -d for debug output
361            supports_read_only: true,   // Supports --approval-mode plan
362            supports_ask: false, // Headless mode has no relayable per-command JSON approval handshake
363            default_model: "flash",
364        }
365    }
366}
367
368// Tests are in rust/tests/gemini_tests.rs