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: Option<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: Option<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            Some(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: Some(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: self.model.as_ref().map(|model| DbLanguageModel {
 628                provider: model.provider_id().to_string(),
 629                model: 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) -> Option<&Arc<dyn LanguageModel>> {
 852        self.model.as_ref()
 853    }
 854
 855    pub fn set_model(&mut self, model: Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
 856        self.model = Some(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        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    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
 947    where
 948        T: Into<UserMessageContent>,
 949    {
 950        let model = self.model().context("No language model configured")?;
 951
 952        log::info!("Thread::send called with model: {:?}", model.name());
 953        self.advance_prompt_id();
 954
 955        let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
 956        log::debug!("Thread::send content: {:?}", content);
 957
 958        self.messages
 959            .push(Message::User(UserMessage { id, content }));
 960        cx.notify();
 961
 962        log::info!("Total messages in thread: {}", self.messages.len());
 963        self.run_turn(cx)
 964    }
 965
 966    fn run_turn(
 967        &mut self,
 968        cx: &mut Context<Self>,
 969    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
 970        self.cancel(cx);
 971
 972        let model = self.model.clone().context("No language model configured")?;
 973        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
 974        let event_stream = ThreadEventStream(events_tx);
 975        let message_ix = self.messages.len().saturating_sub(1);
 976        self.tool_use_limit_reached = false;
 977        self.running_turn = Some(RunningTurn {
 978            event_stream: event_stream.clone(),
 979            _task: cx.spawn(async move |this, cx| {
 980                log::info!("Starting agent turn execution");
 981                let turn_result: Result<()> = async {
 982                    let mut completion_intent = CompletionIntent::UserPrompt;
 983                    loop {
 984                        log::debug!(
 985                            "Building completion request with intent: {:?}",
 986                            completion_intent
 987                        );
 988                        let request = this.update(cx, |this, cx| {
 989                            this.build_completion_request(completion_intent, cx)
 990                        })??;
 991
 992                        log::info!("Calling model.stream_completion");
 993                        let mut events = model.stream_completion(request, cx).await?;
 994                        log::debug!("Stream completion started successfully");
 995
 996                        let mut tool_use_limit_reached = false;
 997                        let mut tool_uses = FuturesUnordered::new();
 998                        while let Some(event) = events.next().await {
 999                            match event? {
1000                                LanguageModelCompletionEvent::StatusUpdate(
1001                                    CompletionRequestStatus::ToolUseLimitReached,
1002                                ) => {
1003                                    tool_use_limit_reached = true;
1004                                }
1005                                LanguageModelCompletionEvent::Stop(reason) => {
1006                                    event_stream.send_stop(reason);
1007                                    if reason == StopReason::Refusal {
1008                                        this.update(cx, |this, cx| {
1009                                            this.flush_pending_message(cx);
1010                                            this.messages.truncate(message_ix);
1011                                        })?;
1012                                        return Ok(());
1013                                    }
1014                                }
1015                                event => {
1016                                    log::trace!("Received completion event: {:?}", event);
1017                                    this.update(cx, |this, cx| {
1018                                        tool_uses.extend(this.handle_streamed_completion_event(
1019                                            event,
1020                                            &event_stream,
1021                                            cx,
1022                                        ));
1023                                    })
1024                                    .ok();
1025                                }
1026                            }
1027                        }
1028
1029                        let used_tools = tool_uses.is_empty();
1030                        while let Some(tool_result) = tool_uses.next().await {
1031                            log::info!("Tool finished {:?}", tool_result);
1032
1033                            event_stream.update_tool_call_fields(
1034                                &tool_result.tool_use_id,
1035                                acp::ToolCallUpdateFields {
1036                                    status: Some(if tool_result.is_error {
1037                                        acp::ToolCallStatus::Failed
1038                                    } else {
1039                                        acp::ToolCallStatus::Completed
1040                                    }),
1041                                    raw_output: tool_result.output.clone(),
1042                                    ..Default::default()
1043                                },
1044                            );
1045                            this.update(cx, |this, _cx| {
1046                                this.pending_message()
1047                                    .tool_results
1048                                    .insert(tool_result.tool_use_id.clone(), tool_result);
1049                            })
1050                            .ok();
1051                        }
1052
1053                        if tool_use_limit_reached {
1054                            log::info!("Tool use limit reached, completing turn");
1055                            this.update(cx, |this, _cx| this.tool_use_limit_reached = true)?;
1056                            return Err(language_model::ToolUseLimitReachedError.into());
1057                        } else if used_tools {
1058                            log::info!("No tool uses found, completing turn");
1059                            return Ok(());
1060                        } else {
1061                            this.update(cx, |this, cx| this.flush_pending_message(cx))?;
1062                            completion_intent = CompletionIntent::ToolResults;
1063                        }
1064                    }
1065                }
1066                .await;
1067
1068                if let Err(error) = turn_result {
1069                    log::error!("Turn execution failed: {:?}", error);
1070                    event_stream.send_error(error);
1071                } else {
1072                    log::info!("Turn execution completed successfully");
1073                }
1074
1075                this.update(cx, |this, cx| {
1076                    this.flush_pending_message(cx);
1077                    this.running_turn.take();
1078                })
1079                .ok();
1080            }),
1081        });
1082        Ok(events_rx)
1083    }
1084
1085    pub fn generate_title_if_needed(&mut self, cx: &mut Context<Self>) {
1086        if !matches!(self.title, ThreadTitle::None) {
1087            return;
1088        }
1089
1090        // todo!() copy logic from agent1 re: tool calls, etc.?
1091        if self.messages.len() < 2 {
1092            return;
1093        }
1094
1095        self.generate_title(cx);
1096    }
1097
1098    fn generate_title(&mut self, cx: &mut Context<Self>) {
1099        let Some(model) = self.summarization_model.clone() else {
1100            println!("No thread summary model");
1101            return;
1102        };
1103        let mut request = LanguageModelRequest {
1104            intent: Some(CompletionIntent::ThreadSummarization),
1105            temperature: AgentSettings::temperature_for_model(&model, cx),
1106            ..Default::default()
1107        };
1108
1109        for message in &self.messages {
1110            request.messages.extend(message.to_request());
1111        }
1112
1113        request.messages.push(LanguageModelRequestMessage {
1114            role: Role::User,
1115            content: vec![MessageContent::Text(SUMMARIZE_THREAD_PROMPT.into())],
1116            cache: false,
1117        });
1118
1119        let task = cx.spawn(async move |this, cx| {
1120            let result = async {
1121                let mut messages = model.stream_completion(request, &cx).await?;
1122
1123                let mut new_summary = String::new();
1124                while let Some(event) = messages.next().await {
1125                    let Ok(event) = event else {
1126                        continue;
1127                    };
1128                    let text = match event {
1129                        LanguageModelCompletionEvent::Text(text) => text,
1130                        LanguageModelCompletionEvent::StatusUpdate(
1131                            CompletionRequestStatus::UsageUpdated { .. },
1132                        ) => {
1133                            // this.update(cx, |thread, cx| {
1134                            //     thread.update_model_request_usage(amount as u32, limit, cx);
1135                            // })?;
1136                            // todo!()? not sure if this is the right place to do this.
1137                            continue;
1138                        }
1139                        _ => continue,
1140                    };
1141
1142                    let mut lines = text.lines();
1143                    new_summary.extend(lines.next());
1144
1145                    // Stop if the LLM generated multiple lines.
1146                    if lines.next().is_some() {
1147                        break;
1148                    }
1149                }
1150
1151                anyhow::Ok(new_summary.into())
1152            }
1153            .await;
1154
1155            this.update(cx, |this, cx| {
1156                this.title = ThreadTitle::Done(result);
1157                cx.notify();
1158            })
1159            .log_err();
1160        });
1161
1162        self.title = ThreadTitle::Pending(task);
1163        cx.notify()
1164    }
1165
1166    pub fn build_system_message(&self) -> LanguageModelRequestMessage {
1167        log::debug!("Building system message");
1168        let prompt = SystemPromptTemplate {
1169            project: &self.project_context.borrow(),
1170            available_tools: self.tools.keys().cloned().collect(),
1171        }
1172        .render(&self.templates)
1173        .context("failed to build system prompt")
1174        .expect("Invalid template");
1175        log::debug!("System message built");
1176        LanguageModelRequestMessage {
1177            role: Role::System,
1178            content: vec![prompt.into()],
1179            cache: true,
1180        }
1181    }
1182
1183    /// A helper method that's called on every streamed completion event.
1184    /// Returns an optional tool result task, which the main agentic loop in
1185    /// send will send back to the model when it resolves.
1186    fn handle_streamed_completion_event(
1187        &mut self,
1188        event: LanguageModelCompletionEvent,
1189        event_stream: &ThreadEventStream,
1190        cx: &mut Context<Self>,
1191    ) -> Option<Task<LanguageModelToolResult>> {
1192        log::trace!("Handling streamed completion event: {:?}", event);
1193        use LanguageModelCompletionEvent::*;
1194
1195        match event {
1196            StartMessage { .. } => {
1197                self.flush_pending_message(cx);
1198                self.pending_message = Some(AgentMessage::default());
1199            }
1200            Text(new_text) => self.handle_text_event(new_text, event_stream, cx),
1201            Thinking { text, signature } => {
1202                self.handle_thinking_event(text, signature, event_stream, cx)
1203            }
1204            RedactedThinking { data } => self.handle_redacted_thinking_event(data, cx),
1205            ToolUse(tool_use) => {
1206                return self.handle_tool_use_event(tool_use, event_stream, cx);
1207            }
1208            ToolUseJsonParseError {
1209                id,
1210                tool_name,
1211                raw_input,
1212                json_parse_error,
1213            } => {
1214                return Some(Task::ready(self.handle_tool_use_json_parse_error_event(
1215                    id,
1216                    tool_name,
1217                    raw_input,
1218                    json_parse_error,
1219                )));
1220            }
1221            UsageUpdate(_) | StatusUpdate(_) => {}
1222            Stop(_) => unreachable!(),
1223        }
1224
1225        None
1226    }
1227
1228    fn handle_text_event(
1229        &mut self,
1230        new_text: String,
1231        event_stream: &ThreadEventStream,
1232        cx: &mut Context<Self>,
1233    ) {
1234        event_stream.send_text(&new_text);
1235
1236        let last_message = self.pending_message();
1237        if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
1238            text.push_str(&new_text);
1239        } else {
1240            last_message
1241                .content
1242                .push(AgentMessageContent::Text(new_text));
1243        }
1244
1245        cx.notify();
1246    }
1247
1248    fn handle_thinking_event(
1249        &mut self,
1250        new_text: String,
1251        new_signature: Option<String>,
1252        event_stream: &ThreadEventStream,
1253        cx: &mut Context<Self>,
1254    ) {
1255        event_stream.send_thinking(&new_text);
1256
1257        let last_message = self.pending_message();
1258        if let Some(AgentMessageContent::Thinking { text, signature }) =
1259            last_message.content.last_mut()
1260        {
1261            text.push_str(&new_text);
1262            *signature = new_signature.or(signature.take());
1263        } else {
1264            last_message.content.push(AgentMessageContent::Thinking {
1265                text: new_text,
1266                signature: new_signature,
1267            });
1268        }
1269
1270        cx.notify();
1271    }
1272
1273    fn handle_redacted_thinking_event(&mut self, data: String, cx: &mut Context<Self>) {
1274        let last_message = self.pending_message();
1275        last_message
1276            .content
1277            .push(AgentMessageContent::RedactedThinking(data));
1278        cx.notify();
1279    }
1280
1281    fn handle_tool_use_event(
1282        &mut self,
1283        tool_use: LanguageModelToolUse,
1284        event_stream: &ThreadEventStream,
1285        cx: &mut Context<Self>,
1286    ) -> Option<Task<LanguageModelToolResult>> {
1287        cx.notify();
1288
1289        let tool = self.tools.get(tool_use.name.as_ref()).cloned();
1290        let mut title = SharedString::from(&tool_use.name);
1291        let mut kind = acp::ToolKind::Other;
1292        if let Some(tool) = tool.as_ref() {
1293            title = tool.initial_title(tool_use.input.clone());
1294            kind = tool.kind();
1295        }
1296
1297        // Ensure the last message ends in the current tool use
1298        let last_message = self.pending_message();
1299        let push_new_tool_use = last_message.content.last_mut().map_or(true, |content| {
1300            if let AgentMessageContent::ToolUse(last_tool_use) = content {
1301                if last_tool_use.id == tool_use.id {
1302                    *last_tool_use = tool_use.clone();
1303                    false
1304                } else {
1305                    true
1306                }
1307            } else {
1308                true
1309            }
1310        });
1311
1312        if push_new_tool_use {
1313            event_stream.send_tool_call(&tool_use.id, title, kind, tool_use.input.clone());
1314            last_message
1315                .content
1316                .push(AgentMessageContent::ToolUse(tool_use.clone()));
1317        } else {
1318            event_stream.update_tool_call_fields(
1319                &tool_use.id,
1320                acp::ToolCallUpdateFields {
1321                    title: Some(title.into()),
1322                    kind: Some(kind),
1323                    raw_input: Some(tool_use.input.clone()),
1324                    ..Default::default()
1325                },
1326            );
1327        }
1328
1329        if !tool_use.is_input_complete {
1330            return None;
1331        }
1332
1333        let Some(tool) = tool else {
1334            let content = format!("No tool named {} exists", tool_use.name);
1335            return Some(Task::ready(LanguageModelToolResult {
1336                content: LanguageModelToolResultContent::Text(Arc::from(content)),
1337                tool_use_id: tool_use.id,
1338                tool_name: tool_use.name,
1339                is_error: true,
1340                output: None,
1341            }));
1342        };
1343
1344        let fs = self.project.read(cx).fs().clone();
1345        let tool_event_stream =
1346            ToolCallEventStream::new(tool_use.id.clone(), event_stream.clone(), Some(fs));
1347        tool_event_stream.update_fields(acp::ToolCallUpdateFields {
1348            status: Some(acp::ToolCallStatus::InProgress),
1349            ..Default::default()
1350        });
1351        let supports_images = self.model().map_or(false, |model| model.supports_images());
1352        let tool_result = tool.run(tool_use.input, tool_event_stream, cx);
1353        log::info!("Running tool {}", tool_use.name);
1354        Some(cx.foreground_executor().spawn(async move {
1355            let tool_result = tool_result.await.and_then(|output| {
1356                if let LanguageModelToolResultContent::Image(_) = &output.llm_output {
1357                    if !supports_images {
1358                        return Err(anyhow!(
1359                            "Attempted to read an image, but this model doesn't support it.",
1360                        ));
1361                    }
1362                }
1363                Ok(output)
1364            });
1365
1366            match tool_result {
1367                Ok(output) => LanguageModelToolResult {
1368                    tool_use_id: tool_use.id,
1369                    tool_name: tool_use.name,
1370                    is_error: false,
1371                    content: output.llm_output,
1372                    output: Some(output.raw_output),
1373                },
1374                Err(error) => LanguageModelToolResult {
1375                    tool_use_id: tool_use.id,
1376                    tool_name: tool_use.name,
1377                    is_error: true,
1378                    content: LanguageModelToolResultContent::Text(Arc::from(error.to_string())),
1379                    output: None,
1380                },
1381            }
1382        }))
1383    }
1384
1385    fn handle_tool_use_json_parse_error_event(
1386        &mut self,
1387        tool_use_id: LanguageModelToolUseId,
1388        tool_name: Arc<str>,
1389        raw_input: Arc<str>,
1390        json_parse_error: String,
1391    ) -> LanguageModelToolResult {
1392        let tool_output = format!("Error parsing input JSON: {json_parse_error}");
1393        LanguageModelToolResult {
1394            tool_use_id,
1395            tool_name,
1396            is_error: true,
1397            content: LanguageModelToolResultContent::Text(tool_output.into()),
1398            output: Some(serde_json::Value::String(raw_input.to_string())),
1399        }
1400    }
1401
1402    fn pending_message(&mut self) -> &mut AgentMessage {
1403        self.pending_message.get_or_insert_default()
1404    }
1405
1406    fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
1407        let Some(mut message) = self.pending_message.take() else {
1408            return;
1409        };
1410
1411        for content in &message.content {
1412            let AgentMessageContent::ToolUse(tool_use) = content else {
1413                continue;
1414            };
1415
1416            if !message.tool_results.contains_key(&tool_use.id) {
1417                message.tool_results.insert(
1418                    tool_use.id.clone(),
1419                    LanguageModelToolResult {
1420                        tool_use_id: tool_use.id.clone(),
1421                        tool_name: tool_use.name.clone(),
1422                        is_error: true,
1423                        content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
1424                        output: None,
1425                    },
1426                );
1427            }
1428        }
1429
1430        self.messages.push(Message::Agent(message));
1431        cx.notify()
1432    }
1433
1434    pub(crate) fn build_completion_request(
1435        &self,
1436        completion_intent: CompletionIntent,
1437        cx: &mut App,
1438    ) -> Result<LanguageModelRequest> {
1439        let model = self.model().context("No language model configured")?;
1440
1441        log::debug!("Building completion request");
1442        log::debug!("Completion intent: {:?}", completion_intent);
1443        log::debug!("Completion mode: {:?}", self.completion_mode);
1444
1445        let messages = self.build_request_messages();
1446        log::info!("Request will include {} messages", messages.len());
1447
1448        let tools = if let Some(tools) = self.tools(cx).log_err() {
1449            tools
1450                .filter_map(|tool| {
1451                    let tool_name = tool.name().to_string();
1452                    log::trace!("Including tool: {}", tool_name);
1453                    Some(LanguageModelRequestTool {
1454                        name: tool_name,
1455                        description: tool.description().to_string(),
1456                        input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
1457                    })
1458                })
1459                .collect()
1460        } else {
1461            Vec::new()
1462        };
1463
1464        log::info!("Request includes {} tools", tools.len());
1465
1466        let request = LanguageModelRequest {
1467            thread_id: Some(self.id.to_string()),
1468            prompt_id: Some(self.prompt_id.to_string()),
1469            intent: Some(completion_intent),
1470            mode: Some(self.completion_mode.into()),
1471            messages,
1472            tools,
1473            tool_choice: None,
1474            stop: Vec::new(),
1475            temperature: AgentSettings::temperature_for_model(&model, cx),
1476            thinking_allowed: true,
1477        };
1478
1479        log::debug!("Completion request built successfully");
1480        Ok(request)
1481    }
1482
1483    fn tools<'a>(&'a self, cx: &'a App) -> Result<impl Iterator<Item = &'a Arc<dyn AnyAgentTool>>> {
1484        let model = self.model().context("No language model configured")?;
1485
1486        let profile = AgentSettings::get_global(cx)
1487            .profiles
1488            .get(&self.profile_id)
1489            .context("profile not found")?;
1490        let provider_id = model.provider_id();
1491
1492        Ok(self
1493            .tools
1494            .iter()
1495            .filter(move |(_, tool)| tool.supported_provider(&provider_id))
1496            .filter_map(|(tool_name, tool)| {
1497                if profile.is_tool_enabled(tool_name) {
1498                    Some(tool)
1499                } else {
1500                    None
1501                }
1502            })
1503            .chain(self.context_server_registry.read(cx).servers().flat_map(
1504                |(server_id, tools)| {
1505                    tools.iter().filter_map(|(tool_name, tool)| {
1506                        if profile.is_context_server_tool_enabled(&server_id.0, tool_name) {
1507                            Some(tool)
1508                        } else {
1509                            None
1510                        }
1511                    })
1512                },
1513            )))
1514    }
1515
1516    fn build_request_messages(&self) -> Vec<LanguageModelRequestMessage> {
1517        log::trace!(
1518            "Building request messages from {} thread messages",
1519            self.messages.len()
1520        );
1521        let mut messages = vec![self.build_system_message()];
1522        for message in &self.messages {
1523            messages.extend(message.to_request());
1524        }
1525
1526        if let Some(message) = self.pending_message.as_ref() {
1527            messages.extend(message.to_request());
1528        }
1529
1530        if let Some(last_user_message) = messages
1531            .iter_mut()
1532            .rev()
1533            .find(|message| message.role == Role::User)
1534        {
1535            last_user_message.cache = true;
1536        }
1537
1538        messages
1539    }
1540
1541    pub fn to_markdown(&self) -> String {
1542        let mut markdown = String::new();
1543        for (ix, message) in self.messages.iter().enumerate() {
1544            if ix > 0 {
1545                markdown.push('\n');
1546            }
1547            markdown.push_str(&message.to_markdown());
1548        }
1549
1550        if let Some(message) = self.pending_message.as_ref() {
1551            markdown.push('\n');
1552            markdown.push_str(&message.to_markdown());
1553        }
1554
1555        markdown
1556    }
1557
1558    fn advance_prompt_id(&mut self) {
1559        self.prompt_id = PromptId::new();
1560    }
1561}
1562
1563struct RunningTurn {
1564    /// Holds the task that handles agent interaction until the end of the turn.
1565    /// Survives across multiple requests as the model performs tool calls and
1566    /// we run tools, report their results.
1567    _task: Task<()>,
1568    /// The current event stream for the running turn. Used to report a final
1569    /// cancellation event if we cancel the turn.
1570    event_stream: ThreadEventStream,
1571}
1572
1573impl RunningTurn {
1574    fn cancel(self) {
1575        log::debug!("Cancelling in progress turn");
1576        self.event_stream.send_canceled();
1577    }
1578}
1579
1580pub trait AgentTool
1581where
1582    Self: 'static + Sized,
1583{
1584    type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
1585    type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
1586
1587    fn name(&self) -> SharedString;
1588
1589    fn description(&self) -> SharedString {
1590        let schema = schemars::schema_for!(Self::Input);
1591        SharedString::new(
1592            schema
1593                .get("description")
1594                .and_then(|description| description.as_str())
1595                .unwrap_or_default(),
1596        )
1597    }
1598
1599    fn kind(&self) -> acp::ToolKind;
1600
1601    /// The initial tool title to display. Can be updated during the tool run.
1602    fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString;
1603
1604    /// Returns the JSON schema that describes the tool's input.
1605    fn input_schema(&self) -> Schema {
1606        schemars::schema_for!(Self::Input)
1607    }
1608
1609    /// Some tools rely on a provider for the underlying billing or other reasons.
1610    /// Allow the tool to check if they are compatible, or should be filtered out.
1611    fn supported_provider(&self, _provider: &LanguageModelProviderId) -> bool {
1612        true
1613    }
1614
1615    /// Runs the tool with the provided input.
1616    fn run(
1617        self: Arc<Self>,
1618        input: Self::Input,
1619        event_stream: ToolCallEventStream,
1620        cx: &mut App,
1621    ) -> Task<Result<Self::Output>>;
1622
1623    /// Emits events for a previous execution of the tool.
1624    fn replay(
1625        &self,
1626        _input: Self::Input,
1627        _output: Self::Output,
1628        _event_stream: ToolCallEventStream,
1629        _cx: &mut App,
1630    ) -> Result<()> {
1631        Ok(())
1632    }
1633
1634    fn erase(self) -> Arc<dyn AnyAgentTool> {
1635        Arc::new(Erased(Arc::new(self)))
1636    }
1637}
1638
1639pub struct Erased<T>(T);
1640
1641pub struct AgentToolOutput {
1642    pub llm_output: LanguageModelToolResultContent,
1643    pub raw_output: serde_json::Value,
1644}
1645
1646pub trait AnyAgentTool {
1647    fn name(&self) -> SharedString;
1648    fn description(&self) -> SharedString;
1649    fn kind(&self) -> acp::ToolKind;
1650    fn initial_title(&self, input: serde_json::Value) -> SharedString;
1651    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
1652    fn supported_provider(&self, _provider: &LanguageModelProviderId) -> bool {
1653        true
1654    }
1655    fn run(
1656        self: Arc<Self>,
1657        input: serde_json::Value,
1658        event_stream: ToolCallEventStream,
1659        cx: &mut App,
1660    ) -> Task<Result<AgentToolOutput>>;
1661    fn replay(
1662        &self,
1663        input: serde_json::Value,
1664        output: serde_json::Value,
1665        event_stream: ToolCallEventStream,
1666        cx: &mut App,
1667    ) -> Result<()>;
1668}
1669
1670impl<T> AnyAgentTool for Erased<Arc<T>>
1671where
1672    T: AgentTool,
1673{
1674    fn name(&self) -> SharedString {
1675        self.0.name()
1676    }
1677
1678    fn description(&self) -> SharedString {
1679        self.0.description()
1680    }
1681
1682    fn kind(&self) -> agent_client_protocol::ToolKind {
1683        self.0.kind()
1684    }
1685
1686    fn initial_title(&self, input: serde_json::Value) -> SharedString {
1687        let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
1688        self.0.initial_title(parsed_input)
1689    }
1690
1691    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
1692        let mut json = serde_json::to_value(self.0.input_schema())?;
1693        adapt_schema_to_format(&mut json, format)?;
1694        Ok(json)
1695    }
1696
1697    fn supported_provider(&self, provider: &LanguageModelProviderId) -> bool {
1698        self.0.supported_provider(provider)
1699    }
1700
1701    fn run(
1702        self: Arc<Self>,
1703        input: serde_json::Value,
1704        event_stream: ToolCallEventStream,
1705        cx: &mut App,
1706    ) -> Task<Result<AgentToolOutput>> {
1707        cx.spawn(async move |cx| {
1708            let input = serde_json::from_value(input)?;
1709            let output = cx
1710                .update(|cx| self.0.clone().run(input, event_stream, cx))?
1711                .await?;
1712            let raw_output = serde_json::to_value(&output)?;
1713            Ok(AgentToolOutput {
1714                llm_output: output.into(),
1715                raw_output,
1716            })
1717        })
1718    }
1719
1720    fn replay(
1721        &self,
1722        input: serde_json::Value,
1723        output: serde_json::Value,
1724        event_stream: ToolCallEventStream,
1725        cx: &mut App,
1726    ) -> Result<()> {
1727        let input = serde_json::from_value(input)?;
1728        let output = serde_json::from_value(output)?;
1729        self.0.replay(input, output, event_stream, cx)
1730    }
1731}
1732
1733#[derive(Clone)]
1734struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
1735
1736impl ThreadEventStream {
1737    fn send_user_message(&self, message: &UserMessage) {
1738        self.0
1739            .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
1740            .ok();
1741    }
1742
1743    fn send_text(&self, text: &str) {
1744        self.0
1745            .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
1746            .ok();
1747    }
1748
1749    fn send_thinking(&self, text: &str) {
1750        self.0
1751            .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
1752            .ok();
1753    }
1754
1755    fn send_tool_call(
1756        &self,
1757        id: &LanguageModelToolUseId,
1758        title: SharedString,
1759        kind: acp::ToolKind,
1760        input: serde_json::Value,
1761    ) {
1762        self.0
1763            .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
1764                id,
1765                title.to_string(),
1766                kind,
1767                input,
1768            ))))
1769            .ok();
1770    }
1771
1772    fn initial_tool_call(
1773        id: &LanguageModelToolUseId,
1774        title: String,
1775        kind: acp::ToolKind,
1776        input: serde_json::Value,
1777    ) -> acp::ToolCall {
1778        acp::ToolCall {
1779            id: acp::ToolCallId(id.to_string().into()),
1780            title,
1781            kind,
1782            status: acp::ToolCallStatus::Pending,
1783            content: vec![],
1784            locations: vec![],
1785            raw_input: Some(input),
1786            raw_output: None,
1787        }
1788    }
1789
1790    fn update_tool_call_fields(
1791        &self,
1792        tool_use_id: &LanguageModelToolUseId,
1793        fields: acp::ToolCallUpdateFields,
1794    ) {
1795        self.0
1796            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
1797                acp::ToolCallUpdate {
1798                    id: acp::ToolCallId(tool_use_id.to_string().into()),
1799                    fields,
1800                }
1801                .into(),
1802            )))
1803            .ok();
1804    }
1805
1806    fn send_stop(&self, reason: StopReason) {
1807        match reason {
1808            StopReason::EndTurn => {
1809                self.0
1810                    .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::EndTurn)))
1811                    .ok();
1812            }
1813            StopReason::MaxTokens => {
1814                self.0
1815                    .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::MaxTokens)))
1816                    .ok();
1817            }
1818            StopReason::Refusal => {
1819                self.0
1820                    .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Refusal)))
1821                    .ok();
1822            }
1823            StopReason::ToolUse => {}
1824        }
1825    }
1826
1827    fn send_canceled(&self) {
1828        self.0
1829            .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Canceled)))
1830            .ok();
1831    }
1832
1833    fn send_error(&self, error: impl Into<anyhow::Error>) {
1834        self.0.unbounded_send(Err(error.into())).ok();
1835    }
1836}
1837
1838#[derive(Clone)]
1839pub struct ToolCallEventStream {
1840    tool_use_id: LanguageModelToolUseId,
1841    stream: ThreadEventStream,
1842    fs: Option<Arc<dyn Fs>>,
1843}
1844
1845impl ToolCallEventStream {
1846    #[cfg(test)]
1847    pub fn test() -> (Self, ToolCallEventStreamReceiver) {
1848        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1849
1850        let stream = ToolCallEventStream::new("test_id".into(), ThreadEventStream(events_tx), None);
1851
1852        (stream, ToolCallEventStreamReceiver(events_rx))
1853    }
1854
1855    fn new(
1856        tool_use_id: LanguageModelToolUseId,
1857        stream: ThreadEventStream,
1858        fs: Option<Arc<dyn Fs>>,
1859    ) -> Self {
1860        Self {
1861            tool_use_id,
1862            stream,
1863            fs,
1864        }
1865    }
1866
1867    pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
1868        self.stream
1869            .update_tool_call_fields(&self.tool_use_id, fields);
1870    }
1871
1872    pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
1873        self.stream
1874            .0
1875            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
1876                acp_thread::ToolCallUpdateDiff {
1877                    id: acp::ToolCallId(self.tool_use_id.to_string().into()),
1878                    diff,
1879                }
1880                .into(),
1881            )))
1882            .ok();
1883    }
1884
1885    pub fn update_terminal(&self, terminal: Entity<acp_thread::Terminal>) {
1886        self.stream
1887            .0
1888            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
1889                acp_thread::ToolCallUpdateTerminal {
1890                    id: acp::ToolCallId(self.tool_use_id.to_string().into()),
1891                    terminal,
1892                }
1893                .into(),
1894            )))
1895            .ok();
1896    }
1897
1898    pub fn authorize(&self, title: impl Into<String>, cx: &mut App) -> Task<Result<()>> {
1899        if agent_settings::AgentSettings::get_global(cx).always_allow_tool_actions {
1900            return Task::ready(Ok(()));
1901        }
1902
1903        let (response_tx, response_rx) = oneshot::channel();
1904        self.stream
1905            .0
1906            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
1907                ToolCallAuthorization {
1908                    tool_call: acp::ToolCallUpdate {
1909                        id: acp::ToolCallId(self.tool_use_id.to_string().into()),
1910                        fields: acp::ToolCallUpdateFields {
1911                            title: Some(title.into()),
1912                            ..Default::default()
1913                        },
1914                    },
1915                    options: vec![
1916                        acp::PermissionOption {
1917                            id: acp::PermissionOptionId("always_allow".into()),
1918                            name: "Always Allow".into(),
1919                            kind: acp::PermissionOptionKind::AllowAlways,
1920                        },
1921                        acp::PermissionOption {
1922                            id: acp::PermissionOptionId("allow".into()),
1923                            name: "Allow".into(),
1924                            kind: acp::PermissionOptionKind::AllowOnce,
1925                        },
1926                        acp::PermissionOption {
1927                            id: acp::PermissionOptionId("deny".into()),
1928                            name: "Deny".into(),
1929                            kind: acp::PermissionOptionKind::RejectOnce,
1930                        },
1931                    ],
1932                    response: response_tx,
1933                },
1934            )))
1935            .ok();
1936        let fs = self.fs.clone();
1937        cx.spawn(async move |cx| match response_rx.await?.0.as_ref() {
1938            "always_allow" => {
1939                if let Some(fs) = fs.clone() {
1940                    cx.update(|cx| {
1941                        update_settings_file::<AgentSettings>(fs, cx, |settings, _| {
1942                            settings.set_always_allow_tool_actions(true);
1943                        });
1944                    })?;
1945                }
1946
1947                Ok(())
1948            }
1949            "allow" => Ok(()),
1950            _ => Err(anyhow!("Permission to run tool denied by user")),
1951        })
1952    }
1953}
1954
1955#[cfg(test)]
1956pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
1957
1958#[cfg(test)]
1959impl ToolCallEventStreamReceiver {
1960    pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
1961        let event = self.0.next().await;
1962        if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
1963            auth
1964        } else {
1965            panic!("Expected ToolCallAuthorization but got: {:?}", event);
1966        }
1967    }
1968
1969    pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
1970        let event = self.0.next().await;
1971        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
1972            update,
1973        )))) = event
1974        {
1975            update.terminal
1976        } else {
1977            panic!("Expected terminal but got: {:?}", event);
1978        }
1979    }
1980}
1981
1982#[cfg(test)]
1983impl std::ops::Deref for ToolCallEventStreamReceiver {
1984    type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
1985
1986    fn deref(&self) -> &Self::Target {
1987        &self.0
1988    }
1989}
1990
1991#[cfg(test)]
1992impl std::ops::DerefMut for ToolCallEventStreamReceiver {
1993    fn deref_mut(&mut self) -> &mut Self::Target {
1994        &mut self.0
1995    }
1996}
1997
1998impl From<&str> for UserMessageContent {
1999    fn from(text: &str) -> Self {
2000        Self::Text(text.into())
2001    }
2002}
2003
2004impl From<acp::ContentBlock> for UserMessageContent {
2005    fn from(value: acp::ContentBlock) -> Self {
2006        match value {
2007            acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
2008            acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
2009            acp::ContentBlock::Audio(_) => {
2010                // TODO
2011                Self::Text("[audio]".to_string())
2012            }
2013            acp::ContentBlock::ResourceLink(resource_link) => {
2014                match MentionUri::parse(&resource_link.uri) {
2015                    Ok(uri) => Self::Mention {
2016                        uri,
2017                        content: String::new(),
2018                    },
2019                    Err(err) => {
2020                        log::error!("Failed to parse mention link: {}", err);
2021                        Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
2022                    }
2023                }
2024            }
2025            acp::ContentBlock::Resource(resource) => match resource.resource {
2026                acp::EmbeddedResourceResource::TextResourceContents(resource) => {
2027                    match MentionUri::parse(&resource.uri) {
2028                        Ok(uri) => Self::Mention {
2029                            uri,
2030                            content: resource.text,
2031                        },
2032                        Err(err) => {
2033                            log::error!("Failed to parse mention link: {}", err);
2034                            Self::Text(
2035                                MarkdownCodeBlock {
2036                                    tag: &resource.uri,
2037                                    text: &resource.text,
2038                                }
2039                                .to_string(),
2040                            )
2041                        }
2042                    }
2043                }
2044                acp::EmbeddedResourceResource::BlobResourceContents(_) => {
2045                    // TODO
2046                    Self::Text("[blob]".to_string())
2047                }
2048            },
2049        }
2050    }
2051}
2052
2053impl From<UserMessageContent> for acp::ContentBlock {
2054    fn from(content: UserMessageContent) -> Self {
2055        match content {
2056            UserMessageContent::Text(text) => acp::ContentBlock::Text(acp::TextContent {
2057                text,
2058                annotations: None,
2059            }),
2060            UserMessageContent::Image(image) => acp::ContentBlock::Image(acp::ImageContent {
2061                data: image.source.to_string(),
2062                mime_type: "image/png".to_string(),
2063                annotations: None,
2064                uri: None,
2065            }),
2066            UserMessageContent::Mention { .. } => {
2067                todo!()
2068            }
2069        }
2070    }
2071}
2072
2073fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
2074    LanguageModelImage {
2075        source: image_content.data.into(),
2076        // TODO: make this optional?
2077        size: gpui::Size::new(0.into(), 0.into()),
2078    }
2079}