cli_agents/adapters/gemini/
mod.rs1mod 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 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 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 if opts.resume_session_id.is_some() {
106 args.push("--resume".into());
107 args.push("latest".into());
108 }
109
110 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 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
134async 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 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 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 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 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}