acp.rs

  1mod server;
  2mod thread_view;
  3
  4use agentic_coding_protocol::{self as acp, Role};
  5use anyhow::{Context as _, Result};
  6use chrono::{DateTime, Utc};
  7use futures::channel::oneshot;
  8use gpui::{AppContext, Context, Entity, EventEmitter, SharedString, Task};
  9use language::LanguageRegistry;
 10use markdown::Markdown;
 11use project::Project;
 12use std::{mem, ops::Range, path::PathBuf, sync::Arc};
 13use ui::App;
 14use util::{ResultExt, debug_panic};
 15
 16pub use server::AcpServer;
 17pub use thread_view::AcpThreadView;
 18
 19#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 20pub struct ThreadId(SharedString);
 21
 22#[derive(Copy, Clone, Debug, PartialEq, Eq)]
 23pub struct FileVersion(u64);
 24
 25#[derive(Debug)]
 26pub struct AgentThreadSummary {
 27    pub id: ThreadId,
 28    pub title: String,
 29    pub created_at: DateTime<Utc>,
 30}
 31
 32#[derive(Clone, Debug, PartialEq, Eq)]
 33pub struct FileContent {
 34    pub path: PathBuf,
 35    pub version: FileVersion,
 36    pub content: SharedString,
 37}
 38
 39#[derive(Clone, Debug, Eq, PartialEq)]
 40pub struct Message {
 41    pub role: acp::Role,
 42    pub chunks: Vec<MessageChunk>,
 43}
 44
 45impl Message {
 46    fn into_acp(self, cx: &App) -> acp::Message {
 47        acp::Message {
 48            role: self.role,
 49            chunks: self
 50                .chunks
 51                .into_iter()
 52                .map(|chunk| chunk.into_acp(cx))
 53                .collect(),
 54        }
 55    }
 56}
 57
 58#[derive(Clone, Debug, Eq, PartialEq)]
 59pub enum MessageChunk {
 60    Text {
 61        chunk: Entity<Markdown>,
 62    },
 63    File {
 64        content: FileContent,
 65    },
 66    Directory {
 67        path: PathBuf,
 68        contents: Vec<FileContent>,
 69    },
 70    Symbol {
 71        path: PathBuf,
 72        range: Range<u64>,
 73        version: FileVersion,
 74        name: SharedString,
 75        content: SharedString,
 76    },
 77    Fetch {
 78        url: SharedString,
 79        content: SharedString,
 80    },
 81}
 82
 83impl MessageChunk {
 84    pub fn from_acp(
 85        chunk: acp::MessageChunk,
 86        language_registry: Arc<LanguageRegistry>,
 87        cx: &mut App,
 88    ) -> Self {
 89        match chunk {
 90            acp::MessageChunk::Text { chunk } => MessageChunk::Text {
 91                chunk: cx.new(|cx| Markdown::new(chunk.into(), Some(language_registry), None, cx)),
 92            },
 93        }
 94    }
 95
 96    pub fn into_acp(self, cx: &App) -> acp::MessageChunk {
 97        match self {
 98            MessageChunk::Text { chunk } => acp::MessageChunk::Text {
 99                chunk: chunk.read(cx).source().to_string(),
100            },
101            MessageChunk::File { .. } => todo!(),
102            MessageChunk::Directory { .. } => todo!(),
103            MessageChunk::Symbol { .. } => todo!(),
104            MessageChunk::Fetch { .. } => todo!(),
105        }
106    }
107
108    pub fn from_str(chunk: &str, language_registry: Arc<LanguageRegistry>, cx: &mut App) -> Self {
109        MessageChunk::Text {
110            chunk: cx.new(|cx| {
111                Markdown::new(chunk.to_owned().into(), Some(language_registry), None, cx)
112            }),
113        }
114    }
115}
116
117#[derive(Debug)]
118pub enum AgentThreadEntryContent {
119    Message(Message),
120    ToolCall(ToolCall),
121}
122
123#[derive(Debug)]
124pub struct ToolCall {
125    id: ToolCallId,
126    display_name: Entity<Markdown>,
127    status: ToolCallStatus,
128}
129
130#[derive(Debug)]
131pub enum ToolCallStatus {
132    WaitingForConfirmation {
133        confirmation: acp::ToolCallConfirmation,
134        respond_tx: oneshot::Sender<acp::ToolCallConfirmationOutcome>,
135    },
136    // todo! Running?
137    Allowed {
138        // todo! should this be variants in crate::ToolCallStatus instead?
139        status: acp::ToolCallStatus,
140        content: Option<Entity<Markdown>>,
141    },
142    Rejected,
143}
144
145/// A `ThreadEntryId` that is known to be a ToolCall
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
147pub struct ToolCallId(ThreadEntryId);
148
149impl ToolCallId {
150    pub fn as_u64(&self) -> u64 {
151        self.0.0
152    }
153}
154
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
156pub struct ThreadEntryId(pub u64);
157
158impl ThreadEntryId {
159    pub fn post_inc(&mut self) -> Self {
160        let id = *self;
161        self.0 += 1;
162        id
163    }
164}
165
166#[derive(Debug)]
167pub struct ThreadEntry {
168    pub id: ThreadEntryId,
169    pub content: AgentThreadEntryContent,
170}
171
172pub struct AcpThread {
173    id: ThreadId,
174    next_entry_id: ThreadEntryId,
175    entries: Vec<ThreadEntry>,
176    server: Arc<AcpServer>,
177    title: SharedString,
178    project: Entity<Project>,
179}
180
181enum AcpThreadEvent {
182    NewEntry,
183    EntryUpdated(usize),
184}
185
186impl EventEmitter<AcpThreadEvent> for AcpThread {}
187
188impl AcpThread {
189    pub fn new(
190        server: Arc<AcpServer>,
191        thread_id: ThreadId,
192        entries: Vec<AgentThreadEntryContent>,
193        project: Entity<Project>,
194        _: &mut Context<Self>,
195    ) -> Self {
196        let mut next_entry_id = ThreadEntryId(0);
197        Self {
198            title: "A new agent2 thread".into(),
199            entries: entries
200                .into_iter()
201                .map(|entry| ThreadEntry {
202                    id: next_entry_id.post_inc(),
203                    content: entry,
204                })
205                .collect(),
206            server,
207            id: thread_id,
208            next_entry_id,
209            project,
210        }
211    }
212
213    pub fn title(&self) -> SharedString {
214        self.title.clone()
215    }
216
217    pub fn entries(&self) -> &[ThreadEntry] {
218        &self.entries
219    }
220
221    pub fn push_entry(
222        &mut self,
223        entry: AgentThreadEntryContent,
224        cx: &mut Context<Self>,
225    ) -> ThreadEntryId {
226        let id = self.next_entry_id.post_inc();
227        self.entries.push(ThreadEntry { id, content: entry });
228        cx.emit(AcpThreadEvent::NewEntry);
229        id
230    }
231
232    pub fn push_assistant_chunk(&mut self, chunk: acp::MessageChunk, cx: &mut Context<Self>) {
233        let entries_len = self.entries.len();
234        if let Some(last_entry) = self.entries.last_mut()
235            && let AgentThreadEntryContent::Message(Message {
236                ref mut chunks,
237                role: Role::Assistant,
238            }) = last_entry.content
239        {
240            cx.emit(AcpThreadEvent::EntryUpdated(entries_len - 1));
241
242            if let (
243                Some(MessageChunk::Text { chunk: old_chunk }),
244                acp::MessageChunk::Text { chunk: new_chunk },
245            ) = (chunks.last_mut(), &chunk)
246            {
247                old_chunk.update(cx, |old_chunk, cx| {
248                    old_chunk.append(&new_chunk, cx);
249                });
250            } else {
251                chunks.push(MessageChunk::from_acp(
252                    chunk,
253                    self.project.read(cx).languages().clone(),
254                    cx,
255                ));
256            }
257
258            return;
259        }
260
261        let chunk = MessageChunk::from_acp(chunk, self.project.read(cx).languages().clone(), cx);
262
263        self.push_entry(
264            AgentThreadEntryContent::Message(Message {
265                role: Role::Assistant,
266                chunks: vec![chunk],
267            }),
268            cx,
269        );
270    }
271
272    pub fn request_tool_call(
273        &mut self,
274        display_name: String,
275        confirmation: acp::ToolCallConfirmation,
276        cx: &mut Context<Self>,
277    ) -> ToolCallRequest {
278        let (tx, rx) = oneshot::channel();
279
280        let status = ToolCallStatus::WaitingForConfirmation {
281            confirmation,
282            respond_tx: tx,
283        };
284
285        let id = self.insert_tool_call(display_name, status, cx);
286        ToolCallRequest { id, outcome: rx }
287    }
288
289    pub fn push_tool_call(&mut self, display_name: String, cx: &mut Context<Self>) -> ToolCallId {
290        let status = ToolCallStatus::Allowed {
291            status: acp::ToolCallStatus::Running,
292            content: None,
293        };
294
295        self.insert_tool_call(display_name, status, cx)
296    }
297
298    fn insert_tool_call(
299        &mut self,
300        display_name: String,
301        status: ToolCallStatus,
302        cx: &mut Context<Self>,
303    ) -> ToolCallId {
304        let language_registry = self.project.read(cx).languages().clone();
305
306        let entry_id = self.push_entry(
307            AgentThreadEntryContent::ToolCall(ToolCall {
308                // todo! clean up id creation
309                id: ToolCallId(ThreadEntryId(self.entries.len() as u64)),
310                display_name: cx.new(|cx| {
311                    Markdown::new(
312                        display_name.into(),
313                        Some(language_registry.clone()),
314                        None,
315                        cx,
316                    )
317                }),
318                status,
319            }),
320            cx,
321        );
322
323        ToolCallId(entry_id)
324    }
325
326    pub fn authorize_tool_call(
327        &mut self,
328        id: ToolCallId,
329        outcome: acp::ToolCallConfirmationOutcome,
330        cx: &mut Context<Self>,
331    ) {
332        let Some(entry) = self.entry_mut(id.0) else {
333            return;
334        };
335
336        let AgentThreadEntryContent::ToolCall(call) = &mut entry.content else {
337            debug_panic!("expected ToolCall");
338            return;
339        };
340
341        let new_status = if outcome == acp::ToolCallConfirmationOutcome::Reject {
342            ToolCallStatus::Rejected
343        } else {
344            ToolCallStatus::Allowed {
345                status: acp::ToolCallStatus::Running,
346                content: None,
347            }
348        };
349
350        let curr_status = mem::replace(&mut call.status, new_status);
351
352        if let ToolCallStatus::WaitingForConfirmation { respond_tx, .. } = curr_status {
353            respond_tx.send(outcome).log_err();
354        } else {
355            debug_panic!("tried to authorize an already authorized tool call");
356        }
357
358        cx.emit(AcpThreadEvent::EntryUpdated(id.as_u64() as usize));
359    }
360
361    pub fn update_tool_call(
362        &mut self,
363        id: ToolCallId,
364        new_status: acp::ToolCallStatus,
365        new_content: Option<acp::ToolCallContent>,
366        cx: &mut Context<Self>,
367    ) -> Result<()> {
368        let language_registry = self.project.read(cx).languages().clone();
369        let entry = self.entry_mut(id.0).context("Entry not found")?;
370
371        match &mut entry.content {
372            AgentThreadEntryContent::ToolCall(call) => match &mut call.status {
373                ToolCallStatus::Allowed { content, status } => {
374                    *content = new_content.map(|new_content| {
375                        let acp::ToolCallContent::Markdown { markdown } = new_content;
376
377                        cx.new(|cx| {
378                            Markdown::new(markdown.into(), Some(language_registry), None, cx)
379                        })
380                    });
381
382                    *status = new_status;
383                }
384                ToolCallStatus::WaitingForConfirmation { .. } => {
385                    anyhow::bail!("Tool call hasn't been authorized yet")
386                }
387                ToolCallStatus::Rejected => {
388                    anyhow::bail!("Tool call was rejected and therefore can't be updated")
389                }
390            },
391            _ => anyhow::bail!("Entry is not a tool call"),
392        }
393
394        cx.emit(AcpThreadEvent::EntryUpdated(id.as_u64() as usize));
395        Ok(())
396    }
397
398    fn entry_mut(&mut self, id: ThreadEntryId) -> Option<&mut ThreadEntry> {
399        let entry = self.entries.get_mut(id.0 as usize);
400        debug_assert!(
401            entry.is_some(),
402            "We shouldn't give out ids to entries that don't exist"
403        );
404        entry
405    }
406
407    /// Returns true if the last turn is awaiting tool authorization
408    pub fn waiting_for_tool_confirmation(&self) -> bool {
409        for entry in self.entries.iter().rev() {
410            match &entry.content {
411                AgentThreadEntryContent::ToolCall(call) => match call.status {
412                    ToolCallStatus::WaitingForConfirmation { .. } => return true,
413                    ToolCallStatus::Allowed { .. } | ToolCallStatus::Rejected => continue,
414                },
415                AgentThreadEntryContent::Message(_) => {
416                    // Reached the beginning of the turn
417                    return false;
418                }
419            }
420        }
421        false
422    }
423
424    pub fn send(&mut self, message: &str, cx: &mut Context<Self>) -> Task<Result<()>> {
425        let agent = self.server.clone();
426        let id = self.id.clone();
427        let chunk = MessageChunk::from_str(message, self.project.read(cx).languages().clone(), cx);
428        let message = Message {
429            role: Role::User,
430            chunks: vec![chunk],
431        };
432        self.push_entry(AgentThreadEntryContent::Message(message.clone()), cx);
433        let acp_message = message.into_acp(cx);
434        cx.spawn(async move |_, cx| {
435            agent.send_message(id, acp_message, cx).await?;
436            Ok(())
437        })
438    }
439}
440
441pub struct ToolCallRequest {
442    pub id: ToolCallId,
443    pub outcome: oneshot::Receiver<acp::ToolCallConfirmationOutcome>,
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449    use gpui::{AsyncApp, TestAppContext};
450    use project::FakeFs;
451    use serde_json::json;
452    use settings::SettingsStore;
453    use std::{env, path::Path, process::Stdio};
454    use util::path;
455
456    fn init_test(cx: &mut TestAppContext) {
457        env_logger::try_init().ok();
458        cx.update(|cx| {
459            let settings_store = SettingsStore::test(cx);
460            cx.set_global(settings_store);
461            Project::init_settings(cx);
462            language::init(cx);
463        });
464    }
465
466    #[gpui::test]
467    async fn test_gemini_basic(cx: &mut TestAppContext) {
468        init_test(cx);
469
470        cx.executor().allow_parking();
471
472        let fs = FakeFs::new(cx.executor());
473        let project = Project::test(fs, [], cx).await;
474        let server = gemini_acp_server(project.clone(), cx.to_async()).unwrap();
475        let thread = server.create_thread(&mut cx.to_async()).await.unwrap();
476        thread
477            .update(cx, |thread, cx| thread.send("Hello from Zed!", cx))
478            .await
479            .unwrap();
480
481        thread.read_with(cx, |thread, _| {
482            assert_eq!(thread.entries.len(), 2);
483            assert!(matches!(
484                thread.entries[0].content,
485                AgentThreadEntryContent::Message(Message {
486                    role: Role::User,
487                    ..
488                })
489            ));
490            assert!(matches!(
491                thread.entries[1].content,
492                AgentThreadEntryContent::Message(Message {
493                    role: Role::Assistant,
494                    ..
495                })
496            ));
497        });
498    }
499
500    #[gpui::test]
501    async fn test_gemini_tool_call(cx: &mut TestAppContext) {
502        init_test(cx);
503
504        cx.executor().allow_parking();
505
506        let fs = FakeFs::new(cx.executor());
507        fs.insert_tree(
508            path!("/private/tmp"),
509            json!({"foo": "Lorem ipsum dolor", "bar": "bar", "baz": "baz"}),
510        )
511        .await;
512        let project = Project::test(fs, [path!("/private/tmp").as_ref()], cx).await;
513        let server = gemini_acp_server(project.clone(), cx.to_async()).unwrap();
514        let thread = server.create_thread(&mut cx.to_async()).await.unwrap();
515        thread
516            .update(cx, |thread, cx| {
517                thread.send(
518                    "Read the '/private/tmp/foo' file and tell me what you see.",
519                    cx,
520                )
521            })
522            .await
523            .unwrap();
524        thread.read_with(cx, |thread, cx| {
525            let AgentThreadEntryContent::ToolCall(ToolCall {
526                id,
527                display_name,
528                status: ToolCallStatus::Allowed { content, .. },
529            }) = &thread.entries()[1].content
530            else {
531                panic!();
532            };
533
534            display_name.read_with(cx, |md, _cx| {
535                assert_eq!(md.source(), "ReadFile");
536            });
537
538            // todo!
539            // description.read_with(cx, |md, _cx| {
540            //     assert!(
541            //         md.source().contains("foo"),
542            //         "Expected description to contain 'foo', but got {}",
543            //         md.source()
544            //     );
545            // });
546            *id
547        });
548    }
549
550    pub fn gemini_acp_server(project: Entity<Project>, mut cx: AsyncApp) -> Result<Arc<AcpServer>> {
551        let cli_path =
552            Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../gemini-cli/packages/cli");
553        let mut command = util::command::new_smol_command("node");
554        command
555            .arg(cli_path)
556            .arg("--acp")
557            .args(["--model", "gemini-2.5-flash"])
558            .current_dir("/private/tmp")
559            .stdin(Stdio::piped())
560            .stdout(Stdio::piped())
561            .stderr(Stdio::inherit())
562            .kill_on_drop(true);
563
564        if let Ok(gemini_key) = std::env::var("GEMINI_API_KEY") {
565            command.env("GEMINI_API_KEY", gemini_key);
566        }
567
568        let child = command.spawn().unwrap();
569
570        Ok(AcpServer::stdio(child, project, &mut cx))
571    }
572}