acp.rs

  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        cx.spawn(async move |cx| {
166            let response = conn
167                .new_session(acp::NewSessionRequest {
168                    mcp_servers: vec![],
169                    cwd,
170                })
171                .await
172                .map_err(|err| {
173                    if err.code == acp::ErrorCode::AUTH_REQUIRED.code {
174                        let mut error = AuthRequired::new();
175
176                        if err.message != acp::ErrorCode::AUTH_REQUIRED.message {
177                            error = error.with_description(err.message);
178                        }
179
180                        anyhow!(error)
181                    } else {
182                        anyhow!(err)
183                    }
184                })?;
185
186            let session_id = response.session_id;
187            let action_log = cx.new(|_| ActionLog::new(project.clone()))?;
188            let thread = cx.new(|cx| {
189                AcpThread::new(
190                    self.server_name.clone(),
191                    self.clone(),
192                    project,
193                    action_log,
194                    session_id.clone(),
195                    // ACP doesn't currently support per-session prompt capabilities or changing capabilities dynamically.
196                    watch::Receiver::constant(self.prompt_capabilities),
197                    cx,
198                )
199            })?;
200
201            let session = AcpSession {
202                thread: thread.downgrade(),
203                suppress_abort_err: false,
204            };
205            sessions.borrow_mut().insert(session_id, session);
206
207            Ok(thread)
208        })
209    }
210
211    fn auth_methods(&self) -> &[acp::AuthMethod] {
212        &self.auth_methods
213    }
214
215    fn authenticate(&self, method_id: acp::AuthMethodId, cx: &mut App) -> Task<Result<()>> {
216        let conn = self.connection.clone();
217        cx.foreground_executor().spawn(async move {
218            let result = conn
219                .authenticate(acp::AuthenticateRequest {
220                    method_id: method_id.clone(),
221                })
222                .await?;
223
224            Ok(result)
225        })
226    }
227
228    fn prompt(
229        &self,
230        _id: Option<acp_thread::UserMessageId>,
231        params: acp::PromptRequest,
232        cx: &mut App,
233    ) -> Task<Result<acp::PromptResponse>> {
234        let conn = self.connection.clone();
235        let sessions = self.sessions.clone();
236        let session_id = params.session_id.clone();
237        cx.foreground_executor().spawn(async move {
238            let result = conn.prompt(params).await;
239
240            let mut suppress_abort_err = false;
241
242            if let Some(session) = sessions.borrow_mut().get_mut(&session_id) {
243                suppress_abort_err = session.suppress_abort_err;
244                session.suppress_abort_err = false;
245            }
246
247            match result {
248                Ok(response) => Ok(response),
249                Err(err) => {
250                    if err.code != ErrorCode::INTERNAL_ERROR.code {
251                        anyhow::bail!(err)
252                    }
253
254                    let Some(data) = &err.data else {
255                        anyhow::bail!(err)
256                    };
257
258                    // Temporary workaround until the following PR is generally available:
259                    // https://github.com/google-gemini/gemini-cli/pull/6656
260
261                    #[derive(Deserialize)]
262                    #[serde(deny_unknown_fields)]
263                    struct ErrorDetails {
264                        details: Box<str>,
265                    }
266
267                    match serde_json::from_value(data.clone()) {
268                        Ok(ErrorDetails { details }) => {
269                            if suppress_abort_err
270                                && (details.contains("This operation was aborted")
271                                    || details.contains("The user aborted a request"))
272                            {
273                                Ok(acp::PromptResponse {
274                                    stop_reason: acp::StopReason::Cancelled,
275                                })
276                            } else {
277                                Err(anyhow!(details))
278                            }
279                        }
280                        Err(_) => Err(anyhow!(err)),
281                    }
282                }
283            }
284        })
285    }
286
287    fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
288        if let Some(session) = self.sessions.borrow_mut().get_mut(session_id) {
289            session.suppress_abort_err = true;
290        }
291        let conn = self.connection.clone();
292        let params = acp::CancelNotification {
293            session_id: session_id.clone(),
294        };
295        cx.foreground_executor()
296            .spawn(async move { conn.cancel(params).await })
297            .detach();
298    }
299
300    fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
301        self
302    }
303}
304
305struct ClientDelegate {
306    sessions: Rc<RefCell<HashMap<acp::SessionId, AcpSession>>>,
307    cx: AsyncApp,
308}
309
310impl acp::Client for ClientDelegate {
311    async fn request_permission(
312        &self,
313        arguments: acp::RequestPermissionRequest,
314    ) -> Result<acp::RequestPermissionResponse, acp::Error> {
315        let cx = &mut self.cx.clone();
316        let rx = self
317            .sessions
318            .borrow()
319            .get(&arguments.session_id)
320            .context("Failed to get session")?
321            .thread
322            .update(cx, |thread, cx| {
323                thread.request_tool_call_authorization(arguments.tool_call, arguments.options, cx)
324            })?;
325
326        let result = rx?.await;
327
328        let outcome = match result {
329            Ok(option) => acp::RequestPermissionOutcome::Selected { option_id: option },
330            Err(oneshot::Canceled) => acp::RequestPermissionOutcome::Cancelled,
331        };
332
333        Ok(acp::RequestPermissionResponse { outcome })
334    }
335
336    async fn write_text_file(
337        &self,
338        arguments: acp::WriteTextFileRequest,
339    ) -> Result<(), acp::Error> {
340        let cx = &mut self.cx.clone();
341        let task = self
342            .sessions
343            .borrow()
344            .get(&arguments.session_id)
345            .context("Failed to get session")?
346            .thread
347            .update(cx, |thread, cx| {
348                thread.write_text_file(arguments.path, arguments.content, cx)
349            })?;
350
351        task.await?;
352
353        Ok(())
354    }
355
356    async fn read_text_file(
357        &self,
358        arguments: acp::ReadTextFileRequest,
359    ) -> Result<acp::ReadTextFileResponse, acp::Error> {
360        let cx = &mut self.cx.clone();
361        let task = self
362            .sessions
363            .borrow()
364            .get(&arguments.session_id)
365            .context("Failed to get session")?
366            .thread
367            .update(cx, |thread, cx| {
368                thread.read_text_file(arguments.path, arguments.line, arguments.limit, false, cx)
369            })?;
370
371        let content = task.await?;
372
373        Ok(acp::ReadTextFileResponse { content })
374    }
375
376    async fn session_notification(
377        &self,
378        notification: acp::SessionNotification,
379    ) -> Result<(), acp::Error> {
380        let cx = &mut self.cx.clone();
381        let sessions = self.sessions.borrow();
382        let session = sessions
383            .get(&notification.session_id)
384            .context("Failed to get session")?;
385
386        session.thread.update(cx, |thread, cx| {
387            thread.handle_session_update(notification.update, cx)
388        })??;
389
390        Ok(())
391    }
392}