1use std::rc::Rc;
2use std::{any::Any, path::Path};
3
4use crate::acp::AcpConnection;
5use crate::{AgentServer, AgentServerDelegate};
6use acp_thread::{AgentConnection, LoadError};
7use anyhow::Result;
8use gpui::{App, AppContext as _, SharedString, Task};
9use language_models::provider::google::GoogleLanguageModelProvider;
10use settings::SettingsStore;
11
12use crate::AllAgentServersSettings;
13
14#[derive(Clone)]
15pub struct Gemini;
16
17const ACP_ARG: &str = "--experimental-acp";
18
19impl AgentServer for Gemini {
20 fn telemetry_id(&self) -> &'static str {
21 "gemini-cli"
22 }
23
24 fn name(&self) -> SharedString {
25 "Gemini CLI".into()
26 }
27
28 fn logo(&self) -> ui::IconName {
29 ui::IconName::AiGemini
30 }
31
32 fn connect(
33 &self,
34 root_dir: &Path,
35 delegate: AgentServerDelegate,
36 cx: &mut App,
37 ) -> Task<Result<Rc<dyn AgentConnection>>> {
38 let root_dir = root_dir.to_path_buf();
39 let server_name = self.name();
40 let settings = cx.read_global(|settings: &SettingsStore, _| {
41 settings.get::<AllAgentServersSettings>(None).gemini.clone()
42 });
43
44 cx.spawn(async move |cx| {
45 let ignore_system_version = settings
46 .as_ref()
47 .and_then(|settings| settings.ignore_system_version)
48 .unwrap_or(true);
49 let mut command = if let Some(settings) = settings
50 && let Some(command) = settings.custom_command()
51 {
52 command
53 } else {
54 cx.update(|cx| {
55 delegate.get_or_npm_install_builtin_agent(
56 Self::BINARY_NAME.into(),
57 Self::PACKAGE_NAME.into(),
58 format!("node_modules/{}/dist/index.js", Self::PACKAGE_NAME).into(),
59 ignore_system_version,
60 Some(Self::MINIMUM_VERSION.parse().unwrap()),
61 cx,
62 )
63 })?
64 .await?
65 };
66 if !command.args.contains(&ACP_ARG.into()) {
67 command.args.push(ACP_ARG.into());
68 }
69
70 if let Some(api_key) = cx.update(GoogleLanguageModelProvider::api_key)?.await.ok() {
71 command
72 .env
73 .get_or_insert_default()
74 .insert("GEMINI_API_KEY".to_owned(), api_key.key);
75 }
76
77 let result = crate::acp::connect(server_name, command.clone(), &root_dir, cx).await;
78 match &result {
79 Ok(connection) => {
80 if let Some(connection) = connection.clone().downcast::<AcpConnection>()
81 && !connection.prompt_capabilities().image
82 {
83 let version_output = util::command::new_smol_command(&command.path)
84 .args(command.args.iter())
85 .arg("--version")
86 .kill_on_drop(true)
87 .output()
88 .await;
89 let current_version =
90 String::from_utf8(version_output?.stdout)?.trim().to_owned();
91
92 log::error!("connected to gemini, but missing prompt_capabilities.image (version is {current_version})");
93 return Err(LoadError::Unsupported {
94 current_version: current_version.into(),
95 command: command.path.to_string_lossy().to_string().into(),
96 minimum_version: Self::MINIMUM_VERSION.into(),
97 }
98 .into());
99 }
100 }
101 Err(e) => {
102 let version_fut = util::command::new_smol_command(&command.path)
103 .args(command.args.iter())
104 .arg("--version")
105 .kill_on_drop(true)
106 .output();
107
108 let help_fut = util::command::new_smol_command(&command.path)
109 .args(command.args.iter())
110 .arg("--help")
111 .kill_on_drop(true)
112 .output();
113
114 let (version_output, help_output) =
115 futures::future::join(version_fut, help_fut).await;
116 let Some(version_output) = version_output.ok().and_then(|output| String::from_utf8(output.stdout).ok()) else {
117 return result;
118 };
119 let Some((help_stdout, help_stderr)) = help_output.ok().and_then(|output| String::from_utf8(output.stdout).ok().zip(String::from_utf8(output.stderr).ok())) else {
120 return result;
121 };
122
123 let current_version = version_output.trim().to_string();
124 let supported = help_stdout.contains(ACP_ARG) || current_version.parse::<semver::Version>().is_ok_and(|version| version >= Self::MINIMUM_VERSION.parse::<semver::Version>().unwrap());
125
126 log::error!("failed to create ACP connection to gemini (version is {current_version}, supported: {supported}): {e}");
127 log::debug!("gemini --help stdout: {help_stdout:?}");
128 log::debug!("gemini --help stderr: {help_stderr:?}");
129 if !supported {
130 return Err(LoadError::Unsupported {
131 current_version: current_version.into(),
132 command: command.path.to_string_lossy().to_string().into(),
133 minimum_version: Self::MINIMUM_VERSION.into(),
134 }
135 .into());
136 }
137 }
138 }
139 result
140 })
141 }
142
143 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
144 self
145 }
146}
147
148impl Gemini {
149 const PACKAGE_NAME: &str = "@google/gemini-cli";
150
151 const MINIMUM_VERSION: &str = "0.2.1";
152
153 const BINARY_NAME: &str = "gemini";
154}
155
156#[cfg(test)]
157pub(crate) mod tests {
158 use super::*;
159 use crate::AgentServerCommand;
160 use std::path::Path;
161
162 crate::common_e2e_tests!(async |_, _, _| Gemini, allow_option_id = "proceed_once");
163
164 pub fn local_command() -> AgentServerCommand {
165 let cli_path = Path::new(env!("CARGO_MANIFEST_DIR"))
166 .join("../../../gemini-cli/packages/cli")
167 .to_string_lossy()
168 .to_string();
169
170 AgentServerCommand {
171 path: "node".into(),
172 args: vec![cli_path],
173 env: None,
174 }
175 }
176}