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