thread.rs

   1use crate::{
   2    ContextServerRegistry, CopyPathTool, CreateDirectoryTool, DbLanguageModel, DbThread,
   3    DeletePathTool, DiagnosticsTool, EditFileTool, FetchTool, FindPathTool, GrepTool,
   4    ListDirectoryTool, MovePathTool, NowTool, OpenTool, ProjectSnapshot, ReadFileTool,
   5    RestoreFileFromDiskTool, SaveFileTool, StreamingEditFileTool, SubagentTool,
   6    SystemPromptTemplate, Template, Templates, TerminalTool, ThinkingTool, ToolPermissionDecision,
   7    WebSearchTool, decide_permission_from_settings,
   8};
   9use acp_thread::{MentionUri, UserMessageId};
  10use action_log::ActionLog;
  11use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt as _, SubagentsFeatureFlag};
  12
  13use agent_client_protocol as acp;
  14use agent_settings::{
  15    AgentProfileId, AgentProfileSettings, AgentSettings, SUMMARIZE_THREAD_DETAILED_PROMPT,
  16    SUMMARIZE_THREAD_PROMPT,
  17};
  18use anyhow::{Context as _, Result, anyhow};
  19use chrono::{DateTime, Utc};
  20use client::UserStore;
  21use cloud_llm_client::{CompletionIntent, Plan};
  22use collections::{HashMap, HashSet, IndexMap};
  23use fs::Fs;
  24use futures::stream;
  25use futures::{
  26    FutureExt,
  27    channel::{mpsc, oneshot},
  28    future::Shared,
  29    stream::FuturesUnordered,
  30};
  31use gpui::{
  32    App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task, WeakEntity,
  33};
  34use language::Buffer;
  35use language_model::{
  36    LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelId,
  37    LanguageModelImage, LanguageModelProviderId, LanguageModelRegistry, LanguageModelRequest,
  38    LanguageModelRequestMessage, LanguageModelRequestTool, LanguageModelToolResult,
  39    LanguageModelToolResultContent, LanguageModelToolSchemaFormat, LanguageModelToolUse,
  40    LanguageModelToolUseId, Role, SelectedModel, StopReason, TokenUsage, ZED_CLOUD_PROVIDER_ID,
  41};
  42use project::Project;
  43use prompt_store::ProjectContext;
  44use schemars::{JsonSchema, Schema};
  45use serde::{Deserialize, Serialize};
  46use settings::{LanguageModelSelection, Settings, ToolPermissionMode, update_settings_file};
  47use smol::stream::StreamExt;
  48use std::{
  49    collections::BTreeMap,
  50    ops::RangeInclusive,
  51    path::Path,
  52    rc::Rc,
  53    sync::Arc,
  54    time::{Duration, Instant},
  55};
  56use std::{fmt::Write, path::PathBuf};
  57use util::{ResultExt, debug_panic, markdown::MarkdownCodeBlock, paths::PathStyle};
  58use uuid::Uuid;
  59
  60const TOOL_CANCELED_MESSAGE: &str = "Tool canceled by user";
  61pub const MAX_TOOL_NAME_LENGTH: usize = 64;
  62pub const MAX_SUBAGENT_DEPTH: u8 = 4;
  63pub const MAX_PARALLEL_SUBAGENTS: usize = 8;
  64
  65/// Context passed to a subagent thread for lifecycle management
  66#[derive(Clone)]
  67pub struct SubagentContext {
  68    /// ID of the parent thread
  69    pub parent_thread_id: acp::SessionId,
  70
  71    /// ID of the tool call that spawned this subagent
  72    pub tool_use_id: LanguageModelToolUseId,
  73
  74    /// Current depth level (0 = root agent, 1 = first-level subagent, etc.)
  75    pub depth: u8,
  76
  77    /// Prompt to send when subagent completes successfully
  78    pub summary_prompt: String,
  79
  80    /// Prompt to send when context is running low (≤25% remaining)
  81    pub context_low_prompt: String,
  82}
  83
  84/// The ID of the user prompt that initiated a request.
  85///
  86/// This equates to the user physically submitting a message to the model (e.g., by pressing the Enter key).
  87#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
  88pub struct PromptId(Arc<str>);
  89
  90impl PromptId {
  91    pub fn new() -> Self {
  92        Self(Uuid::new_v4().to_string().into())
  93    }
  94}
  95
  96impl std::fmt::Display for PromptId {
  97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  98        write!(f, "{}", self.0)
  99    }
 100}
 101
 102pub(crate) const MAX_RETRY_ATTEMPTS: u8 = 4;
 103pub(crate) const BASE_RETRY_DELAY: Duration = Duration::from_secs(5);
 104
 105#[derive(Debug, Clone)]
 106enum RetryStrategy {
 107    ExponentialBackoff {
 108        initial_delay: Duration,
 109        max_attempts: u8,
 110    },
 111    Fixed {
 112        delay: Duration,
 113        max_attempts: u8,
 114    },
 115}
 116
 117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 118pub enum Message {
 119    User(UserMessage),
 120    Agent(AgentMessage),
 121    Resume,
 122}
 123
 124impl Message {
 125    pub fn as_agent_message(&self) -> Option<&AgentMessage> {
 126        match self {
 127            Message::Agent(agent_message) => Some(agent_message),
 128            _ => None,
 129        }
 130    }
 131
 132    pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
 133        match self {
 134            Message::User(message) => {
 135                if message.content.is_empty() {
 136                    vec![]
 137                } else {
 138                    vec![message.to_request()]
 139                }
 140            }
 141            Message::Agent(message) => message.to_request(),
 142            Message::Resume => vec![LanguageModelRequestMessage {
 143                role: Role::User,
 144                content: vec!["Continue where you left off".into()],
 145                cache: false,
 146                reasoning_details: None,
 147            }],
 148        }
 149    }
 150
 151    pub fn to_markdown(&self) -> String {
 152        match self {
 153            Message::User(message) => message.to_markdown(),
 154            Message::Agent(message) => message.to_markdown(),
 155            Message::Resume => "[resume]\n".into(),
 156        }
 157    }
 158
 159    pub fn role(&self) -> Role {
 160        match self {
 161            Message::User(_) | Message::Resume => Role::User,
 162            Message::Agent(_) => Role::Assistant,
 163        }
 164    }
 165}
 166
 167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 168pub struct UserMessage {
 169    pub id: UserMessageId,
 170    pub content: Vec<UserMessageContent>,
 171}
 172
 173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 174pub enum UserMessageContent {
 175    Text(String),
 176    Mention { uri: MentionUri, content: String },
 177    Image(LanguageModelImage),
 178}
 179
 180impl UserMessage {
 181    pub fn to_markdown(&self) -> String {
 182        let mut markdown = String::from("## User\n\n");
 183
 184        for content in &self.content {
 185            match content {
 186                UserMessageContent::Text(text) => {
 187                    markdown.push_str(text);
 188                    markdown.push('\n');
 189                }
 190                UserMessageContent::Image(_) => {
 191                    markdown.push_str("<image />\n");
 192                }
 193                UserMessageContent::Mention { uri, content } => {
 194                    if !content.is_empty() {
 195                        let _ = writeln!(&mut markdown, "{}\n\n{}", uri.as_link(), content);
 196                    } else {
 197                        let _ = writeln!(&mut markdown, "{}", uri.as_link());
 198                    }
 199                }
 200            }
 201        }
 202
 203        markdown
 204    }
 205
 206    fn to_request(&self) -> LanguageModelRequestMessage {
 207        let mut message = LanguageModelRequestMessage {
 208            role: Role::User,
 209            content: Vec::with_capacity(self.content.len()),
 210            cache: false,
 211            reasoning_details: None,
 212        };
 213
 214        const OPEN_CONTEXT: &str = "<context>\n\
 215            The following items were attached by the user. \
 216            They are up-to-date and don't need to be re-read.\n\n";
 217
 218        const OPEN_FILES_TAG: &str = "<files>";
 219        const OPEN_DIRECTORIES_TAG: &str = "<directories>";
 220        const OPEN_SYMBOLS_TAG: &str = "<symbols>";
 221        const OPEN_SELECTIONS_TAG: &str = "<selections>";
 222        const OPEN_THREADS_TAG: &str = "<threads>";
 223        const OPEN_FETCH_TAG: &str = "<fetched_urls>";
 224        const OPEN_RULES_TAG: &str =
 225            "<rules>\nThe user has specified the following rules that should be applied:\n";
 226        const OPEN_DIAGNOSTICS_TAG: &str = "<diagnostics>";
 227
 228        let mut file_context = OPEN_FILES_TAG.to_string();
 229        let mut directory_context = OPEN_DIRECTORIES_TAG.to_string();
 230        let mut symbol_context = OPEN_SYMBOLS_TAG.to_string();
 231        let mut selection_context = OPEN_SELECTIONS_TAG.to_string();
 232        let mut thread_context = OPEN_THREADS_TAG.to_string();
 233        let mut fetch_context = OPEN_FETCH_TAG.to_string();
 234        let mut rules_context = OPEN_RULES_TAG.to_string();
 235        let mut diagnostics_context = OPEN_DIAGNOSTICS_TAG.to_string();
 236
 237        for chunk in &self.content {
 238            let chunk = match chunk {
 239                UserMessageContent::Text(text) => {
 240                    language_model::MessageContent::Text(text.clone())
 241                }
 242                UserMessageContent::Image(value) => {
 243                    language_model::MessageContent::Image(value.clone())
 244                }
 245                UserMessageContent::Mention { uri, content } => {
 246                    match uri {
 247                        MentionUri::File { abs_path } => {
 248                            write!(
 249                                &mut file_context,
 250                                "\n{}",
 251                                MarkdownCodeBlock {
 252                                    tag: &codeblock_tag(abs_path, None),
 253                                    text: &content.to_string(),
 254                                }
 255                            )
 256                            .ok();
 257                        }
 258                        MentionUri::PastedImage => {
 259                            debug_panic!("pasted image URI should not be used in mention content")
 260                        }
 261                        MentionUri::Directory { .. } => {
 262                            write!(&mut directory_context, "\n{}\n", content).ok();
 263                        }
 264                        MentionUri::Symbol {
 265                            abs_path: path,
 266                            line_range,
 267                            ..
 268                        } => {
 269                            write!(
 270                                &mut symbol_context,
 271                                "\n{}",
 272                                MarkdownCodeBlock {
 273                                    tag: &codeblock_tag(path, Some(line_range)),
 274                                    text: content
 275                                }
 276                            )
 277                            .ok();
 278                        }
 279                        MentionUri::Selection {
 280                            abs_path: path,
 281                            line_range,
 282                            ..
 283                        } => {
 284                            write!(
 285                                &mut selection_context,
 286                                "\n{}",
 287                                MarkdownCodeBlock {
 288                                    tag: &codeblock_tag(
 289                                        path.as_deref().unwrap_or("Untitled".as_ref()),
 290                                        Some(line_range)
 291                                    ),
 292                                    text: content
 293                                }
 294                            )
 295                            .ok();
 296                        }
 297                        MentionUri::Thread { .. } => {
 298                            write!(&mut thread_context, "\n{}\n", content).ok();
 299                        }
 300                        MentionUri::TextThread { .. } => {
 301                            write!(&mut thread_context, "\n{}\n", content).ok();
 302                        }
 303                        MentionUri::Rule { .. } => {
 304                            write!(
 305                                &mut rules_context,
 306                                "\n{}",
 307                                MarkdownCodeBlock {
 308                                    tag: "",
 309                                    text: content
 310                                }
 311                            )
 312                            .ok();
 313                        }
 314                        MentionUri::Fetch { url } => {
 315                            write!(&mut fetch_context, "\nFetch: {}\n\n{}", url, content).ok();
 316                        }
 317                        MentionUri::Diagnostics { .. } => {
 318                            write!(&mut diagnostics_context, "\n{}\n", content).ok();
 319                        }
 320                    }
 321
 322                    language_model::MessageContent::Text(uri.as_link().to_string())
 323                }
 324            };
 325
 326            message.content.push(chunk);
 327        }
 328
 329        let len_before_context = message.content.len();
 330
 331        if file_context.len() > OPEN_FILES_TAG.len() {
 332            file_context.push_str("</files>\n");
 333            message
 334                .content
 335                .push(language_model::MessageContent::Text(file_context));
 336        }
 337
 338        if directory_context.len() > OPEN_DIRECTORIES_TAG.len() {
 339            directory_context.push_str("</directories>\n");
 340            message
 341                .content
 342                .push(language_model::MessageContent::Text(directory_context));
 343        }
 344
 345        if symbol_context.len() > OPEN_SYMBOLS_TAG.len() {
 346            symbol_context.push_str("</symbols>\n");
 347            message
 348                .content
 349                .push(language_model::MessageContent::Text(symbol_context));
 350        }
 351
 352        if selection_context.len() > OPEN_SELECTIONS_TAG.len() {
 353            selection_context.push_str("</selections>\n");
 354            message
 355                .content
 356                .push(language_model::MessageContent::Text(selection_context));
 357        }
 358
 359        if thread_context.len() > OPEN_THREADS_TAG.len() {
 360            thread_context.push_str("</threads>\n");
 361            message
 362                .content
 363                .push(language_model::MessageContent::Text(thread_context));
 364        }
 365
 366        if fetch_context.len() > OPEN_FETCH_TAG.len() {
 367            fetch_context.push_str("</fetched_urls>\n");
 368            message
 369                .content
 370                .push(language_model::MessageContent::Text(fetch_context));
 371        }
 372
 373        if rules_context.len() > OPEN_RULES_TAG.len() {
 374            rules_context.push_str("</user_rules>\n");
 375            message
 376                .content
 377                .push(language_model::MessageContent::Text(rules_context));
 378        }
 379
 380        if diagnostics_context.len() > OPEN_DIAGNOSTICS_TAG.len() {
 381            diagnostics_context.push_str("</diagnostics>\n");
 382            message
 383                .content
 384                .push(language_model::MessageContent::Text(diagnostics_context));
 385        }
 386
 387        if message.content.len() > len_before_context {
 388            message.content.insert(
 389                len_before_context,
 390                language_model::MessageContent::Text(OPEN_CONTEXT.into()),
 391            );
 392            message
 393                .content
 394                .push(language_model::MessageContent::Text("</context>".into()));
 395        }
 396
 397        message
 398    }
 399}
 400
 401fn codeblock_tag(full_path: &Path, line_range: Option<&RangeInclusive<u32>>) -> String {
 402    let mut result = String::new();
 403
 404    if let Some(extension) = full_path.extension().and_then(|ext| ext.to_str()) {
 405        let _ = write!(result, "{} ", extension);
 406    }
 407
 408    let _ = write!(result, "{}", full_path.display());
 409
 410    if let Some(range) = line_range {
 411        if range.start() == range.end() {
 412            let _ = write!(result, ":{}", range.start() + 1);
 413        } else {
 414            let _ = write!(result, ":{}-{}", range.start() + 1, range.end() + 1);
 415        }
 416    }
 417
 418    result
 419}
 420
 421impl AgentMessage {
 422    pub fn to_markdown(&self) -> String {
 423        let mut markdown = String::from("## Assistant\n\n");
 424
 425        for content in &self.content {
 426            match content {
 427                AgentMessageContent::Text(text) => {
 428                    markdown.push_str(text);
 429                    markdown.push('\n');
 430                }
 431                AgentMessageContent::Thinking { text, .. } => {
 432                    markdown.push_str("<think>");
 433                    markdown.push_str(text);
 434                    markdown.push_str("</think>\n");
 435                }
 436                AgentMessageContent::RedactedThinking(_) => {
 437                    markdown.push_str("<redacted_thinking />\n")
 438                }
 439                AgentMessageContent::ToolUse(tool_use) => {
 440                    markdown.push_str(&format!(
 441                        "**Tool Use**: {} (ID: {})\n",
 442                        tool_use.name, tool_use.id
 443                    ));
 444                    markdown.push_str(&format!(
 445                        "{}\n",
 446                        MarkdownCodeBlock {
 447                            tag: "json",
 448                            text: &format!("{:#}", tool_use.input)
 449                        }
 450                    ));
 451                }
 452            }
 453        }
 454
 455        for tool_result in self.tool_results.values() {
 456            markdown.push_str(&format!(
 457                "**Tool Result**: {} (ID: {})\n\n",
 458                tool_result.tool_name, tool_result.tool_use_id
 459            ));
 460            if tool_result.is_error {
 461                markdown.push_str("**ERROR:**\n");
 462            }
 463
 464            match &tool_result.content {
 465                LanguageModelToolResultContent::Text(text) => {
 466                    writeln!(markdown, "{text}\n").ok();
 467                }
 468                LanguageModelToolResultContent::Image(_) => {
 469                    writeln!(markdown, "<image />\n").ok();
 470                }
 471            }
 472
 473            if let Some(output) = tool_result.output.as_ref() {
 474                writeln!(
 475                    markdown,
 476                    "**Debug Output**:\n\n```json\n{}\n```\n",
 477                    serde_json::to_string_pretty(output).unwrap()
 478                )
 479                .unwrap();
 480            }
 481        }
 482
 483        markdown
 484    }
 485
 486    pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
 487        let mut assistant_message = LanguageModelRequestMessage {
 488            role: Role::Assistant,
 489            content: Vec::with_capacity(self.content.len()),
 490            cache: false,
 491            reasoning_details: self.reasoning_details.clone(),
 492        };
 493        for chunk in &self.content {
 494            match chunk {
 495                AgentMessageContent::Text(text) => {
 496                    assistant_message
 497                        .content
 498                        .push(language_model::MessageContent::Text(text.clone()));
 499                }
 500                AgentMessageContent::Thinking { text, signature } => {
 501                    assistant_message
 502                        .content
 503                        .push(language_model::MessageContent::Thinking {
 504                            text: text.clone(),
 505                            signature: signature.clone(),
 506                        });
 507                }
 508                AgentMessageContent::RedactedThinking(value) => {
 509                    assistant_message.content.push(
 510                        language_model::MessageContent::RedactedThinking(value.clone()),
 511                    );
 512                }
 513                AgentMessageContent::ToolUse(tool_use) => {
 514                    if self.tool_results.contains_key(&tool_use.id) {
 515                        assistant_message
 516                            .content
 517                            .push(language_model::MessageContent::ToolUse(tool_use.clone()));
 518                    }
 519                }
 520            };
 521        }
 522
 523        let mut user_message = LanguageModelRequestMessage {
 524            role: Role::User,
 525            content: Vec::new(),
 526            cache: false,
 527            reasoning_details: None,
 528        };
 529
 530        for tool_result in self.tool_results.values() {
 531            let mut tool_result = tool_result.clone();
 532            // Surprisingly, the API fails if we return an empty string here.
 533            // It thinks we are sending a tool use without a tool result.
 534            if tool_result.content.is_empty() {
 535                tool_result.content = "<Tool returned an empty string>".into();
 536            }
 537            user_message
 538                .content
 539                .push(language_model::MessageContent::ToolResult(tool_result));
 540        }
 541
 542        let mut messages = Vec::new();
 543        if !assistant_message.content.is_empty() {
 544            messages.push(assistant_message);
 545        }
 546        if !user_message.content.is_empty() {
 547            messages.push(user_message);
 548        }
 549        messages
 550    }
 551}
 552
 553#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 554pub struct AgentMessage {
 555    pub content: Vec<AgentMessageContent>,
 556    pub tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
 557    pub reasoning_details: Option<serde_json::Value>,
 558}
 559
 560#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 561pub enum AgentMessageContent {
 562    Text(String),
 563    Thinking {
 564        text: String,
 565        signature: Option<String>,
 566    },
 567    RedactedThinking(String),
 568    ToolUse(LanguageModelToolUse),
 569}
 570
 571pub trait TerminalHandle {
 572    fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId>;
 573    fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse>;
 574    fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>>;
 575    fn kill(&self, cx: &AsyncApp) -> Result<()>;
 576    fn was_stopped_by_user(&self, cx: &AsyncApp) -> Result<bool>;
 577}
 578
 579pub trait ThreadEnvironment {
 580    fn create_terminal(
 581        &self,
 582        command: String,
 583        cwd: Option<PathBuf>,
 584        output_byte_limit: Option<u64>,
 585        cx: &mut AsyncApp,
 586    ) -> Task<Result<Rc<dyn TerminalHandle>>>;
 587}
 588
 589#[derive(Debug)]
 590pub enum ThreadEvent {
 591    UserMessage(UserMessage),
 592    AgentText(String),
 593    AgentThinking(String),
 594    ToolCall(acp::ToolCall),
 595    ToolCallUpdate(acp_thread::ToolCallUpdate),
 596    ToolCallAuthorization(ToolCallAuthorization),
 597    Retry(acp_thread::RetryStatus),
 598    Stop(acp::StopReason),
 599}
 600
 601#[derive(Debug)]
 602pub struct NewTerminal {
 603    pub command: String,
 604    pub output_byte_limit: Option<u64>,
 605    pub cwd: Option<PathBuf>,
 606    pub response: oneshot::Sender<Result<Entity<acp_thread::Terminal>>>,
 607}
 608
 609#[derive(Debug, Clone)]
 610pub struct ToolPermissionContext {
 611    pub tool_name: String,
 612    pub input_value: String,
 613}
 614
 615impl ToolPermissionContext {
 616    pub fn new(tool_name: impl Into<String>, input_value: impl Into<String>) -> Self {
 617        Self {
 618            tool_name: tool_name.into(),
 619            input_value: input_value.into(),
 620        }
 621    }
 622
 623    /// Builds the permission options for this tool context.
 624    ///
 625    /// This is the canonical source for permission option generation.
 626    /// Tests should use this function rather than manually constructing options.
 627    pub fn build_permission_options(&self) -> acp_thread::PermissionOptions {
 628        use crate::pattern_extraction::*;
 629
 630        let tool_name = &self.tool_name;
 631        let input_value = &self.input_value;
 632
 633        let (pattern, pattern_display) = match tool_name.as_str() {
 634            "terminal" => (
 635                extract_terminal_pattern(input_value),
 636                extract_terminal_pattern_display(input_value),
 637            ),
 638            "edit_file" | "delete_path" | "move_path" | "create_directory" | "save_file" => (
 639                extract_path_pattern(input_value),
 640                extract_path_pattern_display(input_value),
 641            ),
 642            "fetch" => (
 643                extract_url_pattern(input_value),
 644                extract_url_pattern_display(input_value),
 645            ),
 646            _ => (None, None),
 647        };
 648
 649        let mut choices = Vec::new();
 650
 651        let mut push_choice = |label: String, allow_id, deny_id, allow_kind, deny_kind| {
 652            choices.push(acp_thread::PermissionOptionChoice {
 653                allow: acp::PermissionOption::new(
 654                    acp::PermissionOptionId::new(allow_id),
 655                    label.clone(),
 656                    allow_kind,
 657                ),
 658                deny: acp::PermissionOption::new(
 659                    acp::PermissionOptionId::new(deny_id),
 660                    label,
 661                    deny_kind,
 662                ),
 663            });
 664        };
 665
 666        push_choice(
 667            format!("Always for {}", tool_name.replace('_', " ")),
 668            format!("always_allow:{}", tool_name),
 669            format!("always_deny:{}", tool_name),
 670            acp::PermissionOptionKind::AllowAlways,
 671            acp::PermissionOptionKind::RejectAlways,
 672        );
 673
 674        if let (Some(pattern), Some(display)) = (pattern, pattern_display) {
 675            let button_text = match tool_name.as_str() {
 676                "terminal" => format!("Always for `{}` commands", display),
 677                "fetch" => format!("Always for `{}`", display),
 678                _ => format!("Always for `{}`", display),
 679            };
 680            push_choice(
 681                button_text,
 682                format!("always_allow_pattern:{}:{}", tool_name, pattern),
 683                format!("always_deny_pattern:{}:{}", tool_name, pattern),
 684                acp::PermissionOptionKind::AllowAlways,
 685                acp::PermissionOptionKind::RejectAlways,
 686            );
 687        }
 688
 689        push_choice(
 690            "Only this time".to_string(),
 691            "allow".to_string(),
 692            "deny".to_string(),
 693            acp::PermissionOptionKind::AllowOnce,
 694            acp::PermissionOptionKind::RejectOnce,
 695        );
 696
 697        acp_thread::PermissionOptions::Dropdown(choices)
 698    }
 699}
 700
 701#[derive(Debug)]
 702pub struct ToolCallAuthorization {
 703    pub tool_call: acp::ToolCallUpdate,
 704    pub options: acp_thread::PermissionOptions,
 705    pub response: oneshot::Sender<acp::PermissionOptionId>,
 706    pub context: Option<ToolPermissionContext>,
 707}
 708
 709#[derive(Debug, thiserror::Error)]
 710enum CompletionError {
 711    #[error("max tokens")]
 712    MaxTokens,
 713    #[error("refusal")]
 714    Refusal,
 715    #[error(transparent)]
 716    Other(#[from] anyhow::Error),
 717}
 718
 719pub struct QueuedMessage {
 720    pub content: Vec<acp::ContentBlock>,
 721    pub tracked_buffers: Vec<Entity<Buffer>>,
 722}
 723
 724pub struct Thread {
 725    id: acp::SessionId,
 726    prompt_id: PromptId,
 727    updated_at: DateTime<Utc>,
 728    title: Option<SharedString>,
 729    pending_title_generation: Option<Task<()>>,
 730    pending_summary_generation: Option<Shared<Task<Option<SharedString>>>>,
 731    summary: Option<SharedString>,
 732    messages: Vec<Message>,
 733    user_store: Entity<UserStore>,
 734    /// Holds the task that handles agent interaction until the end of the turn.
 735    /// Survives across multiple requests as the model performs tool calls and
 736    /// we run tools, report their results.
 737    running_turn: Option<RunningTurn>,
 738    queued_messages: Vec<QueuedMessage>,
 739    pending_message: Option<AgentMessage>,
 740    tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
 741    request_token_usage: HashMap<UserMessageId, language_model::TokenUsage>,
 742    #[allow(unused)]
 743    cumulative_token_usage: TokenUsage,
 744    #[allow(unused)]
 745    initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
 746    context_server_registry: Entity<ContextServerRegistry>,
 747    profile_id: AgentProfileId,
 748    project_context: Entity<ProjectContext>,
 749    templates: Arc<Templates>,
 750    model: Option<Arc<dyn LanguageModel>>,
 751    summarization_model: Option<Arc<dyn LanguageModel>>,
 752    prompt_capabilities_tx: watch::Sender<acp::PromptCapabilities>,
 753    pub(crate) prompt_capabilities_rx: watch::Receiver<acp::PromptCapabilities>,
 754    pub(crate) project: Entity<Project>,
 755    pub(crate) action_log: Entity<ActionLog>,
 756    /// Tracks the last time files were read by the agent, to detect external modifications
 757    pub(crate) file_read_times: HashMap<PathBuf, fs::MTime>,
 758    /// True if this thread was imported from a shared thread and can be synced.
 759    imported: bool,
 760    /// If this is a subagent thread, contains context about the parent
 761    subagent_context: Option<SubagentContext>,
 762    /// Weak references to running subagent threads for cancellation propagation
 763    running_subagents: Vec<WeakEntity<Thread>>,
 764}
 765
 766impl Thread {
 767    fn prompt_capabilities(model: Option<&dyn LanguageModel>) -> acp::PromptCapabilities {
 768        let image = model.map_or(true, |model| model.supports_images());
 769        acp::PromptCapabilities::new()
 770            .image(image)
 771            .embedded_context(true)
 772    }
 773
 774    pub fn new(
 775        project: Entity<Project>,
 776        project_context: Entity<ProjectContext>,
 777        context_server_registry: Entity<ContextServerRegistry>,
 778        templates: Arc<Templates>,
 779        model: Option<Arc<dyn LanguageModel>>,
 780        cx: &mut Context<Self>,
 781    ) -> Self {
 782        let profile_id = AgentSettings::get_global(cx).default_profile.clone();
 783        let action_log = cx.new(|_cx| ActionLog::new(project.clone()));
 784        let (prompt_capabilities_tx, prompt_capabilities_rx) =
 785            watch::channel(Self::prompt_capabilities(model.as_deref()));
 786        Self {
 787            id: acp::SessionId::new(uuid::Uuid::new_v4().to_string()),
 788            prompt_id: PromptId::new(),
 789            updated_at: Utc::now(),
 790            title: None,
 791            pending_title_generation: None,
 792            pending_summary_generation: None,
 793            summary: None,
 794            messages: Vec::new(),
 795            user_store: project.read(cx).user_store(),
 796            running_turn: None,
 797            queued_messages: Vec::new(),
 798            pending_message: None,
 799            tools: BTreeMap::default(),
 800            request_token_usage: HashMap::default(),
 801            cumulative_token_usage: TokenUsage::default(),
 802            initial_project_snapshot: {
 803                let project_snapshot = Self::project_snapshot(project.clone(), cx);
 804                cx.foreground_executor()
 805                    .spawn(async move { Some(project_snapshot.await) })
 806                    .shared()
 807            },
 808            context_server_registry,
 809            profile_id,
 810            project_context,
 811            templates,
 812            model,
 813            summarization_model: None,
 814            prompt_capabilities_tx,
 815            prompt_capabilities_rx,
 816            project,
 817            action_log,
 818            file_read_times: HashMap::default(),
 819            imported: false,
 820            subagent_context: None,
 821            running_subagents: Vec::new(),
 822        }
 823    }
 824
 825    pub fn new_subagent(
 826        project: Entity<Project>,
 827        project_context: Entity<ProjectContext>,
 828        context_server_registry: Entity<ContextServerRegistry>,
 829        templates: Arc<Templates>,
 830        model: Arc<dyn LanguageModel>,
 831        subagent_context: SubagentContext,
 832        parent_tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
 833        cx: &mut Context<Self>,
 834    ) -> Self {
 835        let profile_id = AgentSettings::get_global(cx).default_profile.clone();
 836        let action_log = cx.new(|_cx| ActionLog::new(project.clone()));
 837        let (prompt_capabilities_tx, prompt_capabilities_rx) =
 838            watch::channel(Self::prompt_capabilities(Some(model.as_ref())));
 839
 840        // Rebind tools that hold thread references to use this subagent's thread
 841        // instead of the parent's thread. This is critical for tools like EditFileTool
 842        // that make model requests using the thread's ID.
 843        let weak_self = cx.weak_entity();
 844        let tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>> = parent_tools
 845            .into_iter()
 846            .map(|(name, tool)| {
 847                let rebound = tool.rebind_thread(weak_self.clone()).unwrap_or(tool);
 848                (name, rebound)
 849            })
 850            .collect();
 851
 852        Self {
 853            id: acp::SessionId::new(uuid::Uuid::new_v4().to_string()),
 854            prompt_id: PromptId::new(),
 855            updated_at: Utc::now(),
 856            title: None,
 857            pending_title_generation: None,
 858            pending_summary_generation: None,
 859            summary: None,
 860            messages: Vec::new(),
 861            user_store: project.read(cx).user_store(),
 862            running_turn: None,
 863            queued_messages: Vec::new(),
 864            pending_message: None,
 865            tools,
 866            request_token_usage: HashMap::default(),
 867            cumulative_token_usage: TokenUsage::default(),
 868            initial_project_snapshot: Task::ready(None).shared(),
 869            context_server_registry,
 870            profile_id,
 871            project_context,
 872            templates,
 873            model: Some(model),
 874            summarization_model: None,
 875            prompt_capabilities_tx,
 876            prompt_capabilities_rx,
 877            project,
 878            action_log,
 879            file_read_times: HashMap::default(),
 880            imported: false,
 881            subagent_context: Some(subagent_context),
 882            running_subagents: Vec::new(),
 883        }
 884    }
 885
 886    pub fn id(&self) -> &acp::SessionId {
 887        &self.id
 888    }
 889
 890    /// Returns true if this thread was imported from a shared thread.
 891    pub fn is_imported(&self) -> bool {
 892        self.imported
 893    }
 894
 895    pub fn replay(
 896        &mut self,
 897        cx: &mut Context<Self>,
 898    ) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {
 899        let (tx, rx) = mpsc::unbounded();
 900        let stream = ThreadEventStream(tx);
 901        for message in &self.messages {
 902            match message {
 903                Message::User(user_message) => stream.send_user_message(user_message),
 904                Message::Agent(assistant_message) => {
 905                    for content in &assistant_message.content {
 906                        match content {
 907                            AgentMessageContent::Text(text) => stream.send_text(text),
 908                            AgentMessageContent::Thinking { text, .. } => {
 909                                stream.send_thinking(text)
 910                            }
 911                            AgentMessageContent::RedactedThinking(_) => {}
 912                            AgentMessageContent::ToolUse(tool_use) => {
 913                                self.replay_tool_call(
 914                                    tool_use,
 915                                    assistant_message.tool_results.get(&tool_use.id),
 916                                    &stream,
 917                                    cx,
 918                                );
 919                            }
 920                        }
 921                    }
 922                }
 923                Message::Resume => {}
 924            }
 925        }
 926        rx
 927    }
 928
 929    fn replay_tool_call(
 930        &self,
 931        tool_use: &LanguageModelToolUse,
 932        tool_result: Option<&LanguageModelToolResult>,
 933        stream: &ThreadEventStream,
 934        cx: &mut Context<Self>,
 935    ) {
 936        let tool = self.tools.get(tool_use.name.as_ref()).cloned().or_else(|| {
 937            self.context_server_registry
 938                .read(cx)
 939                .servers()
 940                .find_map(|(_, tools)| {
 941                    if let Some(tool) = tools.get(tool_use.name.as_ref()) {
 942                        Some(tool.clone())
 943                    } else {
 944                        None
 945                    }
 946                })
 947        });
 948
 949        let Some(tool) = tool else {
 950            stream
 951                .0
 952                .unbounded_send(Ok(ThreadEvent::ToolCall(
 953                    acp::ToolCall::new(tool_use.id.to_string(), tool_use.name.to_string())
 954                        .status(acp::ToolCallStatus::Failed)
 955                        .raw_input(tool_use.input.clone()),
 956                )))
 957                .ok();
 958            return;
 959        };
 960
 961        let title = tool.initial_title(tool_use.input.clone(), cx);
 962        let kind = tool.kind();
 963        stream.send_tool_call(
 964            &tool_use.id,
 965            &tool_use.name,
 966            title,
 967            kind,
 968            tool_use.input.clone(),
 969        );
 970
 971        let output = tool_result
 972            .as_ref()
 973            .and_then(|result| result.output.clone());
 974        if let Some(output) = output.clone() {
 975            // For replay, we use a dummy cancellation receiver since the tool already completed
 976            let (_cancellation_tx, cancellation_rx) = watch::channel(false);
 977            let tool_event_stream = ToolCallEventStream::new(
 978                tool_use.id.clone(),
 979                stream.clone(),
 980                Some(self.project.read(cx).fs().clone()),
 981                cancellation_rx,
 982            );
 983            tool.replay(tool_use.input.clone(), output, tool_event_stream, cx)
 984                .log_err();
 985        }
 986
 987        stream.update_tool_call_fields(
 988            &tool_use.id,
 989            acp::ToolCallUpdateFields::new()
 990                .status(
 991                    tool_result
 992                        .as_ref()
 993                        .map_or(acp::ToolCallStatus::Failed, |result| {
 994                            if result.is_error {
 995                                acp::ToolCallStatus::Failed
 996                            } else {
 997                                acp::ToolCallStatus::Completed
 998                            }
 999                        }),
1000                )
1001                .raw_output(output),
1002        );
1003    }
1004
1005    pub fn from_db(
1006        id: acp::SessionId,
1007        db_thread: DbThread,
1008        project: Entity<Project>,
1009        project_context: Entity<ProjectContext>,
1010        context_server_registry: Entity<ContextServerRegistry>,
1011        templates: Arc<Templates>,
1012        cx: &mut Context<Self>,
1013    ) -> Self {
1014        let profile_id = db_thread
1015            .profile
1016            .unwrap_or_else(|| AgentSettings::get_global(cx).default_profile.clone());
1017
1018        let mut model = LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1019            db_thread
1020                .model
1021                .and_then(|model| {
1022                    let model = SelectedModel {
1023                        provider: model.provider.clone().into(),
1024                        model: model.model.into(),
1025                    };
1026                    registry.select_model(&model, cx)
1027                })
1028                .or_else(|| registry.default_model())
1029                .map(|model| model.model)
1030        });
1031
1032        if model.is_none() {
1033            model = Self::resolve_profile_model(&profile_id, cx);
1034        }
1035        if model.is_none() {
1036            model = LanguageModelRegistry::global(cx).update(cx, |registry, _cx| {
1037                registry.default_model().map(|model| model.model)
1038            });
1039        }
1040
1041        let (prompt_capabilities_tx, prompt_capabilities_rx) =
1042            watch::channel(Self::prompt_capabilities(model.as_deref()));
1043
1044        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1045
1046        Self {
1047            id,
1048            prompt_id: PromptId::new(),
1049            title: if db_thread.title.is_empty() {
1050                None
1051            } else {
1052                Some(db_thread.title.clone())
1053            },
1054            pending_title_generation: None,
1055            pending_summary_generation: None,
1056            summary: db_thread.detailed_summary,
1057            messages: db_thread.messages,
1058            user_store: project.read(cx).user_store(),
1059            running_turn: None,
1060            queued_messages: Vec::new(),
1061            pending_message: None,
1062            tools: BTreeMap::default(),
1063            request_token_usage: db_thread.request_token_usage.clone(),
1064            cumulative_token_usage: db_thread.cumulative_token_usage,
1065            initial_project_snapshot: Task::ready(db_thread.initial_project_snapshot).shared(),
1066            context_server_registry,
1067            profile_id,
1068            project_context,
1069            templates,
1070            model,
1071            summarization_model: None,
1072            project,
1073            action_log,
1074            updated_at: db_thread.updated_at,
1075            prompt_capabilities_tx,
1076            prompt_capabilities_rx,
1077            file_read_times: HashMap::default(),
1078            imported: db_thread.imported,
1079            subagent_context: None,
1080            running_subagents: Vec::new(),
1081        }
1082    }
1083
1084    pub fn to_db(&self, cx: &App) -> Task<DbThread> {
1085        let initial_project_snapshot = self.initial_project_snapshot.clone();
1086        let mut thread = DbThread {
1087            title: self.title(),
1088            messages: self.messages.clone(),
1089            updated_at: self.updated_at,
1090            detailed_summary: self.summary.clone(),
1091            initial_project_snapshot: None,
1092            cumulative_token_usage: self.cumulative_token_usage,
1093            request_token_usage: self.request_token_usage.clone(),
1094            model: self.model.as_ref().map(|model| DbLanguageModel {
1095                provider: model.provider_id().to_string(),
1096                model: model.name().0.to_string(),
1097            }),
1098            profile: Some(self.profile_id.clone()),
1099            imported: self.imported,
1100        };
1101
1102        cx.background_spawn(async move {
1103            let initial_project_snapshot = initial_project_snapshot.await;
1104            thread.initial_project_snapshot = initial_project_snapshot;
1105            thread
1106        })
1107    }
1108
1109    /// Create a snapshot of the current project state including git information and unsaved buffers.
1110    fn project_snapshot(
1111        project: Entity<Project>,
1112        cx: &mut Context<Self>,
1113    ) -> Task<Arc<ProjectSnapshot>> {
1114        let task = project::telemetry_snapshot::TelemetrySnapshot::new(&project, cx);
1115        cx.spawn(async move |_, _| {
1116            let snapshot = task.await;
1117
1118            Arc::new(ProjectSnapshot {
1119                worktree_snapshots: snapshot.worktree_snapshots,
1120                timestamp: Utc::now(),
1121            })
1122        })
1123    }
1124
1125    pub fn project_context(&self) -> &Entity<ProjectContext> {
1126        &self.project_context
1127    }
1128
1129    pub fn project(&self) -> &Entity<Project> {
1130        &self.project
1131    }
1132
1133    pub fn action_log(&self) -> &Entity<ActionLog> {
1134        &self.action_log
1135    }
1136
1137    pub fn is_empty(&self) -> bool {
1138        self.messages.is_empty() && self.title.is_none()
1139    }
1140
1141    pub fn model(&self) -> Option<&Arc<dyn LanguageModel>> {
1142        self.model.as_ref()
1143    }
1144
1145    pub fn set_model(&mut self, model: Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
1146        let old_usage = self.latest_token_usage();
1147        self.model = Some(model);
1148        let new_caps = Self::prompt_capabilities(self.model.as_deref());
1149        let new_usage = self.latest_token_usage();
1150        if old_usage != new_usage {
1151            cx.emit(TokenUsageUpdated(new_usage));
1152        }
1153        self.prompt_capabilities_tx.send(new_caps).log_err();
1154        cx.notify()
1155    }
1156
1157    pub fn summarization_model(&self) -> Option<&Arc<dyn LanguageModel>> {
1158        self.summarization_model.as_ref()
1159    }
1160
1161    pub fn set_summarization_model(
1162        &mut self,
1163        model: Option<Arc<dyn LanguageModel>>,
1164        cx: &mut Context<Self>,
1165    ) {
1166        self.summarization_model = model;
1167        cx.notify()
1168    }
1169
1170    pub fn last_message(&self) -> Option<Message> {
1171        if let Some(message) = self.pending_message.clone() {
1172            Some(Message::Agent(message))
1173        } else {
1174            self.messages.last().cloned()
1175        }
1176    }
1177
1178    pub fn add_default_tools(
1179        &mut self,
1180        environment: Rc<dyn ThreadEnvironment>,
1181        cx: &mut Context<Self>,
1182    ) {
1183        let language_registry = self.project.read(cx).languages().clone();
1184        self.add_tool(CopyPathTool::new(self.project.clone()));
1185        self.add_tool(CreateDirectoryTool::new(self.project.clone()));
1186        self.add_tool(DeletePathTool::new(
1187            self.project.clone(),
1188            self.action_log.clone(),
1189        ));
1190        self.add_tool(DiagnosticsTool::new(self.project.clone()));
1191        self.add_tool(EditFileTool::new(
1192            self.project.clone(),
1193            cx.weak_entity(),
1194            language_registry.clone(),
1195            Templates::new(),
1196        ));
1197        self.add_tool(StreamingEditFileTool::new(
1198            self.project.clone(),
1199            cx.weak_entity(),
1200            language_registry,
1201            Templates::new(),
1202        ));
1203        self.add_tool(FetchTool::new(self.project.read(cx).client().http_client()));
1204        self.add_tool(FindPathTool::new(self.project.clone()));
1205        self.add_tool(GrepTool::new(self.project.clone()));
1206        self.add_tool(ListDirectoryTool::new(self.project.clone()));
1207        self.add_tool(MovePathTool::new(self.project.clone()));
1208        self.add_tool(NowTool);
1209        self.add_tool(OpenTool::new(self.project.clone()));
1210        self.add_tool(ReadFileTool::new(
1211            cx.weak_entity(),
1212            self.project.clone(),
1213            self.action_log.clone(),
1214        ));
1215        self.add_tool(SaveFileTool::new(self.project.clone()));
1216        self.add_tool(RestoreFileFromDiskTool::new(self.project.clone()));
1217        self.add_tool(TerminalTool::new(self.project.clone(), environment));
1218        self.add_tool(ThinkingTool);
1219        self.add_tool(WebSearchTool);
1220
1221        if cx.has_flag::<SubagentsFeatureFlag>() && self.depth() < MAX_SUBAGENT_DEPTH {
1222            let parent_tools = self.tools.clone();
1223            self.add_tool(SubagentTool::new(
1224                cx.weak_entity(),
1225                self.project.clone(),
1226                self.project_context.clone(),
1227                self.context_server_registry.clone(),
1228                self.templates.clone(),
1229                self.depth(),
1230                parent_tools,
1231            ));
1232        }
1233    }
1234
1235    pub fn add_tool<T: AgentTool>(&mut self, tool: T) {
1236        self.tools.insert(T::name().into(), tool.erase());
1237    }
1238
1239    pub fn remove_tool(&mut self, name: &str) -> bool {
1240        self.tools.remove(name).is_some()
1241    }
1242
1243    pub fn restrict_tools(&mut self, allowed: &collections::HashSet<SharedString>) {
1244        self.tools.retain(|name, _| allowed.contains(name));
1245    }
1246
1247    pub fn profile(&self) -> &AgentProfileId {
1248        &self.profile_id
1249    }
1250
1251    pub fn set_profile(&mut self, profile_id: AgentProfileId, cx: &mut Context<Self>) {
1252        if self.profile_id == profile_id {
1253            return;
1254        }
1255
1256        self.profile_id = profile_id;
1257
1258        // Swap to the profile's preferred model when available.
1259        if let Some(model) = Self::resolve_profile_model(&self.profile_id, cx) {
1260            self.set_model(model, cx);
1261        }
1262    }
1263
1264    pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
1265        for subagent in self.running_subagents.drain(..) {
1266            if let Some(subagent) = subagent.upgrade() {
1267                subagent.update(cx, |thread, cx| thread.cancel(cx)).detach();
1268            }
1269        }
1270
1271        let Some(running_turn) = self.running_turn.take() else {
1272            self.flush_pending_message(cx);
1273            return Task::ready(());
1274        };
1275
1276        let turn_task = running_turn.cancel();
1277
1278        cx.spawn(async move |this, cx| {
1279            turn_task.await;
1280            this.update(cx, |this, cx| {
1281                this.flush_pending_message(cx);
1282            })
1283            .ok();
1284        })
1285    }
1286
1287    pub fn queue_message(
1288        &mut self,
1289        content: Vec<acp::ContentBlock>,
1290        tracked_buffers: Vec<Entity<Buffer>>,
1291    ) {
1292        self.queued_messages.push(QueuedMessage {
1293            content,
1294            tracked_buffers,
1295        });
1296    }
1297
1298    pub fn queued_messages(&self) -> &[QueuedMessage] {
1299        &self.queued_messages
1300    }
1301
1302    pub fn remove_queued_message(&mut self, index: usize) -> Option<QueuedMessage> {
1303        if index < self.queued_messages.len() {
1304            Some(self.queued_messages.remove(index))
1305        } else {
1306            None
1307        }
1308    }
1309
1310    pub fn update_queued_message(
1311        &mut self,
1312        index: usize,
1313        content: Vec<acp::ContentBlock>,
1314        tracked_buffers: Vec<Entity<Buffer>>,
1315    ) -> bool {
1316        if index < self.queued_messages.len() {
1317            self.queued_messages[index] = QueuedMessage {
1318                content,
1319                tracked_buffers,
1320            };
1321            true
1322        } else {
1323            false
1324        }
1325    }
1326
1327    pub fn clear_queued_messages(&mut self) {
1328        self.queued_messages.clear();
1329    }
1330
1331    fn has_queued_messages(&self) -> bool {
1332        !self.queued_messages.is_empty()
1333    }
1334
1335    fn update_token_usage(&mut self, update: language_model::TokenUsage, cx: &mut Context<Self>) {
1336        let Some(last_user_message) = self.last_user_message() else {
1337            return;
1338        };
1339
1340        self.request_token_usage
1341            .insert(last_user_message.id.clone(), update);
1342        cx.emit(TokenUsageUpdated(self.latest_token_usage()));
1343        cx.notify();
1344    }
1345
1346    pub fn truncate(&mut self, message_id: UserMessageId, cx: &mut Context<Self>) -> Result<()> {
1347        self.cancel(cx).detach();
1348        // Clear pending message since cancel will try to flush it asynchronously,
1349        // and we don't want that content to be added after we truncate
1350        self.pending_message.take();
1351        let Some(position) = self.messages.iter().position(
1352            |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
1353        ) else {
1354            return Err(anyhow!("Message not found"));
1355        };
1356
1357        for message in self.messages.drain(position..) {
1358            match message {
1359                Message::User(message) => {
1360                    self.request_token_usage.remove(&message.id);
1361                }
1362                Message::Agent(_) | Message::Resume => {}
1363            }
1364        }
1365        self.clear_summary();
1366        cx.notify();
1367        Ok(())
1368    }
1369
1370    pub fn latest_request_token_usage(&self) -> Option<language_model::TokenUsage> {
1371        let last_user_message = self.last_user_message()?;
1372        let tokens = self.request_token_usage.get(&last_user_message.id)?;
1373        Some(*tokens)
1374    }
1375
1376    pub fn latest_token_usage(&self) -> Option<acp_thread::TokenUsage> {
1377        let usage = self.latest_request_token_usage()?;
1378        let model = self.model.clone()?;
1379        Some(acp_thread::TokenUsage {
1380            max_tokens: model.max_token_count(),
1381            used_tokens: usage.total_tokens(),
1382            input_tokens: usage.input_tokens,
1383            output_tokens: usage.output_tokens,
1384        })
1385    }
1386
1387    /// Get the total input token count as of the message before the given message.
1388    ///
1389    /// Returns `None` if:
1390    /// - `target_id` is the first message (no previous message)
1391    /// - The previous message hasn't received a response yet (no usage data)
1392    /// - `target_id` is not found in the messages
1393    pub fn tokens_before_message(&self, target_id: &UserMessageId) -> Option<u64> {
1394        let mut previous_user_message_id: Option<&UserMessageId> = None;
1395
1396        for message in &self.messages {
1397            if let Message::User(user_msg) = message {
1398                if &user_msg.id == target_id {
1399                    let prev_id = previous_user_message_id?;
1400                    let usage = self.request_token_usage.get(prev_id)?;
1401                    return Some(usage.input_tokens);
1402                }
1403                previous_user_message_id = Some(&user_msg.id);
1404            }
1405        }
1406        None
1407    }
1408
1409    /// Look up the active profile and resolve its preferred model if one is configured.
1410    fn resolve_profile_model(
1411        profile_id: &AgentProfileId,
1412        cx: &mut Context<Self>,
1413    ) -> Option<Arc<dyn LanguageModel>> {
1414        let selection = AgentSettings::get_global(cx)
1415            .profiles
1416            .get(profile_id)?
1417            .default_model
1418            .clone()?;
1419        Self::resolve_model_from_selection(&selection, cx)
1420    }
1421
1422    /// Translate a stored model selection into the configured model from the registry.
1423    fn resolve_model_from_selection(
1424        selection: &LanguageModelSelection,
1425        cx: &mut Context<Self>,
1426    ) -> Option<Arc<dyn LanguageModel>> {
1427        let selected = SelectedModel {
1428            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
1429            model: LanguageModelId::from(selection.model.clone()),
1430        };
1431        LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1432            registry
1433                .select_model(&selected, cx)
1434                .map(|configured| configured.model)
1435        })
1436    }
1437
1438    pub fn resume(
1439        &mut self,
1440        cx: &mut Context<Self>,
1441    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1442        self.messages.push(Message::Resume);
1443        cx.notify();
1444
1445        log::debug!("Total messages in thread: {}", self.messages.len());
1446        self.run_turn(cx)
1447    }
1448
1449    /// Sending a message results in the model streaming a response, which could include tool calls.
1450    /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
1451    /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
1452    pub fn send<T>(
1453        &mut self,
1454        id: UserMessageId,
1455        content: impl IntoIterator<Item = T>,
1456        cx: &mut Context<Self>,
1457    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
1458    where
1459        T: Into<UserMessageContent>,
1460    {
1461        let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
1462        log::debug!("Thread::send content: {:?}", content);
1463
1464        self.messages
1465            .push(Message::User(UserMessage { id, content }));
1466        cx.notify();
1467
1468        self.send_existing(cx)
1469    }
1470
1471    pub fn send_existing(
1472        &mut self,
1473        cx: &mut Context<Self>,
1474    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1475        let model = self.model().context("No language model configured")?;
1476
1477        log::info!("Thread::send called with model: {}", model.name().0);
1478        self.advance_prompt_id();
1479
1480        log::debug!("Total messages in thread: {}", self.messages.len());
1481        self.run_turn(cx)
1482    }
1483
1484    pub fn push_acp_user_block(
1485        &mut self,
1486        id: UserMessageId,
1487        blocks: impl IntoIterator<Item = acp::ContentBlock>,
1488        path_style: PathStyle,
1489        cx: &mut Context<Self>,
1490    ) {
1491        let content = blocks
1492            .into_iter()
1493            .map(|block| UserMessageContent::from_content_block(block, path_style))
1494            .collect::<Vec<_>>();
1495        self.messages
1496            .push(Message::User(UserMessage { id, content }));
1497        cx.notify();
1498    }
1499
1500    pub fn push_acp_agent_block(&mut self, block: acp::ContentBlock, cx: &mut Context<Self>) {
1501        let text = match block {
1502            acp::ContentBlock::Text(text_content) => text_content.text,
1503            acp::ContentBlock::Image(_) => "[image]".to_string(),
1504            acp::ContentBlock::Audio(_) => "[audio]".to_string(),
1505            acp::ContentBlock::ResourceLink(resource_link) => resource_link.uri,
1506            acp::ContentBlock::Resource(resource) => match resource.resource {
1507                acp::EmbeddedResourceResource::TextResourceContents(resource) => resource.uri,
1508                acp::EmbeddedResourceResource::BlobResourceContents(resource) => resource.uri,
1509                _ => "[resource]".to_string(),
1510            },
1511            _ => "[unknown]".to_string(),
1512        };
1513
1514        self.messages.push(Message::Agent(AgentMessage {
1515            content: vec![AgentMessageContent::Text(text)],
1516            ..Default::default()
1517        }));
1518        cx.notify();
1519    }
1520
1521    #[cfg(feature = "eval")]
1522    pub fn proceed(
1523        &mut self,
1524        cx: &mut Context<Self>,
1525    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1526        self.run_turn(cx)
1527    }
1528
1529    fn run_turn(
1530        &mut self,
1531        cx: &mut Context<Self>,
1532    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1533        // Flush the old pending message synchronously before cancelling,
1534        // to avoid a race where the detached cancel task might flush the NEW
1535        // turn's pending message instead of the old one.
1536        self.flush_pending_message(cx);
1537        self.cancel(cx).detach();
1538
1539        let model = self.model.clone().context("No language model configured")?;
1540        let profile = AgentSettings::get_global(cx)
1541            .profiles
1542            .get(&self.profile_id)
1543            .context("Profile not found")?;
1544        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1545        let event_stream = ThreadEventStream(events_tx);
1546        let message_ix = self.messages.len().saturating_sub(1);
1547        self.clear_summary();
1548        let (cancellation_tx, mut cancellation_rx) = watch::channel(false);
1549        self.running_turn = Some(RunningTurn {
1550            event_stream: event_stream.clone(),
1551            tools: self.enabled_tools(profile, &model, cx),
1552            cancellation_tx,
1553            _task: cx.spawn(async move |this, cx| {
1554                log::debug!("Starting agent turn execution");
1555
1556                let turn_result = Self::run_turn_internal(
1557                    &this,
1558                    model,
1559                    &event_stream,
1560                    cancellation_rx.clone(),
1561                    cx,
1562                )
1563                .await;
1564
1565                // Check if we were cancelled - if so, cancel() already took running_turn
1566                // and we shouldn't touch it (it might be a NEW turn now)
1567                let was_cancelled = *cancellation_rx.borrow();
1568                if was_cancelled {
1569                    log::debug!("Turn was cancelled, skipping cleanup");
1570                    return;
1571                }
1572
1573                _ = this.update(cx, |this, cx| this.flush_pending_message(cx));
1574
1575                match turn_result {
1576                    Ok(()) => {
1577                        log::debug!("Turn execution completed");
1578                        event_stream.send_stop(acp::StopReason::EndTurn);
1579                    }
1580                    Err(error) => {
1581                        log::error!("Turn execution failed: {:?}", error);
1582                        match error.downcast::<CompletionError>() {
1583                            Ok(CompletionError::Refusal) => {
1584                                event_stream.send_stop(acp::StopReason::Refusal);
1585                                _ = this.update(cx, |this, _| this.messages.truncate(message_ix));
1586                            }
1587                            Ok(CompletionError::MaxTokens) => {
1588                                event_stream.send_stop(acp::StopReason::MaxTokens);
1589                            }
1590                            Ok(CompletionError::Other(error)) | Err(error) => {
1591                                event_stream.send_error(error);
1592                            }
1593                        }
1594                    }
1595                }
1596
1597                _ = this.update(cx, |this, _| this.running_turn.take());
1598            }),
1599        });
1600        Ok(events_rx)
1601    }
1602
1603    async fn run_turn_internal(
1604        this: &WeakEntity<Self>,
1605        model: Arc<dyn LanguageModel>,
1606        event_stream: &ThreadEventStream,
1607        mut cancellation_rx: watch::Receiver<bool>,
1608        cx: &mut AsyncApp,
1609    ) -> Result<()> {
1610        let mut attempt = 0;
1611        let mut intent = CompletionIntent::UserPrompt;
1612        loop {
1613            let request =
1614                this.update(cx, |this, cx| this.build_completion_request(intent, cx))??;
1615
1616            telemetry::event!(
1617                "Agent Thread Completion",
1618                thread_id = this.read_with(cx, |this, _| this.id.to_string())?,
1619                prompt_id = this.read_with(cx, |this, _| this.prompt_id.to_string())?,
1620                model = model.telemetry_id(),
1621                model_provider = model.provider_id().to_string(),
1622                attempt
1623            );
1624
1625            log::debug!("Calling model.stream_completion, attempt {}", attempt);
1626
1627            let (mut events, mut error) = match model.stream_completion(request, cx).await {
1628                Ok(events) => (events.fuse(), None),
1629                Err(err) => (stream::empty().boxed().fuse(), Some(err)),
1630            };
1631            let mut tool_results = FuturesUnordered::new();
1632            let mut cancelled = false;
1633            loop {
1634                // Race between getting the first event and cancellation
1635                let first_event = futures::select! {
1636                    event = events.next().fuse() => event,
1637                    _ = cancellation_rx.changed().fuse() => {
1638                        if *cancellation_rx.borrow() {
1639                            cancelled = true;
1640                            break;
1641                        }
1642                        continue;
1643                    }
1644                };
1645                let Some(first_event) = first_event else {
1646                    break;
1647                };
1648
1649                // Collect all immediately available events to process as a batch
1650                let mut batch = vec![first_event];
1651                while let Some(event) = events.next().now_or_never().flatten() {
1652                    batch.push(event);
1653                }
1654
1655                // Process the batch in a single update
1656                let batch_result = this.update(cx, |this, cx| {
1657                    let mut batch_tool_results = Vec::new();
1658                    let mut batch_error = None;
1659
1660                    for event in batch {
1661                        log::trace!("Received completion event: {:?}", event);
1662                        match event {
1663                            Ok(event) => {
1664                                match this.handle_completion_event(
1665                                    event,
1666                                    event_stream,
1667                                    cancellation_rx.clone(),
1668                                    cx,
1669                                ) {
1670                                    Ok(Some(task)) => batch_tool_results.push(task),
1671                                    Ok(None) => {}
1672                                    Err(err) => {
1673                                        batch_error = Some(err);
1674                                        break;
1675                                    }
1676                                }
1677                            }
1678                            Err(err) => {
1679                                batch_error = Some(err.into());
1680                                break;
1681                            }
1682                        }
1683                    }
1684
1685                    cx.notify();
1686                    (batch_tool_results, batch_error)
1687                })?;
1688
1689                tool_results.extend(batch_result.0);
1690                if let Some(err) = batch_result.1 {
1691                    error = Some(err.downcast()?);
1692                    break;
1693                }
1694            }
1695
1696            let end_turn = tool_results.is_empty();
1697            while let Some(tool_result) = tool_results.next().await {
1698                log::debug!("Tool finished {:?}", tool_result);
1699
1700                event_stream.update_tool_call_fields(
1701                    &tool_result.tool_use_id,
1702                    acp::ToolCallUpdateFields::new()
1703                        .status(if tool_result.is_error {
1704                            acp::ToolCallStatus::Failed
1705                        } else {
1706                            acp::ToolCallStatus::Completed
1707                        })
1708                        .raw_output(tool_result.output.clone()),
1709                );
1710                this.update(cx, |this, _cx| {
1711                    this.pending_message()
1712                        .tool_results
1713                        .insert(tool_result.tool_use_id.clone(), tool_result);
1714                })?;
1715            }
1716
1717            this.update(cx, |this, cx| {
1718                this.flush_pending_message(cx);
1719                if this.title.is_none() && this.pending_title_generation.is_none() {
1720                    this.generate_title(cx);
1721                }
1722            })?;
1723
1724            if cancelled {
1725                log::debug!("Turn cancelled by user, exiting");
1726                return Ok(());
1727            }
1728
1729            if let Some(error) = error {
1730                attempt += 1;
1731                let retry = this.update(cx, |this, cx| {
1732                    let user_store = this.user_store.read(cx);
1733                    this.handle_completion_error(error, attempt, user_store.plan())
1734                })??;
1735                let timer = cx.background_executor().timer(retry.duration);
1736                event_stream.send_retry(retry);
1737                timer.await;
1738                this.update(cx, |this, _cx| {
1739                    if let Some(Message::Agent(message)) = this.messages.last() {
1740                        if message.tool_results.is_empty() {
1741                            intent = CompletionIntent::UserPrompt;
1742                            this.messages.push(Message::Resume);
1743                        }
1744                    }
1745                })?;
1746            } else if end_turn {
1747                return Ok(());
1748            } else {
1749                let has_queued = this.update(cx, |this, _| this.has_queued_messages())?;
1750                if has_queued {
1751                    log::debug!("Queued message found, ending turn at message boundary");
1752                    return Ok(());
1753                }
1754                intent = CompletionIntent::ToolResults;
1755                attempt = 0;
1756            }
1757        }
1758    }
1759
1760    fn handle_completion_error(
1761        &mut self,
1762        error: LanguageModelCompletionError,
1763        attempt: u8,
1764        plan: Option<Plan>,
1765    ) -> Result<acp_thread::RetryStatus> {
1766        let Some(model) = self.model.as_ref() else {
1767            return Err(anyhow!(error));
1768        };
1769
1770        let auto_retry = if model.provider_id() == ZED_CLOUD_PROVIDER_ID {
1771            match plan {
1772                Some(Plan::V2(_)) => true,
1773                None => false,
1774            }
1775        } else {
1776            true
1777        };
1778
1779        if !auto_retry {
1780            return Err(anyhow!(error));
1781        }
1782
1783        let Some(strategy) = Self::retry_strategy_for(&error) else {
1784            return Err(anyhow!(error));
1785        };
1786
1787        let max_attempts = match &strategy {
1788            RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
1789            RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
1790        };
1791
1792        if attempt > max_attempts {
1793            return Err(anyhow!(error));
1794        }
1795
1796        let delay = match &strategy {
1797            RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
1798                let delay_secs = initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
1799                Duration::from_secs(delay_secs)
1800            }
1801            RetryStrategy::Fixed { delay, .. } => *delay,
1802        };
1803        log::debug!("Retry attempt {attempt} with delay {delay:?}");
1804
1805        Ok(acp_thread::RetryStatus {
1806            last_error: error.to_string().into(),
1807            attempt: attempt as usize,
1808            max_attempts: max_attempts as usize,
1809            started_at: Instant::now(),
1810            duration: delay,
1811        })
1812    }
1813
1814    /// A helper method that's called on every streamed completion event.
1815    /// Returns an optional tool result task, which the main agentic loop will
1816    /// send back to the model when it resolves.
1817    fn handle_completion_event(
1818        &mut self,
1819        event: LanguageModelCompletionEvent,
1820        event_stream: &ThreadEventStream,
1821        cancellation_rx: watch::Receiver<bool>,
1822        cx: &mut Context<Self>,
1823    ) -> Result<Option<Task<LanguageModelToolResult>>> {
1824        log::trace!("Handling streamed completion event: {:?}", event);
1825        use LanguageModelCompletionEvent::*;
1826
1827        match event {
1828            StartMessage { .. } => {
1829                self.flush_pending_message(cx);
1830                self.pending_message = Some(AgentMessage::default());
1831            }
1832            Text(new_text) => self.handle_text_event(new_text, event_stream),
1833            Thinking { text, signature } => {
1834                self.handle_thinking_event(text, signature, event_stream)
1835            }
1836            RedactedThinking { data } => self.handle_redacted_thinking_event(data),
1837            ReasoningDetails(details) => {
1838                let last_message = self.pending_message();
1839                // Store the last non-empty reasoning_details (overwrites earlier ones)
1840                // This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
1841                if let serde_json::Value::Array(ref arr) = details {
1842                    if !arr.is_empty() {
1843                        last_message.reasoning_details = Some(details);
1844                    }
1845                } else {
1846                    last_message.reasoning_details = Some(details);
1847                }
1848            }
1849            ToolUse(tool_use) => {
1850                return Ok(self.handle_tool_use_event(tool_use, event_stream, cancellation_rx, cx));
1851            }
1852            ToolUseJsonParseError {
1853                id,
1854                tool_name,
1855                raw_input,
1856                json_parse_error,
1857            } => {
1858                return Ok(Some(Task::ready(
1859                    self.handle_tool_use_json_parse_error_event(
1860                        id,
1861                        tool_name,
1862                        raw_input,
1863                        json_parse_error,
1864                    ),
1865                )));
1866            }
1867            UsageUpdate(usage) => {
1868                telemetry::event!(
1869                    "Agent Thread Completion Usage Updated",
1870                    thread_id = self.id.to_string(),
1871                    prompt_id = self.prompt_id.to_string(),
1872                    model = self.model.as_ref().map(|m| m.telemetry_id()),
1873                    model_provider = self.model.as_ref().map(|m| m.provider_id().to_string()),
1874                    input_tokens = usage.input_tokens,
1875                    output_tokens = usage.output_tokens,
1876                    cache_creation_input_tokens = usage.cache_creation_input_tokens,
1877                    cache_read_input_tokens = usage.cache_read_input_tokens,
1878                );
1879                self.update_token_usage(usage, cx);
1880            }
1881            Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()),
1882            Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()),
1883            Stop(StopReason::ToolUse | StopReason::EndTurn) => {}
1884            Started | Queued { .. } => {}
1885        }
1886
1887        Ok(None)
1888    }
1889
1890    fn handle_text_event(&mut self, new_text: String, event_stream: &ThreadEventStream) {
1891        event_stream.send_text(&new_text);
1892
1893        let last_message = self.pending_message();
1894        if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
1895            text.push_str(&new_text);
1896        } else {
1897            last_message
1898                .content
1899                .push(AgentMessageContent::Text(new_text));
1900        }
1901    }
1902
1903    fn handle_thinking_event(
1904        &mut self,
1905        new_text: String,
1906        new_signature: Option<String>,
1907        event_stream: &ThreadEventStream,
1908    ) {
1909        event_stream.send_thinking(&new_text);
1910
1911        let last_message = self.pending_message();
1912        if let Some(AgentMessageContent::Thinking { text, signature }) =
1913            last_message.content.last_mut()
1914        {
1915            text.push_str(&new_text);
1916            *signature = new_signature.or(signature.take());
1917        } else {
1918            last_message.content.push(AgentMessageContent::Thinking {
1919                text: new_text,
1920                signature: new_signature,
1921            });
1922        }
1923    }
1924
1925    fn handle_redacted_thinking_event(&mut self, data: String) {
1926        let last_message = self.pending_message();
1927        last_message
1928            .content
1929            .push(AgentMessageContent::RedactedThinking(data));
1930    }
1931
1932    fn handle_tool_use_event(
1933        &mut self,
1934        tool_use: LanguageModelToolUse,
1935        event_stream: &ThreadEventStream,
1936        cancellation_rx: watch::Receiver<bool>,
1937        cx: &mut Context<Self>,
1938    ) -> Option<Task<LanguageModelToolResult>> {
1939        cx.notify();
1940
1941        let tool = self.tool(tool_use.name.as_ref());
1942        let mut title = SharedString::from(&tool_use.name);
1943        let mut kind = acp::ToolKind::Other;
1944        if let Some(tool) = tool.as_ref() {
1945            title = tool.initial_title(tool_use.input.clone(), cx);
1946            kind = tool.kind();
1947        }
1948
1949        // Ensure the last message ends in the current tool use
1950        let last_message = self.pending_message();
1951        let push_new_tool_use = last_message.content.last_mut().is_none_or(|content| {
1952            if let AgentMessageContent::ToolUse(last_tool_use) = content {
1953                if last_tool_use.id == tool_use.id {
1954                    *last_tool_use = tool_use.clone();
1955                    false
1956                } else {
1957                    true
1958                }
1959            } else {
1960                true
1961            }
1962        });
1963
1964        if push_new_tool_use {
1965            event_stream.send_tool_call(
1966                &tool_use.id,
1967                &tool_use.name,
1968                title,
1969                kind,
1970                tool_use.input.clone(),
1971            );
1972            last_message
1973                .content
1974                .push(AgentMessageContent::ToolUse(tool_use.clone()));
1975        } else {
1976            event_stream.update_tool_call_fields(
1977                &tool_use.id,
1978                acp::ToolCallUpdateFields::new()
1979                    .title(title.as_str())
1980                    .kind(kind)
1981                    .raw_input(tool_use.input.clone()),
1982            );
1983        }
1984
1985        if !tool_use.is_input_complete {
1986            return None;
1987        }
1988
1989        let Some(tool) = tool else {
1990            let content = format!("No tool named {} exists", tool_use.name);
1991            return Some(Task::ready(LanguageModelToolResult {
1992                content: LanguageModelToolResultContent::Text(Arc::from(content)),
1993                tool_use_id: tool_use.id,
1994                tool_name: tool_use.name,
1995                is_error: true,
1996                output: None,
1997            }));
1998        };
1999
2000        let fs = self.project.read(cx).fs().clone();
2001        let tool_event_stream = ToolCallEventStream::new(
2002            tool_use.id.clone(),
2003            event_stream.clone(),
2004            Some(fs),
2005            cancellation_rx,
2006        );
2007        tool_event_stream.update_fields(
2008            acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
2009        );
2010        let supports_images = self.model().is_some_and(|model| model.supports_images());
2011        let tool_result = tool.run(tool_use.input, tool_event_stream, cx);
2012        log::debug!("Running tool {}", tool_use.name);
2013        Some(cx.foreground_executor().spawn(async move {
2014            let tool_result = tool_result.await.and_then(|output| {
2015                if let LanguageModelToolResultContent::Image(_) = &output.llm_output
2016                    && !supports_images
2017                {
2018                    return Err(anyhow!(
2019                        "Attempted to read an image, but this model doesn't support it.",
2020                    ));
2021                }
2022                Ok(output)
2023            });
2024
2025            match tool_result {
2026                Ok(output) => LanguageModelToolResult {
2027                    tool_use_id: tool_use.id,
2028                    tool_name: tool_use.name,
2029                    is_error: false,
2030                    content: output.llm_output,
2031                    output: Some(output.raw_output),
2032                },
2033                Err(error) => LanguageModelToolResult {
2034                    tool_use_id: tool_use.id,
2035                    tool_name: tool_use.name,
2036                    is_error: true,
2037                    content: LanguageModelToolResultContent::Text(Arc::from(error.to_string())),
2038                    output: Some(error.to_string().into()),
2039                },
2040            }
2041        }))
2042    }
2043
2044    fn handle_tool_use_json_parse_error_event(
2045        &mut self,
2046        tool_use_id: LanguageModelToolUseId,
2047        tool_name: Arc<str>,
2048        raw_input: Arc<str>,
2049        json_parse_error: String,
2050    ) -> LanguageModelToolResult {
2051        let tool_output = format!("Error parsing input JSON: {json_parse_error}");
2052        LanguageModelToolResult {
2053            tool_use_id,
2054            tool_name,
2055            is_error: true,
2056            content: LanguageModelToolResultContent::Text(tool_output.into()),
2057            output: Some(serde_json::Value::String(raw_input.to_string())),
2058        }
2059    }
2060
2061    pub fn title(&self) -> SharedString {
2062        self.title.clone().unwrap_or("New Thread".into())
2063    }
2064
2065    pub fn is_generating_summary(&self) -> bool {
2066        self.pending_summary_generation.is_some()
2067    }
2068
2069    pub fn is_generating_title(&self) -> bool {
2070        self.pending_title_generation.is_some()
2071    }
2072
2073    pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
2074        if let Some(summary) = self.summary.as_ref() {
2075            return Task::ready(Some(summary.clone())).shared();
2076        }
2077        if let Some(task) = self.pending_summary_generation.clone() {
2078            return task;
2079        }
2080        let Some(model) = self.summarization_model.clone() else {
2081            log::error!("No summarization model available");
2082            return Task::ready(None).shared();
2083        };
2084        let mut request = LanguageModelRequest {
2085            intent: Some(CompletionIntent::ThreadContextSummarization),
2086            temperature: AgentSettings::temperature_for_model(&model, cx),
2087            ..Default::default()
2088        };
2089
2090        for message in &self.messages {
2091            request.messages.extend(message.to_request());
2092        }
2093
2094        request.messages.push(LanguageModelRequestMessage {
2095            role: Role::User,
2096            content: vec![SUMMARIZE_THREAD_DETAILED_PROMPT.into()],
2097            cache: false,
2098            reasoning_details: None,
2099        });
2100
2101        let task = cx
2102            .spawn(async move |this, cx| {
2103                let mut summary = String::new();
2104                let mut messages = model.stream_completion(request, cx).await.log_err()?;
2105                while let Some(event) = messages.next().await {
2106                    let event = event.log_err()?;
2107                    let text = match event {
2108                        LanguageModelCompletionEvent::Text(text) => text,
2109                        _ => continue,
2110                    };
2111
2112                    let mut lines = text.lines();
2113                    summary.extend(lines.next());
2114                }
2115
2116                log::debug!("Setting summary: {}", summary);
2117                let summary = SharedString::from(summary);
2118
2119                this.update(cx, |this, cx| {
2120                    this.summary = Some(summary.clone());
2121                    this.pending_summary_generation = None;
2122                    cx.notify()
2123                })
2124                .ok()?;
2125
2126                Some(summary)
2127            })
2128            .shared();
2129        self.pending_summary_generation = Some(task.clone());
2130        task
2131    }
2132
2133    pub fn generate_title(&mut self, cx: &mut Context<Self>) {
2134        let Some(model) = self.summarization_model.clone() else {
2135            return;
2136        };
2137
2138        log::debug!(
2139            "Generating title with model: {:?}",
2140            self.summarization_model.as_ref().map(|model| model.name())
2141        );
2142        let mut request = LanguageModelRequest {
2143            intent: Some(CompletionIntent::ThreadSummarization),
2144            temperature: AgentSettings::temperature_for_model(&model, cx),
2145            ..Default::default()
2146        };
2147
2148        for message in &self.messages {
2149            request.messages.extend(message.to_request());
2150        }
2151
2152        request.messages.push(LanguageModelRequestMessage {
2153            role: Role::User,
2154            content: vec![SUMMARIZE_THREAD_PROMPT.into()],
2155            cache: false,
2156            reasoning_details: None,
2157        });
2158        self.pending_title_generation = Some(cx.spawn(async move |this, cx| {
2159            let mut title = String::new();
2160
2161            let generate = async {
2162                let mut messages = model.stream_completion(request, cx).await?;
2163                while let Some(event) = messages.next().await {
2164                    let event = event?;
2165                    let text = match event {
2166                        LanguageModelCompletionEvent::Text(text) => text,
2167                        _ => continue,
2168                    };
2169
2170                    let mut lines = text.lines();
2171                    title.extend(lines.next());
2172
2173                    // Stop if the LLM generated multiple lines.
2174                    if lines.next().is_some() {
2175                        break;
2176                    }
2177                }
2178                anyhow::Ok(())
2179            };
2180
2181            if generate.await.context("failed to generate title").is_ok() {
2182                _ = this.update(cx, |this, cx| this.set_title(title.into(), cx));
2183            }
2184            _ = this.update(cx, |this, _| this.pending_title_generation = None);
2185        }));
2186    }
2187
2188    pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
2189        self.pending_title_generation = None;
2190        if Some(&title) != self.title.as_ref() {
2191            self.title = Some(title);
2192            cx.emit(TitleUpdated);
2193            cx.notify();
2194        }
2195    }
2196
2197    fn clear_summary(&mut self) {
2198        self.summary = None;
2199        self.pending_summary_generation = None;
2200    }
2201
2202    fn last_user_message(&self) -> Option<&UserMessage> {
2203        self.messages
2204            .iter()
2205            .rev()
2206            .find_map(|message| match message {
2207                Message::User(user_message) => Some(user_message),
2208                Message::Agent(_) => None,
2209                Message::Resume => None,
2210            })
2211    }
2212
2213    fn pending_message(&mut self) -> &mut AgentMessage {
2214        self.pending_message.get_or_insert_default()
2215    }
2216
2217    fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
2218        let Some(mut message) = self.pending_message.take() else {
2219            return;
2220        };
2221
2222        if message.content.is_empty() {
2223            return;
2224        }
2225
2226        for content in &message.content {
2227            let AgentMessageContent::ToolUse(tool_use) = content else {
2228                continue;
2229            };
2230
2231            if !message.tool_results.contains_key(&tool_use.id) {
2232                message.tool_results.insert(
2233                    tool_use.id.clone(),
2234                    LanguageModelToolResult {
2235                        tool_use_id: tool_use.id.clone(),
2236                        tool_name: tool_use.name.clone(),
2237                        is_error: true,
2238                        content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
2239                        output: None,
2240                    },
2241                );
2242            }
2243        }
2244
2245        self.messages.push(Message::Agent(message));
2246        self.updated_at = Utc::now();
2247        self.clear_summary();
2248        cx.notify()
2249    }
2250
2251    pub(crate) fn build_completion_request(
2252        &self,
2253        completion_intent: CompletionIntent,
2254        cx: &App,
2255    ) -> Result<LanguageModelRequest> {
2256        let model = self.model().context("No language model configured")?;
2257        let tools = if let Some(turn) = self.running_turn.as_ref() {
2258            turn.tools
2259                .iter()
2260                .filter_map(|(tool_name, tool)| {
2261                    log::trace!("Including tool: {}", tool_name);
2262                    Some(LanguageModelRequestTool {
2263                        name: tool_name.to_string(),
2264                        description: tool.description().to_string(),
2265                        input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
2266                    })
2267                })
2268                .collect::<Vec<_>>()
2269        } else {
2270            Vec::new()
2271        };
2272
2273        log::debug!("Building completion request");
2274        log::debug!("Completion intent: {:?}", completion_intent);
2275
2276        let available_tools: Vec<_> = self
2277            .running_turn
2278            .as_ref()
2279            .map(|turn| turn.tools.keys().cloned().collect())
2280            .unwrap_or_default();
2281
2282        log::debug!("Request includes {} tools", available_tools.len());
2283        let messages = self.build_request_messages(available_tools, cx);
2284        log::debug!("Request will include {} messages", messages.len());
2285
2286        let request = LanguageModelRequest {
2287            thread_id: Some(self.id.to_string()),
2288            prompt_id: Some(self.prompt_id.to_string()),
2289            intent: Some(completion_intent),
2290            messages,
2291            tools,
2292            tool_choice: None,
2293            stop: Vec::new(),
2294            temperature: AgentSettings::temperature_for_model(model, cx),
2295            thinking_allowed: true,
2296            bypass_rate_limit: false,
2297        };
2298
2299        log::debug!("Completion request built successfully");
2300        Ok(request)
2301    }
2302
2303    fn enabled_tools(
2304        &self,
2305        profile: &AgentProfileSettings,
2306        model: &Arc<dyn LanguageModel>,
2307        cx: &App,
2308    ) -> BTreeMap<SharedString, Arc<dyn AnyAgentTool>> {
2309        fn truncate(tool_name: &SharedString) -> SharedString {
2310            if tool_name.len() > MAX_TOOL_NAME_LENGTH {
2311                let mut truncated = tool_name.to_string();
2312                truncated.truncate(MAX_TOOL_NAME_LENGTH);
2313                truncated.into()
2314            } else {
2315                tool_name.clone()
2316            }
2317        }
2318
2319        let use_streaming_edit_tool =
2320            cx.has_flag::<AgentV2FeatureFlag>() && model.supports_streaming_tools();
2321
2322        let mut tools = self
2323            .tools
2324            .iter()
2325            .filter_map(|(tool_name, tool)| {
2326                // For streaming_edit_file, check profile against "edit_file" since that's what users configure
2327                let profile_tool_name = if tool_name == "streaming_edit_file" {
2328                    "edit_file"
2329                } else {
2330                    tool_name.as_ref()
2331                };
2332
2333                if tool.supports_provider(&model.provider_id())
2334                    && profile.is_tool_enabled(profile_tool_name)
2335                {
2336                    match (tool_name.as_ref(), use_streaming_edit_tool) {
2337                        ("streaming_edit_file", true) => {
2338                            // Expose streaming tool as "edit_file"
2339                            Some((SharedString::from("edit_file"), tool.clone()))
2340                        }
2341                        ("edit_file", true) => None,
2342                        _ => Some((truncate(tool_name), tool.clone())),
2343                    }
2344                } else {
2345                    None
2346                }
2347            })
2348            .collect::<BTreeMap<_, _>>();
2349
2350        let mut context_server_tools = Vec::new();
2351        let mut seen_tools = tools.keys().cloned().collect::<HashSet<_>>();
2352        let mut duplicate_tool_names = HashSet::default();
2353        for (server_id, server_tools) in self.context_server_registry.read(cx).servers() {
2354            for (tool_name, tool) in server_tools {
2355                if profile.is_context_server_tool_enabled(&server_id.0, &tool_name) {
2356                    let tool_name = truncate(tool_name);
2357                    if !seen_tools.insert(tool_name.clone()) {
2358                        duplicate_tool_names.insert(tool_name.clone());
2359                    }
2360                    context_server_tools.push((server_id.clone(), tool_name, tool.clone()));
2361                }
2362            }
2363        }
2364
2365        // When there are duplicate tool names, disambiguate by prefixing them
2366        // with the server ID. In the rare case there isn't enough space for the
2367        // disambiguated tool name, keep only the last tool with this name.
2368        for (server_id, tool_name, tool) in context_server_tools {
2369            if duplicate_tool_names.contains(&tool_name) {
2370                let available = MAX_TOOL_NAME_LENGTH.saturating_sub(tool_name.len());
2371                if available >= 2 {
2372                    let mut disambiguated = server_id.0.to_string();
2373                    disambiguated.truncate(available - 1);
2374                    disambiguated.push('_');
2375                    disambiguated.push_str(&tool_name);
2376                    tools.insert(disambiguated.into(), tool.clone());
2377                } else {
2378                    tools.insert(tool_name, tool.clone());
2379                }
2380            } else {
2381                tools.insert(tool_name, tool.clone());
2382            }
2383        }
2384
2385        tools
2386    }
2387
2388    fn tool(&self, name: &str) -> Option<Arc<dyn AnyAgentTool>> {
2389        self.running_turn.as_ref()?.tools.get(name).cloned()
2390    }
2391
2392    pub fn has_tool(&self, name: &str) -> bool {
2393        self.running_turn
2394            .as_ref()
2395            .is_some_and(|turn| turn.tools.contains_key(name))
2396    }
2397
2398    #[cfg(any(test, feature = "test-support"))]
2399    pub fn has_registered_tool(&self, name: &str) -> bool {
2400        self.tools.contains_key(name)
2401    }
2402
2403    pub fn registered_tool_names(&self) -> Vec<SharedString> {
2404        self.tools.keys().cloned().collect()
2405    }
2406
2407    pub fn register_running_subagent(&mut self, subagent: WeakEntity<Thread>) {
2408        self.running_subagents.push(subagent);
2409    }
2410
2411    pub fn unregister_running_subagent(&mut self, subagent: &WeakEntity<Thread>) {
2412        self.running_subagents
2413            .retain(|s| s.entity_id() != subagent.entity_id());
2414    }
2415
2416    pub fn running_subagent_count(&self) -> usize {
2417        self.running_subagents
2418            .iter()
2419            .filter(|s| s.upgrade().is_some())
2420            .count()
2421    }
2422
2423    pub fn is_subagent(&self) -> bool {
2424        self.subagent_context.is_some()
2425    }
2426
2427    pub fn depth(&self) -> u8 {
2428        self.subagent_context.as_ref().map(|c| c.depth).unwrap_or(0)
2429    }
2430
2431    pub fn is_turn_complete(&self) -> bool {
2432        self.running_turn.is_none()
2433    }
2434
2435    pub fn submit_user_message(
2436        &mut self,
2437        content: impl Into<String>,
2438        cx: &mut Context<Self>,
2439    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
2440        let content = content.into();
2441        self.messages.push(Message::User(UserMessage {
2442            id: UserMessageId::new(),
2443            content: vec![UserMessageContent::Text(content)],
2444        }));
2445        cx.notify();
2446        self.send_existing(cx)
2447    }
2448
2449    pub fn interrupt_for_summary(
2450        &mut self,
2451        cx: &mut Context<Self>,
2452    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
2453        let context = self
2454            .subagent_context
2455            .as_ref()
2456            .context("Not a subagent thread")?;
2457        let prompt = context.context_low_prompt.clone();
2458        self.cancel(cx).detach();
2459        self.submit_user_message(prompt, cx)
2460    }
2461
2462    pub fn request_final_summary(
2463        &mut self,
2464        cx: &mut Context<Self>,
2465    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
2466        let context = self
2467            .subagent_context
2468            .as_ref()
2469            .context("Not a subagent thread")?;
2470        let prompt = context.summary_prompt.clone();
2471        self.submit_user_message(prompt, cx)
2472    }
2473
2474    fn build_request_messages(
2475        &self,
2476        available_tools: Vec<SharedString>,
2477        cx: &App,
2478    ) -> Vec<LanguageModelRequestMessage> {
2479        log::trace!(
2480            "Building request messages from {} thread messages",
2481            self.messages.len()
2482        );
2483
2484        let system_prompt = SystemPromptTemplate {
2485            project: self.project_context.read(cx),
2486            available_tools,
2487            model_name: self.model.as_ref().map(|m| m.name().0.to_string()),
2488        }
2489        .render(&self.templates)
2490        .context("failed to build system prompt")
2491        .expect("Invalid template");
2492        let mut messages = vec![LanguageModelRequestMessage {
2493            role: Role::System,
2494            content: vec![system_prompt.into()],
2495            cache: false,
2496            reasoning_details: None,
2497        }];
2498        for message in &self.messages {
2499            messages.extend(message.to_request());
2500        }
2501
2502        if let Some(last_message) = messages.last_mut() {
2503            last_message.cache = true;
2504        }
2505
2506        if let Some(message) = self.pending_message.as_ref() {
2507            messages.extend(message.to_request());
2508        }
2509
2510        messages
2511    }
2512
2513    pub fn to_markdown(&self) -> String {
2514        let mut markdown = String::new();
2515        for (ix, message) in self.messages.iter().enumerate() {
2516            if ix > 0 {
2517                markdown.push('\n');
2518            }
2519            markdown.push_str(&message.to_markdown());
2520        }
2521
2522        if let Some(message) = self.pending_message.as_ref() {
2523            markdown.push('\n');
2524            markdown.push_str(&message.to_markdown());
2525        }
2526
2527        markdown
2528    }
2529
2530    fn advance_prompt_id(&mut self) {
2531        self.prompt_id = PromptId::new();
2532    }
2533
2534    fn retry_strategy_for(error: &LanguageModelCompletionError) -> Option<RetryStrategy> {
2535        use LanguageModelCompletionError::*;
2536        use http_client::StatusCode;
2537
2538        // General strategy here:
2539        // - If retrying won't help (e.g. invalid API key or payload too large), return None so we don't retry at all.
2540        // - If it's a time-based issue (e.g. server overloaded, rate limit exceeded), retry up to 4 times with exponential backoff.
2541        // - If it's an issue that *might* be fixed by retrying (e.g. internal server error), retry up to 3 times.
2542        match error {
2543            HttpResponseError {
2544                status_code: StatusCode::TOO_MANY_REQUESTS,
2545                ..
2546            } => Some(RetryStrategy::ExponentialBackoff {
2547                initial_delay: BASE_RETRY_DELAY,
2548                max_attempts: MAX_RETRY_ATTEMPTS,
2549            }),
2550            ServerOverloaded { retry_after, .. } | RateLimitExceeded { retry_after, .. } => {
2551                Some(RetryStrategy::Fixed {
2552                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2553                    max_attempts: MAX_RETRY_ATTEMPTS,
2554                })
2555            }
2556            UpstreamProviderError {
2557                status,
2558                retry_after,
2559                ..
2560            } => match *status {
2561                StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
2562                    Some(RetryStrategy::Fixed {
2563                        delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2564                        max_attempts: MAX_RETRY_ATTEMPTS,
2565                    })
2566                }
2567                StatusCode::INTERNAL_SERVER_ERROR => Some(RetryStrategy::Fixed {
2568                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2569                    // Internal Server Error could be anything, retry up to 3 times.
2570                    max_attempts: 3,
2571                }),
2572                status => {
2573                    // There is no StatusCode variant for the unofficial HTTP 529 ("The service is overloaded"),
2574                    // but we frequently get them in practice. See https://http.dev/529
2575                    if status.as_u16() == 529 {
2576                        Some(RetryStrategy::Fixed {
2577                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2578                            max_attempts: MAX_RETRY_ATTEMPTS,
2579                        })
2580                    } else {
2581                        Some(RetryStrategy::Fixed {
2582                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2583                            max_attempts: 2,
2584                        })
2585                    }
2586                }
2587            },
2588            ApiInternalServerError { .. } => Some(RetryStrategy::Fixed {
2589                delay: BASE_RETRY_DELAY,
2590                max_attempts: 3,
2591            }),
2592            ApiReadResponseError { .. }
2593            | HttpSend { .. }
2594            | DeserializeResponse { .. }
2595            | BadRequestFormat { .. } => Some(RetryStrategy::Fixed {
2596                delay: BASE_RETRY_DELAY,
2597                max_attempts: 3,
2598            }),
2599            // Retrying these errors definitely shouldn't help.
2600            HttpResponseError {
2601                status_code:
2602                    StatusCode::PAYLOAD_TOO_LARGE | StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED,
2603                ..
2604            }
2605            | AuthenticationError { .. }
2606            | PermissionError { .. }
2607            | NoApiKey { .. }
2608            | ApiEndpointNotFound { .. }
2609            | PromptTooLarge { .. } => None,
2610            // These errors might be transient, so retry them
2611            SerializeRequest { .. } | BuildRequestBody { .. } => Some(RetryStrategy::Fixed {
2612                delay: BASE_RETRY_DELAY,
2613                max_attempts: 1,
2614            }),
2615            // Retry all other 4xx and 5xx errors once.
2616            HttpResponseError { status_code, .. }
2617                if status_code.is_client_error() || status_code.is_server_error() =>
2618            {
2619                Some(RetryStrategy::Fixed {
2620                    delay: BASE_RETRY_DELAY,
2621                    max_attempts: 3,
2622                })
2623            }
2624            Other(err) if err.is::<language_model::PaymentRequiredError>() => {
2625                // Retrying won't help for Payment Required errors.
2626                None
2627            }
2628            // Conservatively assume that any other errors are non-retryable
2629            HttpResponseError { .. } | Other(..) => Some(RetryStrategy::Fixed {
2630                delay: BASE_RETRY_DELAY,
2631                max_attempts: 2,
2632            }),
2633        }
2634    }
2635}
2636
2637struct RunningTurn {
2638    /// Holds the task that handles agent interaction until the end of the turn.
2639    /// Survives across multiple requests as the model performs tool calls and
2640    /// we run tools, report their results.
2641    _task: Task<()>,
2642    /// The current event stream for the running turn. Used to report a final
2643    /// cancellation event if we cancel the turn.
2644    event_stream: ThreadEventStream,
2645    /// The tools that were enabled for this turn.
2646    tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
2647    /// Sender to signal tool cancellation. When cancel is called, this is
2648    /// set to true so all tools can detect user-initiated cancellation.
2649    cancellation_tx: watch::Sender<bool>,
2650}
2651
2652impl RunningTurn {
2653    fn cancel(mut self) -> Task<()> {
2654        log::debug!("Cancelling in progress turn");
2655        self.cancellation_tx.send(true).ok();
2656        self.event_stream.send_canceled();
2657        self._task
2658    }
2659}
2660
2661pub struct TokenUsageUpdated(pub Option<acp_thread::TokenUsage>);
2662
2663impl EventEmitter<TokenUsageUpdated> for Thread {}
2664
2665pub struct TitleUpdated;
2666
2667impl EventEmitter<TitleUpdated> for Thread {}
2668
2669pub trait AgentTool
2670where
2671    Self: 'static + Sized,
2672{
2673    type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
2674    type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
2675
2676    fn name() -> &'static str;
2677
2678    fn description() -> SharedString {
2679        let schema = schemars::schema_for!(Self::Input);
2680        SharedString::new(
2681            schema
2682                .get("description")
2683                .and_then(|description| description.as_str())
2684                .unwrap_or_default(),
2685        )
2686    }
2687
2688    fn kind() -> acp::ToolKind;
2689
2690    /// The initial tool title to display. Can be updated during the tool run.
2691    fn initial_title(
2692        &self,
2693        input: Result<Self::Input, serde_json::Value>,
2694        cx: &mut App,
2695    ) -> SharedString;
2696
2697    /// Returns the JSON schema that describes the tool's input.
2698    fn input_schema(format: LanguageModelToolSchemaFormat) -> Schema {
2699        language_model::tool_schema::root_schema_for::<Self::Input>(format)
2700    }
2701
2702    /// Some tools rely on a provider for the underlying billing or other reasons.
2703    /// Allow the tool to check if they are compatible, or should be filtered out.
2704    fn supports_provider(_provider: &LanguageModelProviderId) -> bool {
2705        true
2706    }
2707
2708    /// Runs the tool with the provided input.
2709    fn run(
2710        self: Arc<Self>,
2711        input: Self::Input,
2712        event_stream: ToolCallEventStream,
2713        cx: &mut App,
2714    ) -> Task<Result<Self::Output>>;
2715
2716    /// Emits events for a previous execution of the tool.
2717    fn replay(
2718        &self,
2719        _input: Self::Input,
2720        _output: Self::Output,
2721        _event_stream: ToolCallEventStream,
2722        _cx: &mut App,
2723    ) -> Result<()> {
2724        Ok(())
2725    }
2726
2727    fn erase(self) -> Arc<dyn AnyAgentTool> {
2728        Arc::new(Erased(Arc::new(self)))
2729    }
2730
2731    /// Create a new instance of this tool bound to a different thread.
2732    /// This is used when creating subagents, so that tools like EditFileTool
2733    /// that hold a thread reference will use the subagent's thread instead
2734    /// of the parent's thread.
2735    /// Returns None if the tool doesn't need rebinding (most tools).
2736    fn rebind_thread(&self, _new_thread: WeakEntity<Thread>) -> Option<Arc<dyn AnyAgentTool>> {
2737        None
2738    }
2739}
2740
2741pub struct Erased<T>(T);
2742
2743pub struct AgentToolOutput {
2744    pub llm_output: LanguageModelToolResultContent,
2745    pub raw_output: serde_json::Value,
2746}
2747
2748pub trait AnyAgentTool {
2749    fn name(&self) -> SharedString;
2750    fn description(&self) -> SharedString;
2751    fn kind(&self) -> acp::ToolKind;
2752    fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString;
2753    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
2754    fn supports_provider(&self, _provider: &LanguageModelProviderId) -> bool {
2755        true
2756    }
2757    fn run(
2758        self: Arc<Self>,
2759        input: serde_json::Value,
2760        event_stream: ToolCallEventStream,
2761        cx: &mut App,
2762    ) -> Task<Result<AgentToolOutput>>;
2763    fn replay(
2764        &self,
2765        input: serde_json::Value,
2766        output: serde_json::Value,
2767        event_stream: ToolCallEventStream,
2768        cx: &mut App,
2769    ) -> Result<()>;
2770    /// Create a new instance of this tool bound to a different thread.
2771    /// This is used when creating subagents, so that tools like EditFileTool
2772    /// that hold a thread reference will use the subagent's thread instead
2773    /// of the parent's thread.
2774    /// Returns None if the tool doesn't need rebinding (most tools).
2775    fn rebind_thread(&self, _new_thread: WeakEntity<Thread>) -> Option<Arc<dyn AnyAgentTool>> {
2776        None
2777    }
2778}
2779
2780impl<T> AnyAgentTool for Erased<Arc<T>>
2781where
2782    T: AgentTool,
2783{
2784    fn name(&self) -> SharedString {
2785        T::name().into()
2786    }
2787
2788    fn description(&self) -> SharedString {
2789        T::description()
2790    }
2791
2792    fn kind(&self) -> agent_client_protocol::ToolKind {
2793        T::kind()
2794    }
2795
2796    fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString {
2797        let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
2798        self.0.initial_title(parsed_input, _cx)
2799    }
2800
2801    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
2802        let mut json = serde_json::to_value(T::input_schema(format))?;
2803        language_model::tool_schema::adapt_schema_to_format(&mut json, format)?;
2804        Ok(json)
2805    }
2806
2807    fn supports_provider(&self, provider: &LanguageModelProviderId) -> bool {
2808        T::supports_provider(provider)
2809    }
2810
2811    fn run(
2812        self: Arc<Self>,
2813        input: serde_json::Value,
2814        event_stream: ToolCallEventStream,
2815        cx: &mut App,
2816    ) -> Task<Result<AgentToolOutput>> {
2817        cx.spawn(async move |cx| {
2818            let input = serde_json::from_value(input)?;
2819            let output = cx
2820                .update(|cx| self.0.clone().run(input, event_stream, cx))
2821                .await?;
2822            let raw_output = serde_json::to_value(&output)?;
2823            Ok(AgentToolOutput {
2824                llm_output: output.into(),
2825                raw_output,
2826            })
2827        })
2828    }
2829
2830    fn replay(
2831        &self,
2832        input: serde_json::Value,
2833        output: serde_json::Value,
2834        event_stream: ToolCallEventStream,
2835        cx: &mut App,
2836    ) -> Result<()> {
2837        let input = serde_json::from_value(input)?;
2838        let output = serde_json::from_value(output)?;
2839        self.0.replay(input, output, event_stream, cx)
2840    }
2841
2842    fn rebind_thread(&self, new_thread: WeakEntity<Thread>) -> Option<Arc<dyn AnyAgentTool>> {
2843        self.0.rebind_thread(new_thread)
2844    }
2845}
2846
2847#[derive(Clone)]
2848struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
2849
2850impl ThreadEventStream {
2851    fn send_user_message(&self, message: &UserMessage) {
2852        self.0
2853            .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
2854            .ok();
2855    }
2856
2857    fn send_text(&self, text: &str) {
2858        self.0
2859            .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
2860            .ok();
2861    }
2862
2863    fn send_thinking(&self, text: &str) {
2864        self.0
2865            .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
2866            .ok();
2867    }
2868
2869    fn send_tool_call(
2870        &self,
2871        id: &LanguageModelToolUseId,
2872        tool_name: &str,
2873        title: SharedString,
2874        kind: acp::ToolKind,
2875        input: serde_json::Value,
2876    ) {
2877        self.0
2878            .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
2879                id,
2880                tool_name,
2881                title.to_string(),
2882                kind,
2883                input,
2884            ))))
2885            .ok();
2886    }
2887
2888    fn initial_tool_call(
2889        id: &LanguageModelToolUseId,
2890        tool_name: &str,
2891        title: String,
2892        kind: acp::ToolKind,
2893        input: serde_json::Value,
2894    ) -> acp::ToolCall {
2895        acp::ToolCall::new(id.to_string(), title)
2896            .kind(kind)
2897            .raw_input(input)
2898            .meta(acp_thread::meta_with_tool_name(tool_name))
2899    }
2900
2901    fn update_tool_call_fields(
2902        &self,
2903        tool_use_id: &LanguageModelToolUseId,
2904        fields: acp::ToolCallUpdateFields,
2905    ) {
2906        self.0
2907            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
2908                acp::ToolCallUpdate::new(tool_use_id.to_string(), fields).into(),
2909            )))
2910            .ok();
2911    }
2912
2913    fn send_retry(&self, status: acp_thread::RetryStatus) {
2914        self.0.unbounded_send(Ok(ThreadEvent::Retry(status))).ok();
2915    }
2916
2917    fn send_stop(&self, reason: acp::StopReason) {
2918        self.0.unbounded_send(Ok(ThreadEvent::Stop(reason))).ok();
2919    }
2920
2921    fn send_canceled(&self) {
2922        self.0
2923            .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))
2924            .ok();
2925    }
2926
2927    fn send_error(&self, error: impl Into<anyhow::Error>) {
2928        self.0.unbounded_send(Err(error.into())).ok();
2929    }
2930}
2931
2932#[derive(Clone)]
2933pub struct ToolCallEventStream {
2934    tool_use_id: LanguageModelToolUseId,
2935    stream: ThreadEventStream,
2936    fs: Option<Arc<dyn Fs>>,
2937    cancellation_rx: watch::Receiver<bool>,
2938}
2939
2940impl ToolCallEventStream {
2941    #[cfg(any(test, feature = "test-support"))]
2942    pub fn test() -> (Self, ToolCallEventStreamReceiver) {
2943        let (stream, receiver, _cancellation_tx) = Self::test_with_cancellation();
2944        (stream, receiver)
2945    }
2946
2947    #[cfg(any(test, feature = "test-support"))]
2948    pub fn test_with_cancellation() -> (Self, ToolCallEventStreamReceiver, watch::Sender<bool>) {
2949        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
2950        let (cancellation_tx, cancellation_rx) = watch::channel(false);
2951
2952        let stream = ToolCallEventStream::new(
2953            "test_id".into(),
2954            ThreadEventStream(events_tx),
2955            None,
2956            cancellation_rx,
2957        );
2958
2959        (
2960            stream,
2961            ToolCallEventStreamReceiver(events_rx),
2962            cancellation_tx,
2963        )
2964    }
2965
2966    /// Signal cancellation for this event stream. Only available in tests.
2967    #[cfg(any(test, feature = "test-support"))]
2968    pub fn signal_cancellation_with_sender(cancellation_tx: &mut watch::Sender<bool>) {
2969        cancellation_tx.send(true).ok();
2970    }
2971
2972    fn new(
2973        tool_use_id: LanguageModelToolUseId,
2974        stream: ThreadEventStream,
2975        fs: Option<Arc<dyn Fs>>,
2976        cancellation_rx: watch::Receiver<bool>,
2977    ) -> Self {
2978        Self {
2979            tool_use_id,
2980            stream,
2981            fs,
2982            cancellation_rx,
2983        }
2984    }
2985
2986    /// Returns a future that resolves when the user cancels the tool call.
2987    /// Tools should select on this alongside their main work to detect user cancellation.
2988    pub fn cancelled_by_user(&self) -> impl std::future::Future<Output = ()> + '_ {
2989        let mut rx = self.cancellation_rx.clone();
2990        async move {
2991            loop {
2992                if *rx.borrow() {
2993                    return;
2994                }
2995                if rx.changed().await.is_err() {
2996                    // Sender dropped, will never be cancelled
2997                    std::future::pending::<()>().await;
2998                }
2999            }
3000        }
3001    }
3002
3003    /// Returns true if the user has cancelled this tool call.
3004    /// This is useful for checking cancellation state after an operation completes,
3005    /// to determine if the completion was due to user cancellation.
3006    pub fn was_cancelled_by_user(&self) -> bool {
3007        *self.cancellation_rx.clone().borrow()
3008    }
3009
3010    pub fn tool_use_id(&self) -> &LanguageModelToolUseId {
3011        &self.tool_use_id
3012    }
3013
3014    pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
3015        self.stream
3016            .update_tool_call_fields(&self.tool_use_id, fields);
3017    }
3018
3019    pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
3020        self.stream
3021            .0
3022            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3023                acp_thread::ToolCallUpdateDiff {
3024                    id: acp::ToolCallId::new(self.tool_use_id.to_string()),
3025                    diff,
3026                }
3027                .into(),
3028            )))
3029            .ok();
3030    }
3031
3032    pub fn update_subagent_thread(&self, thread: Entity<acp_thread::AcpThread>) {
3033        self.stream
3034            .0
3035            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3036                acp_thread::ToolCallUpdateSubagentThread {
3037                    id: acp::ToolCallId::new(self.tool_use_id.to_string()),
3038                    thread,
3039                }
3040                .into(),
3041            )))
3042            .ok();
3043    }
3044
3045    /// Authorize a third-party tool (e.g., MCP tool from a context server).
3046    ///
3047    /// Unlike built-in tools, third-party tools don't support pattern-based permissions.
3048    /// They only support `default_mode` (allow/deny/confirm) per tool.
3049    ///
3050    /// Uses the dropdown authorization flow with two granularities:
3051    /// - "Always for <display_name> MCP tool" → sets `tools.<tool_id>.default_mode = "allow"` or "deny"
3052    /// - "Only this time" → allow/deny once
3053    pub fn authorize_third_party_tool(
3054        &self,
3055        title: impl Into<String>,
3056        tool_id: String,
3057        display_name: String,
3058        cx: &mut App,
3059    ) -> Task<Result<()>> {
3060        let settings = agent_settings::AgentSettings::get_global(cx);
3061
3062        let decision = decide_permission_from_settings(&tool_id, "", &settings);
3063
3064        match decision {
3065            ToolPermissionDecision::Allow => return Task::ready(Ok(())),
3066            ToolPermissionDecision::Deny(reason) => return Task::ready(Err(anyhow!(reason))),
3067            ToolPermissionDecision::Confirm => {}
3068        }
3069
3070        let (response_tx, response_rx) = oneshot::channel();
3071        self.stream
3072            .0
3073            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3074                ToolCallAuthorization {
3075                    tool_call: acp::ToolCallUpdate::new(
3076                        self.tool_use_id.to_string(),
3077                        acp::ToolCallUpdateFields::new().title(title.into()),
3078                    ),
3079                    options: acp_thread::PermissionOptions::Dropdown(vec![
3080                        acp_thread::PermissionOptionChoice {
3081                            allow: acp::PermissionOption::new(
3082                                acp::PermissionOptionId::new(format!(
3083                                    "always_allow_mcp:{}",
3084                                    tool_id
3085                                )),
3086                                format!("Always for {} MCP tool", display_name),
3087                                acp::PermissionOptionKind::AllowAlways,
3088                            ),
3089                            deny: acp::PermissionOption::new(
3090                                acp::PermissionOptionId::new(format!(
3091                                    "always_deny_mcp:{}",
3092                                    tool_id
3093                                )),
3094                                format!("Always for {} MCP tool", display_name),
3095                                acp::PermissionOptionKind::RejectAlways,
3096                            ),
3097                        },
3098                        acp_thread::PermissionOptionChoice {
3099                            allow: acp::PermissionOption::new(
3100                                acp::PermissionOptionId::new("allow"),
3101                                "Only this time",
3102                                acp::PermissionOptionKind::AllowOnce,
3103                            ),
3104                            deny: acp::PermissionOption::new(
3105                                acp::PermissionOptionId::new("deny"),
3106                                "Only this time",
3107                                acp::PermissionOptionKind::RejectOnce,
3108                            ),
3109                        },
3110                    ]),
3111                    response: response_tx,
3112                    context: None,
3113                },
3114            )))
3115            .ok();
3116
3117        let fs = self.fs.clone();
3118        cx.spawn(async move |cx| {
3119            let response_str = response_rx.await?.0.to_string();
3120
3121            if response_str == format!("always_allow_mcp:{}", tool_id) {
3122                if let Some(fs) = fs.clone() {
3123                    cx.update(|cx| {
3124                        update_settings_file(fs, cx, move |settings, _| {
3125                            settings
3126                                .agent
3127                                .get_or_insert_default()
3128                                .set_tool_default_mode(&tool_id, ToolPermissionMode::Allow);
3129                        });
3130                    });
3131                }
3132                return Ok(());
3133            }
3134            if response_str == format!("always_deny_mcp:{}", tool_id) {
3135                if let Some(fs) = fs.clone() {
3136                    cx.update(|cx| {
3137                        update_settings_file(fs, cx, move |settings, _| {
3138                            settings
3139                                .agent
3140                                .get_or_insert_default()
3141                                .set_tool_default_mode(&tool_id, ToolPermissionMode::Deny);
3142                        });
3143                    });
3144                }
3145                return Err(anyhow!("Permission to run tool denied by user"));
3146            }
3147
3148            if response_str == "allow" {
3149                return Ok(());
3150            }
3151
3152            Err(anyhow!("Permission to run tool denied by user"))
3153        })
3154    }
3155
3156    pub fn authorize(
3157        &self,
3158        title: impl Into<String>,
3159        context: ToolPermissionContext,
3160        cx: &mut App,
3161    ) -> Task<Result<()>> {
3162        use settings::ToolPermissionMode;
3163
3164        let options = context.build_permission_options();
3165
3166        let (response_tx, response_rx) = oneshot::channel();
3167        self.stream
3168            .0
3169            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3170                ToolCallAuthorization {
3171                    tool_call: acp::ToolCallUpdate::new(
3172                        self.tool_use_id.to_string(),
3173                        acp::ToolCallUpdateFields::new().title(title.into()),
3174                    ),
3175                    options,
3176                    response: response_tx,
3177                    context: Some(context),
3178                },
3179            )))
3180            .ok();
3181
3182        let fs = self.fs.clone();
3183        cx.spawn(async move |cx| {
3184            let response_str = response_rx.await?.0.to_string();
3185
3186            // Handle "always allow tool" - e.g., "always_allow:terminal"
3187            if let Some(tool) = response_str.strip_prefix("always_allow:") {
3188                if let Some(fs) = fs.clone() {
3189                    let tool = tool.to_string();
3190                    cx.update(|cx| {
3191                        update_settings_file(fs, cx, move |settings, _| {
3192                            settings
3193                                .agent
3194                                .get_or_insert_default()
3195                                .set_tool_default_mode(&tool, ToolPermissionMode::Allow);
3196                        });
3197                    });
3198                }
3199                return Ok(());
3200            }
3201
3202            // Handle "always deny tool" - e.g., "always_deny:terminal"
3203            if let Some(tool) = response_str.strip_prefix("always_deny:") {
3204                if let Some(fs) = fs.clone() {
3205                    let tool = tool.to_string();
3206                    cx.update(|cx| {
3207                        update_settings_file(fs, cx, move |settings, _| {
3208                            settings
3209                                .agent
3210                                .get_or_insert_default()
3211                                .set_tool_default_mode(&tool, ToolPermissionMode::Deny);
3212                        });
3213                    });
3214                }
3215                return Err(anyhow!("Permission to run tool denied by user"));
3216            }
3217
3218            // Handle "always allow pattern" - e.g., "always_allow_pattern:terminal:^cargo\s"
3219            if response_str.starts_with("always_allow_pattern:") {
3220                let parts: Vec<&str> = response_str.splitn(3, ':').collect();
3221                if parts.len() == 3 {
3222                    let pattern_tool_name = parts[1].to_string();
3223                    let pattern = parts[2].to_string();
3224                    if let Some(fs) = fs.clone() {
3225                        cx.update(|cx| {
3226                            update_settings_file(fs, cx, move |settings, _| {
3227                                settings
3228                                    .agent
3229                                    .get_or_insert_default()
3230                                    .add_tool_allow_pattern(&pattern_tool_name, pattern);
3231                            });
3232                        });
3233                    }
3234                }
3235                return Ok(());
3236            }
3237
3238            // Handle "always deny pattern" - e.g., "always_deny_pattern:terminal:^cargo\s"
3239            if response_str.starts_with("always_deny_pattern:") {
3240                let parts: Vec<&str> = response_str.splitn(3, ':').collect();
3241                if parts.len() == 3 {
3242                    let pattern_tool_name = parts[1].to_string();
3243                    let pattern = parts[2].to_string();
3244                    if let Some(fs) = fs.clone() {
3245                        cx.update(|cx| {
3246                            update_settings_file(fs, cx, move |settings, _| {
3247                                settings
3248                                    .agent
3249                                    .get_or_insert_default()
3250                                    .add_tool_deny_pattern(&pattern_tool_name, pattern);
3251                            });
3252                        });
3253                    }
3254                }
3255                return Err(anyhow!("Permission to run tool denied by user"));
3256            }
3257
3258            // Handle simple "allow" (allow once)
3259            if response_str == "allow" {
3260                return Ok(());
3261            }
3262
3263            // Handle simple "deny" (deny once)
3264            Err(anyhow!("Permission to run tool denied by user"))
3265        })
3266    }
3267}
3268
3269#[cfg(any(test, feature = "test-support"))]
3270pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
3271
3272#[cfg(any(test, feature = "test-support"))]
3273impl ToolCallEventStreamReceiver {
3274    pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
3275        let event = self.0.next().await;
3276        if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
3277            auth
3278        } else {
3279            panic!("Expected ToolCallAuthorization but got: {:?}", event);
3280        }
3281    }
3282
3283    pub async fn expect_update_fields(&mut self) -> acp::ToolCallUpdateFields {
3284        let event = self.0.next().await;
3285        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
3286            update,
3287        )))) = event
3288        {
3289            update.fields
3290        } else {
3291            panic!("Expected update fields but got: {:?}", event);
3292        }
3293    }
3294
3295    pub async fn expect_diff(&mut self) -> Entity<acp_thread::Diff> {
3296        let event = self.0.next().await;
3297        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateDiff(
3298            update,
3299        )))) = event
3300        {
3301            update.diff
3302        } else {
3303            panic!("Expected diff but got: {:?}", event);
3304        }
3305    }
3306
3307    pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
3308        let event = self.0.next().await;
3309        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
3310            update,
3311        )))) = event
3312        {
3313            update.terminal
3314        } else {
3315            panic!("Expected terminal but got: {:?}", event);
3316        }
3317    }
3318}
3319
3320#[cfg(any(test, feature = "test-support"))]
3321impl std::ops::Deref for ToolCallEventStreamReceiver {
3322    type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
3323
3324    fn deref(&self) -> &Self::Target {
3325        &self.0
3326    }
3327}
3328
3329#[cfg(any(test, feature = "test-support"))]
3330impl std::ops::DerefMut for ToolCallEventStreamReceiver {
3331    fn deref_mut(&mut self) -> &mut Self::Target {
3332        &mut self.0
3333    }
3334}
3335
3336impl From<&str> for UserMessageContent {
3337    fn from(text: &str) -> Self {
3338        Self::Text(text.into())
3339    }
3340}
3341
3342impl UserMessageContent {
3343    pub fn from_content_block(value: acp::ContentBlock, path_style: PathStyle) -> Self {
3344        match value {
3345            acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
3346            acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
3347            acp::ContentBlock::Audio(_) => {
3348                // TODO
3349                Self::Text("[audio]".to_string())
3350            }
3351            acp::ContentBlock::ResourceLink(resource_link) => {
3352                match MentionUri::parse(&resource_link.uri, path_style) {
3353                    Ok(uri) => Self::Mention {
3354                        uri,
3355                        content: String::new(),
3356                    },
3357                    Err(err) => {
3358                        log::error!("Failed to parse mention link: {}", err);
3359                        Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
3360                    }
3361                }
3362            }
3363            acp::ContentBlock::Resource(resource) => match resource.resource {
3364                acp::EmbeddedResourceResource::TextResourceContents(resource) => {
3365                    match MentionUri::parse(&resource.uri, path_style) {
3366                        Ok(uri) => Self::Mention {
3367                            uri,
3368                            content: resource.text,
3369                        },
3370                        Err(err) => {
3371                            log::error!("Failed to parse mention link: {}", err);
3372                            Self::Text(
3373                                MarkdownCodeBlock {
3374                                    tag: &resource.uri,
3375                                    text: &resource.text,
3376                                }
3377                                .to_string(),
3378                            )
3379                        }
3380                    }
3381                }
3382                acp::EmbeddedResourceResource::BlobResourceContents(_) => {
3383                    // TODO
3384                    Self::Text("[blob]".to_string())
3385                }
3386                other => {
3387                    log::warn!("Unexpected content type: {:?}", other);
3388                    Self::Text("[unknown]".to_string())
3389                }
3390            },
3391            other => {
3392                log::warn!("Unexpected content type: {:?}", other);
3393                Self::Text("[unknown]".to_string())
3394            }
3395        }
3396    }
3397}
3398
3399impl From<UserMessageContent> for acp::ContentBlock {
3400    fn from(content: UserMessageContent) -> Self {
3401        match content {
3402            UserMessageContent::Text(text) => text.into(),
3403            UserMessageContent::Image(image) => {
3404                acp::ContentBlock::Image(acp::ImageContent::new(image.source, "image/png"))
3405            }
3406            UserMessageContent::Mention { uri, content } => acp::ContentBlock::Resource(
3407                acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(
3408                    acp::TextResourceContents::new(content, uri.to_uri().to_string()),
3409                )),
3410            ),
3411        }
3412    }
3413}
3414
3415fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
3416    LanguageModelImage {
3417        source: image_content.data.into(),
3418        size: None,
3419    }
3420}