agent.rs

   1use crate::native_agent_server::NATIVE_AGENT_SERVER_NAME;
   2use crate::{
   3    ContextServerRegistry, CopyPathTool, CreateDirectoryTool, DeletePathTool, DiagnosticsTool,
   4    EditFileTool, FetchTool, FindPathTool, GrepTool, ListDirectoryTool, MovePathTool, NowTool,
   5    OpenTool, ReadFileTool, TerminalTool, ThinkingTool, Thread, ThreadEvent, ToolCallAuthorization,
   6    UserMessageContent, WebSearchTool, templates::Templates,
   7};
   8use crate::{ThreadsDatabase, generate_session_id};
   9use acp_thread::{AcpThread, AcpThreadMetadata, AgentModelSelector};
  10use agent_client_protocol as acp;
  11use agent_settings::AgentSettings;
  12use anyhow::{Context as _, Result, anyhow};
  13use collections::{HashSet, IndexMap};
  14use fs::Fs;
  15use futures::channel::mpsc;
  16use futures::{StreamExt, future};
  17use gpui::{
  18    App, AppContext, AsyncApp, Context, Entity, SharedString, Subscription, Task, WeakEntity,
  19};
  20use language_model::{LanguageModel, LanguageModelProvider, LanguageModelRegistry, SelectedModel};
  21use project::{Project, ProjectItem, ProjectPath, Worktree};
  22use prompt_store::{
  23    ProjectContext, PromptId, PromptStore, RulesFileContext, UserRulesContext, WorktreeContext,
  24};
  25use settings::update_settings_file;
  26use std::any::Any;
  27use std::cell::RefCell;
  28use std::collections::HashMap;
  29use std::path::Path;
  30use std::rc::Rc;
  31use std::sync::Arc;
  32use std::time::Duration;
  33use util::ResultExt;
  34
  35const RULES_FILE_NAMES: [&'static str; 9] = [
  36    ".rules",
  37    ".cursorrules",
  38    ".windsurfrules",
  39    ".clinerules",
  40    ".github/copilot-instructions.md",
  41    "CLAUDE.md",
  42    "AGENT.md",
  43    "AGENTS.md",
  44    "GEMINI.md",
  45];
  46
  47const SAVE_THREAD_DEBOUNCE: Duration = Duration::from_millis(500);
  48
  49pub struct RulesLoadingError {
  50    pub message: SharedString,
  51}
  52
  53/// Holds both the internal Thread and the AcpThread for a session
  54struct Session {
  55    /// The internal thread that processes messages
  56    thread: Entity<Thread>,
  57    /// The ACP thread that handles protocol communication
  58    acp_thread: WeakEntity<acp_thread::AcpThread>,
  59    save_task: Task<Result<()>>,
  60    _subscriptions: Vec<Subscription>,
  61}
  62
  63pub struct LanguageModels {
  64    /// Access language model by ID
  65    models: HashMap<acp_thread::AgentModelId, Arc<dyn LanguageModel>>,
  66    /// Cached list for returning language model information
  67    model_list: acp_thread::AgentModelList,
  68    refresh_models_rx: watch::Receiver<()>,
  69    refresh_models_tx: watch::Sender<()>,
  70}
  71
  72impl LanguageModels {
  73    fn new(cx: &App) -> Self {
  74        let (refresh_models_tx, refresh_models_rx) = watch::channel(());
  75        let mut this = Self {
  76            models: HashMap::default(),
  77            model_list: acp_thread::AgentModelList::Grouped(IndexMap::default()),
  78            refresh_models_rx,
  79            refresh_models_tx,
  80        };
  81        this.refresh_list(cx);
  82        this
  83    }
  84
  85    fn refresh_list(&mut self, cx: &App) {
  86        let providers = LanguageModelRegistry::global(cx)
  87            .read(cx)
  88            .providers()
  89            .into_iter()
  90            .filter(|provider| provider.is_authenticated(cx))
  91            .collect::<Vec<_>>();
  92
  93        let mut language_model_list = IndexMap::default();
  94        let mut recommended_models = HashSet::default();
  95
  96        let mut recommended = Vec::new();
  97        for provider in &providers {
  98            for model in provider.recommended_models(cx) {
  99                recommended_models.insert(model.id());
 100                recommended.push(Self::map_language_model_to_info(&model, &provider));
 101            }
 102        }
 103        if !recommended.is_empty() {
 104            language_model_list.insert(
 105                acp_thread::AgentModelGroupName("Recommended".into()),
 106                recommended,
 107            );
 108        }
 109
 110        let mut models = HashMap::default();
 111        for provider in providers {
 112            let mut provider_models = Vec::new();
 113            for model in provider.provided_models(cx) {
 114                let model_info = Self::map_language_model_to_info(&model, &provider);
 115                let model_id = model_info.id.clone();
 116                if !recommended_models.contains(&model.id()) {
 117                    provider_models.push(model_info);
 118                }
 119                models.insert(model_id, model);
 120            }
 121            if !provider_models.is_empty() {
 122                language_model_list.insert(
 123                    acp_thread::AgentModelGroupName(provider.name().0.clone()),
 124                    provider_models,
 125                );
 126            }
 127        }
 128
 129        self.models = models;
 130        self.model_list = acp_thread::AgentModelList::Grouped(language_model_list);
 131        self.refresh_models_tx.send(()).ok();
 132    }
 133
 134    fn watch(&self) -> watch::Receiver<()> {
 135        self.refresh_models_rx.clone()
 136    }
 137
 138    pub fn model_from_id(
 139        &self,
 140        model_id: &acp_thread::AgentModelId,
 141    ) -> Option<Arc<dyn LanguageModel>> {
 142        dbg!(&self.models.len());
 143        self.models.get(model_id).cloned()
 144    }
 145
 146    fn map_language_model_to_info(
 147        model: &Arc<dyn LanguageModel>,
 148        provider: &Arc<dyn LanguageModelProvider>,
 149    ) -> acp_thread::AgentModelInfo {
 150        acp_thread::AgentModelInfo {
 151            id: Self::model_id(model),
 152            name: model.name().0,
 153            icon: Some(provider.icon()),
 154        }
 155    }
 156
 157    fn model_id(model: &Arc<dyn LanguageModel>) -> acp_thread::AgentModelId {
 158        acp_thread::AgentModelId(format!("{}/{}", model.provider_id().0, model.id().0).into())
 159    }
 160}
 161
 162pub struct NativeAgent {
 163    /// Session ID -> Session mapping
 164    sessions: HashMap<acp::SessionId, Session>,
 165    /// Shared project context for all threads
 166    project_context: Rc<RefCell<ProjectContext>>,
 167    project_context_needs_refresh: watch::Sender<()>,
 168    _maintain_project_context: Task<Result<()>>,
 169    context_server_registry: Entity<ContextServerRegistry>,
 170    /// Shared templates for all threads
 171    templates: Arc<Templates>,
 172    /// Cached model information
 173    models: LanguageModels,
 174    project: Entity<Project>,
 175    prompt_store: Option<Entity<PromptStore>>,
 176    thread_database: Arc<ThreadsDatabase>,
 177    history: watch::Sender<Option<Vec<AcpThreadMetadata>>>,
 178    load_history: Task<()>,
 179    fs: Arc<dyn Fs>,
 180    _subscriptions: Vec<Subscription>,
 181}
 182
 183impl NativeAgent {
 184    pub async fn new(
 185        project: Entity<Project>,
 186        templates: Arc<Templates>,
 187        prompt_store: Option<Entity<PromptStore>>,
 188        fs: Arc<dyn Fs>,
 189        cx: &mut AsyncApp,
 190    ) -> Result<Entity<NativeAgent>> {
 191        log::info!("Creating new NativeAgent");
 192
 193        let project_context = cx
 194            .update(|cx| Self::build_project_context(&project, prompt_store.as_ref(), cx))?
 195            .await;
 196
 197        let thread_database = cx
 198            .update(|cx| ThreadsDatabase::connect(cx))?
 199            .await
 200            .map_err(|e| anyhow!(e))?;
 201
 202        cx.new(|cx| {
 203            let mut subscriptions = vec![
 204                cx.subscribe(&project, Self::handle_project_event),
 205                cx.subscribe(
 206                    &LanguageModelRegistry::global(cx),
 207                    Self::handle_models_updated_event,
 208                ),
 209            ];
 210            if let Some(prompt_store) = prompt_store.as_ref() {
 211                subscriptions.push(cx.subscribe(prompt_store, Self::handle_prompts_updated_event))
 212            }
 213
 214            let (project_context_needs_refresh_tx, project_context_needs_refresh_rx) =
 215                watch::channel(());
 216            let mut this = Self {
 217                sessions: HashMap::new(),
 218                project_context: Rc::new(RefCell::new(project_context)),
 219                project_context_needs_refresh: project_context_needs_refresh_tx,
 220                _maintain_project_context: cx.spawn(async move |this, cx| {
 221                    Self::maintain_project_context(this, project_context_needs_refresh_rx, cx).await
 222                }),
 223                context_server_registry: cx.new(|cx| {
 224                    ContextServerRegistry::new(project.read(cx).context_server_store(), cx)
 225                }),
 226                thread_database,
 227                templates,
 228                models: LanguageModels::new(cx),
 229                project,
 230                prompt_store,
 231                fs,
 232                history: watch::channel(None).0,
 233                load_history: Task::ready(()),
 234                _subscriptions: subscriptions,
 235            };
 236            this.reload_history(cx);
 237            this
 238        })
 239    }
 240
 241    pub fn insert_session(
 242        &mut self,
 243        thread: Entity<Thread>,
 244        acp_thread: Entity<AcpThread>,
 245        cx: &mut Context<Self>,
 246    ) {
 247        let id = thread.read(cx).id().clone();
 248        self.sessions.insert(
 249            id,
 250            Session {
 251                thread: thread.clone(),
 252                acp_thread: acp_thread.downgrade(),
 253                save_task: Task::ready(Ok(())),
 254                _subscriptions: vec![
 255                    cx.observe_release(&acp_thread, |this, acp_thread, _cx| {
 256                        this.sessions.remove(acp_thread.session_id());
 257                    }),
 258                    cx.observe(&thread, |this, thread, cx| {
 259                        thread.update(cx, |thread, cx| {
 260                            thread.generate_title_if_needed(cx);
 261                        });
 262                        this.save_thread(thread.clone(), cx)
 263                    }),
 264                ],
 265            },
 266        );
 267    }
 268
 269    fn save_thread(&mut self, thread_handle: Entity<Thread>, cx: &mut Context<Self>) {
 270        let thread = thread_handle.read(cx);
 271        let id = thread.id().clone();
 272        let Some(session) = self.sessions.get_mut(&id) else {
 273            return;
 274        };
 275
 276        let thread = thread_handle.downgrade();
 277        let thread_database = self.thread_database.clone();
 278        session.save_task = cx.spawn(async move |this, cx| {
 279            cx.background_executor().timer(SAVE_THREAD_DEBOUNCE).await;
 280            let db_thread = thread.update(cx, |thread, cx| thread.to_db(cx))?.await;
 281            thread_database.save_thread(id, db_thread).await?;
 282            this.update(cx, |this, cx| this.reload_history(cx))?;
 283            Ok(())
 284        });
 285    }
 286
 287    fn reload_history(&mut self, cx: &mut Context<Self>) {
 288        let thread_database = self.thread_database.clone();
 289        self.load_history = cx.spawn(async move |this, cx| {
 290            let results = cx
 291                .background_spawn(async move {
 292                    let results = thread_database.list_threads().await?;
 293                    anyhow::Ok(
 294                        results
 295                            .into_iter()
 296                            .map(|thread| AcpThreadMetadata {
 297                                agent: NATIVE_AGENT_SERVER_NAME.clone(),
 298                                id: thread.id.into(),
 299                                title: thread.title,
 300                                updated_at: thread.updated_at,
 301                            })
 302                            .collect(),
 303                    )
 304                })
 305                .await;
 306            if let Some(results) = results.log_err() {
 307                this.update(cx, |this, _| this.history.send(Some(results)))
 308                    .ok();
 309            }
 310        });
 311    }
 312
 313    pub fn models(&self) -> &LanguageModels {
 314        &self.models
 315    }
 316
 317    async fn maintain_project_context(
 318        this: WeakEntity<Self>,
 319        mut needs_refresh: watch::Receiver<()>,
 320        cx: &mut AsyncApp,
 321    ) -> Result<()> {
 322        while needs_refresh.changed().await.is_ok() {
 323            let project_context = this
 324                .update(cx, |this, cx| {
 325                    Self::build_project_context(&this.project, this.prompt_store.as_ref(), cx)
 326                })?
 327                .await;
 328            this.update(cx, |this, _| this.project_context.replace(project_context))?;
 329        }
 330
 331        Ok(())
 332    }
 333
 334    fn build_project_context(
 335        project: &Entity<Project>,
 336        prompt_store: Option<&Entity<PromptStore>>,
 337        cx: &mut App,
 338    ) -> Task<ProjectContext> {
 339        let worktrees = project.read(cx).visible_worktrees(cx).collect::<Vec<_>>();
 340        let worktree_tasks = worktrees
 341            .into_iter()
 342            .map(|worktree| {
 343                Self::load_worktree_info_for_system_prompt(worktree, project.clone(), cx)
 344            })
 345            .collect::<Vec<_>>();
 346        let default_user_rules_task = if let Some(prompt_store) = prompt_store.as_ref() {
 347            prompt_store.read_with(cx, |prompt_store, cx| {
 348                let prompts = prompt_store.default_prompt_metadata();
 349                let load_tasks = prompts.into_iter().map(|prompt_metadata| {
 350                    let contents = prompt_store.load(prompt_metadata.id, cx);
 351                    async move { (contents.await, prompt_metadata) }
 352                });
 353                cx.background_spawn(future::join_all(load_tasks))
 354            })
 355        } else {
 356            Task::ready(vec![])
 357        };
 358
 359        cx.spawn(async move |_cx| {
 360            let (worktrees, default_user_rules) =
 361                future::join(future::join_all(worktree_tasks), default_user_rules_task).await;
 362
 363            let worktrees = worktrees
 364                .into_iter()
 365                .map(|(worktree, _rules_error)| {
 366                    // TODO: show error message
 367                    // if let Some(rules_error) = rules_error {
 368                    //     this.update(cx, |_, cx| cx.emit(rules_error)).ok();
 369                    // }
 370                    worktree
 371                })
 372                .collect::<Vec<_>>();
 373
 374            let default_user_rules = default_user_rules
 375                .into_iter()
 376                .flat_map(|(contents, prompt_metadata)| match contents {
 377                    Ok(contents) => Some(UserRulesContext {
 378                        uuid: match prompt_metadata.id {
 379                            PromptId::User { uuid } => uuid,
 380                            PromptId::EditWorkflow => return None,
 381                        },
 382                        title: prompt_metadata.title.map(|title| title.to_string()),
 383                        contents,
 384                    }),
 385                    Err(_err) => {
 386                        // TODO: show error message
 387                        // this.update(cx, |_, cx| {
 388                        //     cx.emit(RulesLoadingError {
 389                        //         message: format!("{err:?}").into(),
 390                        //     });
 391                        // })
 392                        // .ok();
 393                        None
 394                    }
 395                })
 396                .collect::<Vec<_>>();
 397
 398            ProjectContext::new(worktrees, default_user_rules)
 399        })
 400    }
 401
 402    fn load_worktree_info_for_system_prompt(
 403        worktree: Entity<Worktree>,
 404        project: Entity<Project>,
 405        cx: &mut App,
 406    ) -> Task<(WorktreeContext, Option<RulesLoadingError>)> {
 407        let tree = worktree.read(cx);
 408        let root_name = tree.root_name().into();
 409        let abs_path = tree.abs_path();
 410
 411        let mut context = WorktreeContext {
 412            root_name,
 413            abs_path,
 414            rules_file: None,
 415        };
 416
 417        let rules_task = Self::load_worktree_rules_file(worktree, project, cx);
 418        let Some(rules_task) = rules_task else {
 419            return Task::ready((context, None));
 420        };
 421
 422        cx.spawn(async move |_| {
 423            let (rules_file, rules_file_error) = match rules_task.await {
 424                Ok(rules_file) => (Some(rules_file), None),
 425                Err(err) => (
 426                    None,
 427                    Some(RulesLoadingError {
 428                        message: format!("{err}").into(),
 429                    }),
 430                ),
 431            };
 432            context.rules_file = rules_file;
 433            (context, rules_file_error)
 434        })
 435    }
 436
 437    fn load_worktree_rules_file(
 438        worktree: Entity<Worktree>,
 439        project: Entity<Project>,
 440        cx: &mut App,
 441    ) -> Option<Task<Result<RulesFileContext>>> {
 442        let worktree = worktree.read(cx);
 443        let worktree_id = worktree.id();
 444        let selected_rules_file = RULES_FILE_NAMES
 445            .into_iter()
 446            .filter_map(|name| {
 447                worktree
 448                    .entry_for_path(name)
 449                    .filter(|entry| entry.is_file())
 450                    .map(|entry| entry.path.clone())
 451            })
 452            .next();
 453
 454        // Note that Cline supports `.clinerules` being a directory, but that is not currently
 455        // supported. This doesn't seem to occur often in GitHub repositories.
 456        selected_rules_file.map(|path_in_worktree| {
 457            let project_path = ProjectPath {
 458                worktree_id,
 459                path: path_in_worktree.clone(),
 460            };
 461            let buffer_task =
 462                project.update(cx, |project, cx| project.open_buffer(project_path, cx));
 463            let rope_task = cx.spawn(async move |cx| {
 464                buffer_task.await?.read_with(cx, |buffer, cx| {
 465                    let project_entry_id = buffer.entry_id(cx).context("buffer has no file")?;
 466                    anyhow::Ok((project_entry_id, buffer.as_rope().clone()))
 467                })?
 468            });
 469            // Build a string from the rope on a background thread.
 470            cx.background_spawn(async move {
 471                let (project_entry_id, rope) = rope_task.await?;
 472                anyhow::Ok(RulesFileContext {
 473                    path_in_worktree,
 474                    text: rope.to_string().trim().to_string(),
 475                    project_entry_id: project_entry_id.to_usize(),
 476                })
 477            })
 478        })
 479    }
 480
 481    fn handle_project_event(
 482        &mut self,
 483        _project: Entity<Project>,
 484        event: &project::Event,
 485        _cx: &mut Context<Self>,
 486    ) {
 487        match event {
 488            project::Event::WorktreeAdded(_) | project::Event::WorktreeRemoved(_) => {
 489                self.project_context_needs_refresh.send(()).ok();
 490            }
 491            project::Event::WorktreeUpdatedEntries(_, items) => {
 492                if items.iter().any(|(path, _, _)| {
 493                    RULES_FILE_NAMES
 494                        .iter()
 495                        .any(|name| path.as_ref() == Path::new(name))
 496                }) {
 497                    self.project_context_needs_refresh.send(()).ok();
 498                }
 499            }
 500            _ => {}
 501        }
 502    }
 503
 504    fn handle_prompts_updated_event(
 505        &mut self,
 506        _prompt_store: Entity<PromptStore>,
 507        _event: &prompt_store::PromptsUpdatedEvent,
 508        _cx: &mut Context<Self>,
 509    ) {
 510        self.project_context_needs_refresh.send(()).ok();
 511    }
 512
 513    fn handle_models_updated_event(
 514        &mut self,
 515        registry: Entity<LanguageModelRegistry>,
 516        _event: &language_model::Event,
 517        cx: &mut Context<Self>,
 518    ) {
 519        self.models.refresh_list(cx);
 520
 521        let default_model = LanguageModelRegistry::read_global(cx)
 522            .default_model()
 523            .map(|m| m.model.clone());
 524
 525        for session in self.sessions.values_mut() {
 526            session.thread.update(cx, |thread, cx| {
 527                if thread.model().is_none()
 528                    && let Some(model) = default_model.clone()
 529                {
 530                    thread.set_model(model);
 531                    cx.notify();
 532                }
 533                let summarization_model = registry
 534                    .read(cx)
 535                    .thread_summary_model()
 536                    .map(|model| model.model.clone());
 537                thread.set_summarization_model(summarization_model, cx);
 538            });
 539        }
 540    }
 541}
 542
 543/// Wrapper struct that implements the AgentConnection trait
 544#[derive(Clone)]
 545pub struct NativeAgentConnection(pub Entity<NativeAgent>);
 546
 547impl NativeAgentConnection {
 548    pub fn thread(&self, session_id: &acp::SessionId, cx: &App) -> Option<Entity<Thread>> {
 549        self.0
 550            .read(cx)
 551            .sessions
 552            .get(session_id)
 553            .map(|session| session.thread.clone())
 554    }
 555
 556    fn run_turn(
 557        &self,
 558        session_id: acp::SessionId,
 559        cx: &mut App,
 560        f: impl 'static
 561        + FnOnce(Entity<Thread>, &mut App) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>,
 562    ) -> Task<Result<acp::PromptResponse>> {
 563        let Some((thread, acp_thread)) = self.0.update(cx, |agent, _cx| {
 564            agent
 565                .sessions
 566                .get_mut(&session_id)
 567                .map(|s| (s.thread.clone(), s.acp_thread.clone()))
 568        }) else {
 569            return Task::ready(Err(anyhow!("Session not found")));
 570        };
 571        log::debug!("Found session for: {}", session_id);
 572
 573        let response_stream = match f(thread, cx) {
 574            Ok(stream) => stream,
 575            Err(err) => return Task::ready(Err(err)),
 576        };
 577        Self::handle_thread_events(response_stream, acp_thread, cx)
 578    }
 579
 580    fn handle_thread_events(
 581        mut response_stream: mpsc::UnboundedReceiver<Result<ThreadEvent>>,
 582        acp_thread: WeakEntity<AcpThread>,
 583        cx: &mut App,
 584    ) -> Task<Result<acp::PromptResponse>> {
 585        cx.spawn(async move |cx| {
 586            // Handle response stream and forward to session.acp_thread
 587            while let Some(result) = response_stream.next().await {
 588                match result {
 589                    Ok(event) => {
 590                        log::trace!("Received completion event: {:?}", event);
 591
 592                        match event {
 593                            ThreadEvent::UserMessage(message) => {
 594                                acp_thread.update(cx, |thread, cx| {
 595                                    for content in message.content {
 596                                        thread.push_user_content_block(
 597                                            Some(message.id.clone()),
 598                                            content.into(),
 599                                            cx,
 600                                        );
 601                                    }
 602                                })?;
 603                            }
 604                            ThreadEvent::AgentText(text) => {
 605                                acp_thread.update(cx, |thread, cx| {
 606                                    thread.push_assistant_content_block(
 607                                        acp::ContentBlock::Text(acp::TextContent {
 608                                            text,
 609                                            annotations: None,
 610                                        }),
 611                                        false,
 612                                        cx,
 613                                    )
 614                                })?;
 615                            }
 616                            ThreadEvent::AgentThinking(text) => {
 617                                acp_thread.update(cx, |thread, cx| {
 618                                    thread.push_assistant_content_block(
 619                                        acp::ContentBlock::Text(acp::TextContent {
 620                                            text,
 621                                            annotations: None,
 622                                        }),
 623                                        true,
 624                                        cx,
 625                                    )
 626                                })?;
 627                            }
 628                            ThreadEvent::ToolCallAuthorization(ToolCallAuthorization {
 629                                tool_call,
 630                                options,
 631                                response,
 632                            }) => {
 633                                let recv = acp_thread.update(cx, |thread, cx| {
 634                                    thread.request_tool_call_authorization(tool_call, options, cx)
 635                                })?;
 636                                cx.background_spawn(async move {
 637                                    if let Some(recv) = recv.log_err()
 638                                        && let Some(option) = recv
 639                                            .await
 640                                            .context("authorization sender was dropped")
 641                                            .log_err()
 642                                    {
 643                                        response
 644                                            .send(option)
 645                                            .map(|_| anyhow!("authorization receiver was dropped"))
 646                                            .log_err();
 647                                    }
 648                                })
 649                                .detach();
 650                            }
 651                            ThreadEvent::ToolCall(tool_call) => {
 652                                acp_thread.update(cx, |thread, cx| {
 653                                    thread.upsert_tool_call(tool_call, cx)
 654                                })??;
 655                            }
 656                            ThreadEvent::ToolCallUpdate(update) => {
 657                                acp_thread.update(cx, |thread, cx| {
 658                                    thread.update_tool_call(update, cx)
 659                                })??;
 660                            }
 661                            ThreadEvent::TitleUpdate(title) => {
 662                                acp_thread
 663                                    .update(cx, |thread, cx| thread.update_title(title, cx))??;
 664                            }
 665                            ThreadEvent::Stop(stop_reason) => {
 666                                log::debug!("Assistant message complete: {:?}", stop_reason);
 667                                return Ok(acp::PromptResponse { stop_reason });
 668                            }
 669                        }
 670                    }
 671                    Err(e) => {
 672                        log::error!("Error in model response stream: {:?}", e);
 673                        return Err(e);
 674                    }
 675                }
 676            }
 677
 678            log::info!("Response stream completed");
 679            anyhow::Ok(acp::PromptResponse {
 680                stop_reason: acp::StopReason::EndTurn,
 681            })
 682        })
 683    }
 684
 685    fn register_tools(
 686        thread: &mut Thread,
 687        project: Entity<Project>,
 688        action_log: Entity<action_log::ActionLog>,
 689        cx: &mut Context<Thread>,
 690    ) {
 691        let language_registry = project.read(cx).languages().clone();
 692        thread.add_tool(CopyPathTool::new(project.clone()));
 693        thread.add_tool(CreateDirectoryTool::new(project.clone()));
 694        thread.add_tool(DeletePathTool::new(project.clone(), action_log.clone()));
 695        thread.add_tool(DiagnosticsTool::new(project.clone()));
 696        thread.add_tool(EditFileTool::new(cx.weak_entity(), language_registry));
 697        thread.add_tool(FetchTool::new(project.read(cx).client().http_client()));
 698        thread.add_tool(FindPathTool::new(project.clone()));
 699        thread.add_tool(GrepTool::new(project.clone()));
 700        thread.add_tool(ListDirectoryTool::new(project.clone()));
 701        thread.add_tool(MovePathTool::new(project.clone()));
 702        thread.add_tool(NowTool);
 703        thread.add_tool(OpenTool::new(project.clone()));
 704        thread.add_tool(ReadFileTool::new(project.clone(), action_log));
 705        thread.add_tool(TerminalTool::new(project.clone(), cx));
 706        thread.add_tool(ThinkingTool);
 707        thread.add_tool(WebSearchTool); // TODO: Enable this only if it's a zed model.
 708    }
 709}
 710
 711impl AgentModelSelector for NativeAgentConnection {
 712    fn list_models(&self, cx: &mut App) -> Task<Result<acp_thread::AgentModelList>> {
 713        log::debug!("NativeAgentConnection::list_models called");
 714        let list = self.0.read(cx).models.model_list.clone();
 715        Task::ready(if list.is_empty() {
 716            Err(anyhow::anyhow!("No models available"))
 717        } else {
 718            Ok(list)
 719        })
 720    }
 721
 722    fn select_model(
 723        &self,
 724        session_id: acp::SessionId,
 725        model_id: acp_thread::AgentModelId,
 726        cx: &mut App,
 727    ) -> Task<Result<()>> {
 728        log::info!("Setting model for session {}: {}", session_id, model_id);
 729        let Some(thread) = self
 730            .0
 731            .read(cx)
 732            .sessions
 733            .get(&session_id)
 734            .map(|session| session.thread.clone())
 735        else {
 736            return Task::ready(Err(anyhow!("Session not found")));
 737        };
 738
 739        let Some(model) = self.0.read(cx).models.model_from_id(&model_id) else {
 740            return Task::ready(Err(anyhow!("Invalid model ID {}", model_id)));
 741        };
 742
 743        thread.update(cx, |thread, cx| {
 744            thread.set_model(model.clone(), cx);
 745        });
 746
 747        update_settings_file::<AgentSettings>(
 748            self.0.read(cx).fs.clone(),
 749            cx,
 750            move |settings, _cx| {
 751                settings.set_model(model);
 752            },
 753        );
 754
 755        Task::ready(Ok(()))
 756    }
 757
 758    fn selected_model(
 759        &self,
 760        session_id: &acp::SessionId,
 761        cx: &mut App,
 762    ) -> Task<Result<acp_thread::AgentModelInfo>> {
 763        let session_id = session_id.clone();
 764
 765        let Some(thread) = self
 766            .0
 767            .read(cx)
 768            .sessions
 769            .get(&session_id)
 770            .map(|session| session.thread.clone())
 771        else {
 772            return Task::ready(Err(anyhow!("Session not found")));
 773        };
 774        let Some(model) = thread.read(cx).model() else {
 775            return Task::ready(Err(anyhow!("Model not found")));
 776        };
 777        let Some(provider) = LanguageModelRegistry::read_global(cx).provider(&model.provider_id())
 778        else {
 779            return Task::ready(Err(anyhow!("Provider not found")));
 780        };
 781        Task::ready(Ok(LanguageModels::map_language_model_to_info(
 782            model, &provider,
 783        )))
 784    }
 785
 786    fn watch(&self, cx: &mut App) -> watch::Receiver<()> {
 787        self.0.read(cx).models.watch()
 788    }
 789}
 790
 791impl acp_thread::AgentConnection for NativeAgentConnection {
 792    fn new_thread(
 793        self: Rc<Self>,
 794        project: Entity<Project>,
 795        cwd: &Path,
 796        cx: &mut App,
 797    ) -> Task<Result<Entity<acp_thread::AcpThread>>> {
 798        let agent = self.0.clone();
 799        log::info!("Creating new thread for project at: {:?}", cwd);
 800
 801        cx.spawn(async move |cx| {
 802            log::debug!("Starting thread creation in async context");
 803
 804            // Generate session ID
 805            let session_id = generate_session_id();
 806            log::info!("Created session with ID: {}", session_id);
 807
 808            // Create AcpThread
 809            let acp_thread = cx.update(|cx| {
 810                cx.new(|cx| {
 811                    acp_thread::AcpThread::new(
 812                        "agent2",
 813                        self.clone(),
 814                        project.clone(),
 815                        session_id.clone(),
 816                        cx,
 817                    )
 818                })
 819            })?;
 820            let action_log = cx.update(|cx| acp_thread.read(cx).action_log().clone())?;
 821
 822            // Create Thread
 823            let thread = agent.update(
 824                cx,
 825                |agent, cx: &mut gpui::Context<NativeAgent>| -> Result<_> {
 826                    // Fetch default model from registry settings
 827                    let registry = LanguageModelRegistry::read_global(cx);
 828
 829                    // Log available models for debugging
 830                    let available_count = registry.available_models(cx).count();
 831                    log::debug!("Total available models: {}", available_count);
 832
 833                    let default_model = registry.default_model().and_then(|default_model| {
 834                        agent
 835                            .models
 836                            .model_from_id(&LanguageModels::model_id(&default_model.model))
 837                    });
 838
 839                    let summarization_model = registry.thread_summary_model().map(|c| c.model);
 840
 841                    let thread = cx.new(|cx| {
 842                        let mut thread = Thread::new(
 843                            session_id.clone(),
 844                            project.clone(),
 845                            agent.project_context.clone(),
 846                            agent.context_server_registry.clone(),
 847                            action_log.clone(),
 848                            agent.templates.clone(),
 849                            default_model,
 850                            summarization_model,
 851                            cx,
 852                        );
 853                        Self::register_tools(&mut thread, project, action_log, cx);
 854                        thread
 855                    });
 856
 857                    Ok(thread)
 858                },
 859            )??;
 860
 861            // Store the session
 862            agent.update(cx, |agent, cx| {
 863                agent.insert_session(thread, acp_thread.clone(), cx)
 864            })?;
 865
 866            Ok(acp_thread)
 867        })
 868    }
 869
 870    fn auth_methods(&self) -> &[acp::AuthMethod] {
 871        &[] // No auth for in-process
 872    }
 873
 874    fn authenticate(&self, _method: acp::AuthMethodId, _cx: &mut App) -> Task<Result<()>> {
 875        Task::ready(Ok(()))
 876    }
 877
 878    fn list_threads(
 879        &self,
 880        cx: &mut App,
 881    ) -> Option<watch::Receiver<Option<Vec<AcpThreadMetadata>>>> {
 882        Some(self.0.read(cx).history.receiver())
 883    }
 884
 885    fn load_thread(
 886        self: Rc<Self>,
 887        project: Entity<Project>,
 888        _cwd: &Path,
 889        session_id: acp::SessionId,
 890        cx: &mut App,
 891    ) -> Task<Result<Entity<acp_thread::AcpThread>>> {
 892        let database = self.0.update(cx, |this, _| this.thread_database.clone());
 893        cx.spawn(async move |cx| {
 894            let db_thread = database
 895                .load_thread(session_id.clone())
 896                .await?
 897                .context("no such thread found")?;
 898
 899            let acp_thread = cx.update(|cx| {
 900                cx.new(|cx| {
 901                    acp_thread::AcpThread::new(
 902                        db_thread.title.clone(),
 903                        self.clone(),
 904                        project.clone(),
 905                        session_id.clone(),
 906                        cx,
 907                    )
 908                })
 909            })?;
 910            let action_log = cx.update(|cx| acp_thread.read(cx).action_log().clone())?;
 911            let agent = self.0.clone();
 912
 913            // Create Thread
 914            let thread = agent.update(cx, |agent, cx| {
 915                let language_model_registry = LanguageModelRegistry::global(cx);
 916                let configured_model = language_model_registry
 917                    .update(cx, |registry, cx| {
 918                        db_thread
 919                            .model
 920                            .as_ref()
 921                            .and_then(|model| {
 922                                let model = SelectedModel {
 923                                    provider: model.provider.clone().into(),
 924                                    model: model.model.clone().into(),
 925                                };
 926                                registry.select_model(&model, cx)
 927                            })
 928                            .or_else(|| registry.default_model())
 929                    })
 930                    .context("no default model configured")?;
 931
 932                let model = agent
 933                    .models
 934                    .model_from_id(&LanguageModels::model_id(&configured_model.model))
 935                    .context("no model by id")?;
 936
 937                let summarization_model = language_model_registry
 938                    .read(cx)
 939                    .thread_summary_model()
 940                    .map(|c| c.model);
 941
 942                let thread = cx.new(|cx| {
 943                    let mut thread = Thread::from_db(
 944                        session_id,
 945                        db_thread,
 946                        project.clone(),
 947                        agent.project_context.clone(),
 948                        agent.context_server_registry.clone(),
 949                        action_log.clone(),
 950                        agent.templates.clone(),
 951                        model,
 952                        summarization_model,
 953                        cx,
 954                    );
 955                    Self::register_tools(&mut thread, project, action_log, cx);
 956                    thread
 957                });
 958
 959                anyhow::Ok(thread)
 960            })??;
 961
 962            // Store the session
 963            agent.update(cx, |agent, cx| {
 964                agent.insert_session(thread.clone(), acp_thread.clone(), cx)
 965            })?;
 966
 967            let events = thread.update(cx, |thread, cx| thread.replay(cx))?;
 968            cx.update(|cx| Self::handle_thread_events(events, acp_thread.downgrade(), cx))?
 969                .await?;
 970
 971            Ok(acp_thread)
 972        })
 973    }
 974
 975    fn model_selector(&self) -> Option<Rc<dyn AgentModelSelector>> {
 976        Some(Rc::new(self.clone()) as Rc<dyn AgentModelSelector>)
 977    }
 978
 979    fn prompt(
 980        &self,
 981        id: Option<acp_thread::UserMessageId>,
 982        params: acp::PromptRequest,
 983        cx: &mut App,
 984    ) -> Task<Result<acp::PromptResponse>> {
 985        let id = id.expect("UserMessageId is required");
 986        let session_id = params.session_id.clone();
 987        log::info!("Received prompt request for session: {}", session_id);
 988        log::debug!("Prompt blocks count: {}", params.prompt.len());
 989
 990        self.run_turn(session_id, cx, |thread, cx| {
 991            let content: Vec<UserMessageContent> = params
 992                .prompt
 993                .into_iter()
 994                .map(Into::into)
 995                .collect::<Vec<_>>();
 996            log::info!("Converted prompt to message: {} chars", content.len());
 997            log::debug!("Message id: {:?}", id);
 998            log::debug!("Message content: {:?}", content);
 999
1000            thread.update(cx, |thread, cx| thread.send(id, content, cx))
1001        })
1002    }
1003
1004    fn resume(
1005        &self,
1006        session_id: &acp::SessionId,
1007        _cx: &mut App,
1008    ) -> Option<Rc<dyn acp_thread::AgentSessionResume>> {
1009        Some(Rc::new(NativeAgentSessionResume {
1010            connection: self.clone(),
1011            session_id: session_id.clone(),
1012        }) as _)
1013    }
1014
1015    fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
1016        log::info!("Cancelling on session: {}", session_id);
1017        self.0.update(cx, |agent, cx| {
1018            if let Some(agent) = agent.sessions.get(session_id) {
1019                agent.thread.update(cx, |thread, cx| thread.cancel(cx));
1020            }
1021        });
1022    }
1023
1024    fn session_editor(
1025        &self,
1026        session_id: &agent_client_protocol::SessionId,
1027        cx: &mut App,
1028    ) -> Option<Rc<dyn acp_thread::AgentSessionEditor>> {
1029        self.0.update(cx, |agent, _cx| {
1030            agent
1031                .sessions
1032                .get(session_id)
1033                .map(|session| Rc::new(NativeAgentSessionEditor(session.thread.clone())) as _)
1034        })
1035    }
1036
1037    fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
1038        self
1039    }
1040}
1041
1042struct NativeAgentSessionEditor(Entity<Thread>);
1043
1044impl acp_thread::AgentSessionEditor for NativeAgentSessionEditor {
1045    fn truncate(&self, message_id: acp_thread::UserMessageId, cx: &mut App) -> Task<Result<()>> {
1046        Task::ready(
1047            self.0
1048                .update(cx, |thread, cx| thread.truncate(message_id, cx)),
1049        )
1050    }
1051}
1052
1053struct NativeAgentSessionResume {
1054    connection: NativeAgentConnection,
1055    session_id: acp::SessionId,
1056}
1057
1058impl acp_thread::AgentSessionResume for NativeAgentSessionResume {
1059    fn run(&self, cx: &mut App) -> Task<Result<acp::PromptResponse>> {
1060        self.connection
1061            .run_turn(self.session_id.clone(), cx, |thread, cx| {
1062                thread.update(cx, |thread, cx| thread.resume(cx))
1063            })
1064    }
1065}
1066
1067#[cfg(test)]
1068mod tests {
1069    use crate::HistoryStore;
1070
1071    use super::*;
1072    use acp_thread::{AgentConnection, AgentModelGroupName, AgentModelId, AgentModelInfo};
1073    use fs::FakeFs;
1074    use gpui::TestAppContext;
1075    use language_model::fake_provider::FakeLanguageModel;
1076    use serde_json::json;
1077    use settings::SettingsStore;
1078    use util::path;
1079
1080    #[gpui::test]
1081    async fn test_maintaining_project_context(cx: &mut TestAppContext) {
1082        init_test(cx);
1083        let fs = FakeFs::new(cx.executor());
1084        fs.insert_tree(
1085            "/",
1086            json!({
1087                "a": {}
1088            }),
1089        )
1090        .await;
1091        let project = Project::test(fs.clone(), [], cx).await;
1092        let agent = NativeAgent::new(
1093            project.clone(),
1094            Templates::new(),
1095            None,
1096            fs.clone(),
1097            &mut cx.to_async(),
1098        )
1099        .await
1100        .unwrap();
1101        agent.read_with(cx, |agent, _| {
1102            assert_eq!(agent.project_context.borrow().worktrees, vec![])
1103        });
1104
1105        let worktree = project
1106            .update(cx, |project, cx| project.create_worktree("/a", true, cx))
1107            .await
1108            .unwrap();
1109        cx.run_until_parked();
1110        agent.read_with(cx, |agent, _| {
1111            assert_eq!(
1112                agent.project_context.borrow().worktrees,
1113                vec![WorktreeContext {
1114                    root_name: "a".into(),
1115                    abs_path: Path::new("/a").into(),
1116                    rules_file: None
1117                }]
1118            )
1119        });
1120
1121        // Creating `/a/.rules` updates the project context.
1122        fs.insert_file("/a/.rules", Vec::new()).await;
1123        cx.run_until_parked();
1124        agent.read_with(cx, |agent, cx| {
1125            let rules_entry = worktree.read(cx).entry_for_path(".rules").unwrap();
1126            assert_eq!(
1127                agent.project_context.borrow().worktrees,
1128                vec![WorktreeContext {
1129                    root_name: "a".into(),
1130                    abs_path: Path::new("/a").into(),
1131                    rules_file: Some(RulesFileContext {
1132                        path_in_worktree: Path::new(".rules").into(),
1133                        text: "".into(),
1134                        project_entry_id: rules_entry.id.to_usize()
1135                    })
1136                }]
1137            )
1138        });
1139    }
1140
1141    #[gpui::test]
1142    async fn test_listing_models(cx: &mut TestAppContext) {
1143        init_test(cx);
1144        let fs = FakeFs::new(cx.executor());
1145        fs.insert_tree("/", json!({ "a": {}  })).await;
1146        let project = Project::test(fs.clone(), [], cx).await;
1147        let connection = NativeAgentConnection(
1148            NativeAgent::new(
1149                project.clone(),
1150                Templates::new(),
1151                None,
1152                fs.clone(),
1153                &mut cx.to_async(),
1154            )
1155            .await
1156            .unwrap(),
1157        );
1158
1159        let models = cx.update(|cx| connection.list_models(cx)).await.unwrap();
1160
1161        let acp_thread::AgentModelList::Grouped(models) = models else {
1162            panic!("Unexpected model group");
1163        };
1164        assert_eq!(
1165            models,
1166            IndexMap::from_iter([(
1167                AgentModelGroupName("Fake".into()),
1168                vec![AgentModelInfo {
1169                    id: AgentModelId("fake/fake".into()),
1170                    name: "Fake".into(),
1171                    icon: Some(ui::IconName::ZedAssistant),
1172                }]
1173            )])
1174        );
1175    }
1176
1177    #[gpui::test]
1178    async fn test_model_selection_persists_to_settings(cx: &mut TestAppContext) {
1179        init_test(cx);
1180        let fs = FakeFs::new(cx.executor());
1181        fs.create_dir(paths::settings_file().parent().unwrap())
1182            .await
1183            .unwrap();
1184        fs.insert_file(
1185            paths::settings_file(),
1186            json!({
1187                "agent": {
1188                    "default_model": {
1189                        "provider": "foo",
1190                        "model": "bar"
1191                    }
1192                }
1193            })
1194            .to_string()
1195            .into_bytes(),
1196        )
1197        .await;
1198        let project = Project::test(fs.clone(), [], cx).await;
1199
1200        // Create the agent and connection
1201        let agent = NativeAgent::new(
1202            project.clone(),
1203            Templates::new(),
1204            None,
1205            fs.clone(),
1206            &mut cx.to_async(),
1207        )
1208        .await
1209        .unwrap();
1210        let connection = NativeAgentConnection(agent.clone());
1211
1212        // Create a thread/session
1213        let acp_thread = cx
1214            .update(|cx| {
1215                Rc::new(connection.clone()).new_thread(project.clone(), Path::new("/a"), cx)
1216            })
1217            .await
1218            .unwrap();
1219
1220        let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());
1221
1222        // Select a model
1223        let model_id = AgentModelId("fake/fake".into());
1224        cx.update(|cx| connection.select_model(session_id.clone(), model_id.clone(), cx))
1225            .await
1226            .unwrap();
1227
1228        // Verify the thread has the selected model
1229        agent.read_with(cx, |agent, _| {
1230            let session = agent.sessions.get(&session_id).unwrap();
1231            session.thread.read_with(cx, |thread, _| {
1232                assert_eq!(thread.model().unwrap().id().0, "fake");
1233            });
1234        });
1235
1236        cx.run_until_parked();
1237
1238        // Verify settings file was updated
1239        let settings_content = fs.load(paths::settings_file()).await.unwrap();
1240        let settings_json: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1241
1242        // Check that the agent settings contain the selected model
1243        assert_eq!(
1244            settings_json["agent"]["default_model"]["model"],
1245            json!("fake")
1246        );
1247        assert_eq!(
1248            settings_json["agent"]["default_model"]["provider"],
1249            json!("fake")
1250        );
1251    }
1252
1253    #[gpui::test]
1254    async fn test_history(cx: &mut TestAppContext) {
1255        init_test(cx);
1256        let fs = FakeFs::new(cx.executor());
1257        let project = Project::test(fs.clone(), [], cx).await;
1258
1259        let agent = NativeAgent::new(
1260            project.clone(),
1261            Templates::new(),
1262            None,
1263            fs.clone(),
1264            &mut cx.to_async(),
1265        )
1266        .await
1267        .unwrap();
1268        let connection = NativeAgentConnection(agent.clone());
1269        let history_store = cx.new(|cx| {
1270            let mut store = HistoryStore::new(cx);
1271            store.register_agent(NATIVE_AGENT_SERVER_NAME.clone(), &connection, cx);
1272            store
1273        });
1274
1275        let acp_thread = cx
1276            .update(|cx| {
1277                Rc::new(connection.clone()).new_thread(project.clone(), Path::new(path!("")), cx)
1278            })
1279            .await
1280            .unwrap();
1281        let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());
1282        let selector = connection.model_selector().unwrap();
1283
1284        let summarization_model: Arc<dyn LanguageModel> =
1285            Arc::new(FakeLanguageModel::default()) as _;
1286
1287        agent.update(cx, |agent, cx| {
1288            let thread = agent.sessions.get(&session_id).unwrap().thread.clone();
1289            thread.update(cx, |thread, cx| {
1290                thread.set_summarization_model(Some(summarization_model.clone()), cx);
1291            })
1292        });
1293
1294        let model = cx
1295            .update(|cx| selector.selected_model(&session_id, cx))
1296            .await
1297            .expect("selected_model should succeed");
1298        let model = cx
1299            .update(|cx| agent.read(cx).models().model_from_id(&model.id))
1300            .unwrap();
1301        let model = model.as_fake();
1302
1303        let send = acp_thread.update(cx, |thread, cx| thread.send_raw("Hi", cx));
1304        let send = cx.foreground_executor().spawn(send);
1305        cx.run_until_parked();
1306        model.send_last_completion_stream_text_chunk("Hey");
1307        model.end_last_completion_stream();
1308        send.await.unwrap();
1309
1310        summarization_model
1311            .as_fake()
1312            .send_last_completion_stream_text_chunk("Saying Hello");
1313        summarization_model.as_fake().end_last_completion_stream();
1314        cx.executor().advance_clock(SAVE_THREAD_DEBOUNCE);
1315
1316        let history = history_store.update(cx, |store, cx| store.entries(cx));
1317        assert_eq!(history.len(), 1);
1318        assert_eq!(history[0].title(), "Saying Hello");
1319    }
1320
1321    fn init_test(cx: &mut TestAppContext) {
1322        env_logger::try_init().ok();
1323        cx.update(|cx| {
1324            let settings_store = SettingsStore::test(cx);
1325            cx.set_global(settings_store);
1326            Project::init_settings(cx);
1327            agent_settings::init(cx);
1328            language::init(cx);
1329            LanguageModelRegistry::test(cx);
1330        });
1331    }
1332}