1use crate::AgentServerCommand;
2use acp_thread::AgentConnection;
3use acp_tools::AcpConnectionRegistry;
4use action_log::ActionLog;
5use agent_client_protocol::{self as acp, Agent as _, ErrorCode};
6use anyhow::anyhow;
7use collections::HashMap;
8use futures::AsyncBufReadExt as _;
9use futures::channel::oneshot;
10use futures::io::BufReader;
11use project::Project;
12use serde::Deserialize;
13use std::{any::Any, cell::RefCell};
14use std::{path::Path, rc::Rc};
15use thiserror::Error;
16
17use anyhow::{Context as _, Result};
18use gpui::{App, AppContext as _, AsyncApp, Entity, SharedString, Task, WeakEntity};
19
20use acp_thread::{AcpThread, AuthRequired, LoadError};
21
22#[derive(Debug, Error)]
23#[error("Unsupported version")]
24pub struct UnsupportedVersion;
25
26pub struct AcpConnection {
27 server_name: SharedString,
28 connection: Rc<acp::ClientSideConnection>,
29 sessions: Rc<RefCell<HashMap<acp::SessionId, AcpSession>>>,
30 auth_methods: Vec<acp::AuthMethod>,
31 prompt_capabilities: acp::PromptCapabilities,
32 _io_task: Task<Result<()>>,
33}
34
35pub struct AcpSession {
36 thread: WeakEntity<AcpThread>,
37 suppress_abort_err: bool,
38}
39
40pub async fn connect(
41 server_name: SharedString,
42 command: AgentServerCommand,
43 root_dir: &Path,
44 cx: &mut AsyncApp,
45) -> Result<Rc<dyn AgentConnection>> {
46 let conn = AcpConnection::stdio(server_name, command.clone(), root_dir, cx).await?;
47 Ok(Rc::new(conn) as _)
48}
49
50const MINIMUM_SUPPORTED_VERSION: acp::ProtocolVersion = acp::V1;
51
52impl AcpConnection {
53 pub async fn stdio(
54 server_name: SharedString,
55 command: AgentServerCommand,
56 root_dir: &Path,
57 cx: &mut AsyncApp,
58 ) -> Result<Self> {
59 let mut child = util::command::new_smol_command(&command.path)
60 .args(command.args.iter().map(|arg| arg.as_str()))
61 .envs(command.env.iter().flatten())
62 .current_dir(root_dir)
63 .stdin(std::process::Stdio::piped())
64 .stdout(std::process::Stdio::piped())
65 .stderr(std::process::Stdio::piped())
66 .kill_on_drop(true)
67 .spawn()?;
68
69 let stdout = child.stdout.take().context("Failed to take stdout")?;
70 let stdin = child.stdin.take().context("Failed to take stdin")?;
71 let stderr = child.stderr.take().context("Failed to take stderr")?;
72 log::trace!("Spawned (pid: {})", child.id());
73
74 let sessions = Rc::new(RefCell::new(HashMap::default()));
75
76 let client = ClientDelegate {
77 sessions: sessions.clone(),
78 cx: cx.clone(),
79 };
80 let (connection, io_task) = acp::ClientSideConnection::new(client, stdin, stdout, {
81 let foreground_executor = cx.foreground_executor().clone();
82 move |fut| {
83 foreground_executor.spawn(fut).detach();
84 }
85 });
86
87 let io_task = cx.background_spawn(io_task);
88
89 cx.background_spawn(async move {
90 let mut stderr = BufReader::new(stderr);
91 let mut line = String::new();
92 while let Ok(n) = stderr.read_line(&mut line).await
93 && n > 0
94 {
95 log::warn!("agent stderr: {}", &line);
96 line.clear();
97 }
98 })
99 .detach();
100
101 cx.spawn({
102 let sessions = sessions.clone();
103 async move |cx| {
104 let status = child.status().await?;
105
106 for session in sessions.borrow().values() {
107 session
108 .thread
109 .update(cx, |thread, cx| {
110 thread.emit_load_error(LoadError::Exited { status }, cx)
111 })
112 .ok();
113 }
114
115 anyhow::Ok(())
116 }
117 })
118 .detach();
119
120 let connection = Rc::new(connection);
121
122 cx.update(|cx| {
123 AcpConnectionRegistry::default_global(cx).update(cx, |registry, cx| {
124 registry.set_active_connection(server_name.clone(), &connection, cx)
125 });
126 })?;
127
128 let response = connection
129 .initialize(acp::InitializeRequest {
130 protocol_version: acp::VERSION,
131 client_capabilities: acp::ClientCapabilities {
132 fs: acp::FileSystemCapability {
133 read_text_file: true,
134 write_text_file: true,
135 },
136 },
137 })
138 .await?;
139
140 if response.protocol_version < MINIMUM_SUPPORTED_VERSION {
141 return Err(UnsupportedVersion.into());
142 }
143
144 Ok(Self {
145 auth_methods: response.auth_methods,
146 connection,
147 server_name,
148 sessions,
149 prompt_capabilities: response.agent_capabilities.prompt_capabilities,
150 _io_task: io_task,
151 })
152 }
153}
154
155impl AgentConnection for AcpConnection {
156 fn new_thread(
157 self: Rc<Self>,
158 project: Entity<Project>,
159 cwd: &Path,
160 cx: &mut App,
161 ) -> Task<Result<Entity<AcpThread>>> {
162 let conn = self.connection.clone();
163 let sessions = self.sessions.clone();
164 let cwd = cwd.to_path_buf();
165 let context_server_store = project.read(cx).context_server_store().read(cx);
166 let mcp_servers = context_server_store
167 .configured_server_ids()
168 .iter()
169 .filter_map(|id| {
170 let configuration = context_server_store.configuration_for_server(id)?;
171 let command = configuration.command();
172 Some(acp::McpServer {
173 name: id.0.to_string(),
174 command: command.path.clone(),
175 args: command.args.clone(),
176 env: if let Some(env) = command.env.as_ref() {
177 env.iter()
178 .map(|(name, value)| acp::EnvVariable {
179 name: name.clone(),
180 value: value.clone(),
181 })
182 .collect()
183 } else {
184 vec![]
185 },
186 })
187 })
188 .collect();
189
190 cx.spawn(async move |cx| {
191 let response = conn
192 .new_session(acp::NewSessionRequest { mcp_servers, cwd })
193 .await
194 .map_err(|err| {
195 if err.code == acp::ErrorCode::AUTH_REQUIRED.code {
196 let mut error = AuthRequired::new();
197
198 if err.message != acp::ErrorCode::AUTH_REQUIRED.message {
199 error = error.with_description(err.message);
200 }
201
202 anyhow!(error)
203 } else {
204 anyhow!(err)
205 }
206 })?;
207
208 let session_id = response.session_id;
209 let action_log = cx.new(|_| ActionLog::new(project.clone()))?;
210 let thread = cx.new(|cx| {
211 AcpThread::new(
212 self.server_name.clone(),
213 self.clone(),
214 project,
215 action_log,
216 session_id.clone(),
217 // ACP doesn't currently support per-session prompt capabilities or changing capabilities dynamically.
218 watch::Receiver::constant(self.prompt_capabilities),
219 cx,
220 )
221 })?;
222
223 let session = AcpSession {
224 thread: thread.downgrade(),
225 suppress_abort_err: false,
226 };
227 sessions.borrow_mut().insert(session_id, session);
228
229 Ok(thread)
230 })
231 }
232
233 fn auth_methods(&self) -> &[acp::AuthMethod] {
234 &self.auth_methods
235 }
236
237 fn authenticate(&self, method_id: acp::AuthMethodId, cx: &mut App) -> Task<Result<()>> {
238 let conn = self.connection.clone();
239 cx.foreground_executor().spawn(async move {
240 let result = conn
241 .authenticate(acp::AuthenticateRequest {
242 method_id: method_id.clone(),
243 })
244 .await?;
245
246 Ok(result)
247 })
248 }
249
250 fn prompt(
251 &self,
252 _id: Option<acp_thread::UserMessageId>,
253 params: acp::PromptRequest,
254 cx: &mut App,
255 ) -> Task<Result<acp::PromptResponse>> {
256 let conn = self.connection.clone();
257 let sessions = self.sessions.clone();
258 let session_id = params.session_id.clone();
259 cx.foreground_executor().spawn(async move {
260 let result = conn.prompt(params).await;
261
262 let mut suppress_abort_err = false;
263
264 if let Some(session) = sessions.borrow_mut().get_mut(&session_id) {
265 suppress_abort_err = session.suppress_abort_err;
266 session.suppress_abort_err = false;
267 }
268
269 match result {
270 Ok(response) => Ok(response),
271 Err(err) => {
272 if err.code != ErrorCode::INTERNAL_ERROR.code {
273 anyhow::bail!(err)
274 }
275
276 let Some(data) = &err.data else {
277 anyhow::bail!(err)
278 };
279
280 // Temporary workaround until the following PR is generally available:
281 // https://github.com/google-gemini/gemini-cli/pull/6656
282
283 #[derive(Deserialize)]
284 #[serde(deny_unknown_fields)]
285 struct ErrorDetails {
286 details: Box<str>,
287 }
288
289 match serde_json::from_value(data.clone()) {
290 Ok(ErrorDetails { details }) => {
291 if suppress_abort_err
292 && (details.contains("This operation was aborted")
293 || details.contains("The user aborted a request"))
294 {
295 Ok(acp::PromptResponse {
296 stop_reason: acp::StopReason::Cancelled,
297 })
298 } else {
299 Err(anyhow!(details))
300 }
301 }
302 Err(_) => Err(anyhow!(err)),
303 }
304 }
305 }
306 })
307 }
308
309 fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
310 if let Some(session) = self.sessions.borrow_mut().get_mut(session_id) {
311 session.suppress_abort_err = true;
312 }
313 let conn = self.connection.clone();
314 let params = acp::CancelNotification {
315 session_id: session_id.clone(),
316 };
317 cx.foreground_executor()
318 .spawn(async move { conn.cancel(params).await })
319 .detach();
320 }
321
322 fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
323 self
324 }
325}
326
327struct ClientDelegate {
328 sessions: Rc<RefCell<HashMap<acp::SessionId, AcpSession>>>,
329 cx: AsyncApp,
330}
331
332impl acp::Client for ClientDelegate {
333 async fn request_permission(
334 &self,
335 arguments: acp::RequestPermissionRequest,
336 ) -> Result<acp::RequestPermissionResponse, acp::Error> {
337 let cx = &mut self.cx.clone();
338 let rx = self
339 .sessions
340 .borrow()
341 .get(&arguments.session_id)
342 .context("Failed to get session")?
343 .thread
344 .update(cx, |thread, cx| {
345 thread.request_tool_call_authorization(arguments.tool_call, arguments.options, cx)
346 })?;
347
348 let result = rx?.await;
349
350 let outcome = match result {
351 Ok(option) => acp::RequestPermissionOutcome::Selected { option_id: option },
352 Err(oneshot::Canceled) => acp::RequestPermissionOutcome::Cancelled,
353 };
354
355 Ok(acp::RequestPermissionResponse { outcome })
356 }
357
358 async fn write_text_file(
359 &self,
360 arguments: acp::WriteTextFileRequest,
361 ) -> Result<(), acp::Error> {
362 let cx = &mut self.cx.clone();
363 let task = self
364 .sessions
365 .borrow()
366 .get(&arguments.session_id)
367 .context("Failed to get session")?
368 .thread
369 .update(cx, |thread, cx| {
370 thread.write_text_file(arguments.path, arguments.content, cx)
371 })?;
372
373 task.await?;
374
375 Ok(())
376 }
377
378 async fn read_text_file(
379 &self,
380 arguments: acp::ReadTextFileRequest,
381 ) -> Result<acp::ReadTextFileResponse, acp::Error> {
382 let cx = &mut self.cx.clone();
383 let task = self
384 .sessions
385 .borrow()
386 .get(&arguments.session_id)
387 .context("Failed to get session")?
388 .thread
389 .update(cx, |thread, cx| {
390 thread.read_text_file(arguments.path, arguments.line, arguments.limit, false, cx)
391 })?;
392
393 let content = task.await?;
394
395 Ok(acp::ReadTextFileResponse { content })
396 }
397
398 async fn session_notification(
399 &self,
400 notification: acp::SessionNotification,
401 ) -> Result<(), acp::Error> {
402 let cx = &mut self.cx.clone();
403 let sessions = self.sessions.borrow();
404 let session = sessions
405 .get(¬ification.session_id)
406 .context("Failed to get session")?;
407
408 session.thread.update(cx, |thread, cx| {
409 thread.handle_session_update(notification.update, cx)
410 })??;
411
412 Ok(())
413 }
414}