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