thread.rs

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