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_ndjson;
6use crate::tools::shell::{build_command_head, escape_arg};
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("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
37/// Map model alias to full model ID
38///
39/// # Arguments
40/// * `model` - Model alias or full ID
41///
42/// # Returns
43/// Full model ID
44pub 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/// Gemini command build options
53#[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    /// Create new options with yolo enabled by default (for autonomous agent use)
75    pub fn new() -> Self {
76        Self {
77            yolo: true,
78            ..Default::default()
79        }
80    }
81}
82
83/// Build command line arguments for Gemini CLI
84///
85/// # Arguments
86/// * `options` - Build options
87///
88/// # Returns
89/// Vector of CLI arguments
90pub 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        // Enable yolo mode for autonomous execution (auto-approve all tool calls)
107        args.push("--yolo".to_string());
108    }
109
110    // Sandbox mode for secure execution
111    if options.sandbox {
112        args.push("--sandbox".to_string());
113    }
114
115    // Debug output
116    if options.debug {
117        args.push("-d".to_string());
118    }
119
120    // Checkpointing for file modifications
121    if options.checkpointing {
122        args.push("--checkpointing".to_string());
123    }
124
125    // JSON output mode - use stream-json for streaming events
126    if options.json {
127        args.push("--output-format".to_string());
128        args.push("stream-json".to_string());
129    }
130
131    // Add prompt for non-interactive mode
132    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
146/// Build complete command string for Gemini CLI
147///
148/// # Arguments
149/// * `options` - Build options
150///
151/// # Returns
152/// Complete command string
153pub fn build_command(options: &GeminiBuildOptions) -> String {
154    // Gemini CLI supports system prompt via GEMINI_SYSTEM_PROMPT env var
155    // or via .gemini/system.md file. For now, combine with user prompt.
156    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
191/// Parse JSON messages from Gemini CLI output
192/// Gemini CLI outputs NDJSON (newline-delimited JSON) in stream-json mode
193///
194/// # Arguments
195/// * `output` - Raw output string
196///
197/// # Returns
198/// Vector of parsed JSON messages
199pub fn parse_output(output: &str) -> Vec<Value> {
200    // Native single JSON output can be formatted across multiple lines.
201    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
209/// Extract session ID from Gemini CLI output
210///
211/// # Arguments
212/// * `output` - Raw output string
213///
214/// # Returns
215/// Session ID or None
216pub 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        // Gemini might use different session identifier
224        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/// Usage statistics
233#[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
244/// Extract usage statistics from Gemini CLI output
245///
246/// # Arguments
247/// * `output` - Raw output string
248///
249/// # Returns
250/// Usage statistics
251pub 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/// Error detection result
269#[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
276/// Detect errors in Gemini CLI output
277///
278/// # Arguments
279/// * `output` - Raw output string
280///
281/// # Returns
282/// Error detection result
283pub fn detect_errors(output: &str) -> GeminiErrorResult {
284    let messages = parse_output(output);
285
286    for msg in messages {
287        // Check for explicit error message types
288        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/// Gemini CLI tool configuration
321#[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, // Gemini CLI uses -p flag for prompts, not stdin JSON
347            supports_system_prompt: false, // System prompt via env var or file, combined with user
348            supports_resume: true,      // Native --resume SESSION in headless mode
349            supports_yolo: true,        // Supports --yolo for autonomous execution
350            supports_sandbox: true,     // Supports --sandbox for secure execution
351            supports_checkpointing: true, // Supports --checkpointing
352            supports_debug: true,       // Supports -d for debug output
353            supports_read_only: true,   // Supports --approval-mode plan
354            supports_ask: false, // Headless mode has no relayable per-command JSON approval handshake
355            default_model: "flash",
356        }
357    }
358}
359
360// Tests are in rust/tests/gemini_tests.rs