Skip to main content

cli_agents/adapters/gemini/
mod.rs

1mod parse;
2
3use crate::DEFAULT_MAX_OUTPUT_BYTES;
4use crate::adapters::CliAdapter;
5use crate::discovery::discover_binary;
6use crate::error::{Error, Result};
7use crate::events::StreamEvent;
8use crate::types::{CliName, McpServer, RunOptions, RunResult};
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<(HashMap<String, String>, Option<String>, Option<tempfile::TempDir>)> {
140    let has_mcp = opts.mcp_servers.as_ref().is_some_and(|s| !s.is_empty());
141    let needs_prompt_file = opts.system_prompt_file.is_none() && opts.system_prompt.is_some();
142
143    // system_prompt_file doesn't need a temp dir — it points to the file directly.
144    if !has_mcp && !needs_prompt_file {
145        let mut env = HashMap::new();
146        if let Some(path) = &opts.system_prompt_file {
147            env.insert("GEMINI_SYSTEM_MD".into(), path.clone());
148        }
149        return Ok((env, None, None));
150    }
151
152    let tmp_dir = tempfile::tempdir().map_err(Error::Io)?;
153    let mut env = HashMap::new();
154
155    // MCP servers → workspace-level .gemini/settings.json.
156    // Gemini CLI merges workspace config (from cwd) with user config (~/.gemini/),
157    // preserving auth credentials while adding our MCP servers.
158    //
159    // If opts.cwd is set, write config there (persistent, enables session resume).
160    // Otherwise, use the temp dir (ephemeral, no session resume).
161    let cwd_override = if let Some(servers) = &opts.mcp_servers {
162        if !servers.is_empty() {
163            let config_dir = if let Some(cwd) = &opts.cwd {
164                std::path::PathBuf::from(cwd)
165            } else {
166                tmp_dir.path().to_path_buf()
167            };
168
169            let gemini_dir = config_dir.join(".gemini");
170            tokio::fs::create_dir_all(&gemini_dir)
171                .await
172                .map_err(Error::Io)?;
173
174            let settings = build_mcp_settings(servers);
175            let settings_path = gemini_dir.join("settings.json");
176            tokio::fs::write(&settings_path, serde_json::to_string_pretty(&settings)?)
177                .await
178                .map_err(Error::Io)?;
179
180            // If we wrote to opts.cwd, no override needed — the adapter
181            // already uses opts.cwd. If we wrote to temp dir, override cwd.
182            if opts.cwd.is_none() {
183                Some(tmp_dir.path().to_string_lossy().into_owned())
184            } else {
185                None
186            }
187        } else {
188            None
189        }
190    } else {
191        None
192    };
193
194    // System prompt → file referenced by GEMINI_SYSTEM_MD
195    // system_prompt_file takes precedence (use the file directly).
196    if let Some(path) = &opts.system_prompt_file {
197        env.insert("GEMINI_SYSTEM_MD".into(), path.clone());
198    } else if let Some(prompt) = &opts.system_prompt {
199        let prompt_path = tmp_dir.path().join("system-prompt.md");
200        tokio::fs::write(&prompt_path, prompt)
201            .await
202            .map_err(Error::Io)?;
203        env.insert(
204            "GEMINI_SYSTEM_MD".into(),
205            prompt_path.to_string_lossy().into_owned(),
206        );
207    }
208
209    Ok((env, cwd_override, Some(tmp_dir)))
210}
211
212fn build_mcp_settings(servers: &HashMap<String, McpServer>) -> serde_json::Value {
213    let mut mcp_map = serde_json::Map::new();
214
215    for (name, server) in servers {
216        let mut entry = serde_json::Map::new();
217
218        if let Some(url) = &server.url {
219            entry.insert("url".into(), serde_json::Value::String(url.clone()));
220            let t = match server.transport_type {
221                Some(crate::types::McpTransport::Http) => "http",
222                _ => "sse",
223            };
224            entry.insert("type".into(), serde_json::Value::String(t.into()));
225            if let Some(headers) = &server.headers {
226                entry.insert(
227                    "headers".into(),
228                    serde_json::to_value(headers).unwrap_or_default(),
229                );
230            }
231        } else {
232            if let Some(cmd) = &server.command {
233                entry.insert("command".into(), serde_json::Value::String(cmd.clone()));
234            }
235            if let Some(a) = &server.args {
236                entry.insert("args".into(), serde_json::to_value(a).unwrap_or_default());
237            }
238            if let Some(e) = &server.env {
239                entry.insert("env".into(), serde_json::to_value(e).unwrap_or_default());
240            }
241            if let Some(cwd) = &server.cwd {
242                entry.insert("cwd".into(), serde_json::Value::String(cwd.clone()));
243            }
244        }
245
246        if let Some(include) = &server.include_tools {
247            entry.insert(
248                "includeTools".into(),
249                serde_json::to_value(include).unwrap_or_default(),
250            );
251        }
252        if let Some(exclude) = &server.exclude_tools {
253            entry.insert(
254                "excludeTools".into(),
255                serde_json::to_value(exclude).unwrap_or_default(),
256            );
257        }
258        if let Some(timeout) = server.timeout {
259            entry.insert("timeout".into(), serde_json::Value::Number(timeout.into()));
260        }
261
262        mcp_map.insert(name.clone(), serde_json::Value::Object(entry));
263    }
264
265    let mut root = serde_json::Map::new();
266    root.insert("mcpServers".into(), serde_json::Value::Object(mcp_map));
267    serde_json::Value::Object(root)
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    #[test]
275    fn build_args_minimal() {
276        let opts = RunOptions {
277            task: "hello".into(),
278            ..Default::default()
279        };
280        let args = build_args(&opts);
281        assert_eq!(args, vec!["-p", "hello", "--output-format", "stream-json"]);
282    }
283
284    #[test]
285    fn build_args_skip_permissions() {
286        let opts = RunOptions {
287            task: "hello".into(),
288            skip_permissions: true,
289            ..Default::default()
290        };
291        let args = build_args(&opts);
292        assert!(args.contains(&"--yolo".to_string()));
293    }
294
295    #[test]
296    fn build_args_no_permission_bypass_by_default() {
297        let opts = RunOptions {
298            task: "hello".into(),
299            ..Default::default()
300        };
301        let args = build_args(&opts);
302        assert!(!args.contains(&"--yolo".to_string()));
303    }
304
305    #[test]
306    fn build_args_with_options() {
307        let opts = RunOptions {
308            task: "do something".into(),
309            model: Some("gemini-2.0-flash".into()),
310            resume_session_id: Some("sess-1".into()),
311            providers: Some(crate::types::ProviderOptions {
312                gemini: Some(crate::types::GeminiOptions {
313                    sandbox: Some(true),
314                    approval_mode: Some("auto".into()),
315                    extra_args: Some(vec!["--verbose".into()]),
316                }),
317                ..Default::default()
318            }),
319            ..Default::default()
320        };
321        let args = build_args(&opts);
322        assert!(args.contains(&"-s".to_string()));
323        assert!(args.contains(&"--model".to_string()));
324        assert!(args.contains(&"gemini-2.0-flash".to_string()));
325        assert!(args.contains(&"--resume".to_string()));
326        assert!(args.contains(&"--approval-mode".to_string()));
327        assert!(args.contains(&"--verbose".to_string()));
328    }
329}