thread.rs

   1use crate::{
   2    ContextServerRegistry, DbLanguageModel, DbThread, SystemPromptTemplate, Template, Templates,
   3};
   4use acp_thread::{MentionUri, UserMessageId};
   5use action_log::ActionLog;
   6use agent::thread::{DetailedSummaryState, GitState, ProjectSnapshot, WorktreeSnapshot};
   7use agent_client_protocol as acp;
   8use agent_settings::{AgentProfileId, AgentSettings, CompletionMode, SUMMARIZE_THREAD_PROMPT};
   9use anyhow::{Context as _, Result, anyhow};
  10use assistant_tool::adapt_schema_to_format;
  11use chrono::{DateTime, Utc};
  12use cloud_llm_client::{CompletionIntent, CompletionRequestStatus};
  13use collections::IndexMap;
  14use fs::Fs;
  15use futures::{
  16    FutureExt,
  17    channel::{mpsc, oneshot},
  18    future::Shared,
  19    stream::FuturesUnordered,
  20};
  21use git::repository::DiffType;
  22use gpui::{App, AppContext, Context, Entity, SharedString, Task};
  23use language_model::{
  24    LanguageModel, LanguageModelCompletionEvent, LanguageModelImage, LanguageModelProviderId,
  25    LanguageModelRequest, LanguageModelRequestMessage, LanguageModelRequestTool,
  26    LanguageModelToolResult, LanguageModelToolResultContent, LanguageModelToolSchemaFormat,
  27    LanguageModelToolUse, LanguageModelToolUseId, MessageContent, Role, StopReason, TokenUsage,
  28};
  29use project::{
  30    Project,
  31    git_store::{GitStore, RepositoryState},
  32};
  33use prompt_store::ProjectContext;
  34use schemars::{JsonSchema, Schema};
  35use serde::{Deserialize, Serialize};
  36use settings::{Settings, update_settings_file};
  37use smol::stream::StreamExt;
  38use std::{cell::RefCell, collections::BTreeMap, path::Path, rc::Rc, sync::Arc};
  39use std::{fmt::Write, ops::Range};
  40use util::{ResultExt, markdown::MarkdownCodeBlock};
  41use uuid::Uuid;
  42
  43const TOOL_CANCELED_MESSAGE: &str = "Tool canceled by user";
  44
  45/// The ID of the user prompt that initiated a request.
  46///
  47/// This equates to the user physically submitting a message to the model (e.g., by pressing the Enter key).
  48#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
  49pub struct PromptId(Arc<str>);
  50
  51impl PromptId {
  52    pub fn new() -> Self {
  53        Self(Uuid::new_v4().to_string().into())
  54    }
  55}
  56
  57impl std::fmt::Display for PromptId {
  58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  59        write!(f, "{}", self.0)
  60    }
  61}
  62
  63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  64pub enum Message {
  65    User(UserMessage),
  66    Agent(AgentMessage),
  67    Resume,
  68}
  69
  70impl Message {
  71    pub fn as_agent_message(&self) -> Option<&AgentMessage> {
  72        match self {
  73            Message::Agent(agent_message) => Some(agent_message),
  74            _ => None,
  75        }
  76    }
  77
  78    pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
  79        match self {
  80            Message::User(message) => vec![message.to_request()],
  81            Message::Agent(message) => message.to_request(),
  82            Message::Resume => vec![LanguageModelRequestMessage {
  83                role: Role::User,
  84                content: vec!["Continue where you left off".into()],
  85                cache: false,
  86            }],
  87        }
  88    }
  89
  90    pub fn to_markdown(&self) -> String {
  91        match self {
  92            Message::User(message) => message.to_markdown(),
  93            Message::Agent(message) => message.to_markdown(),
  94            Message::Resume => "[resumed after tool use limit was reached]".into(),
  95        }
  96    }
  97
  98    pub fn role(&self) -> Role {
  99        match self {
 100            Message::User(_) | Message::Resume => Role::User,
 101            Message::Agent(_) => Role::Assistant,
 102        }
 103    }
 104}
 105
 106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 107pub struct UserMessage {
 108    pub id: UserMessageId,
 109    pub content: Vec<UserMessageContent>,
 110}
 111
 112#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 113pub enum UserMessageContent {
 114    Text(String),
 115    Mention { uri: MentionUri, content: String },
 116    Image(LanguageModelImage),
 117}
 118
 119impl UserMessage {
 120    pub fn to_markdown(&self) -> String {
 121        let mut markdown = String::from("## User\n\n");
 122
 123        for content in &self.content {
 124            match content {
 125                UserMessageContent::Text(text) => {
 126                    markdown.push_str(text);
 127                    markdown.push('\n');
 128                }
 129                UserMessageContent::Image(_) => {
 130                    markdown.push_str("<image />\n");
 131                }
 132                UserMessageContent::Mention { uri, content } => {
 133                    if !content.is_empty() {
 134                        let _ = write!(&mut markdown, "{}\n\n{}\n", uri.as_link(), content);
 135                    } else {
 136                        let _ = write!(&mut markdown, "{}\n", uri.as_link());
 137                    }
 138                }
 139            }
 140        }
 141
 142        markdown
 143    }
 144
 145    fn to_request(&self) -> LanguageModelRequestMessage {
 146        let mut message = LanguageModelRequestMessage {
 147            role: Role::User,
 148            content: Vec::with_capacity(self.content.len()),
 149            cache: false,
 150        };
 151
 152        const OPEN_CONTEXT: &str = "<context>\n\
 153            The following items were attached by the user. \
 154            They are up-to-date and don't need to be re-read.\n\n";
 155
 156        const OPEN_FILES_TAG: &str = "<files>";
 157        const OPEN_SYMBOLS_TAG: &str = "<symbols>";
 158        const OPEN_THREADS_TAG: &str = "<threads>";
 159        const OPEN_FETCH_TAG: &str = "<fetched_urls>";
 160        const OPEN_RULES_TAG: &str =
 161            "<rules>\nThe user has specified the following rules that should be applied:\n";
 162
 163        let mut file_context = OPEN_FILES_TAG.to_string();
 164        let mut symbol_context = OPEN_SYMBOLS_TAG.to_string();
 165        let mut thread_context = OPEN_THREADS_TAG.to_string();
 166        let mut fetch_context = OPEN_FETCH_TAG.to_string();
 167        let mut rules_context = OPEN_RULES_TAG.to_string();
 168
 169        for chunk in &self.content {
 170            let chunk = match chunk {
 171                UserMessageContent::Text(text) => {
 172                    language_model::MessageContent::Text(text.clone())
 173                }
 174                UserMessageContent::Image(value) => {
 175                    language_model::MessageContent::Image(value.clone())
 176                }
 177                UserMessageContent::Mention { uri, content } => {
 178                    match uri {
 179                        MentionUri::File { abs_path, .. } => {
 180                            write!(
 181                                &mut symbol_context,
 182                                "\n{}",
 183                                MarkdownCodeBlock {
 184                                    tag: &codeblock_tag(&abs_path, None),
 185                                    text: &content.to_string(),
 186                                }
 187                            )
 188                            .ok();
 189                        }
 190                        MentionUri::Symbol {
 191                            path, line_range, ..
 192                        }
 193                        | MentionUri::Selection {
 194                            path, line_range, ..
 195                        } => {
 196                            write!(
 197                                &mut rules_context,
 198                                "\n{}",
 199                                MarkdownCodeBlock {
 200                                    tag: &codeblock_tag(&path, Some(line_range)),
 201                                    text: &content
 202                                }
 203                            )
 204                            .ok();
 205                        }
 206                        MentionUri::Thread { .. } => {
 207                            write!(&mut thread_context, "\n{}\n", content).ok();
 208                        }
 209                        MentionUri::TextThread { .. } => {
 210                            write!(&mut thread_context, "\n{}\n", content).ok();
 211                        }
 212                        MentionUri::Rule { .. } => {
 213                            write!(
 214                                &mut rules_context,
 215                                "\n{}",
 216                                MarkdownCodeBlock {
 217                                    tag: "",
 218                                    text: &content
 219                                }
 220                            )
 221                            .ok();
 222                        }
 223                        MentionUri::Fetch { url } => {
 224                            write!(&mut fetch_context, "\nFetch: {}\n\n{}", url, content).ok();
 225                        }
 226                    }
 227
 228                    language_model::MessageContent::Text(uri.as_link().to_string())
 229                }
 230            };
 231
 232            message.content.push(chunk);
 233        }
 234
 235        let len_before_context = message.content.len();
 236
 237        if file_context.len() > OPEN_FILES_TAG.len() {
 238            file_context.push_str("</files>\n");
 239            message
 240                .content
 241                .push(language_model::MessageContent::Text(file_context));
 242        }
 243
 244        if symbol_context.len() > OPEN_SYMBOLS_TAG.len() {
 245            symbol_context.push_str("</symbols>\n");
 246            message
 247                .content
 248                .push(language_model::MessageContent::Text(symbol_context));
 249        }
 250
 251        if thread_context.len() > OPEN_THREADS_TAG.len() {
 252            thread_context.push_str("</threads>\n");
 253            message
 254                .content
 255                .push(language_model::MessageContent::Text(thread_context));
 256        }
 257
 258        if fetch_context.len() > OPEN_FETCH_TAG.len() {
 259            fetch_context.push_str("</fetched_urls>\n");
 260            message
 261                .content
 262                .push(language_model::MessageContent::Text(fetch_context));
 263        }
 264
 265        if rules_context.len() > OPEN_RULES_TAG.len() {
 266            rules_context.push_str("</user_rules>\n");
 267            message
 268                .content
 269                .push(language_model::MessageContent::Text(rules_context));
 270        }
 271
 272        if message.content.len() > len_before_context {
 273            message.content.insert(
 274                len_before_context,
 275                language_model::MessageContent::Text(OPEN_CONTEXT.into()),
 276            );
 277            message
 278                .content
 279                .push(language_model::MessageContent::Text("</context>".into()));
 280        }
 281
 282        message
 283    }
 284}
 285
 286fn codeblock_tag(full_path: &Path, line_range: Option<&Range<u32>>) -> String {
 287    let mut result = String::new();
 288
 289    if let Some(extension) = full_path.extension().and_then(|ext| ext.to_str()) {
 290        let _ = write!(result, "{} ", extension);
 291    }
 292
 293    let _ = write!(result, "{}", full_path.display());
 294
 295    if let Some(range) = line_range {
 296        if range.start == range.end {
 297            let _ = write!(result, ":{}", range.start + 1);
 298        } else {
 299            let _ = write!(result, ":{}-{}", range.start + 1, range.end + 1);
 300        }
 301    }
 302
 303    result
 304}
 305
 306impl AgentMessage {
 307    pub fn to_markdown(&self) -> String {
 308        let mut markdown = String::from("## Assistant\n\n");
 309
 310        for content in &self.content {
 311            match content {
 312                AgentMessageContent::Text(text) => {
 313                    markdown.push_str(text);
 314                    markdown.push('\n');
 315                }
 316                AgentMessageContent::Thinking { text, .. } => {
 317                    markdown.push_str("<think>");
 318                    markdown.push_str(text);
 319                    markdown.push_str("</think>\n");
 320                }
 321                AgentMessageContent::RedactedThinking(_) => {
 322                    markdown.push_str("<redacted_thinking />\n")
 323                }
 324                AgentMessageContent::ToolUse(tool_use) => {
 325                    markdown.push_str(&format!(
 326                        "**Tool Use**: {} (ID: {})\n",
 327                        tool_use.name, tool_use.id
 328                    ));
 329                    markdown.push_str(&format!(
 330                        "{}\n",
 331                        MarkdownCodeBlock {
 332                            tag: "json",
 333                            text: &format!("{:#}", tool_use.input)
 334                        }
 335                    ));
 336                }
 337            }
 338        }
 339
 340        for tool_result in self.tool_results.values() {
 341            markdown.push_str(&format!(
 342                "**Tool Result**: {} (ID: {})\n\n",
 343                tool_result.tool_name, tool_result.tool_use_id
 344            ));
 345            if tool_result.is_error {
 346                markdown.push_str("**ERROR:**\n");
 347            }
 348
 349            match &tool_result.content {
 350                LanguageModelToolResultContent::Text(text) => {
 351                    writeln!(markdown, "{text}\n").ok();
 352                }
 353                LanguageModelToolResultContent::Image(_) => {
 354                    writeln!(markdown, "<image />\n").ok();
 355                }
 356            }
 357
 358            if let Some(output) = tool_result.output.as_ref() {
 359                writeln!(
 360                    markdown,
 361                    "**Debug Output**:\n\n```json\n{}\n```\n",
 362                    serde_json::to_string_pretty(output).unwrap()
 363                )
 364                .unwrap();
 365            }
 366        }
 367
 368        markdown
 369    }
 370
 371    pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
 372        let mut assistant_message = LanguageModelRequestMessage {
 373            role: Role::Assistant,
 374            content: Vec::with_capacity(self.content.len()),
 375            cache: false,
 376        };
 377        for chunk in &self.content {
 378            let chunk = match chunk {
 379                AgentMessageContent::Text(text) => {
 380                    language_model::MessageContent::Text(text.clone())
 381                }
 382                AgentMessageContent::Thinking { text, signature } => {
 383                    language_model::MessageContent::Thinking {
 384                        text: text.clone(),
 385                        signature: signature.clone(),
 386                    }
 387                }
 388                AgentMessageContent::RedactedThinking(value) => {
 389                    language_model::MessageContent::RedactedThinking(value.clone())
 390                }
 391                AgentMessageContent::ToolUse(value) => {
 392                    language_model::MessageContent::ToolUse(value.clone())
 393                }
 394            };
 395            assistant_message.content.push(chunk);
 396        }
 397
 398        let mut user_message = LanguageModelRequestMessage {
 399            role: Role::User,
 400            content: Vec::new(),
 401            cache: false,
 402        };
 403
 404        for tool_result in self.tool_results.values() {
 405            user_message
 406                .content
 407                .push(language_model::MessageContent::ToolResult(
 408                    tool_result.clone(),
 409                ));
 410        }
 411
 412        let mut messages = Vec::new();
 413        if !assistant_message.content.is_empty() {
 414            messages.push(assistant_message);
 415        }
 416        if !user_message.content.is_empty() {
 417            messages.push(user_message);
 418        }
 419        messages
 420    }
 421}
 422
 423#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 424pub struct AgentMessage {
 425    pub content: Vec<AgentMessageContent>,
 426    pub tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
 427}
 428
 429#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 430pub enum AgentMessageContent {
 431    Text(String),
 432    Thinking {
 433        text: String,
 434        signature: Option<String>,
 435    },
 436    RedactedThinking(String),
 437    ToolUse(LanguageModelToolUse),
 438}
 439
 440#[derive(Debug)]
 441pub enum ThreadEvent {
 442    UserMessage(UserMessage),
 443    AgentText(String),
 444    AgentThinking(String),
 445    ToolCall(acp::ToolCall),
 446    ToolCallUpdate(acp_thread::ToolCallUpdate),
 447    ToolCallAuthorization(ToolCallAuthorization),
 448    TitleUpdate(SharedString),
 449    Stop(acp::StopReason),
 450}
 451
 452#[derive(Debug)]
 453pub struct ToolCallAuthorization {
 454    pub tool_call: acp::ToolCallUpdate,
 455    pub options: Vec<acp::PermissionOption>,
 456    pub response: oneshot::Sender<acp::PermissionOptionId>,
 457}
 458
 459enum ThreadTitle {
 460    None,
 461    Pending(Task<()>),
 462    Done(Result<SharedString>),
 463}
 464
 465impl ThreadTitle {
 466    pub fn unwrap_or_default(&self) -> SharedString {
 467        if let ThreadTitle::Done(Ok(title)) = self {
 468            title.clone()
 469        } else {
 470            "New Thread".into()
 471        }
 472    }
 473}
 474
 475pub struct Thread {
 476    id: acp::SessionId,
 477    prompt_id: PromptId,
 478    updated_at: DateTime<Utc>,
 479    title: ThreadTitle,
 480    summary: DetailedSummaryState,
 481    messages: Vec<Message>,
 482    completion_mode: CompletionMode,
 483    /// Holds the task that handles agent interaction until the end of the turn.
 484    /// Survives across multiple requests as the model performs tool calls and
 485    /// we run tools, report their results.
 486    running_turn: Option<RunningTurn>,
 487    pending_message: Option<AgentMessage>,
 488    tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
 489    tool_use_limit_reached: bool,
 490    request_token_usage: Vec<TokenUsage>,
 491    cumulative_token_usage: TokenUsage,
 492    initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
 493    context_server_registry: Entity<ContextServerRegistry>,
 494    profile_id: AgentProfileId,
 495    project_context: Rc<RefCell<ProjectContext>>,
 496    templates: Arc<Templates>,
 497    model: Arc<dyn LanguageModel>,
 498    summarization_model: Option<Arc<dyn LanguageModel>>,
 499    project: Entity<Project>,
 500    action_log: Entity<ActionLog>,
 501}
 502
 503impl Thread {
 504    pub fn new(
 505        id: acp::SessionId,
 506        project: Entity<Project>,
 507        project_context: Rc<RefCell<ProjectContext>>,
 508        context_server_registry: Entity<ContextServerRegistry>,
 509        action_log: Entity<ActionLog>,
 510        templates: Arc<Templates>,
 511        model: Arc<dyn LanguageModel>,
 512        summarization_model: Option<Arc<dyn LanguageModel>>,
 513        cx: &mut Context<Self>,
 514    ) -> Self {
 515        let profile_id = AgentSettings::get_global(cx).default_profile.clone();
 516        Self {
 517            id,
 518            prompt_id: PromptId::new(),
 519            updated_at: Utc::now(),
 520            title: ThreadTitle::None,
 521            summary: DetailedSummaryState::default(),
 522            messages: Vec::new(),
 523            completion_mode: CompletionMode::Normal,
 524            running_turn: None,
 525            pending_message: None,
 526            tools: BTreeMap::default(),
 527            tool_use_limit_reached: false,
 528            request_token_usage: Vec::new(),
 529            cumulative_token_usage: TokenUsage::default(),
 530            initial_project_snapshot: {
 531                let project_snapshot = Self::project_snapshot(project.clone(), cx);
 532                cx.foreground_executor()
 533                    .spawn(async move { Some(project_snapshot.await) })
 534                    .shared()
 535            },
 536            context_server_registry,
 537            profile_id,
 538            project_context,
 539            templates,
 540            model,
 541            summarization_model,
 542            project,
 543            action_log,
 544        }
 545    }
 546
 547    #[cfg(any(test, feature = "test-support"))]
 548    pub fn test(
 549        model: Arc<dyn LanguageModel>,
 550        project: Entity<Project>,
 551        action_log: Entity<ActionLog>,
 552        cx: &mut Context<Self>,
 553    ) -> Self {
 554        use crate::generate_session_id;
 555
 556        let context_server_registry =
 557            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
 558
 559        Self::new(
 560            generate_session_id(),
 561            project,
 562            Rc::default(),
 563            context_server_registry,
 564            action_log,
 565            Templates::new(),
 566            model,
 567            None,
 568            cx,
 569        )
 570    }
 571
 572    pub fn id(&self) -> &acp::SessionId {
 573        &self.id
 574    }
 575
 576    pub fn from_db(
 577        id: acp::SessionId,
 578        db_thread: DbThread,
 579        project: Entity<Project>,
 580        project_context: Rc<RefCell<ProjectContext>>,
 581        context_server_registry: Entity<ContextServerRegistry>,
 582        action_log: Entity<ActionLog>,
 583        templates: Arc<Templates>,
 584        model: Arc<dyn LanguageModel>,
 585        summarization_model: Option<Arc<dyn LanguageModel>>,
 586        cx: &mut Context<Self>,
 587    ) -> Self {
 588        let profile_id = db_thread
 589            .profile
 590            .unwrap_or_else(|| AgentSettings::get_global(cx).default_profile.clone());
 591        Self {
 592            id,
 593            prompt_id: PromptId::new(),
 594            title: ThreadTitle::Done(Ok(db_thread.title.clone())),
 595            summary: db_thread.summary,
 596            messages: db_thread.messages,
 597            completion_mode: CompletionMode::Normal,
 598            running_turn: None,
 599            pending_message: None,
 600            tools: BTreeMap::default(),
 601            tool_use_limit_reached: false,
 602            request_token_usage: db_thread.request_token_usage.clone(),
 603            cumulative_token_usage: db_thread.cumulative_token_usage.clone(),
 604            initial_project_snapshot: Task::ready(db_thread.initial_project_snapshot).shared(),
 605            context_server_registry,
 606            profile_id,
 607            project_context,
 608            templates,
 609            model,
 610            summarization_model,
 611            project,
 612            action_log,
 613            updated_at: db_thread.updated_at, // todo!(figure out if we can remove the "recently opened" list)
 614        }
 615    }
 616
 617    pub fn to_db(&self, cx: &App) -> Task<DbThread> {
 618        let initial_project_snapshot = self.initial_project_snapshot.clone();
 619        let mut thread = DbThread {
 620            title: self.title.unwrap_or_default(),
 621            messages: self.messages.clone(),
 622            updated_at: self.updated_at.clone(),
 623            summary: self.summary.clone(),
 624            initial_project_snapshot: None,
 625            cumulative_token_usage: self.cumulative_token_usage.clone(),
 626            request_token_usage: self.request_token_usage.clone(),
 627            model: Some(DbLanguageModel {
 628                provider: self.model.provider_id().to_string(),
 629                model: self.model.name().0.to_string(),
 630            }),
 631            completion_mode: Some(self.completion_mode.into()),
 632            profile: Some(self.profile_id.clone()),
 633        };
 634
 635        cx.background_spawn(async move {
 636            let initial_project_snapshot = initial_project_snapshot.await;
 637            thread.initial_project_snapshot = initial_project_snapshot;
 638            thread
 639        })
 640    }
 641
 642    pub fn replay(
 643        &mut self,
 644        cx: &mut Context<Self>,
 645    ) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {
 646        let (tx, rx) = mpsc::unbounded();
 647        let stream = ThreadEventStream(tx);
 648        for message in &self.messages {
 649            match message {
 650                Message::User(user_message) => stream.send_user_message(&user_message),
 651                Message::Agent(assistant_message) => {
 652                    for content in &assistant_message.content {
 653                        match content {
 654                            AgentMessageContent::Text(text) => stream.send_text(text),
 655                            AgentMessageContent::Thinking { text, .. } => {
 656                                stream.send_thinking(text)
 657                            }
 658                            AgentMessageContent::RedactedThinking(_) => {}
 659                            AgentMessageContent::ToolUse(tool_use) => {
 660                                self.replay_tool_call(
 661                                    tool_use,
 662                                    assistant_message.tool_results.get(&tool_use.id),
 663                                    &stream,
 664                                    cx,
 665                                );
 666                            }
 667                        }
 668                    }
 669                }
 670                Message::Resume => {}
 671            }
 672        }
 673        rx
 674    }
 675
 676    fn replay_tool_call(
 677        &self,
 678        tool_use: &LanguageModelToolUse,
 679        tool_result: Option<&LanguageModelToolResult>,
 680        stream: &ThreadEventStream,
 681        cx: &mut Context<Self>,
 682    ) {
 683        let Some(tool) = self.tools.get(tool_use.name.as_ref()) else {
 684            stream
 685                .0
 686                .unbounded_send(Ok(ThreadEvent::ToolCall(acp::ToolCall {
 687                    id: acp::ToolCallId(tool_use.id.to_string().into()),
 688                    title: tool_use.name.to_string(),
 689                    kind: acp::ToolKind::Other,
 690                    status: acp::ToolCallStatus::Failed,
 691                    content: Vec::new(),
 692                    locations: Vec::new(),
 693                    raw_input: Some(tool_use.input.clone()),
 694                    raw_output: None,
 695                })))
 696                .ok();
 697            return;
 698        };
 699
 700        let title = tool.initial_title(tool_use.input.clone());
 701        let kind = tool.kind();
 702        stream.send_tool_call(&tool_use.id, title, kind, tool_use.input.clone());
 703
 704        let output = tool_result
 705            .as_ref()
 706            .and_then(|result| result.output.clone());
 707        if let Some(output) = output.clone() {
 708            let tool_event_stream = ToolCallEventStream::new(
 709                tool_use.id.clone(),
 710                stream.clone(),
 711                Some(self.project.read(cx).fs().clone()),
 712            );
 713            tool.replay(tool_use.input.clone(), output, tool_event_stream, cx)
 714                .log_err();
 715        }
 716
 717        stream.update_tool_call_fields(
 718            &tool_use.id,
 719            acp::ToolCallUpdateFields {
 720                status: Some(acp::ToolCallStatus::Completed),
 721                raw_output: output,
 722                ..Default::default()
 723            },
 724        );
 725    }
 726
 727    /// Create a snapshot of the current project state including git information and unsaved buffers.
 728    fn project_snapshot(
 729        project: Entity<Project>,
 730        cx: &mut Context<Self>,
 731    ) -> Task<Arc<agent::thread::ProjectSnapshot>> {
 732        let git_store = project.read(cx).git_store().clone();
 733        let worktree_snapshots: Vec<_> = project
 734            .read(cx)
 735            .visible_worktrees(cx)
 736            .map(|worktree| Self::worktree_snapshot(worktree, git_store.clone(), cx))
 737            .collect();
 738
 739        cx.spawn(async move |_, cx| {
 740            let worktree_snapshots = futures::future::join_all(worktree_snapshots).await;
 741
 742            let mut unsaved_buffers = Vec::new();
 743            cx.update(|app_cx| {
 744                let buffer_store = project.read(app_cx).buffer_store();
 745                for buffer_handle in buffer_store.read(app_cx).buffers() {
 746                    let buffer = buffer_handle.read(app_cx);
 747                    if buffer.is_dirty() {
 748                        if let Some(file) = buffer.file() {
 749                            let path = file.path().to_string_lossy().to_string();
 750                            unsaved_buffers.push(path);
 751                        }
 752                    }
 753                }
 754            })
 755            .ok();
 756
 757            Arc::new(ProjectSnapshot {
 758                worktree_snapshots,
 759                unsaved_buffer_paths: unsaved_buffers,
 760                timestamp: Utc::now(),
 761            })
 762        })
 763    }
 764
 765    fn worktree_snapshot(
 766        worktree: Entity<project::Worktree>,
 767        git_store: Entity<GitStore>,
 768        cx: &App,
 769    ) -> Task<agent::thread::WorktreeSnapshot> {
 770        cx.spawn(async move |cx| {
 771            // Get worktree path and snapshot
 772            let worktree_info = cx.update(|app_cx| {
 773                let worktree = worktree.read(app_cx);
 774                let path = worktree.abs_path().to_string_lossy().to_string();
 775                let snapshot = worktree.snapshot();
 776                (path, snapshot)
 777            });
 778
 779            let Ok((worktree_path, _snapshot)) = worktree_info else {
 780                return WorktreeSnapshot {
 781                    worktree_path: String::new(),
 782                    git_state: None,
 783                };
 784            };
 785
 786            let git_state = git_store
 787                .update(cx, |git_store, cx| {
 788                    git_store
 789                        .repositories()
 790                        .values()
 791                        .find(|repo| {
 792                            repo.read(cx)
 793                                .abs_path_to_repo_path(&worktree.read(cx).abs_path())
 794                                .is_some()
 795                        })
 796                        .cloned()
 797                })
 798                .ok()
 799                .flatten()
 800                .map(|repo| {
 801                    repo.update(cx, |repo, _| {
 802                        let current_branch =
 803                            repo.branch.as_ref().map(|branch| branch.name().to_owned());
 804                        repo.send_job(None, |state, _| async move {
 805                            let RepositoryState::Local { backend, .. } = state else {
 806                                return GitState {
 807                                    remote_url: None,
 808                                    head_sha: None,
 809                                    current_branch,
 810                                    diff: None,
 811                                };
 812                            };
 813
 814                            let remote_url = backend.remote_url("origin");
 815                            let head_sha = backend.head_sha().await;
 816                            let diff = backend.diff(DiffType::HeadToWorktree).await.ok();
 817
 818                            GitState {
 819                                remote_url,
 820                                head_sha,
 821                                current_branch,
 822                                diff,
 823                            }
 824                        })
 825                    })
 826                });
 827
 828            let git_state = match git_state {
 829                Some(git_state) => match git_state.ok() {
 830                    Some(git_state) => git_state.await.ok(),
 831                    None => None,
 832                },
 833                None => None,
 834            };
 835
 836            WorktreeSnapshot {
 837                worktree_path,
 838                git_state,
 839            }
 840        })
 841    }
 842
 843    pub fn project(&self) -> &Entity<Project> {
 844        &self.project
 845    }
 846
 847    pub fn action_log(&self) -> &Entity<ActionLog> {
 848        &self.action_log
 849    }
 850
 851    pub fn model(&self) -> &Arc<dyn LanguageModel> {
 852        &self.model
 853    }
 854
 855    pub fn set_model(&mut self, model: Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
 856        self.model = model;
 857        cx.notify()
 858    }
 859
 860    pub fn set_summarization_model(
 861        &mut self,
 862        model: Option<Arc<dyn LanguageModel>>,
 863        cx: &mut Context<Self>,
 864    ) {
 865        self.summarization_model = model;
 866        cx.notify()
 867    }
 868
 869    pub fn completion_mode(&self) -> CompletionMode {
 870        self.completion_mode
 871    }
 872
 873    pub fn set_completion_mode(&mut self, mode: CompletionMode, cx: &mut Context<Self>) {
 874        self.completion_mode = mode;
 875        cx.notify()
 876    }
 877
 878    #[cfg(any(test, feature = "test-support"))]
 879    pub fn last_message(&self) -> Option<Message> {
 880        if let Some(message) = self.pending_message.clone() {
 881            Some(Message::Agent(message))
 882        } else {
 883            self.messages.last().cloned()
 884        }
 885    }
 886
 887    pub fn add_tool(&mut self, tool: impl AgentTool) {
 888        self.tools.insert(tool.name(), tool.erase());
 889    }
 890
 891    pub fn remove_tool(&mut self, name: &str) -> bool {
 892        self.tools.remove(name).is_some()
 893    }
 894
 895    pub fn profile(&self) -> &AgentProfileId {
 896        &self.profile_id
 897    }
 898
 899    pub fn set_profile(&mut self, profile_id: AgentProfileId) {
 900        self.profile_id = profile_id;
 901    }
 902
 903    pub fn cancel(&mut self, cx: &mut Context<Self>) {
 904        if let Some(running_turn) = self.running_turn.take() {
 905            running_turn.cancel();
 906        }
 907        self.flush_pending_message(cx);
 908    }
 909
 910    pub fn truncate(&mut self, message_id: UserMessageId, cx: &mut Context<Self>) -> Result<()> {
 911        self.cancel(cx);
 912        let Some(position) = self.messages.iter().position(
 913            |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
 914        ) else {
 915            return Err(anyhow!("Message not found"));
 916        };
 917        self.messages.truncate(position);
 918        cx.notify();
 919        Ok(())
 920    }
 921
 922    pub fn resume(
 923        &mut self,
 924        cx: &mut Context<Self>,
 925    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
 926        anyhow::ensure!(
 927            self.tool_use_limit_reached,
 928            "can only resume after tool use limit is reached"
 929        );
 930
 931        self.messages.push(Message::Resume);
 932        cx.notify();
 933
 934        log::info!("Total messages in thread: {}", self.messages.len());
 935        Ok(self.run_turn(cx))
 936    }
 937
 938    /// Sending a message results in the model streaming a response, which could include tool calls.
 939    /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
 940    /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
 941    pub fn send<T>(
 942        &mut self,
 943        id: UserMessageId,
 944        content: impl IntoIterator<Item = T>,
 945        cx: &mut Context<Self>,
 946    ) -> mpsc::UnboundedReceiver<Result<ThreadEvent>>
 947    where
 948        T: Into<UserMessageContent>,
 949    {
 950        log::info!("Thread::send called with model: {:?}", self.model.name());
 951        self.advance_prompt_id();
 952
 953        let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
 954        log::debug!("Thread::send content: {:?}", content);
 955
 956        self.messages
 957            .push(Message::User(UserMessage { id, content }));
 958        cx.notify();
 959
 960        log::info!("Total messages in thread: {}", self.messages.len());
 961        self.run_turn(cx)
 962    }
 963
 964    fn run_turn(&mut self, cx: &mut Context<Self>) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {
 965        self.cancel(cx);
 966
 967        let model = self.model.clone();
 968        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
 969        let event_stream = ThreadEventStream(events_tx);
 970        let message_ix = self.messages.len().saturating_sub(1);
 971        self.tool_use_limit_reached = false;
 972        self.running_turn = Some(RunningTurn {
 973            event_stream: event_stream.clone(),
 974            _task: cx.spawn(async move |this, cx| {
 975                log::info!("Starting agent turn execution");
 976                let turn_result: Result<()> = async {
 977                    let mut completion_intent = CompletionIntent::UserPrompt;
 978                    loop {
 979                        log::debug!(
 980                            "Building completion request with intent: {:?}",
 981                            completion_intent
 982                        );
 983                        let request = this.update(cx, |this, cx| {
 984                            this.build_completion_request(completion_intent, cx)
 985                        })?;
 986
 987                        log::info!("Calling model.stream_completion");
 988                        let mut events = model.stream_completion(request, cx).await?;
 989                        log::debug!("Stream completion started successfully");
 990
 991                        let mut tool_use_limit_reached = false;
 992                        let mut tool_uses = FuturesUnordered::new();
 993                        while let Some(event) = events.next().await {
 994                            match event? {
 995                                LanguageModelCompletionEvent::StatusUpdate(
 996                                    CompletionRequestStatus::ToolUseLimitReached,
 997                                ) => {
 998                                    tool_use_limit_reached = true;
 999                                }
1000                                LanguageModelCompletionEvent::Stop(reason) => {
1001                                    event_stream.send_stop(reason);
1002                                    if reason == StopReason::Refusal {
1003                                        this.update(cx, |this, cx| {
1004                                            this.flush_pending_message(cx);
1005                                            this.messages.truncate(message_ix);
1006                                        })?;
1007                                        return Ok(());
1008                                    }
1009                                }
1010                                event => {
1011                                    log::trace!("Received completion event: {:?}", event);
1012                                    this.update(cx, |this, cx| {
1013                                        tool_uses.extend(this.handle_streamed_completion_event(
1014                                            event,
1015                                            &event_stream,
1016                                            cx,
1017                                        ));
1018                                    })
1019                                    .ok();
1020                                }
1021                            }
1022                        }
1023
1024                        let used_tools = tool_uses.is_empty();
1025                        while let Some(tool_result) = tool_uses.next().await {
1026                            log::info!("Tool finished {:?}", tool_result);
1027
1028                            event_stream.update_tool_call_fields(
1029                                &tool_result.tool_use_id,
1030                                acp::ToolCallUpdateFields {
1031                                    status: Some(if tool_result.is_error {
1032                                        acp::ToolCallStatus::Failed
1033                                    } else {
1034                                        acp::ToolCallStatus::Completed
1035                                    }),
1036                                    raw_output: tool_result.output.clone(),
1037                                    ..Default::default()
1038                                },
1039                            );
1040                            this.update(cx, |this, _cx| {
1041                                this.pending_message()
1042                                    .tool_results
1043                                    .insert(tool_result.tool_use_id.clone(), tool_result);
1044                            })
1045                            .ok();
1046                        }
1047
1048                        if tool_use_limit_reached {
1049                            log::info!("Tool use limit reached, completing turn");
1050                            this.update(cx, |this, _cx| this.tool_use_limit_reached = true)?;
1051                            return Err(language_model::ToolUseLimitReachedError.into());
1052                        } else if used_tools {
1053                            log::info!("No tool uses found, completing turn");
1054                            return Ok(());
1055                        } else {
1056                            this.update(cx, |this, cx| this.flush_pending_message(cx))?;
1057                            completion_intent = CompletionIntent::ToolResults;
1058                        }
1059                    }
1060                }
1061                .await;
1062
1063                if let Err(error) = turn_result {
1064                    log::error!("Turn execution failed: {:?}", error);
1065                    event_stream.send_error(error);
1066                } else {
1067                    log::info!("Turn execution completed successfully");
1068                }
1069
1070                this.update(cx, |this, cx| {
1071                    this.flush_pending_message(cx);
1072                    this.running_turn.take();
1073                })
1074                .ok();
1075            }),
1076        });
1077        events_rx
1078    }
1079
1080    pub fn generate_title_if_needed(&mut self, cx: &mut Context<Self>) {
1081        if !matches!(self.title, ThreadTitle::None) {
1082            return;
1083        }
1084
1085        // todo!() copy logic from agent1 re: tool calls, etc.?
1086        if self.messages.len() < 2 {
1087            return;
1088        }
1089
1090        self.generate_title(cx);
1091    }
1092
1093    fn generate_title(&mut self, cx: &mut Context<Self>) {
1094        let Some(model) = self.summarization_model.clone() else {
1095            println!("No thread summary model");
1096            return;
1097        };
1098        let mut request = LanguageModelRequest {
1099            intent: Some(CompletionIntent::ThreadSummarization),
1100            temperature: AgentSettings::temperature_for_model(&model, cx),
1101            ..Default::default()
1102        };
1103
1104        for message in &self.messages {
1105            request.messages.extend(message.to_request());
1106        }
1107
1108        request.messages.push(LanguageModelRequestMessage {
1109            role: Role::User,
1110            content: vec![MessageContent::Text(SUMMARIZE_THREAD_PROMPT.into())],
1111            cache: false,
1112        });
1113
1114        let task = cx.spawn(async move |this, cx| {
1115            let result = async {
1116                let mut messages = model.stream_completion(request, &cx).await?;
1117
1118                let mut new_summary = String::new();
1119                while let Some(event) = messages.next().await {
1120                    let Ok(event) = event else {
1121                        continue;
1122                    };
1123                    let text = match event {
1124                        LanguageModelCompletionEvent::Text(text) => text,
1125                        LanguageModelCompletionEvent::StatusUpdate(
1126                            CompletionRequestStatus::UsageUpdated { .. },
1127                        ) => {
1128                            // this.update(cx, |thread, cx| {
1129                            //     thread.update_model_request_usage(amount as u32, limit, cx);
1130                            // })?;
1131                            // todo!()? not sure if this is the right place to do this.
1132                            continue;
1133                        }
1134                        _ => continue,
1135                    };
1136
1137                    let mut lines = text.lines();
1138                    new_summary.extend(lines.next());
1139
1140                    // Stop if the LLM generated multiple lines.
1141                    if lines.next().is_some() {
1142                        break;
1143                    }
1144                }
1145
1146                anyhow::Ok(new_summary.into())
1147            }
1148            .await;
1149
1150            this.update(cx, |this, cx| {
1151                this.title = ThreadTitle::Done(result);
1152                cx.notify();
1153            })
1154            .log_err();
1155        });
1156
1157        self.title = ThreadTitle::Pending(task);
1158    }
1159
1160    pub fn build_system_message(&self) -> LanguageModelRequestMessage {
1161        log::debug!("Building system message");
1162        let prompt = SystemPromptTemplate {
1163            project: &self.project_context.borrow(),
1164            available_tools: self.tools.keys().cloned().collect(),
1165        }
1166        .render(&self.templates)
1167        .context("failed to build system prompt")
1168        .expect("Invalid template");
1169        log::debug!("System message built");
1170        LanguageModelRequestMessage {
1171            role: Role::System,
1172            content: vec![prompt.into()],
1173            cache: true,
1174        }
1175    }
1176
1177    /// A helper method that's called on every streamed completion event.
1178    /// Returns an optional tool result task, which the main agentic loop in
1179    /// send will send back to the model when it resolves.
1180    fn handle_streamed_completion_event(
1181        &mut self,
1182        event: LanguageModelCompletionEvent,
1183        event_stream: &ThreadEventStream,
1184        cx: &mut Context<Self>,
1185    ) -> Option<Task<LanguageModelToolResult>> {
1186        log::trace!("Handling streamed completion event: {:?}", event);
1187        use LanguageModelCompletionEvent::*;
1188
1189        match event {
1190            StartMessage { .. } => {
1191                self.flush_pending_message(cx);
1192                self.pending_message = Some(AgentMessage::default());
1193            }
1194            Text(new_text) => self.handle_text_event(new_text, event_stream, cx),
1195            Thinking { text, signature } => {
1196                self.handle_thinking_event(text, signature, event_stream, cx)
1197            }
1198            RedactedThinking { data } => self.handle_redacted_thinking_event(data, cx),
1199            ToolUse(tool_use) => {
1200                return self.handle_tool_use_event(tool_use, event_stream, cx);
1201            }
1202            ToolUseJsonParseError {
1203                id,
1204                tool_name,
1205                raw_input,
1206                json_parse_error,
1207            } => {
1208                return Some(Task::ready(self.handle_tool_use_json_parse_error_event(
1209                    id,
1210                    tool_name,
1211                    raw_input,
1212                    json_parse_error,
1213                )));
1214            }
1215            UsageUpdate(_) | StatusUpdate(_) => {}
1216            Stop(_) => unreachable!(),
1217        }
1218
1219        None
1220    }
1221
1222    fn handle_text_event(
1223        &mut self,
1224        new_text: String,
1225        event_stream: &ThreadEventStream,
1226        cx: &mut Context<Self>,
1227    ) {
1228        event_stream.send_text(&new_text);
1229
1230        let last_message = self.pending_message();
1231        if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
1232            text.push_str(&new_text);
1233        } else {
1234            last_message
1235                .content
1236                .push(AgentMessageContent::Text(new_text));
1237        }
1238
1239        cx.notify();
1240    }
1241
1242    fn handle_thinking_event(
1243        &mut self,
1244        new_text: String,
1245        new_signature: Option<String>,
1246        event_stream: &ThreadEventStream,
1247        cx: &mut Context<Self>,
1248    ) {
1249        event_stream.send_thinking(&new_text);
1250
1251        let last_message = self.pending_message();
1252        if let Some(AgentMessageContent::Thinking { text, signature }) =
1253            last_message.content.last_mut()
1254        {
1255            text.push_str(&new_text);
1256            *signature = new_signature.or(signature.take());
1257        } else {
1258            last_message.content.push(AgentMessageContent::Thinking {
1259                text: new_text,
1260                signature: new_signature,
1261            });
1262        }
1263
1264        cx.notify();
1265    }
1266
1267    fn handle_redacted_thinking_event(&mut self, data: String, cx: &mut Context<Self>) {
1268        let last_message = self.pending_message();
1269        last_message
1270            .content
1271            .push(AgentMessageContent::RedactedThinking(data));
1272        cx.notify();
1273    }
1274
1275    fn handle_tool_use_event(
1276        &mut self,
1277        tool_use: LanguageModelToolUse,
1278        event_stream: &ThreadEventStream,
1279        cx: &mut Context<Self>,
1280    ) -> Option<Task<LanguageModelToolResult>> {
1281        cx.notify();
1282
1283        let tool = self.tools.get(tool_use.name.as_ref()).cloned();
1284        let mut title = SharedString::from(&tool_use.name);
1285        let mut kind = acp::ToolKind::Other;
1286        if let Some(tool) = tool.as_ref() {
1287            title = tool.initial_title(tool_use.input.clone());
1288            kind = tool.kind();
1289        }
1290
1291        // Ensure the last message ends in the current tool use
1292        let last_message = self.pending_message();
1293        let push_new_tool_use = last_message.content.last_mut().map_or(true, |content| {
1294            if let AgentMessageContent::ToolUse(last_tool_use) = content {
1295                if last_tool_use.id == tool_use.id {
1296                    *last_tool_use = tool_use.clone();
1297                    false
1298                } else {
1299                    true
1300                }
1301            } else {
1302                true
1303            }
1304        });
1305
1306        if push_new_tool_use {
1307            event_stream.send_tool_call(&tool_use.id, title, kind, tool_use.input.clone());
1308            last_message
1309                .content
1310                .push(AgentMessageContent::ToolUse(tool_use.clone()));
1311        } else {
1312            event_stream.update_tool_call_fields(
1313                &tool_use.id,
1314                acp::ToolCallUpdateFields {
1315                    title: Some(title.into()),
1316                    kind: Some(kind),
1317                    raw_input: Some(tool_use.input.clone()),
1318                    ..Default::default()
1319                },
1320            );
1321        }
1322
1323        if !tool_use.is_input_complete {
1324            return None;
1325        }
1326
1327        let Some(tool) = tool else {
1328            let content = format!("No tool named {} exists", tool_use.name);
1329            return Some(Task::ready(LanguageModelToolResult {
1330                content: LanguageModelToolResultContent::Text(Arc::from(content)),
1331                tool_use_id: tool_use.id,
1332                tool_name: tool_use.name,
1333                is_error: true,
1334                output: None,
1335            }));
1336        };
1337
1338        let fs = self.project.read(cx).fs().clone();
1339        let tool_event_stream =
1340            ToolCallEventStream::new(tool_use.id.clone(), event_stream.clone(), Some(fs));
1341        tool_event_stream.update_fields(acp::ToolCallUpdateFields {
1342            status: Some(acp::ToolCallStatus::InProgress),
1343            ..Default::default()
1344        });
1345        let supports_images = self.model.supports_images();
1346        let tool_result = tool.run(tool_use.input, tool_event_stream, cx);
1347        log::info!("Running tool {}", tool_use.name);
1348        Some(cx.foreground_executor().spawn(async move {
1349            let tool_result = tool_result.await.and_then(|output| {
1350                if let LanguageModelToolResultContent::Image(_) = &output.llm_output {
1351                    if !supports_images {
1352                        return Err(anyhow!(
1353                            "Attempted to read an image, but this model doesn't support it.",
1354                        ));
1355                    }
1356                }
1357                Ok(output)
1358            });
1359
1360            match tool_result {
1361                Ok(output) => LanguageModelToolResult {
1362                    tool_use_id: tool_use.id,
1363                    tool_name: tool_use.name,
1364                    is_error: false,
1365                    content: output.llm_output,
1366                    output: Some(output.raw_output),
1367                },
1368                Err(error) => LanguageModelToolResult {
1369                    tool_use_id: tool_use.id,
1370                    tool_name: tool_use.name,
1371                    is_error: true,
1372                    content: LanguageModelToolResultContent::Text(Arc::from(error.to_string())),
1373                    output: None,
1374                },
1375            }
1376        }))
1377    }
1378
1379    fn handle_tool_use_json_parse_error_event(
1380        &mut self,
1381        tool_use_id: LanguageModelToolUseId,
1382        tool_name: Arc<str>,
1383        raw_input: Arc<str>,
1384        json_parse_error: String,
1385    ) -> LanguageModelToolResult {
1386        let tool_output = format!("Error parsing input JSON: {json_parse_error}");
1387        LanguageModelToolResult {
1388            tool_use_id,
1389            tool_name,
1390            is_error: true,
1391            content: LanguageModelToolResultContent::Text(tool_output.into()),
1392            output: Some(serde_json::Value::String(raw_input.to_string())),
1393        }
1394    }
1395
1396    fn pending_message(&mut self) -> &mut AgentMessage {
1397        self.pending_message.get_or_insert_default()
1398    }
1399
1400    fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
1401        let Some(mut message) = self.pending_message.take() else {
1402            return;
1403        };
1404
1405        for content in &message.content {
1406            let AgentMessageContent::ToolUse(tool_use) = content else {
1407                continue;
1408            };
1409
1410            if !message.tool_results.contains_key(&tool_use.id) {
1411                message.tool_results.insert(
1412                    tool_use.id.clone(),
1413                    LanguageModelToolResult {
1414                        tool_use_id: tool_use.id.clone(),
1415                        tool_name: tool_use.name.clone(),
1416                        is_error: true,
1417                        content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
1418                        output: None,
1419                    },
1420                );
1421            }
1422        }
1423
1424        self.messages.push(Message::Agent(message));
1425        cx.notify()
1426    }
1427
1428    pub(crate) fn build_completion_request(
1429        &self,
1430        completion_intent: CompletionIntent,
1431        cx: &mut App,
1432    ) -> LanguageModelRequest {
1433        log::debug!("Building completion request");
1434        log::debug!("Completion intent: {:?}", completion_intent);
1435        log::debug!("Completion mode: {:?}", self.completion_mode);
1436
1437        let messages = self.build_request_messages();
1438        log::info!("Request will include {} messages", messages.len());
1439
1440        let tools = if let Some(tools) = self.tools(cx).log_err() {
1441            tools
1442                .filter_map(|tool| {
1443                    let tool_name = tool.name().to_string();
1444                    log::trace!("Including tool: {}", tool_name);
1445                    Some(LanguageModelRequestTool {
1446                        name: tool_name,
1447                        description: tool.description().to_string(),
1448                        input_schema: tool
1449                            .input_schema(self.model.tool_input_format())
1450                            .log_err()?,
1451                    })
1452                })
1453                .collect()
1454        } else {
1455            Vec::new()
1456        };
1457
1458        log::info!("Request includes {} tools", tools.len());
1459
1460        let request = LanguageModelRequest {
1461            thread_id: Some(self.id.to_string()),
1462            prompt_id: Some(self.prompt_id.to_string()),
1463            intent: Some(completion_intent),
1464            mode: Some(self.completion_mode.into()),
1465            messages,
1466            tools,
1467            tool_choice: None,
1468            stop: Vec::new(),
1469            temperature: AgentSettings::temperature_for_model(self.model(), cx),
1470            thinking_allowed: true,
1471        };
1472
1473        log::debug!("Completion request built successfully");
1474        request
1475    }
1476
1477    fn tools<'a>(&'a self, cx: &'a App) -> Result<impl Iterator<Item = &'a Arc<dyn AnyAgentTool>>> {
1478        let profile = AgentSettings::get_global(cx)
1479            .profiles
1480            .get(&self.profile_id)
1481            .context("profile not found")?;
1482        let provider_id = self.model.provider_id();
1483
1484        Ok(self
1485            .tools
1486            .iter()
1487            .filter(move |(_, tool)| tool.supported_provider(&provider_id))
1488            .filter_map(|(tool_name, tool)| {
1489                if profile.is_tool_enabled(tool_name) {
1490                    Some(tool)
1491                } else {
1492                    None
1493                }
1494            })
1495            .chain(self.context_server_registry.read(cx).servers().flat_map(
1496                |(server_id, tools)| {
1497                    tools.iter().filter_map(|(tool_name, tool)| {
1498                        if profile.is_context_server_tool_enabled(&server_id.0, tool_name) {
1499                            Some(tool)
1500                        } else {
1501                            None
1502                        }
1503                    })
1504                },
1505            )))
1506    }
1507
1508    fn build_request_messages(&self) -> Vec<LanguageModelRequestMessage> {
1509        log::trace!(
1510            "Building request messages from {} thread messages",
1511            self.messages.len()
1512        );
1513        let mut messages = vec![self.build_system_message()];
1514        for message in &self.messages {
1515            messages.extend(message.to_request());
1516        }
1517
1518        if let Some(message) = self.pending_message.as_ref() {
1519            messages.extend(message.to_request());
1520        }
1521
1522        if let Some(last_user_message) = messages
1523            .iter_mut()
1524            .rev()
1525            .find(|message| message.role == Role::User)
1526        {
1527            last_user_message.cache = true;
1528        }
1529
1530        messages
1531    }
1532
1533    pub fn to_markdown(&self) -> String {
1534        let mut markdown = String::new();
1535        for (ix, message) in self.messages.iter().enumerate() {
1536            if ix > 0 {
1537                markdown.push('\n');
1538            }
1539            markdown.push_str(&message.to_markdown());
1540        }
1541
1542        if let Some(message) = self.pending_message.as_ref() {
1543            markdown.push('\n');
1544            markdown.push_str(&message.to_markdown());
1545        }
1546
1547        markdown
1548    }
1549
1550    fn advance_prompt_id(&mut self) {
1551        self.prompt_id = PromptId::new();
1552    }
1553}
1554
1555struct RunningTurn {
1556    /// Holds the task that handles agent interaction until the end of the turn.
1557    /// Survives across multiple requests as the model performs tool calls and
1558    /// we run tools, report their results.
1559    _task: Task<()>,
1560    /// The current event stream for the running turn. Used to report a final
1561    /// cancellation event if we cancel the turn.
1562    event_stream: ThreadEventStream,
1563}
1564
1565impl RunningTurn {
1566    fn cancel(self) {
1567        log::debug!("Cancelling in progress turn");
1568        self.event_stream.send_canceled();
1569    }
1570}
1571
1572pub trait AgentTool
1573where
1574    Self: 'static + Sized,
1575{
1576    type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
1577    type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
1578
1579    fn name(&self) -> SharedString;
1580
1581    fn description(&self) -> SharedString {
1582        let schema = schemars::schema_for!(Self::Input);
1583        SharedString::new(
1584            schema
1585                .get("description")
1586                .and_then(|description| description.as_str())
1587                .unwrap_or_default(),
1588        )
1589    }
1590
1591    fn kind(&self) -> acp::ToolKind;
1592
1593    /// The initial tool title to display. Can be updated during the tool run.
1594    fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString;
1595
1596    /// Returns the JSON schema that describes the tool's input.
1597    fn input_schema(&self) -> Schema {
1598        schemars::schema_for!(Self::Input)
1599    }
1600
1601    /// Some tools rely on a provider for the underlying billing or other reasons.
1602    /// Allow the tool to check if they are compatible, or should be filtered out.
1603    fn supported_provider(&self, _provider: &LanguageModelProviderId) -> bool {
1604        true
1605    }
1606
1607    /// Runs the tool with the provided input.
1608    fn run(
1609        self: Arc<Self>,
1610        input: Self::Input,
1611        event_stream: ToolCallEventStream,
1612        cx: &mut App,
1613    ) -> Task<Result<Self::Output>>;
1614
1615    /// Emits events for a previous execution of the tool.
1616    fn replay(
1617        &self,
1618        _input: Self::Input,
1619        _output: Self::Output,
1620        _event_stream: ToolCallEventStream,
1621        _cx: &mut App,
1622    ) -> Result<()> {
1623        Ok(())
1624    }
1625
1626    fn erase(self) -> Arc<dyn AnyAgentTool> {
1627        Arc::new(Erased(Arc::new(self)))
1628    }
1629}
1630
1631pub struct Erased<T>(T);
1632
1633pub struct AgentToolOutput {
1634    pub llm_output: LanguageModelToolResultContent,
1635    pub raw_output: serde_json::Value,
1636}
1637
1638pub trait AnyAgentTool {
1639    fn name(&self) -> SharedString;
1640    fn description(&self) -> SharedString;
1641    fn kind(&self) -> acp::ToolKind;
1642    fn initial_title(&self, input: serde_json::Value) -> SharedString;
1643    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
1644    fn supported_provider(&self, _provider: &LanguageModelProviderId) -> bool {
1645        true
1646    }
1647    fn run(
1648        self: Arc<Self>,
1649        input: serde_json::Value,
1650        event_stream: ToolCallEventStream,
1651        cx: &mut App,
1652    ) -> Task<Result<AgentToolOutput>>;
1653    fn replay(
1654        &self,
1655        input: serde_json::Value,
1656        output: serde_json::Value,
1657        event_stream: ToolCallEventStream,
1658        cx: &mut App,
1659    ) -> Result<()>;
1660}
1661
1662impl<T> AnyAgentTool for Erased<Arc<T>>
1663where
1664    T: AgentTool,
1665{
1666    fn name(&self) -> SharedString {
1667        self.0.name()
1668    }
1669
1670    fn description(&self) -> SharedString {
1671        self.0.description()
1672    }
1673
1674    fn kind(&self) -> agent_client_protocol::ToolKind {
1675        self.0.kind()
1676    }
1677
1678    fn initial_title(&self, input: serde_json::Value) -> SharedString {
1679        let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
1680        self.0.initial_title(parsed_input)
1681    }
1682
1683    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
1684        let mut json = serde_json::to_value(self.0.input_schema())?;
1685        adapt_schema_to_format(&mut json, format)?;
1686        Ok(json)
1687    }
1688
1689    fn supported_provider(&self, provider: &LanguageModelProviderId) -> bool {
1690        self.0.supported_provider(provider)
1691    }
1692
1693    fn run(
1694        self: Arc<Self>,
1695        input: serde_json::Value,
1696        event_stream: ToolCallEventStream,
1697        cx: &mut App,
1698    ) -> Task<Result<AgentToolOutput>> {
1699        cx.spawn(async move |cx| {
1700            let input = serde_json::from_value(input)?;
1701            let output = cx
1702                .update(|cx| self.0.clone().run(input, event_stream, cx))?
1703                .await?;
1704            let raw_output = serde_json::to_value(&output)?;
1705            Ok(AgentToolOutput {
1706                llm_output: output.into(),
1707                raw_output,
1708            })
1709        })
1710    }
1711
1712    fn replay(
1713        &self,
1714        input: serde_json::Value,
1715        output: serde_json::Value,
1716        event_stream: ToolCallEventStream,
1717        cx: &mut App,
1718    ) -> Result<()> {
1719        let input = serde_json::from_value(input)?;
1720        let output = serde_json::from_value(output)?;
1721        self.0.replay(input, output, event_stream, cx)
1722    }
1723}
1724
1725#[derive(Clone)]
1726struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
1727
1728impl ThreadEventStream {
1729    fn send_user_message(&self, message: &UserMessage) {
1730        self.0
1731            .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
1732            .ok();
1733    }
1734
1735    fn send_text(&self, text: &str) {
1736        self.0
1737            .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
1738            .ok();
1739    }
1740
1741    fn send_thinking(&self, text: &str) {
1742        self.0
1743            .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
1744            .ok();
1745    }
1746
1747    fn send_tool_call(
1748        &self,
1749        id: &LanguageModelToolUseId,
1750        title: SharedString,
1751        kind: acp::ToolKind,
1752        input: serde_json::Value,
1753    ) {
1754        self.0
1755            .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
1756                id,
1757                title.to_string(),
1758                kind,
1759                input,
1760            ))))
1761            .ok();
1762    }
1763
1764    fn initial_tool_call(
1765        id: &LanguageModelToolUseId,
1766        title: String,
1767        kind: acp::ToolKind,
1768        input: serde_json::Value,
1769    ) -> acp::ToolCall {
1770        acp::ToolCall {
1771            id: acp::ToolCallId(id.to_string().into()),
1772            title,
1773            kind,
1774            status: acp::ToolCallStatus::Pending,
1775            content: vec![],
1776            locations: vec![],
1777            raw_input: Some(input),
1778            raw_output: None,
1779        }
1780    }
1781
1782    fn update_tool_call_fields(
1783        &self,
1784        tool_use_id: &LanguageModelToolUseId,
1785        fields: acp::ToolCallUpdateFields,
1786    ) {
1787        self.0
1788            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
1789                acp::ToolCallUpdate {
1790                    id: acp::ToolCallId(tool_use_id.to_string().into()),
1791                    fields,
1792                }
1793                .into(),
1794            )))
1795            .ok();
1796    }
1797
1798    fn send_stop(&self, reason: StopReason) {
1799        match reason {
1800            StopReason::EndTurn => {
1801                self.0
1802                    .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::EndTurn)))
1803                    .ok();
1804            }
1805            StopReason::MaxTokens => {
1806                self.0
1807                    .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::MaxTokens)))
1808                    .ok();
1809            }
1810            StopReason::Refusal => {
1811                self.0
1812                    .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Refusal)))
1813                    .ok();
1814            }
1815            StopReason::ToolUse => {}
1816        }
1817    }
1818
1819    fn send_canceled(&self) {
1820        self.0
1821            .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Canceled)))
1822            .ok();
1823    }
1824
1825    fn send_error(&self, error: impl Into<anyhow::Error>) {
1826        self.0.unbounded_send(Err(error.into())).ok();
1827    }
1828}
1829
1830#[derive(Clone)]
1831pub struct ToolCallEventStream {
1832    tool_use_id: LanguageModelToolUseId,
1833    stream: ThreadEventStream,
1834    fs: Option<Arc<dyn Fs>>,
1835}
1836
1837impl ToolCallEventStream {
1838    #[cfg(test)]
1839    pub fn test() -> (Self, ToolCallEventStreamReceiver) {
1840        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1841
1842        let stream = ToolCallEventStream::new("test_id".into(), ThreadEventStream(events_tx), None);
1843
1844        (stream, ToolCallEventStreamReceiver(events_rx))
1845    }
1846
1847    fn new(
1848        tool_use_id: LanguageModelToolUseId,
1849        stream: ThreadEventStream,
1850        fs: Option<Arc<dyn Fs>>,
1851    ) -> Self {
1852        Self {
1853            tool_use_id,
1854            stream,
1855            fs,
1856        }
1857    }
1858
1859    pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
1860        self.stream
1861            .update_tool_call_fields(&self.tool_use_id, fields);
1862    }
1863
1864    pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
1865        self.stream
1866            .0
1867            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
1868                acp_thread::ToolCallUpdateDiff {
1869                    id: acp::ToolCallId(self.tool_use_id.to_string().into()),
1870                    diff,
1871                }
1872                .into(),
1873            )))
1874            .ok();
1875    }
1876
1877    pub fn update_terminal(&self, terminal: Entity<acp_thread::Terminal>) {
1878        self.stream
1879            .0
1880            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
1881                acp_thread::ToolCallUpdateTerminal {
1882                    id: acp::ToolCallId(self.tool_use_id.to_string().into()),
1883                    terminal,
1884                }
1885                .into(),
1886            )))
1887            .ok();
1888    }
1889
1890    pub fn authorize(&self, title: impl Into<String>, cx: &mut App) -> Task<Result<()>> {
1891        if agent_settings::AgentSettings::get_global(cx).always_allow_tool_actions {
1892            return Task::ready(Ok(()));
1893        }
1894
1895        let (response_tx, response_rx) = oneshot::channel();
1896        self.stream
1897            .0
1898            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
1899                ToolCallAuthorization {
1900                    tool_call: acp::ToolCallUpdate {
1901                        id: acp::ToolCallId(self.tool_use_id.to_string().into()),
1902                        fields: acp::ToolCallUpdateFields {
1903                            title: Some(title.into()),
1904                            ..Default::default()
1905                        },
1906                    },
1907                    options: vec![
1908                        acp::PermissionOption {
1909                            id: acp::PermissionOptionId("always_allow".into()),
1910                            name: "Always Allow".into(),
1911                            kind: acp::PermissionOptionKind::AllowAlways,
1912                        },
1913                        acp::PermissionOption {
1914                            id: acp::PermissionOptionId("allow".into()),
1915                            name: "Allow".into(),
1916                            kind: acp::PermissionOptionKind::AllowOnce,
1917                        },
1918                        acp::PermissionOption {
1919                            id: acp::PermissionOptionId("deny".into()),
1920                            name: "Deny".into(),
1921                            kind: acp::PermissionOptionKind::RejectOnce,
1922                        },
1923                    ],
1924                    response: response_tx,
1925                },
1926            )))
1927            .ok();
1928        let fs = self.fs.clone();
1929        cx.spawn(async move |cx| match response_rx.await?.0.as_ref() {
1930            "always_allow" => {
1931                if let Some(fs) = fs.clone() {
1932                    cx.update(|cx| {
1933                        update_settings_file::<AgentSettings>(fs, cx, |settings, _| {
1934                            settings.set_always_allow_tool_actions(true);
1935                        });
1936                    })?;
1937                }
1938
1939                Ok(())
1940            }
1941            "allow" => Ok(()),
1942            _ => Err(anyhow!("Permission to run tool denied by user")),
1943        })
1944    }
1945}
1946
1947#[cfg(test)]
1948pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
1949
1950#[cfg(test)]
1951impl ToolCallEventStreamReceiver {
1952    pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
1953        let event = self.0.next().await;
1954        if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
1955            auth
1956        } else {
1957            panic!("Expected ToolCallAuthorization but got: {:?}", event);
1958        }
1959    }
1960
1961    pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
1962        let event = self.0.next().await;
1963        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
1964            update,
1965        )))) = event
1966        {
1967            update.terminal
1968        } else {
1969            panic!("Expected terminal but got: {:?}", event);
1970        }
1971    }
1972}
1973
1974#[cfg(test)]
1975impl std::ops::Deref for ToolCallEventStreamReceiver {
1976    type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
1977
1978    fn deref(&self) -> &Self::Target {
1979        &self.0
1980    }
1981}
1982
1983#[cfg(test)]
1984impl std::ops::DerefMut for ToolCallEventStreamReceiver {
1985    fn deref_mut(&mut self) -> &mut Self::Target {
1986        &mut self.0
1987    }
1988}
1989
1990impl From<&str> for UserMessageContent {
1991    fn from(text: &str) -> Self {
1992        Self::Text(text.into())
1993    }
1994}
1995
1996impl From<acp::ContentBlock> for UserMessageContent {
1997    fn from(value: acp::ContentBlock) -> Self {
1998        match value {
1999            acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
2000            acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
2001            acp::ContentBlock::Audio(_) => {
2002                // TODO
2003                Self::Text("[audio]".to_string())
2004            }
2005            acp::ContentBlock::ResourceLink(resource_link) => {
2006                match MentionUri::parse(&resource_link.uri) {
2007                    Ok(uri) => Self::Mention {
2008                        uri,
2009                        content: String::new(),
2010                    },
2011                    Err(err) => {
2012                        log::error!("Failed to parse mention link: {}", err);
2013                        Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
2014                    }
2015                }
2016            }
2017            acp::ContentBlock::Resource(resource) => match resource.resource {
2018                acp::EmbeddedResourceResource::TextResourceContents(resource) => {
2019                    match MentionUri::parse(&resource.uri) {
2020                        Ok(uri) => Self::Mention {
2021                            uri,
2022                            content: resource.text,
2023                        },
2024                        Err(err) => {
2025                            log::error!("Failed to parse mention link: {}", err);
2026                            Self::Text(
2027                                MarkdownCodeBlock {
2028                                    tag: &resource.uri,
2029                                    text: &resource.text,
2030                                }
2031                                .to_string(),
2032                            )
2033                        }
2034                    }
2035                }
2036                acp::EmbeddedResourceResource::BlobResourceContents(_) => {
2037                    // TODO
2038                    Self::Text("[blob]".to_string())
2039                }
2040            },
2041        }
2042    }
2043}
2044
2045impl From<UserMessageContent> for acp::ContentBlock {
2046    fn from(content: UserMessageContent) -> Self {
2047        match content {
2048            UserMessageContent::Text(text) => acp::ContentBlock::Text(acp::TextContent {
2049                text,
2050                annotations: None,
2051            }),
2052            UserMessageContent::Image(image) => acp::ContentBlock::Image(acp::ImageContent {
2053                data: image.source.to_string(),
2054                mime_type: "image/png".to_string(),
2055                annotations: None,
2056                uri: None,
2057            }),
2058            UserMessageContent::Mention { .. } => {
2059                todo!()
2060            }
2061        }
2062    }
2063}
2064
2065fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
2066    LanguageModelImage {
2067        source: image_content.data.into(),
2068        // TODO: make this optional?
2069        size: gpui::Size::new(0.into(), 0.into()),
2070    }
2071}