Skip to main content

cli_agents/adapters/gemini/
mod.rs

1mod parse;
2
3use crate::adapters::CliAdapter;
4use crate::discovery::discover_binary;
5use crate::error::{Error, Result};
6use crate::events::StreamEvent;
7use crate::types::{CliName, McpServer, RunOptions, RunResult};
8use crate::DEFAULT_MAX_OUTPUT_BYTES;
9use std::collections::HashMap;
10use tokio_util::sync::CancellationToken;
11
12pub struct GeminiAdapter;
13
14impl CliAdapter for GeminiAdapter {
15    fn name(&self) -> CliName {
16        CliName::Gemini
17    }
18
19    async fn run(
20        &self,
21        opts: &RunOptions,
22        emit: &(dyn Fn(StreamEvent) + Send + Sync),
23        cancel: CancellationToken,
24    ) -> Result<RunResult> {
25        let binary = match &opts.executable_path {
26            Some(p) => p.clone(),
27            None => discover_binary(CliName::Gemini).await.ok_or(Error::NoCli)?,
28        };
29
30        // Write temp configs if needed.
31        // Hold the TempDir so it lives until the child process exits.
32        let (config_env, cwd_override, _tmp_dir) = write_configs(opts).await?;
33
34        let cli_args = build_args(opts);
35        let mut extra_env = opts.env.clone().unwrap_or_default();
36        extra_env.extend(config_env);
37        let max_bytes = opts.max_output_bytes.unwrap_or(DEFAULT_MAX_OUTPUT_BYTES);
38
39        // Use cwd override (temp dir with workspace MCP config) if set,
40        // otherwise use the user-specified cwd.
41        let effective_cwd = cwd_override
42            .as_deref()
43            .or(opts.cwd.as_deref())
44            .unwrap_or(".");
45
46        let mut state = parse::ParseState::default();
47
48        let outcome = crate::adapters::spawn_and_stream(
49            crate::adapters::SpawnParams {
50                cli_label: "gemini",
51                binary: &binary,
52                args: &cli_args,
53                extra_env: &extra_env,
54                strip_env: &[],
55                cwd: effective_cwd,
56                max_bytes,
57                cancel: &cancel,
58            },
59            |line| parse::parse_line(line, &mut state, emit),
60        )
61        .await?;
62
63        match outcome {
64            crate::adapters::SpawnOutcome::Cancelled => Ok(RunResult {
65                success: false,
66                text: Some("Cancelled.".into()),
67                ..Default::default()
68            }),
69            crate::adapters::SpawnOutcome::Done { exit_code, stderr } => {
70                let success = exit_code == 0;
71                let text = if !success && state.result_text.is_none() {
72                    crate::adapters::extract_error_message(stderr.as_deref())
73                } else {
74                    state.result_text
75                };
76                Ok(RunResult {
77                    success,
78                    text,
79                    exit_code: Some(exit_code),
80                    stats: state.stats,
81                    session_id: state.session_id,
82                    stderr,
83                    cost_usd: None,
84                })
85            }
86        }
87    }
88}
89
90fn build_args(opts: &RunOptions) -> Vec<String> {
91    let mut args = vec![
92        "-p".into(),
93        opts.task.clone(),
94        "--output-format".into(),
95        "stream-json".into(),
96    ];
97
98    if let Some(model) = &opts.model {
99        args.push("--model".into());
100        args.push(model.clone());
101    }
102
103    // Gemini's --resume takes "latest" or an index, not a UUID session ID.
104    // Use "latest" to resume the most recent session in the cwd.
105    if opts.resume_session_id.is_some() {
106        args.push("--resume".into());
107        args.push("latest".into());
108    }
109
110    // Permission bypass for non-interactive use (opt-in)
111    if opts.skip_permissions {
112        args.push("--yolo".into());
113    }
114
115    if let Some(gemini) = opts.providers.as_ref().and_then(|p| p.gemini.as_ref()) {
116        if gemini.sandbox == Some(true) {
117            args.push("-s".into());
118        }
119        // Skip --approval-mode when --yolo is already set (they conflict in Gemini CLI).
120        if !opts.skip_permissions {
121            if let Some(mode) = &gemini.approval_mode {
122                args.push("--approval-mode".into());
123                args.push(mode.clone());
124            }
125        }
126        if let Some(extra) = &gemini.extra_args {
127            args.extend(extra.clone());
128        }
129    }
130
131    args
132}
133
134/// Write temporary config files for MCP servers and system prompts.
135///
136/// Returns env vars, an optional cwd override, and the temp dir handle
137/// (must be kept alive until the child process exits).
138async fn write_configs(
139    opts: &RunOptions,
140) -> Result<(
141    HashMap<String, String>,
142    Option<String>,
143    Option<tempfile::TempDir>,
144)> {
145    let has_mcp = opts.mcp_servers.as_ref().is_some_and(|s| !s.is_empty());
146    let needs_prompt_file = opts.system_prompt_file.is_none() && opts.system_prompt.is_some();
147
148    // system_prompt_file doesn't need a temp dir — it points to the file directly.
149    if !has_mcp && !needs_prompt_file {
150        let mut env = HashMap::new();
151        if let Some(path) = &opts.system_prompt_file {
152            env.insert("GEMINI_SYSTEM_MD".into(), path.clone());
153        }
154        return Ok((env, None, None));
155    }
156
157    let tmp_dir = tempfile::tempdir().map_err(Error::Io)?;
158    let mut env = HashMap::new();
159
160    // MCP servers → workspace-level .gemini/settings.json.
161    // Gemini CLI merges workspace config (from cwd) with user config (~/.gemini/),
162    // preserving auth credentials while adding our MCP servers.
163    //
164    // If opts.cwd is set, write config there (persistent, enables session resume).
165    // Otherwise, use the temp dir (ephemeral, no session resume).
166    let cwd_override = if let Some(servers) = &opts.mcp_servers {
167        if !servers.is_empty() {
168            let config_dir = if let Some(cwd) = &opts.cwd {
169                std::path::PathBuf::from(cwd)
170            } else {
171                tmp_dir.path().to_path_buf()
172            };
173
174            let gemini_dir = config_dir.join(".gemini");
175            tokio::fs::create_dir_all(&gemini_dir)
176                .await
177                .map_err(Error::Io)?;
178
179            let settings = build_mcp_settings(servers);
180            let settings_path = gemini_dir.join("settings.json");
181            tokio::fs::write(&settings_path, serde_json::to_string_pretty(&settings)?)
182                .await
183                .map_err(Error::Io)?;
184
185            // If we wrote to opts.cwd, no override needed — the adapter
186            // already uses opts.cwd. If we wrote to temp dir, override cwd.
187            if opts.cwd.is_none() {
188                Some(tmp_dir.path().to_string_lossy().into_owned())
189            } else {
190                None
191            }
192        } else {
193            None
194        }
195    } else {
196        None
197    };
198
199    // System prompt → file referenced by GEMINI_SYSTEM_MD
200    // system_prompt_file takes precedence (use the file directly).
201    if let Some(path) = &opts.system_prompt_file {
202        env.insert("GEMINI_SYSTEM_MD".into(), path.clone());
203    } else if let Some(prompt) = &opts.system_prompt {
204        let prompt_path = tmp_dir.path().join("system-prompt.md");
205        tokio::fs::write(&prompt_path, prompt)
206            .await
207            .map_err(Error::Io)?;
208        env.insert(
209            "GEMINI_SYSTEM_MD".into(),
210            prompt_path.to_string_lossy().into_owned(),
211        );
212    }
213
214    Ok((env, cwd_override, Some(tmp_dir)))
215}
216
217fn build_mcp_settings(servers: &HashMap<String, McpServer>) -> serde_json::Value {
218    let mut mcp_map = serde_json::Map::new();
219
220    for (name, server) in servers {
221        let mut entry = serde_json::Map::new();
222
223        if let Some(url) = &server.url {
224            entry.insert("url".into(), serde_json::Value::String(url.clone()));
225            let t = match server.transport_type {
226                Some(crate::types::McpTransport::Http) => "http",
227                _ => "sse",
228            };
229            entry.insert("type".into(), serde_json::Value::String(t.into()));
230            if let Some(headers) = &server.headers {
231                entry.insert(
232                    "headers".into(),
233                    serde_json::to_value(headers).unwrap_or_default(),
234                );
235            }
236        } else {
237            if let Some(cmd) = &server.command {
238                entry.insert("command".into(), serde_json::Value::String(cmd.clone()));
239            }
240            if let Some(a) = &server.args {
241                entry.insert("args".into(), serde_json::to_value(a).unwrap_or_default());
242            }
243            if let Some(e) = &server.env {
244                entry.insert("env".into(), serde_json::to_value(e).unwrap_or_default());
245            }
246            if let Some(cwd) = &server.cwd {
247                entry.insert("cwd".into(), serde_json::Value::String(cwd.clone()));
248            }
249        }
250
251        if let Some(include) = &server.include_tools {
252            entry.insert(
253                "includeTools".into(),
254                serde_json::to_value(include).unwrap_or_default(),
255            );
256        }
257        if let Some(exclude) = &server.exclude_tools {
258            entry.insert(
259                "excludeTools".into(),
260                serde_json::to_value(exclude).unwrap_or_default(),
261            );
262        }
263        if let Some(timeout) = server.timeout {
264            entry.insert("timeout".into(), serde_json::Value::Number(timeout.into()));
265        }
266
267        mcp_map.insert(name.clone(), serde_json::Value::Object(entry));
268    }
269
270    let mut root = serde_json::Map::new();
271    root.insert("mcpServers".into(), serde_json::Value::Object(mcp_map));
272    serde_json::Value::Object(root)
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278
279    #[test]
280    fn build_args_minimal() {
281        let opts = RunOptions {
282            task: "hello".into(),
283            ..Default::default()
284        };
285        let args = build_args(&opts);
286        assert_eq!(args, vec!["-p", "hello", "--output-format", "stream-json"]);
287    }
288
289    #[test]
290    fn build_args_skip_permissions() {
291        let opts = RunOptions {
292            task: "hello".into(),
293            skip_permissions: true,
294            ..Default::default()
295        };
296        let args = build_args(&opts);
297        assert!(args.contains(&"--yolo".to_string()));
298    }
299
300    #[test]
301    fn build_args_no_permission_bypass_by_default() {
302        let opts = RunOptions {
303            task: "hello".into(),
304            ..Default::default()
305        };
306        let args = build_args(&opts);
307        assert!(!args.contains(&"--yolo".to_string()));
308    }
309
310    #[test]
311    fn build_args_with_options() {
312        let opts = RunOptions {
313            task: "do something".into(),
314            model: Some("gemini-2.0-flash".into()),
315            resume_session_id: Some("sess-1".into()),
316            providers: Some(crate::types::ProviderOptions {
317                gemini: Some(crate::types::GeminiOptions {
318                    sandbox: Some(true),
319                    approval_mode: Some("auto".into()),
320                    extra_args: Some(vec!["--verbose".into()]),
321                }),
322                ..Default::default()
323            }),
324            ..Default::default()
325        };
326        let args = build_args(&opts);
327        assert!(args.contains(&"-s".to_string()));
328        assert!(args.contains(&"--model".to_string()));
329        assert!(args.contains(&"gemini-2.0-flash".to_string()));
330        assert!(args.contains(&"--resume".to_string()));
331        assert!(args.contains(&"--approval-mode".to_string()));
332        assert!(args.contains(&"--verbose".to_string()));
333    }
334}