agent-commander 0.3.2

A Rust library to control agents enclosed in CLI commands like Anthropic Claude Code CLI
Documentation
//! Gemini CLI tool configuration
//! Based on Google's official gemini-cli: https://github.com/google-gemini/gemini-cli

use super::usage::{self, count};
use crate::streaming::parse_ndjson;
use crate::tools::shell::{build_command_head, escape_arg};
use serde_json::Value;
use std::collections::HashMap;

/// Get the Gemini model map
pub fn get_model_map() -> HashMap<&'static str, &'static str> {
    let mut map = HashMap::new();
    // Pinned Hive Mind catalogue; generated by experiments/sync-model-catalog.py.
    map.insert("formal-ai", "formal-ai");
    map.insert("formalai/formal-ai", "formal-ai");
    map.insert("auto", "auto");
    map.insert("gemini", "gemini-2.5-flash");
    map.insert("flash", "gemini-2.5-flash");
    map.insert("2.5-flash", "gemini-2.5-flash");
    map.insert("pro", "gemini-2.5-pro");
    map.insert("2.5-pro", "gemini-2.5-pro");
    map.insert("lite", "gemini-2.5-flash-lite");
    map.insert("2.5-lite", "gemini-2.5-flash-lite");
    map.insert("flash-lite", "gemini-2.5-flash-lite");
    map.insert("3-flash", "gemini-3-flash-preview");
    map.insert("3-pro", "gemini-3-pro-preview");
    map.insert("gemini-flash", "gemini-2.5-flash");
    map.insert("gemini-pro", "gemini-2.5-pro");
    map.insert("gemini-2.5-flash", "gemini-2.5-flash");
    map.insert("gemini-2.5-pro", "gemini-2.5-pro");
    map.insert("gemini-2.5-flash-lite", "gemini-2.5-flash-lite");
    map.insert("gemini-3-flash-preview", "gemini-3-flash-preview");
    map.insert("gemini-3-pro-preview", "gemini-3-pro-preview");
    map
}

/// Map model alias to full model ID
///
/// # Arguments
/// * `model` - Model alias or full ID
///
/// # Returns
/// Full model ID
pub fn map_model_to_id(model: &str) -> String {
    let model_map = get_model_map();
    model_map
        .get(model)
        .map(|s| s.to_string())
        .unwrap_or_else(|| model.to_string())
}

/// Gemini command build options
#[derive(Debug, Clone, Default)]
pub struct GeminiBuildOptions {
    pub prompt: Option<String>,
    pub prompt_file: Option<String>,
    pub system_prompt: Option<String>,
    pub model: Option<String>,
    pub resume: Option<String>,
    pub json: bool,
    pub yolo: bool,
    pub read_only: bool,
    pub sandbox: bool,
    pub debug: bool,
    pub checkpointing: bool,
    pub interactive: bool,
    pub executable: Option<String>,
    pub extra_env: Vec<(String, String)>,
    pub extra_args: Vec<String>,
    pub skip_default_safety_flags: bool,
}

impl GeminiBuildOptions {
    /// Create new options with yolo enabled by default (for autonomous agent use)
    pub fn new() -> Self {
        Self {
            yolo: true,
            ..Default::default()
        }
    }
}

/// Build command line arguments for Gemini CLI
///
/// # Arguments
/// * `options` - Build options
///
/// # Returns
/// Vector of CLI arguments
pub fn build_args(options: &GeminiBuildOptions) -> Vec<String> {
    let mut args = Vec::new();
    if let Some(resume) = &options.resume {
        args.extend(["--resume".into(), resume.clone()]);
    }

    if let Some(ref model) = options.model {
        let mapped_model = map_model_to_id(model);
        args.push("-m".to_string());
        args.push(mapped_model);
    }

    if options.read_only {
        args.push("--approval-mode".to_string());
        args.push("plan".to_string());
    } else if options.yolo && !options.skip_default_safety_flags {
        // Enable yolo mode for autonomous execution (auto-approve all tool calls)
        args.push("--yolo".to_string());
    }

    // Sandbox mode for secure execution
    if options.sandbox {
        args.push("--sandbox".to_string());
    }

    // Debug output
    if options.debug {
        args.push("-d".to_string());
    }

    // Checkpointing for file modifications
    if options.checkpointing {
        args.push("--checkpointing".to_string());
    }

    // JSON output mode - use stream-json for streaming events
    if options.json {
        args.push("--output-format".to_string());
        args.push("stream-json".to_string());
    }

    // Add prompt for non-interactive mode
    if let Some(ref prompt) = options.prompt {
        if options.interactive {
            args.push("-i".to_string());
        } else {
            args.push("-p".to_string());
        }
        args.push(prompt.clone());
    }

    args.extend(options.extra_args.clone());

    args
}

/// Build complete command string for Gemini CLI
///
/// # Arguments
/// * `options` - Build options
///
/// # Returns
/// Complete command string
pub fn build_command(options: &GeminiBuildOptions) -> String {
    // Gemini CLI supports system prompt via GEMINI_SYSTEM_PROMPT env var
    // or via .gemini/system.md file. For now, combine with user prompt.
    let combined_prompt = if options.prompt_file.is_some() {
        None
    } else {
        match (&options.system_prompt, &options.prompt) {
            (Some(sys), Some(prompt)) => Some(format!("{}\n\n{}", sys, prompt)),
            (Some(sys), None) => Some(sys.clone()),
            (None, Some(prompt)) => Some(prompt.clone()),
            (None, None) => None,
        }
    };

    let modified_options = GeminiBuildOptions {
        prompt: combined_prompt,
        system_prompt: None,
        ..options.clone()
    };

    let args = build_args(&modified_options);
    let args_str: Vec<String> = args.iter().map(|a| escape_arg(a)).collect();
    let executable = options.executable.as_deref().unwrap_or("gemini");
    let command = format!(
        "{} {}",
        build_command_head(executable, &options.extra_env, &[]),
        args_str.join(" ")
    )
    .trim()
    .to_string();

    if let Some(prompt_file) = &options.prompt_file {
        return format!("cat {} | {}", escape_arg(prompt_file), command);
    }

    command
}

/// Parse JSON messages from Gemini CLI output
/// Gemini CLI outputs NDJSON (newline-delimited JSON) in stream-json mode
///
/// # Arguments
/// * `output` - Raw output string
///
/// # Returns
/// Vector of parsed JSON messages
pub fn parse_output(output: &str) -> Vec<Value> {
    // Native single JSON output can be formatted across multiple lines.
    if let Ok(message) = serde_json::from_str::<Value>(output) {
        if message.is_object() {
            return vec![message];
        }
    }
    parse_ndjson(output)
}

/// Extract session ID from Gemini CLI output
///
/// # Arguments
/// * `output` - Raw output string
///
/// # Returns
/// Session ID or None
pub fn extract_session_id(output: &str) -> Option<String> {
    let messages = parse_output(output);

    for msg in messages {
        if let Some(session_id) = msg.get("session_id").and_then(|v| v.as_str()) {
            return Some(session_id.to_string());
        }
        // Gemini might use different session identifier
        if let Some(conv_id) = msg.get("conversation_id").and_then(|v| v.as_str()) {
            return Some(conv_id.to_string());
        }
    }

    None
}

/// Usage statistics
#[derive(Debug, Clone, Default, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GeminiUsage {
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub total_tokens: u64,
    pub cache_read_tokens: u64,
    pub reasoning_tokens: u64,
    pub cache_creation_tokens: u64,
}

/// Extract usage statistics from Gemini CLI output
///
/// # Arguments
/// * `output` - Raw output string
///
/// # Returns
/// Usage statistics
pub fn extract_usage(output: &str) -> GeminiUsage {
    let messages = parse_output(output);
    let mut result = GeminiUsage::default();
    for record in usage::records("gemini", &messages) {
        result.input_tokens += count(record, usage::INPUT);
        result.output_tokens += count(record, usage::OUTPUT);
        result.cache_read_tokens += count(record, usage::CACHE_READ);
        result.reasoning_tokens += count(record, usage::REASONING);
        result.cache_creation_tokens += count(record, usage::CACHE_WRITE);
        result.total_tokens += count(record, usage::TOTAL);
    }
    if result.total_tokens == 0 {
        result.total_tokens = result.input_tokens + result.output_tokens;
    }
    result
}

/// Error detection result
#[derive(Debug, Clone, Default)]
pub struct GeminiErrorResult {
    pub has_error: bool,
    pub error_type: Option<String>,
    pub message: Option<String>,
}

/// Detect errors in Gemini CLI output
///
/// # Arguments
/// * `output` - Raw output string
///
/// # Returns
/// Error detection result
pub fn detect_errors(output: &str) -> GeminiErrorResult {
    let messages = parse_output(output);

    for msg in messages {
        // Check for explicit error message types
        let is_error =
            msg.get("type").and_then(|v| v.as_str()) == Some("error") || msg.get("error").is_some();

        if is_error {
            let error_type = msg
                .get("type")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string())
                .or_else(|| Some("error".to_string()));

            let message = msg
                .get("message")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string())
                .or_else(|| {
                    msg.get("error")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string())
                })
                .or_else(|| Some("Unknown error".to_string()));

            return GeminiErrorResult {
                has_error: true,
                error_type,
                message,
            };
        }
    }

    GeminiErrorResult::default()
}

/// Gemini CLI tool configuration
#[derive(Debug, Clone)]
pub struct GeminiTool {
    pub name: &'static str,
    pub display_name: &'static str,
    pub executable: &'static str,
    pub supports_json_output: bool,
    pub supports_json_input: bool,
    pub supports_system_prompt: bool,
    pub supports_resume: bool,
    pub supports_yolo: bool,
    pub supports_sandbox: bool,
    pub supports_checkpointing: bool,
    pub supports_debug: bool,
    pub supports_read_only: bool,
    pub supports_ask: bool,
    pub default_model: &'static str,
}

impl Default for GeminiTool {
    fn default() -> Self {
        Self {
            name: "gemini",
            display_name: "Gemini CLI",
            executable: "gemini",
            supports_json_output: true,
            supports_json_input: false, // Gemini CLI uses -p flag for prompts, not stdin JSON
            supports_system_prompt: false, // System prompt via env var or file, combined with user
            supports_resume: true,      // Native --resume SESSION in headless mode
            supports_yolo: true,        // Supports --yolo for autonomous execution
            supports_sandbox: true,     // Supports --sandbox for secure execution
            supports_checkpointing: true, // Supports --checkpointing
            supports_debug: true,       // Supports -d for debug output
            supports_read_only: true,   // Supports --approval-mode plan
            supports_ask: false, // Headless mode has no relayable per-command JSON approval handshake
            default_model: "flash",
        }
    }
}

// Tests are in rust/tests/gemini_tests.rs