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    tool_name: Entity<Markdown>,
127    status: ToolCallStatus,
128}
129
130#[derive(Debug)]
131pub enum ToolCallStatus {
132    WaitingForConfirmation {
133        description: Entity<Markdown>,
134        respond_tx: oneshot::Sender<bool>,
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 push_tool_call(
273        &mut self,
274        title: String,
275        description: String,
276        confirmation_tx: Option<oneshot::Sender<bool>>,
277        cx: &mut Context<Self>,
278    ) -> ToolCallId {
279        let language_registry = self.project.read(cx).languages().clone();
280
281        let description = cx.new(|cx| {
282            Markdown::new(
283                description.into(),
284                Some(language_registry.clone()),
285                None,
286                cx,
287            )
288        });
289
290        let entry_id = self.push_entry(
291            AgentThreadEntryContent::ToolCall(ToolCall {
292                // todo! clean up id creation
293                id: ToolCallId(ThreadEntryId(self.entries.len() as u64)),
294                tool_name: cx.new(|cx| {
295                    Markdown::new(title.into(), Some(language_registry.clone()), None, cx)
296                }),
297                status: if let Some(respond_tx) = confirmation_tx {
298                    ToolCallStatus::WaitingForConfirmation {
299                        description,
300                        respond_tx,
301                    }
302                } else {
303                    ToolCallStatus::Allowed {
304                        status: acp::ToolCallStatus::Running,
305                        content: Some(description),
306                    }
307                },
308            }),
309            cx,
310        );
311
312        ToolCallId(entry_id)
313    }
314
315    pub fn authorize_tool_call(&mut self, id: ToolCallId, allowed: bool, cx: &mut Context<Self>) {
316        let Some(entry) = self.entry_mut(id.0) else {
317            return;
318        };
319
320        let AgentThreadEntryContent::ToolCall(call) = &mut entry.content else {
321            debug_panic!("expected ToolCall");
322            return;
323        };
324
325        let new_status = if allowed {
326            ToolCallStatus::Allowed {
327                status: acp::ToolCallStatus::Running,
328                content: None,
329            }
330        } else {
331            ToolCallStatus::Rejected
332        };
333
334        let curr_status = mem::replace(&mut call.status, new_status);
335
336        if let ToolCallStatus::WaitingForConfirmation { respond_tx, .. } = curr_status {
337            respond_tx.send(allowed).log_err();
338        } else {
339            debug_panic!("tried to authorize an already authorized tool call");
340        }
341
342        cx.emit(AcpThreadEvent::EntryUpdated(id.as_u64() as usize));
343    }
344
345    pub fn update_tool_call(
346        &mut self,
347        id: ToolCallId,
348        new_status: acp::ToolCallStatus,
349        new_content: Option<acp::ToolCallContent>,
350        cx: &mut Context<Self>,
351    ) -> Result<()> {
352        let language_registry = self.project.read(cx).languages().clone();
353        let entry = self.entry_mut(id.0).context("Entry not found")?;
354
355        match &mut entry.content {
356            AgentThreadEntryContent::ToolCall(call) => match &mut call.status {
357                ToolCallStatus::Allowed { content, status } => {
358                    *content = new_content.map(|new_content| {
359                        let acp::ToolCallContent::Markdown { markdown } = new_content;
360
361                        cx.new(|cx| {
362                            Markdown::new(markdown.into(), Some(language_registry), None, cx)
363                        })
364                    });
365
366                    *status = new_status;
367                }
368                ToolCallStatus::WaitingForConfirmation { .. } => {
369                    anyhow::bail!("Tool call hasn't been authorized yet")
370                }
371                ToolCallStatus::Rejected => {
372                    anyhow::bail!("Tool call was rejected and therefore can't be updated")
373                }
374            },
375            _ => anyhow::bail!("Entry is not a tool call"),
376        }
377
378        cx.emit(AcpThreadEvent::EntryUpdated(id.as_u64() as usize));
379        Ok(())
380    }
381
382    fn entry_mut(&mut self, id: ThreadEntryId) -> Option<&mut ThreadEntry> {
383        let entry = self.entries.get_mut(id.0 as usize);
384        debug_assert!(
385            entry.is_some(),
386            "We shouldn't give out ids to entries that don't exist"
387        );
388        entry
389    }
390
391    /// Returns true if the last turn is awaiting tool authorization
392    pub fn waiting_for_tool_confirmation(&self) -> bool {
393        for entry in self.entries.iter().rev() {
394            match &entry.content {
395                AgentThreadEntryContent::ToolCall(call) => match call.status {
396                    ToolCallStatus::WaitingForConfirmation { .. } => return true,
397                    ToolCallStatus::Allowed { .. } | ToolCallStatus::Rejected => continue,
398                },
399                AgentThreadEntryContent::Message(_) => {
400                    // Reached the beginning of the turn
401                    return false;
402                }
403            }
404        }
405        false
406    }
407
408    pub fn send(&mut self, message: &str, cx: &mut Context<Self>) -> Task<Result<()>> {
409        let agent = self.server.clone();
410        let id = self.id.clone();
411        let chunk = MessageChunk::from_str(message, self.project.read(cx).languages().clone(), cx);
412        let message = Message {
413            role: Role::User,
414            chunks: vec![chunk],
415        };
416        self.push_entry(AgentThreadEntryContent::Message(message.clone()), cx);
417        let acp_message = message.into_acp(cx);
418        cx.spawn(async move |_, cx| {
419            agent.send_message(id, acp_message, cx).await?;
420            Ok(())
421        })
422    }
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428    use futures::{FutureExt as _, channel::mpsc, select};
429    use gpui::{AsyncApp, TestAppContext};
430    use project::FakeFs;
431    use serde_json::json;
432    use settings::SettingsStore;
433    use smol::stream::StreamExt;
434    use std::{env, path::Path, process::Stdio, time::Duration};
435    use util::path;
436
437    fn init_test(cx: &mut TestAppContext) {
438        env_logger::try_init().ok();
439        cx.update(|cx| {
440            let settings_store = SettingsStore::test(cx);
441            cx.set_global(settings_store);
442            Project::init_settings(cx);
443            language::init(cx);
444        });
445    }
446
447    #[gpui::test]
448    async fn test_gemini_basic(cx: &mut TestAppContext) {
449        init_test(cx);
450
451        cx.executor().allow_parking();
452
453        let fs = FakeFs::new(cx.executor());
454        let project = Project::test(fs, [], cx).await;
455        let server = gemini_acp_server(project.clone(), cx.to_async()).unwrap();
456        let thread = server.create_thread(&mut cx.to_async()).await.unwrap();
457        thread
458            .update(cx, |thread, cx| thread.send("Hello from Zed!", cx))
459            .await
460            .unwrap();
461
462        thread.read_with(cx, |thread, _| {
463            assert_eq!(thread.entries.len(), 2);
464            assert!(matches!(
465                thread.entries[0].content,
466                AgentThreadEntryContent::Message(Message {
467                    role: Role::User,
468                    ..
469                })
470            ));
471            assert!(matches!(
472                thread.entries[1].content,
473                AgentThreadEntryContent::Message(Message {
474                    role: Role::Assistant,
475                    ..
476                })
477            ));
478        });
479    }
480
481    #[gpui::test]
482    async fn test_gemini_tool_call(cx: &mut TestAppContext) {
483        init_test(cx);
484
485        cx.executor().allow_parking();
486
487        let fs = FakeFs::new(cx.executor());
488        fs.insert_tree(
489            path!("/private/tmp"),
490            json!({"foo": "Lorem ipsum dolor", "bar": "bar", "baz": "baz"}),
491        )
492        .await;
493        let project = Project::test(fs, [path!("/private/tmp").as_ref()], cx).await;
494        let server = gemini_acp_server(project.clone(), cx.to_async()).unwrap();
495        let thread = server.create_thread(&mut cx.to_async()).await.unwrap();
496        let full_turn = thread.update(cx, |thread, cx| {
497            thread.send(
498                "Read the '/private/tmp/foo' file and tell me what you see.",
499                cx,
500            )
501        });
502
503        run_until_tool_call(&thread, cx).await;
504
505        let tool_call_id = thread.read_with(cx, |thread, cx| {
506            let AgentThreadEntryContent::ToolCall(ToolCall {
507                id,
508                tool_name,
509                status: ToolCallStatus::WaitingForConfirmation { description, .. },
510            }) = &thread.entries().last().unwrap().content
511            else {
512                panic!();
513            };
514
515            tool_name.read_with(cx, |md, _cx| {
516                assert_eq!(md.source(), "read_file");
517            });
518
519            description.read_with(cx, |md, _cx| {
520                assert!(
521                    md.source().contains("foo"),
522                    "Expected description to contain 'foo', but got {}",
523                    md.source()
524                );
525            });
526            *id
527        });
528
529        thread.update(cx, |thread, cx| {
530            thread.authorize_tool_call(tool_call_id, true, cx);
531            assert!(matches!(
532                thread.entries().last().unwrap().content,
533                AgentThreadEntryContent::ToolCall(ToolCall {
534                    status: ToolCallStatus::Allowed { .. },
535                    ..
536                })
537            ));
538        });
539
540        full_turn.await.unwrap();
541
542        thread.read_with(cx, |thread, _| {
543            assert!(thread.entries.len() >= 3, "{:?}", &thread.entries);
544            assert!(matches!(
545                thread.entries[0].content,
546                AgentThreadEntryContent::Message(Message {
547                    role: Role::User,
548                    ..
549                })
550            ));
551            assert!(matches!(
552                thread.entries[1].content,
553                AgentThreadEntryContent::ToolCall(ToolCall {
554                    status: ToolCallStatus::Allowed { .. },
555                    ..
556                })
557            ));
558            assert!(matches!(
559                thread.entries[2].content,
560                AgentThreadEntryContent::Message(Message {
561                    role: Role::Assistant,
562                    ..
563                })
564            ));
565        });
566    }
567
568    async fn run_until_tool_call(thread: &Entity<AcpThread>, cx: &mut TestAppContext) {
569        let (mut tx, mut rx) = mpsc::channel(1);
570
571        let subscription = cx.update(|cx| {
572            cx.subscribe(thread, move |thread, _, cx| {
573                if thread
574                    .read(cx)
575                    .entries
576                    .iter()
577                    .any(|e| matches!(e.content, AgentThreadEntryContent::ToolCall(_)))
578                {
579                    tx.try_send(()).unwrap();
580                }
581            })
582        });
583
584        select! {
585            _ = cx.executor().timer(Duration::from_secs(5)).fuse() => {
586                panic!("Timeout waiting for tool call")
587            }
588            _ = rx.next().fuse() => {
589                drop(subscription);
590            }
591        }
592    }
593
594    pub fn gemini_acp_server(project: Entity<Project>, mut cx: AsyncApp) -> Result<Arc<AcpServer>> {
595        let cli_path =
596            Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../gemini-cli/packages/cli");
597        let mut command = util::command::new_smol_command("node");
598        command
599            .arg(cli_path)
600            .arg("--acp")
601            .args(["--model", "gemini-2.5-flash"])
602            .current_dir("/private/tmp")
603            .stdin(Stdio::piped())
604            .stdout(Stdio::piped())
605            .stderr(Stdio::inherit())
606            .kill_on_drop(true);
607
608        if let Ok(gemini_key) = std::env::var("GEMINI_API_KEY") {
609            command.env("GEMINI_API_KEY", gemini_key);
610        }
611
612        let child = command.spawn().unwrap();
613
614        Ok(AcpServer::stdio(child, project, &mut cx))
615    }
616}