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