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::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
11/// Get the Gemini model map
12pub fn get_model_map() -> HashMap<&'static str, &'static str> {
13    let mut map = HashMap::new();
14    // Pinned Hive Mind catalogue; generated by experiments/sync-model-catalog.py.
15    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
52/// Map model alias to full model ID
53///
54/// # Arguments
55/// * `model` - Model alias or full ID
56///
57/// # Returns
58/// Full model ID
59pub 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/// Gemini command build options
64#[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    /// Variables removed from the inherited environment (`env -u`)
81    pub unset_env: Vec<String>,
82    pub extra_args: Vec<String>,
83    pub skip_default_safety_flags: bool,
84    /// Shared launch options (reasoning effort, MCP servers, extra directories)
85    pub launch: LaunchOptions,
86}
87
88impl GeminiBuildOptions {
89    /// Create new options with yolo enabled by default (for autonomous agent use)
90    pub fn new() -> Self {
91        Self {
92            yolo: true,
93            ..Default::default()
94        }
95    }
96}
97
98/// Build command line arguments for Gemini CLI
99///
100/// # Arguments
101/// * `options` - Build options
102///
103/// # Returns
104/// Vector of CLI arguments
105pub 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        // Enable yolo mode for autonomous execution (auto-approve all tool calls)
122        args.push("--yolo".to_string());
123    }
124
125    push_directories(
126        &mut args,
127        "--include-directories",
128        &options.launch.additional_directories,
129    );
130
131    // Sandbox mode for secure execution
132    if options.sandbox {
133        args.push("--sandbox".to_string());
134    }
135
136    // Debug output
137    if options.debug {
138        args.push("-d".to_string());
139    }
140
141    // Checkpointing for file modifications
142    if options.checkpointing {
143        args.push("--checkpointing".to_string());
144    }
145
146    // JSON output mode - use stream-json for streaming events
147    if options.json {
148        args.push("--output-format".to_string());
149        args.push("stream-json".to_string());
150    }
151
152    // Add prompt for non-interactive mode
153    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
167/// Build complete command string for Gemini CLI
168///
169/// # Arguments
170/// * `options` - Build options
171///
172/// # Returns
173/// Complete command string
174pub fn build_command(options: &GeminiBuildOptions) -> String {
175    // Gemini CLI supports system prompt via GEMINI_SYSTEM_PROMPT env var
176    // or via .gemini/system.md file. For now, combine with user prompt.
177    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, &[], &[], &[]),
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
212/// Parse JSON messages from Gemini CLI output
213/// Gemini CLI outputs NDJSON (newline-delimited JSON) in stream-json mode
214///
215/// # Arguments
216/// * `output` - Raw output string
217///
218/// # Returns
219/// Vector of parsed JSON messages
220pub fn parse_output(output: &str) -> Vec<Value> {
221    // Native single JSON output can be formatted across multiple lines; the
222    // record scanner handles it together with stream-json NDJSON.
223    parse_json_records(output)
224}
225
226/// Extract session ID from Gemini CLI output
227///
228/// # Arguments
229/// * `output` - Raw output string
230///
231/// # Returns
232/// Session ID or None
233pub 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        // Gemini might use different session identifier
241        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/// Usage statistics
250#[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
261/// Extract usage statistics from Gemini CLI output
262///
263/// # Arguments
264/// * `output` - Raw output string
265///
266/// # Returns
267/// Usage statistics
268pub 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/// Error detection result
286#[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
293/// Detect errors in Gemini CLI output
294///
295/// # Arguments
296/// * `output` - Raw output string
297///
298/// # Returns
299/// Error detection result
300pub fn detect_errors(output: &str) -> GeminiErrorResult {
301    let messages = parse_output(output);
302
303    for msg in messages {
304        // Check for explicit error message types
305        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/// Gemini CLI tool configuration
338#[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, // Gemini CLI uses -p flag for prompts, not stdin JSON
364            supports_system_prompt: false, // System prompt via env var or file, combined with user
365            supports_resume: true,      // Native --resume SESSION in headless mode
366            supports_yolo: true,        // Supports --yolo for autonomous execution
367            supports_sandbox: true,     // Supports --sandbox for secure execution
368            supports_checkpointing: true, // Supports --checkpointing
369            supports_debug: true,       // Supports -d for debug output
370            supports_read_only: true,   // Supports --approval-mode plan
371            supports_ask: false, // Headless mode has no relayable per-command JSON approval handshake
372            default_model: "flash",
373        }
374    }
375}
376
377// Tests are in rust/tests/gemini_tests.rs