thread.rs

   1use crate::{
   2    ContextServerRegistry, CopyPathTool, CreateDirectoryTool, DbLanguageModel, DbThread,
   3    DeletePathTool, DiagnosticsTool, EditFileTool, FetchTool, FindPathTool, GrepTool,
   4    ListDirectoryTool, MovePathTool, NowTool, OpenTool, ProjectSnapshot, ReadFileTool,
   5    RestoreFileFromDiskTool, SaveFileTool, StreamingEditFileTool, SubagentTool,
   6    SystemPromptTemplate, Template, Templates, TerminalTool, ThinkingTool, ToolPermissionDecision,
   7    WebSearchTool, decide_permission_from_settings,
   8};
   9use acp_thread::{MentionUri, UserMessageId};
  10use action_log::ActionLog;
  11use feature_flags::{FeatureFlagAppExt as _, SubagentsFeatureFlag};
  12
  13use agent_client_protocol as acp;
  14use agent_settings::{
  15    AgentProfileId, AgentProfileSettings, AgentSettings, SUMMARIZE_THREAD_DETAILED_PROMPT,
  16    SUMMARIZE_THREAD_PROMPT,
  17};
  18use anyhow::{Context as _, Result, anyhow};
  19use chrono::{DateTime, Utc};
  20use client::UserStore;
  21use cloud_api_types::Plan;
  22use cloud_llm_client::CompletionIntent;
  23use collections::{HashMap, HashSet, IndexMap};
  24use fs::Fs;
  25use futures::stream;
  26use futures::{
  27    FutureExt,
  28    channel::{mpsc, oneshot},
  29    future::Shared,
  30    stream::FuturesUnordered,
  31};
  32use gpui::{
  33    App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task, WeakEntity,
  34};
  35use language_model::{
  36    LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelId,
  37    LanguageModelImage, LanguageModelProviderId, LanguageModelRegistry, LanguageModelRequest,
  38    LanguageModelRequestMessage, LanguageModelRequestTool, LanguageModelToolResult,
  39    LanguageModelToolResultContent, LanguageModelToolSchemaFormat, LanguageModelToolUse,
  40    LanguageModelToolUseId, Role, SelectedModel, StopReason, TokenUsage, ZED_CLOUD_PROVIDER_ID,
  41};
  42use project::Project;
  43use prompt_store::ProjectContext;
  44use schemars::{JsonSchema, Schema};
  45use serde::{Deserialize, Serialize};
  46use settings::{LanguageModelSelection, Settings, ToolPermissionMode, update_settings_file};
  47use smol::stream::StreamExt;
  48use std::{
  49    collections::BTreeMap,
  50    ops::RangeInclusive,
  51    path::Path,
  52    rc::Rc,
  53    sync::Arc,
  54    time::{Duration, Instant},
  55};
  56use std::{fmt::Write, path::PathBuf};
  57use util::{ResultExt, debug_panic, markdown::MarkdownCodeBlock, paths::PathStyle};
  58use uuid::Uuid;
  59
  60const TOOL_CANCELED_MESSAGE: &str = "Tool canceled by user";
  61pub const MAX_TOOL_NAME_LENGTH: usize = 64;
  62pub const MAX_SUBAGENT_DEPTH: u8 = 4;
  63pub const MAX_PARALLEL_SUBAGENTS: usize = 8;
  64
  65/// Context passed to a subagent thread for lifecycle management
  66#[derive(Clone)]
  67pub struct SubagentContext {
  68    /// ID of the parent thread
  69    pub parent_thread_id: acp::SessionId,
  70
  71    /// ID of the tool call that spawned this subagent
  72    pub tool_use_id: LanguageModelToolUseId,
  73
  74    /// Current depth level (0 = root agent, 1 = first-level subagent, etc.)
  75    pub depth: u8,
  76
  77    /// Prompt to send when subagent completes successfully
  78    pub summary_prompt: String,
  79
  80    /// Prompt to send when context is running low (≤25% remaining)
  81    pub context_low_prompt: String,
  82}
  83
  84/// The ID of the user prompt that initiated a request.
  85///
  86/// This equates to the user physically submitting a message to the model (e.g., by pressing the Enter key).
  87#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
  88pub struct PromptId(Arc<str>);
  89
  90impl PromptId {
  91    pub fn new() -> Self {
  92        Self(Uuid::new_v4().to_string().into())
  93    }
  94}
  95
  96impl std::fmt::Display for PromptId {
  97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  98        write!(f, "{}", self.0)
  99    }
 100}
 101
 102pub(crate) const MAX_RETRY_ATTEMPTS: u8 = 4;
 103pub(crate) const BASE_RETRY_DELAY: Duration = Duration::from_secs(5);
 104
 105#[derive(Debug, Clone)]
 106enum RetryStrategy {
 107    ExponentialBackoff {
 108        initial_delay: Duration,
 109        max_attempts: u8,
 110    },
 111    Fixed {
 112        delay: Duration,
 113        max_attempts: u8,
 114    },
 115}
 116
 117#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 118pub enum Message {
 119    User(UserMessage),
 120    Agent(AgentMessage),
 121    Resume,
 122}
 123
 124impl Message {
 125    pub fn as_agent_message(&self) -> Option<&AgentMessage> {
 126        match self {
 127            Message::Agent(agent_message) => Some(agent_message),
 128            _ => None,
 129        }
 130    }
 131
 132    pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
 133        match self {
 134            Message::User(message) => {
 135                if message.content.is_empty() {
 136                    vec![]
 137                } else {
 138                    vec![message.to_request()]
 139                }
 140            }
 141            Message::Agent(message) => message.to_request(),
 142            Message::Resume => vec![LanguageModelRequestMessage {
 143                role: Role::User,
 144                content: vec!["Continue where you left off".into()],
 145                cache: false,
 146                reasoning_details: None,
 147            }],
 148        }
 149    }
 150
 151    pub fn to_markdown(&self) -> String {
 152        match self {
 153            Message::User(message) => message.to_markdown(),
 154            Message::Agent(message) => message.to_markdown(),
 155            Message::Resume => "[resume]\n".into(),
 156        }
 157    }
 158
 159    pub fn role(&self) -> Role {
 160        match self {
 161            Message::User(_) | Message::Resume => Role::User,
 162            Message::Agent(_) => Role::Assistant,
 163        }
 164    }
 165}
 166
 167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 168pub struct UserMessage {
 169    pub id: UserMessageId,
 170    pub content: Vec<UserMessageContent>,
 171}
 172
 173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 174pub enum UserMessageContent {
 175    Text(String),
 176    Mention { uri: MentionUri, content: String },
 177    Image(LanguageModelImage),
 178}
 179
 180impl UserMessage {
 181    pub fn to_markdown(&self) -> String {
 182        let mut markdown = String::from("## User\n\n");
 183
 184        for content in &self.content {
 185            match content {
 186                UserMessageContent::Text(text) => {
 187                    markdown.push_str(text);
 188                    markdown.push('\n');
 189                }
 190                UserMessageContent::Image(_) => {
 191                    markdown.push_str("<image />\n");
 192                }
 193                UserMessageContent::Mention { uri, content } => {
 194                    if !content.is_empty() {
 195                        let _ = writeln!(&mut markdown, "{}\n\n{}", uri.as_link(), content);
 196                    } else {
 197                        let _ = writeln!(&mut markdown, "{}", uri.as_link());
 198                    }
 199                }
 200            }
 201        }
 202
 203        markdown
 204    }
 205
 206    fn to_request(&self) -> LanguageModelRequestMessage {
 207        let mut message = LanguageModelRequestMessage {
 208            role: Role::User,
 209            content: Vec::with_capacity(self.content.len()),
 210            cache: false,
 211            reasoning_details: None,
 212        };
 213
 214        const OPEN_CONTEXT: &str = "<context>\n\
 215            The following items were attached by the user. \
 216            They are up-to-date and don't need to be re-read.\n\n";
 217
 218        const OPEN_FILES_TAG: &str = "<files>";
 219        const OPEN_DIRECTORIES_TAG: &str = "<directories>";
 220        const OPEN_SYMBOLS_TAG: &str = "<symbols>";
 221        const OPEN_SELECTIONS_TAG: &str = "<selections>";
 222        const OPEN_THREADS_TAG: &str = "<threads>";
 223        const OPEN_FETCH_TAG: &str = "<fetched_urls>";
 224        const OPEN_RULES_TAG: &str =
 225            "<rules>\nThe user has specified the following rules that should be applied:\n";
 226        const OPEN_DIAGNOSTICS_TAG: &str = "<diagnostics>";
 227
 228        let mut file_context = OPEN_FILES_TAG.to_string();
 229        let mut directory_context = OPEN_DIRECTORIES_TAG.to_string();
 230        let mut symbol_context = OPEN_SYMBOLS_TAG.to_string();
 231        let mut selection_context = OPEN_SELECTIONS_TAG.to_string();
 232        let mut thread_context = OPEN_THREADS_TAG.to_string();
 233        let mut fetch_context = OPEN_FETCH_TAG.to_string();
 234        let mut rules_context = OPEN_RULES_TAG.to_string();
 235        let mut diagnostics_context = OPEN_DIAGNOSTICS_TAG.to_string();
 236
 237        for chunk in &self.content {
 238            let chunk = match chunk {
 239                UserMessageContent::Text(text) => {
 240                    language_model::MessageContent::Text(text.clone())
 241                }
 242                UserMessageContent::Image(value) => {
 243                    language_model::MessageContent::Image(value.clone())
 244                }
 245                UserMessageContent::Mention { uri, content } => {
 246                    match uri {
 247                        MentionUri::File { abs_path } => {
 248                            write!(
 249                                &mut file_context,
 250                                "\n{}",
 251                                MarkdownCodeBlock {
 252                                    tag: &codeblock_tag(abs_path, None),
 253                                    text: &content.to_string(),
 254                                }
 255                            )
 256                            .ok();
 257                        }
 258                        MentionUri::PastedImage => {
 259                            debug_panic!("pasted image URI should not be used in mention content")
 260                        }
 261                        MentionUri::Directory { .. } => {
 262                            write!(&mut directory_context, "\n{}\n", content).ok();
 263                        }
 264                        MentionUri::Symbol {
 265                            abs_path: path,
 266                            line_range,
 267                            ..
 268                        } => {
 269                            write!(
 270                                &mut symbol_context,
 271                                "\n{}",
 272                                MarkdownCodeBlock {
 273                                    tag: &codeblock_tag(path, Some(line_range)),
 274                                    text: content
 275                                }
 276                            )
 277                            .ok();
 278                        }
 279                        MentionUri::Selection {
 280                            abs_path: path,
 281                            line_range,
 282                            ..
 283                        } => {
 284                            write!(
 285                                &mut selection_context,
 286                                "\n{}",
 287                                MarkdownCodeBlock {
 288                                    tag: &codeblock_tag(
 289                                        path.as_deref().unwrap_or("Untitled".as_ref()),
 290                                        Some(line_range)
 291                                    ),
 292                                    text: content
 293                                }
 294                            )
 295                            .ok();
 296                        }
 297                        MentionUri::Thread { .. } => {
 298                            write!(&mut thread_context, "\n{}\n", content).ok();
 299                        }
 300                        MentionUri::TextThread { .. } => {
 301                            write!(&mut thread_context, "\n{}\n", content).ok();
 302                        }
 303                        MentionUri::Rule { .. } => {
 304                            write!(
 305                                &mut rules_context,
 306                                "\n{}",
 307                                MarkdownCodeBlock {
 308                                    tag: "",
 309                                    text: content
 310                                }
 311                            )
 312                            .ok();
 313                        }
 314                        MentionUri::Fetch { url } => {
 315                            write!(&mut fetch_context, "\nFetch: {}\n\n{}", url, content).ok();
 316                        }
 317                        MentionUri::Diagnostics { .. } => {
 318                            write!(&mut diagnostics_context, "\n{}\n", content).ok();
 319                        }
 320                        MentionUri::TerminalSelection { .. } => {
 321                            write!(
 322                                &mut selection_context,
 323                                "\n{}",
 324                                MarkdownCodeBlock {
 325                                    tag: "console",
 326                                    text: content
 327                                }
 328                            )
 329                            .ok();
 330                        }
 331                    }
 332
 333                    language_model::MessageContent::Text(uri.as_link().to_string())
 334                }
 335            };
 336
 337            message.content.push(chunk);
 338        }
 339
 340        let len_before_context = message.content.len();
 341
 342        if file_context.len() > OPEN_FILES_TAG.len() {
 343            file_context.push_str("</files>\n");
 344            message
 345                .content
 346                .push(language_model::MessageContent::Text(file_context));
 347        }
 348
 349        if directory_context.len() > OPEN_DIRECTORIES_TAG.len() {
 350            directory_context.push_str("</directories>\n");
 351            message
 352                .content
 353                .push(language_model::MessageContent::Text(directory_context));
 354        }
 355
 356        if symbol_context.len() > OPEN_SYMBOLS_TAG.len() {
 357            symbol_context.push_str("</symbols>\n");
 358            message
 359                .content
 360                .push(language_model::MessageContent::Text(symbol_context));
 361        }
 362
 363        if selection_context.len() > OPEN_SELECTIONS_TAG.len() {
 364            selection_context.push_str("</selections>\n");
 365            message
 366                .content
 367                .push(language_model::MessageContent::Text(selection_context));
 368        }
 369
 370        if thread_context.len() > OPEN_THREADS_TAG.len() {
 371            thread_context.push_str("</threads>\n");
 372            message
 373                .content
 374                .push(language_model::MessageContent::Text(thread_context));
 375        }
 376
 377        if fetch_context.len() > OPEN_FETCH_TAG.len() {
 378            fetch_context.push_str("</fetched_urls>\n");
 379            message
 380                .content
 381                .push(language_model::MessageContent::Text(fetch_context));
 382        }
 383
 384        if rules_context.len() > OPEN_RULES_TAG.len() {
 385            rules_context.push_str("</user_rules>\n");
 386            message
 387                .content
 388                .push(language_model::MessageContent::Text(rules_context));
 389        }
 390
 391        if diagnostics_context.len() > OPEN_DIAGNOSTICS_TAG.len() {
 392            diagnostics_context.push_str("</diagnostics>\n");
 393            message
 394                .content
 395                .push(language_model::MessageContent::Text(diagnostics_context));
 396        }
 397
 398        if message.content.len() > len_before_context {
 399            message.content.insert(
 400                len_before_context,
 401                language_model::MessageContent::Text(OPEN_CONTEXT.into()),
 402            );
 403            message
 404                .content
 405                .push(language_model::MessageContent::Text("</context>".into()));
 406        }
 407
 408        message
 409    }
 410}
 411
 412fn codeblock_tag(full_path: &Path, line_range: Option<&RangeInclusive<u32>>) -> String {
 413    let mut result = String::new();
 414
 415    if let Some(extension) = full_path.extension().and_then(|ext| ext.to_str()) {
 416        let _ = write!(result, "{} ", extension);
 417    }
 418
 419    let _ = write!(result, "{}", full_path.display());
 420
 421    if let Some(range) = line_range {
 422        if range.start() == range.end() {
 423            let _ = write!(result, ":{}", range.start() + 1);
 424        } else {
 425            let _ = write!(result, ":{}-{}", range.start() + 1, range.end() + 1);
 426        }
 427    }
 428
 429    result
 430}
 431
 432impl AgentMessage {
 433    pub fn to_markdown(&self) -> String {
 434        let mut markdown = String::from("## Assistant\n\n");
 435
 436        for content in &self.content {
 437            match content {
 438                AgentMessageContent::Text(text) => {
 439                    markdown.push_str(text);
 440                    markdown.push('\n');
 441                }
 442                AgentMessageContent::Thinking { text, .. } => {
 443                    markdown.push_str("<think>");
 444                    markdown.push_str(text);
 445                    markdown.push_str("</think>\n");
 446                }
 447                AgentMessageContent::RedactedThinking(_) => {
 448                    markdown.push_str("<redacted_thinking />\n")
 449                }
 450                AgentMessageContent::ToolUse(tool_use) => {
 451                    markdown.push_str(&format!(
 452                        "**Tool Use**: {} (ID: {})\n",
 453                        tool_use.name, tool_use.id
 454                    ));
 455                    markdown.push_str(&format!(
 456                        "{}\n",
 457                        MarkdownCodeBlock {
 458                            tag: "json",
 459                            text: &format!("{:#}", tool_use.input)
 460                        }
 461                    ));
 462                }
 463            }
 464        }
 465
 466        for tool_result in self.tool_results.values() {
 467            markdown.push_str(&format!(
 468                "**Tool Result**: {} (ID: {})\n\n",
 469                tool_result.tool_name, tool_result.tool_use_id
 470            ));
 471            if tool_result.is_error {
 472                markdown.push_str("**ERROR:**\n");
 473            }
 474
 475            match &tool_result.content {
 476                LanguageModelToolResultContent::Text(text) => {
 477                    writeln!(markdown, "{text}\n").ok();
 478                }
 479                LanguageModelToolResultContent::Image(_) => {
 480                    writeln!(markdown, "<image />\n").ok();
 481                }
 482            }
 483
 484            if let Some(output) = tool_result.output.as_ref() {
 485                writeln!(
 486                    markdown,
 487                    "**Debug Output**:\n\n```json\n{}\n```\n",
 488                    serde_json::to_string_pretty(output).unwrap()
 489                )
 490                .unwrap();
 491            }
 492        }
 493
 494        markdown
 495    }
 496
 497    pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
 498        let mut assistant_message = LanguageModelRequestMessage {
 499            role: Role::Assistant,
 500            content: Vec::with_capacity(self.content.len()),
 501            cache: false,
 502            reasoning_details: self.reasoning_details.clone(),
 503        };
 504        for chunk in &self.content {
 505            match chunk {
 506                AgentMessageContent::Text(text) => {
 507                    assistant_message
 508                        .content
 509                        .push(language_model::MessageContent::Text(text.clone()));
 510                }
 511                AgentMessageContent::Thinking { text, signature } => {
 512                    assistant_message
 513                        .content
 514                        .push(language_model::MessageContent::Thinking {
 515                            text: text.clone(),
 516                            signature: signature.clone(),
 517                        });
 518                }
 519                AgentMessageContent::RedactedThinking(value) => {
 520                    assistant_message.content.push(
 521                        language_model::MessageContent::RedactedThinking(value.clone()),
 522                    );
 523                }
 524                AgentMessageContent::ToolUse(tool_use) => {
 525                    if self.tool_results.contains_key(&tool_use.id) {
 526                        assistant_message
 527                            .content
 528                            .push(language_model::MessageContent::ToolUse(tool_use.clone()));
 529                    }
 530                }
 531            };
 532        }
 533
 534        let mut user_message = LanguageModelRequestMessage {
 535            role: Role::User,
 536            content: Vec::new(),
 537            cache: false,
 538            reasoning_details: None,
 539        };
 540
 541        for tool_result in self.tool_results.values() {
 542            let mut tool_result = tool_result.clone();
 543            // Surprisingly, the API fails if we return an empty string here.
 544            // It thinks we are sending a tool use without a tool result.
 545            if tool_result.content.is_empty() {
 546                tool_result.content = "<Tool returned an empty string>".into();
 547            }
 548            user_message
 549                .content
 550                .push(language_model::MessageContent::ToolResult(tool_result));
 551        }
 552
 553        let mut messages = Vec::new();
 554        if !assistant_message.content.is_empty() {
 555            messages.push(assistant_message);
 556        }
 557        if !user_message.content.is_empty() {
 558            messages.push(user_message);
 559        }
 560        messages
 561    }
 562}
 563
 564#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 565pub struct AgentMessage {
 566    pub content: Vec<AgentMessageContent>,
 567    pub tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
 568    pub reasoning_details: Option<serde_json::Value>,
 569}
 570
 571#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 572pub enum AgentMessageContent {
 573    Text(String),
 574    Thinking {
 575        text: String,
 576        signature: Option<String>,
 577    },
 578    RedactedThinking(String),
 579    ToolUse(LanguageModelToolUse),
 580}
 581
 582pub trait TerminalHandle {
 583    fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId>;
 584    fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse>;
 585    fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>>;
 586    fn kill(&self, cx: &AsyncApp) -> Result<()>;
 587    fn was_stopped_by_user(&self, cx: &AsyncApp) -> Result<bool>;
 588}
 589
 590pub trait ThreadEnvironment {
 591    fn create_terminal(
 592        &self,
 593        command: String,
 594        cwd: Option<PathBuf>,
 595        output_byte_limit: Option<u64>,
 596        cx: &mut AsyncApp,
 597    ) -> Task<Result<Rc<dyn TerminalHandle>>>;
 598}
 599
 600#[derive(Debug)]
 601pub enum ThreadEvent {
 602    UserMessage(UserMessage),
 603    AgentText(String),
 604    AgentThinking(String),
 605    ToolCall(acp::ToolCall),
 606    ToolCallUpdate(acp_thread::ToolCallUpdate),
 607    ToolCallAuthorization(ToolCallAuthorization),
 608    Retry(acp_thread::RetryStatus),
 609    Stop(acp::StopReason),
 610}
 611
 612#[derive(Debug)]
 613pub struct NewTerminal {
 614    pub command: String,
 615    pub output_byte_limit: Option<u64>,
 616    pub cwd: Option<PathBuf>,
 617    pub response: oneshot::Sender<Result<Entity<acp_thread::Terminal>>>,
 618}
 619
 620#[derive(Debug, Clone)]
 621pub struct ToolPermissionContext {
 622    pub tool_name: String,
 623    pub input_value: String,
 624}
 625
 626impl ToolPermissionContext {
 627    pub fn new(tool_name: impl Into<String>, input_value: impl Into<String>) -> Self {
 628        Self {
 629            tool_name: tool_name.into(),
 630            input_value: input_value.into(),
 631        }
 632    }
 633
 634    /// Builds the permission options for this tool context.
 635    ///
 636    /// This is the canonical source for permission option generation.
 637    /// Tests should use this function rather than manually constructing options.
 638    ///
 639    /// # Shell Compatibility for Terminal Tool
 640    ///
 641    /// For the terminal tool, "Always allow" options are only shown when the user's
 642    /// shell supports POSIX-like command chaining syntax (`&&`, `||`, `;`, `|`).
 643    ///
 644    /// **Why this matters:** When a user sets up an "always allow" pattern like `^cargo`,
 645    /// we need to parse the command to extract all sub-commands and verify that EVERY
 646    /// sub-command matches the pattern. Otherwise, an attacker could craft a command like
 647    /// `cargo build && rm -rf /` that would bypass the security check.
 648    ///
 649    /// **Supported shells:** Posix (sh, bash, dash, zsh), Fish 3.0+, PowerShell 7+/Pwsh,
 650    /// Cmd, Xonsh, Csh, Tcsh
 651    ///
 652    /// **Unsupported shells:** Nushell (uses `and`/`or` keywords), Elvish (uses `and`/`or`
 653    /// keywords), Rc (Plan 9 shell - no `&&`/`||` operators)
 654    ///
 655    /// For unsupported shells, we hide the "Always allow" UI options entirely, and if
 656    /// the user has `always_allow` rules configured in settings, `ToolPermissionDecision::from_input`
 657    /// will return a `Deny` with an explanatory error message.
 658    pub fn build_permission_options(&self) -> acp_thread::PermissionOptions {
 659        use crate::pattern_extraction::*;
 660        use util::shell::ShellKind;
 661
 662        let tool_name = &self.tool_name;
 663        let input_value = &self.input_value;
 664
 665        // Check if the user's shell supports POSIX-like command chaining.
 666        // See the doc comment above for the full explanation of why this is needed.
 667        let shell_supports_always_allow = if tool_name == TerminalTool::name() {
 668            ShellKind::system().supports_posix_chaining()
 669        } else {
 670            true
 671        };
 672
 673        let (pattern, pattern_display) = if tool_name == TerminalTool::name() {
 674            (
 675                extract_terminal_pattern(input_value),
 676                extract_terminal_pattern_display(input_value),
 677            )
 678        } else if tool_name == EditFileTool::name()
 679            || tool_name == DeletePathTool::name()
 680            || tool_name == MovePathTool::name()
 681            || tool_name == CreateDirectoryTool::name()
 682            || tool_name == SaveFileTool::name()
 683        {
 684            (
 685                extract_path_pattern(input_value),
 686                extract_path_pattern_display(input_value),
 687            )
 688        } else if tool_name == FetchTool::name() {
 689            (
 690                extract_url_pattern(input_value),
 691                extract_url_pattern_display(input_value),
 692            )
 693        } else {
 694            (None, None)
 695        };
 696
 697        let mut choices = Vec::new();
 698
 699        let mut push_choice = |label: String, allow_id, deny_id, allow_kind, deny_kind| {
 700            choices.push(acp_thread::PermissionOptionChoice {
 701                allow: acp::PermissionOption::new(
 702                    acp::PermissionOptionId::new(allow_id),
 703                    label.clone(),
 704                    allow_kind,
 705                ),
 706                deny: acp::PermissionOption::new(
 707                    acp::PermissionOptionId::new(deny_id),
 708                    label,
 709                    deny_kind,
 710                ),
 711            });
 712        };
 713
 714        if shell_supports_always_allow {
 715            push_choice(
 716                format!("Always for {}", tool_name.replace('_', " ")),
 717                format!("always_allow:{}", tool_name),
 718                format!("always_deny:{}", tool_name),
 719                acp::PermissionOptionKind::AllowAlways,
 720                acp::PermissionOptionKind::RejectAlways,
 721            );
 722
 723            if let (Some(pattern), Some(display)) = (pattern, pattern_display) {
 724                let button_text = if tool_name == TerminalTool::name() {
 725                    format!("Always for `{}` commands", display)
 726                } else {
 727                    format!("Always for `{}`", display)
 728                };
 729                push_choice(
 730                    button_text,
 731                    format!("always_allow_pattern:{}:{}", tool_name, pattern),
 732                    format!("always_deny_pattern:{}:{}", tool_name, pattern),
 733                    acp::PermissionOptionKind::AllowAlways,
 734                    acp::PermissionOptionKind::RejectAlways,
 735                );
 736            }
 737        }
 738
 739        push_choice(
 740            "Only this time".to_string(),
 741            "allow".to_string(),
 742            "deny".to_string(),
 743            acp::PermissionOptionKind::AllowOnce,
 744            acp::PermissionOptionKind::RejectOnce,
 745        );
 746
 747        acp_thread::PermissionOptions::Dropdown(choices)
 748    }
 749}
 750
 751#[derive(Debug)]
 752pub struct ToolCallAuthorization {
 753    pub tool_call: acp::ToolCallUpdate,
 754    pub options: acp_thread::PermissionOptions,
 755    pub response: oneshot::Sender<acp::PermissionOptionId>,
 756    pub context: Option<ToolPermissionContext>,
 757}
 758
 759#[derive(Debug, thiserror::Error)]
 760enum CompletionError {
 761    #[error("max tokens")]
 762    MaxTokens,
 763    #[error("refusal")]
 764    Refusal,
 765    #[error(transparent)]
 766    Other(#[from] anyhow::Error),
 767}
 768
 769pub struct Thread {
 770    id: acp::SessionId,
 771    prompt_id: PromptId,
 772    updated_at: DateTime<Utc>,
 773    title: Option<SharedString>,
 774    pending_title_generation: Option<Task<()>>,
 775    pending_summary_generation: Option<Shared<Task<Option<SharedString>>>>,
 776    summary: Option<SharedString>,
 777    messages: Vec<Message>,
 778    user_store: Entity<UserStore>,
 779    /// Holds the task that handles agent interaction until the end of the turn.
 780    /// Survives across multiple requests as the model performs tool calls and
 781    /// we run tools, report their results.
 782    running_turn: Option<RunningTurn>,
 783    /// Flag indicating the UI has a queued message waiting to be sent.
 784    /// Used to signal that the turn should end at the next message boundary.
 785    has_queued_message: bool,
 786    pending_message: Option<AgentMessage>,
 787    pub(crate) tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
 788    request_token_usage: HashMap<UserMessageId, language_model::TokenUsage>,
 789    #[allow(unused)]
 790    cumulative_token_usage: TokenUsage,
 791    #[allow(unused)]
 792    initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
 793    pub(crate) context_server_registry: Entity<ContextServerRegistry>,
 794    profile_id: AgentProfileId,
 795    project_context: Entity<ProjectContext>,
 796    pub(crate) templates: Arc<Templates>,
 797    model: Option<Arc<dyn LanguageModel>>,
 798    summarization_model: Option<Arc<dyn LanguageModel>>,
 799    thinking_enabled: bool,
 800    prompt_capabilities_tx: watch::Sender<acp::PromptCapabilities>,
 801    pub(crate) prompt_capabilities_rx: watch::Receiver<acp::PromptCapabilities>,
 802    pub(crate) project: Entity<Project>,
 803    pub(crate) action_log: Entity<ActionLog>,
 804    /// Tracks the last time files were read by the agent, to detect external modifications
 805    pub(crate) file_read_times: HashMap<PathBuf, fs::MTime>,
 806    /// True if this thread was imported from a shared thread and can be synced.
 807    imported: bool,
 808    /// If this is a subagent thread, contains context about the parent
 809    subagent_context: Option<SubagentContext>,
 810    /// Weak references to running subagent threads for cancellation propagation
 811    running_subagents: Vec<WeakEntity<Thread>>,
 812}
 813
 814impl Thread {
 815    fn prompt_capabilities(model: Option<&dyn LanguageModel>) -> acp::PromptCapabilities {
 816        let image = model.map_or(true, |model| model.supports_images());
 817        acp::PromptCapabilities::new()
 818            .image(image)
 819            .embedded_context(true)
 820    }
 821
 822    pub fn new(
 823        project: Entity<Project>,
 824        project_context: Entity<ProjectContext>,
 825        context_server_registry: Entity<ContextServerRegistry>,
 826        templates: Arc<Templates>,
 827        model: Option<Arc<dyn LanguageModel>>,
 828        cx: &mut Context<Self>,
 829    ) -> Self {
 830        let profile_id = AgentSettings::get_global(cx).default_profile.clone();
 831        let action_log = cx.new(|_cx| ActionLog::new(project.clone()));
 832        let (prompt_capabilities_tx, prompt_capabilities_rx) =
 833            watch::channel(Self::prompt_capabilities(model.as_deref()));
 834        Self {
 835            id: acp::SessionId::new(uuid::Uuid::new_v4().to_string()),
 836            prompt_id: PromptId::new(),
 837            updated_at: Utc::now(),
 838            title: None,
 839            pending_title_generation: None,
 840            pending_summary_generation: None,
 841            summary: None,
 842            messages: Vec::new(),
 843            user_store: project.read(cx).user_store(),
 844            running_turn: None,
 845            has_queued_message: false,
 846            pending_message: None,
 847            tools: BTreeMap::default(),
 848            request_token_usage: HashMap::default(),
 849            cumulative_token_usage: TokenUsage::default(),
 850            initial_project_snapshot: {
 851                let project_snapshot = Self::project_snapshot(project.clone(), cx);
 852                cx.foreground_executor()
 853                    .spawn(async move { Some(project_snapshot.await) })
 854                    .shared()
 855            },
 856            context_server_registry,
 857            profile_id,
 858            project_context,
 859            templates,
 860            model,
 861            summarization_model: None,
 862            thinking_enabled: true,
 863            prompt_capabilities_tx,
 864            prompt_capabilities_rx,
 865            project,
 866            action_log,
 867            file_read_times: HashMap::default(),
 868            imported: false,
 869            subagent_context: None,
 870            running_subagents: Vec::new(),
 871        }
 872    }
 873
 874    pub fn new_subagent(
 875        project: Entity<Project>,
 876        project_context: Entity<ProjectContext>,
 877        context_server_registry: Entity<ContextServerRegistry>,
 878        templates: Arc<Templates>,
 879        model: Arc<dyn LanguageModel>,
 880        subagent_context: SubagentContext,
 881        parent_tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
 882        cx: &mut Context<Self>,
 883    ) -> Self {
 884        let profile_id = AgentSettings::get_global(cx).default_profile.clone();
 885        let action_log = cx.new(|_cx| ActionLog::new(project.clone()));
 886        let (prompt_capabilities_tx, prompt_capabilities_rx) =
 887            watch::channel(Self::prompt_capabilities(Some(model.as_ref())));
 888
 889        // Rebind tools that hold thread references to use this subagent's thread
 890        // instead of the parent's thread. This is critical for tools like EditFileTool
 891        // that make model requests using the thread's ID.
 892        let weak_self = cx.weak_entity();
 893        let tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>> = parent_tools
 894            .into_iter()
 895            .map(|(name, tool)| {
 896                let rebound = tool.rebind_thread(weak_self.clone()).unwrap_or(tool);
 897                (name, rebound)
 898            })
 899            .collect();
 900
 901        Self {
 902            id: acp::SessionId::new(uuid::Uuid::new_v4().to_string()),
 903            prompt_id: PromptId::new(),
 904            updated_at: Utc::now(),
 905            title: None,
 906            pending_title_generation: None,
 907            pending_summary_generation: None,
 908            summary: None,
 909            messages: Vec::new(),
 910            user_store: project.read(cx).user_store(),
 911            running_turn: None,
 912            has_queued_message: false,
 913            pending_message: None,
 914            tools,
 915            request_token_usage: HashMap::default(),
 916            cumulative_token_usage: TokenUsage::default(),
 917            initial_project_snapshot: Task::ready(None).shared(),
 918            context_server_registry,
 919            profile_id,
 920            project_context,
 921            templates,
 922            model: Some(model),
 923            summarization_model: None,
 924            thinking_enabled: true,
 925            prompt_capabilities_tx,
 926            prompt_capabilities_rx,
 927            project,
 928            action_log,
 929            file_read_times: HashMap::default(),
 930            imported: false,
 931            subagent_context: Some(subagent_context),
 932            running_subagents: Vec::new(),
 933        }
 934    }
 935
 936    pub fn id(&self) -> &acp::SessionId {
 937        &self.id
 938    }
 939
 940    /// Returns true if this thread was imported from a shared thread.
 941    pub fn is_imported(&self) -> bool {
 942        self.imported
 943    }
 944
 945    pub fn replay(
 946        &mut self,
 947        cx: &mut Context<Self>,
 948    ) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {
 949        let (tx, rx) = mpsc::unbounded();
 950        let stream = ThreadEventStream(tx);
 951        for message in &self.messages {
 952            match message {
 953                Message::User(user_message) => stream.send_user_message(user_message),
 954                Message::Agent(assistant_message) => {
 955                    for content in &assistant_message.content {
 956                        match content {
 957                            AgentMessageContent::Text(text) => stream.send_text(text),
 958                            AgentMessageContent::Thinking { text, .. } => {
 959                                stream.send_thinking(text)
 960                            }
 961                            AgentMessageContent::RedactedThinking(_) => {}
 962                            AgentMessageContent::ToolUse(tool_use) => {
 963                                self.replay_tool_call(
 964                                    tool_use,
 965                                    assistant_message.tool_results.get(&tool_use.id),
 966                                    &stream,
 967                                    cx,
 968                                );
 969                            }
 970                        }
 971                    }
 972                }
 973                Message::Resume => {}
 974            }
 975        }
 976        rx
 977    }
 978
 979    fn replay_tool_call(
 980        &self,
 981        tool_use: &LanguageModelToolUse,
 982        tool_result: Option<&LanguageModelToolResult>,
 983        stream: &ThreadEventStream,
 984        cx: &mut Context<Self>,
 985    ) {
 986        let tool = self.tools.get(tool_use.name.as_ref()).cloned().or_else(|| {
 987            self.context_server_registry
 988                .read(cx)
 989                .servers()
 990                .find_map(|(_, tools)| {
 991                    if let Some(tool) = tools.get(tool_use.name.as_ref()) {
 992                        Some(tool.clone())
 993                    } else {
 994                        None
 995                    }
 996                })
 997        });
 998
 999        let Some(tool) = tool else {
1000            stream
1001                .0
1002                .unbounded_send(Ok(ThreadEvent::ToolCall(
1003                    acp::ToolCall::new(tool_use.id.to_string(), tool_use.name.to_string())
1004                        .status(acp::ToolCallStatus::Failed)
1005                        .raw_input(tool_use.input.clone()),
1006                )))
1007                .ok();
1008            return;
1009        };
1010
1011        let title = tool.initial_title(tool_use.input.clone(), cx);
1012        let kind = tool.kind();
1013        stream.send_tool_call(
1014            &tool_use.id,
1015            &tool_use.name,
1016            title,
1017            kind,
1018            tool_use.input.clone(),
1019        );
1020
1021        let output = tool_result
1022            .as_ref()
1023            .and_then(|result| result.output.clone());
1024        if let Some(output) = output.clone() {
1025            // For replay, we use a dummy cancellation receiver since the tool already completed
1026            let (_cancellation_tx, cancellation_rx) = watch::channel(false);
1027            let tool_event_stream = ToolCallEventStream::new(
1028                tool_use.id.clone(),
1029                stream.clone(),
1030                Some(self.project.read(cx).fs().clone()),
1031                cancellation_rx,
1032            );
1033            tool.replay(tool_use.input.clone(), output, tool_event_stream, cx)
1034                .log_err();
1035        }
1036
1037        stream.update_tool_call_fields(
1038            &tool_use.id,
1039            acp::ToolCallUpdateFields::new()
1040                .status(
1041                    tool_result
1042                        .as_ref()
1043                        .map_or(acp::ToolCallStatus::Failed, |result| {
1044                            if result.is_error {
1045                                acp::ToolCallStatus::Failed
1046                            } else {
1047                                acp::ToolCallStatus::Completed
1048                            }
1049                        }),
1050                )
1051                .raw_output(output),
1052        );
1053    }
1054
1055    pub fn from_db(
1056        id: acp::SessionId,
1057        db_thread: DbThread,
1058        project: Entity<Project>,
1059        project_context: Entity<ProjectContext>,
1060        context_server_registry: Entity<ContextServerRegistry>,
1061        templates: Arc<Templates>,
1062        cx: &mut Context<Self>,
1063    ) -> Self {
1064        let profile_id = db_thread
1065            .profile
1066            .unwrap_or_else(|| AgentSettings::get_global(cx).default_profile.clone());
1067
1068        let mut model = LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1069            db_thread
1070                .model
1071                .and_then(|model| {
1072                    let model = SelectedModel {
1073                        provider: model.provider.clone().into(),
1074                        model: model.model.into(),
1075                    };
1076                    registry.select_model(&model, cx)
1077                })
1078                .or_else(|| registry.default_model())
1079                .map(|model| model.model)
1080        });
1081
1082        if model.is_none() {
1083            model = Self::resolve_profile_model(&profile_id, cx);
1084        }
1085        if model.is_none() {
1086            model = LanguageModelRegistry::global(cx).update(cx, |registry, _cx| {
1087                registry.default_model().map(|model| model.model)
1088            });
1089        }
1090
1091        let (prompt_capabilities_tx, prompt_capabilities_rx) =
1092            watch::channel(Self::prompt_capabilities(model.as_deref()));
1093
1094        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1095
1096        Self {
1097            id,
1098            prompt_id: PromptId::new(),
1099            title: if db_thread.title.is_empty() {
1100                None
1101            } else {
1102                Some(db_thread.title.clone())
1103            },
1104            pending_title_generation: None,
1105            pending_summary_generation: None,
1106            summary: db_thread.detailed_summary,
1107            messages: db_thread.messages,
1108            user_store: project.read(cx).user_store(),
1109            running_turn: None,
1110            has_queued_message: false,
1111            pending_message: None,
1112            tools: BTreeMap::default(),
1113            request_token_usage: db_thread.request_token_usage.clone(),
1114            cumulative_token_usage: db_thread.cumulative_token_usage,
1115            initial_project_snapshot: Task::ready(db_thread.initial_project_snapshot).shared(),
1116            context_server_registry,
1117            profile_id,
1118            project_context,
1119            templates,
1120            model,
1121            summarization_model: None,
1122            // TODO: Persist this on the `DbThread`.
1123            thinking_enabled: true,
1124            project,
1125            action_log,
1126            updated_at: db_thread.updated_at,
1127            prompt_capabilities_tx,
1128            prompt_capabilities_rx,
1129            file_read_times: HashMap::default(),
1130            imported: db_thread.imported,
1131            subagent_context: None,
1132            running_subagents: Vec::new(),
1133        }
1134    }
1135
1136    pub fn to_db(&self, cx: &App) -> Task<DbThread> {
1137        let initial_project_snapshot = self.initial_project_snapshot.clone();
1138        let mut thread = DbThread {
1139            title: self.title(),
1140            messages: self.messages.clone(),
1141            updated_at: self.updated_at,
1142            detailed_summary: self.summary.clone(),
1143            initial_project_snapshot: None,
1144            cumulative_token_usage: self.cumulative_token_usage,
1145            request_token_usage: self.request_token_usage.clone(),
1146            model: self.model.as_ref().map(|model| DbLanguageModel {
1147                provider: model.provider_id().to_string(),
1148                model: model.name().0.to_string(),
1149            }),
1150            profile: Some(self.profile_id.clone()),
1151            imported: self.imported,
1152        };
1153
1154        cx.background_spawn(async move {
1155            let initial_project_snapshot = initial_project_snapshot.await;
1156            thread.initial_project_snapshot = initial_project_snapshot;
1157            thread
1158        })
1159    }
1160
1161    /// Create a snapshot of the current project state including git information and unsaved buffers.
1162    fn project_snapshot(
1163        project: Entity<Project>,
1164        cx: &mut Context<Self>,
1165    ) -> Task<Arc<ProjectSnapshot>> {
1166        let task = project::telemetry_snapshot::TelemetrySnapshot::new(&project, cx);
1167        cx.spawn(async move |_, _| {
1168            let snapshot = task.await;
1169
1170            Arc::new(ProjectSnapshot {
1171                worktree_snapshots: snapshot.worktree_snapshots,
1172                timestamp: Utc::now(),
1173            })
1174        })
1175    }
1176
1177    pub fn project_context(&self) -> &Entity<ProjectContext> {
1178        &self.project_context
1179    }
1180
1181    pub fn project(&self) -> &Entity<Project> {
1182        &self.project
1183    }
1184
1185    pub fn action_log(&self) -> &Entity<ActionLog> {
1186        &self.action_log
1187    }
1188
1189    pub fn is_empty(&self) -> bool {
1190        self.messages.is_empty() && self.title.is_none()
1191    }
1192
1193    pub fn model(&self) -> Option<&Arc<dyn LanguageModel>> {
1194        self.model.as_ref()
1195    }
1196
1197    pub fn set_model(&mut self, model: Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
1198        let old_usage = self.latest_token_usage();
1199        self.model = Some(model);
1200        let new_caps = Self::prompt_capabilities(self.model.as_deref());
1201        let new_usage = self.latest_token_usage();
1202        if old_usage != new_usage {
1203            cx.emit(TokenUsageUpdated(new_usage));
1204        }
1205        self.prompt_capabilities_tx.send(new_caps).log_err();
1206        cx.notify()
1207    }
1208
1209    pub fn summarization_model(&self) -> Option<&Arc<dyn LanguageModel>> {
1210        self.summarization_model.as_ref()
1211    }
1212
1213    pub fn set_summarization_model(
1214        &mut self,
1215        model: Option<Arc<dyn LanguageModel>>,
1216        cx: &mut Context<Self>,
1217    ) {
1218        self.summarization_model = model;
1219        cx.notify()
1220    }
1221
1222    pub fn thinking_enabled(&self) -> bool {
1223        self.thinking_enabled
1224    }
1225
1226    pub fn set_thinking_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
1227        self.thinking_enabled = enabled;
1228        cx.notify();
1229    }
1230
1231    pub fn last_message(&self) -> Option<Message> {
1232        if let Some(message) = self.pending_message.clone() {
1233            Some(Message::Agent(message))
1234        } else {
1235            self.messages.last().cloned()
1236        }
1237    }
1238
1239    pub fn add_default_tools(
1240        &mut self,
1241        environment: Rc<dyn ThreadEnvironment>,
1242        cx: &mut Context<Self>,
1243    ) {
1244        let language_registry = self.project.read(cx).languages().clone();
1245        self.add_tool(CopyPathTool::new(self.project.clone()));
1246        self.add_tool(CreateDirectoryTool::new(self.project.clone()));
1247        self.add_tool(DeletePathTool::new(
1248            self.project.clone(),
1249            self.action_log.clone(),
1250        ));
1251        self.add_tool(DiagnosticsTool::new(self.project.clone()));
1252        self.add_tool(EditFileTool::new(
1253            self.project.clone(),
1254            cx.weak_entity(),
1255            language_registry.clone(),
1256            Templates::new(),
1257        ));
1258        self.add_tool(StreamingEditFileTool::new(
1259            self.project.clone(),
1260            cx.weak_entity(),
1261            language_registry,
1262            Templates::new(),
1263        ));
1264        self.add_tool(FetchTool::new(self.project.read(cx).client().http_client()));
1265        self.add_tool(FindPathTool::new(self.project.clone()));
1266        self.add_tool(GrepTool::new(self.project.clone()));
1267        self.add_tool(ListDirectoryTool::new(self.project.clone()));
1268        self.add_tool(MovePathTool::new(self.project.clone()));
1269        self.add_tool(NowTool);
1270        self.add_tool(OpenTool::new(self.project.clone()));
1271        self.add_tool(ReadFileTool::new(
1272            cx.weak_entity(),
1273            self.project.clone(),
1274            self.action_log.clone(),
1275        ));
1276        self.add_tool(SaveFileTool::new(self.project.clone()));
1277        self.add_tool(RestoreFileFromDiskTool::new(self.project.clone()));
1278        self.add_tool(TerminalTool::new(self.project.clone(), environment));
1279        self.add_tool(ThinkingTool);
1280        self.add_tool(WebSearchTool);
1281
1282        if cx.has_flag::<SubagentsFeatureFlag>() && self.depth() < MAX_SUBAGENT_DEPTH {
1283            self.add_tool(SubagentTool::new(cx.weak_entity(), self.depth()));
1284        }
1285    }
1286
1287    pub fn add_tool<T: AgentTool>(&mut self, tool: T) {
1288        self.tools.insert(T::name().into(), tool.erase());
1289    }
1290
1291    pub fn remove_tool(&mut self, name: &str) -> bool {
1292        self.tools.remove(name).is_some()
1293    }
1294
1295    pub fn restrict_tools(&mut self, allowed: &collections::HashSet<SharedString>) {
1296        self.tools.retain(|name, _| allowed.contains(name));
1297    }
1298
1299    pub fn profile(&self) -> &AgentProfileId {
1300        &self.profile_id
1301    }
1302
1303    pub fn set_profile(&mut self, profile_id: AgentProfileId, cx: &mut Context<Self>) {
1304        if self.profile_id == profile_id {
1305            return;
1306        }
1307
1308        self.profile_id = profile_id;
1309
1310        // Swap to the profile's preferred model when available.
1311        if let Some(model) = Self::resolve_profile_model(&self.profile_id, cx) {
1312            self.set_model(model, cx);
1313        }
1314    }
1315
1316    pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
1317        for subagent in self.running_subagents.drain(..) {
1318            if let Some(subagent) = subagent.upgrade() {
1319                subagent.update(cx, |thread, cx| thread.cancel(cx)).detach();
1320            }
1321        }
1322
1323        let Some(running_turn) = self.running_turn.take() else {
1324            self.flush_pending_message(cx);
1325            return Task::ready(());
1326        };
1327
1328        let turn_task = running_turn.cancel();
1329
1330        cx.spawn(async move |this, cx| {
1331            turn_task.await;
1332            this.update(cx, |this, cx| {
1333                this.flush_pending_message(cx);
1334            })
1335            .ok();
1336        })
1337    }
1338
1339    pub fn set_has_queued_message(&mut self, has_queued: bool) {
1340        self.has_queued_message = has_queued;
1341    }
1342
1343    pub fn has_queued_message(&self) -> bool {
1344        self.has_queued_message
1345    }
1346
1347    fn update_token_usage(&mut self, update: language_model::TokenUsage, cx: &mut Context<Self>) {
1348        let Some(last_user_message) = self.last_user_message() else {
1349            return;
1350        };
1351
1352        self.request_token_usage
1353            .insert(last_user_message.id.clone(), update);
1354        cx.emit(TokenUsageUpdated(self.latest_token_usage()));
1355        cx.notify();
1356    }
1357
1358    pub fn truncate(&mut self, message_id: UserMessageId, cx: &mut Context<Self>) -> Result<()> {
1359        self.cancel(cx).detach();
1360        // Clear pending message since cancel will try to flush it asynchronously,
1361        // and we don't want that content to be added after we truncate
1362        self.pending_message.take();
1363        let Some(position) = self.messages.iter().position(
1364            |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
1365        ) else {
1366            return Err(anyhow!("Message not found"));
1367        };
1368
1369        for message in self.messages.drain(position..) {
1370            match message {
1371                Message::User(message) => {
1372                    self.request_token_usage.remove(&message.id);
1373                }
1374                Message::Agent(_) | Message::Resume => {}
1375            }
1376        }
1377        self.clear_summary();
1378        cx.notify();
1379        Ok(())
1380    }
1381
1382    pub fn latest_request_token_usage(&self) -> Option<language_model::TokenUsage> {
1383        let last_user_message = self.last_user_message()?;
1384        let tokens = self.request_token_usage.get(&last_user_message.id)?;
1385        Some(*tokens)
1386    }
1387
1388    pub fn latest_token_usage(&self) -> Option<acp_thread::TokenUsage> {
1389        let usage = self.latest_request_token_usage()?;
1390        let model = self.model.clone()?;
1391        Some(acp_thread::TokenUsage {
1392            max_tokens: model.max_token_count(),
1393            used_tokens: usage.total_tokens(),
1394            input_tokens: usage.input_tokens,
1395            output_tokens: usage.output_tokens,
1396        })
1397    }
1398
1399    /// Get the total input token count as of the message before the given message.
1400    ///
1401    /// Returns `None` if:
1402    /// - `target_id` is the first message (no previous message)
1403    /// - The previous message hasn't received a response yet (no usage data)
1404    /// - `target_id` is not found in the messages
1405    pub fn tokens_before_message(&self, target_id: &UserMessageId) -> Option<u64> {
1406        let mut previous_user_message_id: Option<&UserMessageId> = None;
1407
1408        for message in &self.messages {
1409            if let Message::User(user_msg) = message {
1410                if &user_msg.id == target_id {
1411                    let prev_id = previous_user_message_id?;
1412                    let usage = self.request_token_usage.get(prev_id)?;
1413                    return Some(usage.input_tokens);
1414                }
1415                previous_user_message_id = Some(&user_msg.id);
1416            }
1417        }
1418        None
1419    }
1420
1421    /// Look up the active profile and resolve its preferred model if one is configured.
1422    fn resolve_profile_model(
1423        profile_id: &AgentProfileId,
1424        cx: &mut Context<Self>,
1425    ) -> Option<Arc<dyn LanguageModel>> {
1426        let selection = AgentSettings::get_global(cx)
1427            .profiles
1428            .get(profile_id)?
1429            .default_model
1430            .clone()?;
1431        Self::resolve_model_from_selection(&selection, cx)
1432    }
1433
1434    /// Translate a stored model selection into the configured model from the registry.
1435    fn resolve_model_from_selection(
1436        selection: &LanguageModelSelection,
1437        cx: &mut Context<Self>,
1438    ) -> Option<Arc<dyn LanguageModel>> {
1439        let selected = SelectedModel {
1440            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
1441            model: LanguageModelId::from(selection.model.clone()),
1442        };
1443        LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1444            registry
1445                .select_model(&selected, cx)
1446                .map(|configured| configured.model)
1447        })
1448    }
1449
1450    pub fn resume(
1451        &mut self,
1452        cx: &mut Context<Self>,
1453    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1454        self.messages.push(Message::Resume);
1455        cx.notify();
1456
1457        log::debug!("Total messages in thread: {}", self.messages.len());
1458        self.run_turn(cx)
1459    }
1460
1461    /// Sending a message results in the model streaming a response, which could include tool calls.
1462    /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
1463    /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
1464    pub fn send<T>(
1465        &mut self,
1466        id: UserMessageId,
1467        content: impl IntoIterator<Item = T>,
1468        cx: &mut Context<Self>,
1469    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
1470    where
1471        T: Into<UserMessageContent>,
1472    {
1473        let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
1474        log::debug!("Thread::send content: {:?}", content);
1475
1476        self.messages
1477            .push(Message::User(UserMessage { id, content }));
1478        cx.notify();
1479
1480        self.send_existing(cx)
1481    }
1482
1483    pub fn send_existing(
1484        &mut self,
1485        cx: &mut Context<Self>,
1486    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1487        let model = self.model().context("No language model configured")?;
1488
1489        log::info!("Thread::send called with model: {}", model.name().0);
1490        self.advance_prompt_id();
1491
1492        log::debug!("Total messages in thread: {}", self.messages.len());
1493        self.run_turn(cx)
1494    }
1495
1496    pub fn push_acp_user_block(
1497        &mut self,
1498        id: UserMessageId,
1499        blocks: impl IntoIterator<Item = acp::ContentBlock>,
1500        path_style: PathStyle,
1501        cx: &mut Context<Self>,
1502    ) {
1503        let content = blocks
1504            .into_iter()
1505            .map(|block| UserMessageContent::from_content_block(block, path_style))
1506            .collect::<Vec<_>>();
1507        self.messages
1508            .push(Message::User(UserMessage { id, content }));
1509        cx.notify();
1510    }
1511
1512    pub fn push_acp_agent_block(&mut self, block: acp::ContentBlock, cx: &mut Context<Self>) {
1513        let text = match block {
1514            acp::ContentBlock::Text(text_content) => text_content.text,
1515            acp::ContentBlock::Image(_) => "[image]".to_string(),
1516            acp::ContentBlock::Audio(_) => "[audio]".to_string(),
1517            acp::ContentBlock::ResourceLink(resource_link) => resource_link.uri,
1518            acp::ContentBlock::Resource(resource) => match resource.resource {
1519                acp::EmbeddedResourceResource::TextResourceContents(resource) => resource.uri,
1520                acp::EmbeddedResourceResource::BlobResourceContents(resource) => resource.uri,
1521                _ => "[resource]".to_string(),
1522            },
1523            _ => "[unknown]".to_string(),
1524        };
1525
1526        self.messages.push(Message::Agent(AgentMessage {
1527            content: vec![AgentMessageContent::Text(text)],
1528            ..Default::default()
1529        }));
1530        cx.notify();
1531    }
1532
1533    #[cfg(feature = "eval")]
1534    pub fn proceed(
1535        &mut self,
1536        cx: &mut Context<Self>,
1537    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1538        self.run_turn(cx)
1539    }
1540
1541    fn run_turn(
1542        &mut self,
1543        cx: &mut Context<Self>,
1544    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1545        // Flush the old pending message synchronously before cancelling,
1546        // to avoid a race where the detached cancel task might flush the NEW
1547        // turn's pending message instead of the old one.
1548        self.flush_pending_message(cx);
1549        self.cancel(cx).detach();
1550
1551        let model = self.model.clone().context("No language model configured")?;
1552        let profile = AgentSettings::get_global(cx)
1553            .profiles
1554            .get(&self.profile_id)
1555            .context("Profile not found")?;
1556        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1557        let event_stream = ThreadEventStream(events_tx);
1558        let message_ix = self.messages.len().saturating_sub(1);
1559        self.clear_summary();
1560        let (cancellation_tx, mut cancellation_rx) = watch::channel(false);
1561        self.running_turn = Some(RunningTurn {
1562            event_stream: event_stream.clone(),
1563            tools: self.enabled_tools(profile, &model, cx),
1564            cancellation_tx,
1565            _task: cx.spawn(async move |this, cx| {
1566                log::debug!("Starting agent turn execution");
1567
1568                let turn_result = Self::run_turn_internal(
1569                    &this,
1570                    model,
1571                    &event_stream,
1572                    cancellation_rx.clone(),
1573                    cx,
1574                )
1575                .await;
1576
1577                // Check if we were cancelled - if so, cancel() already took running_turn
1578                // and we shouldn't touch it (it might be a NEW turn now)
1579                let was_cancelled = *cancellation_rx.borrow();
1580                if was_cancelled {
1581                    log::debug!("Turn was cancelled, skipping cleanup");
1582                    return;
1583                }
1584
1585                _ = this.update(cx, |this, cx| this.flush_pending_message(cx));
1586
1587                match turn_result {
1588                    Ok(()) => {
1589                        log::debug!("Turn execution completed");
1590                        event_stream.send_stop(acp::StopReason::EndTurn);
1591                    }
1592                    Err(error) => {
1593                        log::error!("Turn execution failed: {:?}", error);
1594                        match error.downcast::<CompletionError>() {
1595                            Ok(CompletionError::Refusal) => {
1596                                event_stream.send_stop(acp::StopReason::Refusal);
1597                                _ = this.update(cx, |this, _| this.messages.truncate(message_ix));
1598                            }
1599                            Ok(CompletionError::MaxTokens) => {
1600                                event_stream.send_stop(acp::StopReason::MaxTokens);
1601                            }
1602                            Ok(CompletionError::Other(error)) | Err(error) => {
1603                                event_stream.send_error(error);
1604                            }
1605                        }
1606                    }
1607                }
1608
1609                _ = this.update(cx, |this, _| this.running_turn.take());
1610            }),
1611        });
1612        Ok(events_rx)
1613    }
1614
1615    async fn run_turn_internal(
1616        this: &WeakEntity<Self>,
1617        model: Arc<dyn LanguageModel>,
1618        event_stream: &ThreadEventStream,
1619        mut cancellation_rx: watch::Receiver<bool>,
1620        cx: &mut AsyncApp,
1621    ) -> Result<()> {
1622        let mut attempt = 0;
1623        let mut intent = CompletionIntent::UserPrompt;
1624        loop {
1625            let request =
1626                this.update(cx, |this, cx| this.build_completion_request(intent, cx))??;
1627
1628            telemetry::event!(
1629                "Agent Thread Completion",
1630                thread_id = this.read_with(cx, |this, _| this.id.to_string())?,
1631                prompt_id = this.read_with(cx, |this, _| this.prompt_id.to_string())?,
1632                model = model.telemetry_id(),
1633                model_provider = model.provider_id().to_string(),
1634                attempt
1635            );
1636
1637            log::debug!("Calling model.stream_completion, attempt {}", attempt);
1638
1639            let (mut events, mut error) = match model.stream_completion(request, cx).await {
1640                Ok(events) => (events.fuse(), None),
1641                Err(err) => (stream::empty().boxed().fuse(), Some(err)),
1642            };
1643            let mut tool_results = FuturesUnordered::new();
1644            let mut cancelled = false;
1645            loop {
1646                // Race between getting the first event and cancellation
1647                let first_event = futures::select! {
1648                    event = events.next().fuse() => event,
1649                    _ = cancellation_rx.changed().fuse() => {
1650                        if *cancellation_rx.borrow() {
1651                            cancelled = true;
1652                            break;
1653                        }
1654                        continue;
1655                    }
1656                };
1657                let Some(first_event) = first_event else {
1658                    break;
1659                };
1660
1661                // Collect all immediately available events to process as a batch
1662                let mut batch = vec![first_event];
1663                while let Some(event) = events.next().now_or_never().flatten() {
1664                    batch.push(event);
1665                }
1666
1667                // Process the batch in a single update
1668                let batch_result = this.update(cx, |this, cx| {
1669                    let mut batch_tool_results = Vec::new();
1670                    let mut batch_error = None;
1671
1672                    for event in batch {
1673                        log::trace!("Received completion event: {:?}", event);
1674                        match event {
1675                            Ok(event) => {
1676                                match this.handle_completion_event(
1677                                    event,
1678                                    event_stream,
1679                                    cancellation_rx.clone(),
1680                                    cx,
1681                                ) {
1682                                    Ok(Some(task)) => batch_tool_results.push(task),
1683                                    Ok(None) => {}
1684                                    Err(err) => {
1685                                        batch_error = Some(err);
1686                                        break;
1687                                    }
1688                                }
1689                            }
1690                            Err(err) => {
1691                                batch_error = Some(err.into());
1692                                break;
1693                            }
1694                        }
1695                    }
1696
1697                    cx.notify();
1698                    (batch_tool_results, batch_error)
1699                })?;
1700
1701                tool_results.extend(batch_result.0);
1702                if let Some(err) = batch_result.1 {
1703                    error = Some(err.downcast()?);
1704                    break;
1705                }
1706            }
1707
1708            // Drop the stream to release the rate limit permit before tool execution.
1709            // The stream holds a semaphore guard that limits concurrent requests.
1710            // Without this, the permit would be held during potentially long-running
1711            // tool execution, which could cause deadlocks when tools spawn subagents
1712            // that need their own permits.
1713            drop(events);
1714
1715            let end_turn = tool_results.is_empty();
1716            while let Some(tool_result) = tool_results.next().await {
1717                log::debug!("Tool finished {:?}", tool_result);
1718
1719                event_stream.update_tool_call_fields(
1720                    &tool_result.tool_use_id,
1721                    acp::ToolCallUpdateFields::new()
1722                        .status(if tool_result.is_error {
1723                            acp::ToolCallStatus::Failed
1724                        } else {
1725                            acp::ToolCallStatus::Completed
1726                        })
1727                        .raw_output(tool_result.output.clone()),
1728                );
1729                this.update(cx, |this, _cx| {
1730                    this.pending_message()
1731                        .tool_results
1732                        .insert(tool_result.tool_use_id.clone(), tool_result);
1733                })?;
1734            }
1735
1736            this.update(cx, |this, cx| {
1737                this.flush_pending_message(cx);
1738                if this.title.is_none() && this.pending_title_generation.is_none() {
1739                    this.generate_title(cx);
1740                }
1741            })?;
1742
1743            if cancelled {
1744                log::debug!("Turn cancelled by user, exiting");
1745                return Ok(());
1746            }
1747
1748            if let Some(error) = error {
1749                attempt += 1;
1750                let retry = this.update(cx, |this, cx| {
1751                    let user_store = this.user_store.read(cx);
1752                    this.handle_completion_error(error, attempt, user_store.plan())
1753                })??;
1754                let timer = cx.background_executor().timer(retry.duration);
1755                event_stream.send_retry(retry);
1756                timer.await;
1757                this.update(cx, |this, _cx| {
1758                    if let Some(Message::Agent(message)) = this.messages.last() {
1759                        if message.tool_results.is_empty() {
1760                            intent = CompletionIntent::UserPrompt;
1761                            this.messages.push(Message::Resume);
1762                        }
1763                    }
1764                })?;
1765            } else if end_turn {
1766                return Ok(());
1767            } else {
1768                let has_queued = this.update(cx, |this, _| this.has_queued_message())?;
1769                if has_queued {
1770                    log::debug!("Queued message found, ending turn at message boundary");
1771                    return Ok(());
1772                }
1773                intent = CompletionIntent::ToolResults;
1774                attempt = 0;
1775            }
1776        }
1777    }
1778
1779    fn handle_completion_error(
1780        &mut self,
1781        error: LanguageModelCompletionError,
1782        attempt: u8,
1783        plan: Option<Plan>,
1784    ) -> Result<acp_thread::RetryStatus> {
1785        let Some(model) = self.model.as_ref() else {
1786            return Err(anyhow!(error));
1787        };
1788
1789        let auto_retry = if model.provider_id() == ZED_CLOUD_PROVIDER_ID {
1790            plan.is_some()
1791        } else {
1792            true
1793        };
1794
1795        if !auto_retry {
1796            return Err(anyhow!(error));
1797        }
1798
1799        let Some(strategy) = Self::retry_strategy_for(&error) else {
1800            return Err(anyhow!(error));
1801        };
1802
1803        let max_attempts = match &strategy {
1804            RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
1805            RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
1806        };
1807
1808        if attempt > max_attempts {
1809            return Err(anyhow!(error));
1810        }
1811
1812        let delay = match &strategy {
1813            RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
1814                let delay_secs = initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
1815                Duration::from_secs(delay_secs)
1816            }
1817            RetryStrategy::Fixed { delay, .. } => *delay,
1818        };
1819        log::debug!("Retry attempt {attempt} with delay {delay:?}");
1820
1821        Ok(acp_thread::RetryStatus {
1822            last_error: error.to_string().into(),
1823            attempt: attempt as usize,
1824            max_attempts: max_attempts as usize,
1825            started_at: Instant::now(),
1826            duration: delay,
1827        })
1828    }
1829
1830    /// A helper method that's called on every streamed completion event.
1831    /// Returns an optional tool result task, which the main agentic loop will
1832    /// send back to the model when it resolves.
1833    fn handle_completion_event(
1834        &mut self,
1835        event: LanguageModelCompletionEvent,
1836        event_stream: &ThreadEventStream,
1837        cancellation_rx: watch::Receiver<bool>,
1838        cx: &mut Context<Self>,
1839    ) -> Result<Option<Task<LanguageModelToolResult>>> {
1840        log::trace!("Handling streamed completion event: {:?}", event);
1841        use LanguageModelCompletionEvent::*;
1842
1843        match event {
1844            StartMessage { .. } => {
1845                self.flush_pending_message(cx);
1846                self.pending_message = Some(AgentMessage::default());
1847            }
1848            Text(new_text) => self.handle_text_event(new_text, event_stream),
1849            Thinking { text, signature } => {
1850                self.handle_thinking_event(text, signature, event_stream)
1851            }
1852            RedactedThinking { data } => self.handle_redacted_thinking_event(data),
1853            ReasoningDetails(details) => {
1854                let last_message = self.pending_message();
1855                // Store the last non-empty reasoning_details (overwrites earlier ones)
1856                // This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
1857                if let serde_json::Value::Array(ref arr) = details {
1858                    if !arr.is_empty() {
1859                        last_message.reasoning_details = Some(details);
1860                    }
1861                } else {
1862                    last_message.reasoning_details = Some(details);
1863                }
1864            }
1865            ToolUse(tool_use) => {
1866                return Ok(self.handle_tool_use_event(tool_use, event_stream, cancellation_rx, cx));
1867            }
1868            ToolUseJsonParseError {
1869                id,
1870                tool_name,
1871                raw_input,
1872                json_parse_error,
1873            } => {
1874                return Ok(Some(Task::ready(
1875                    self.handle_tool_use_json_parse_error_event(
1876                        id,
1877                        tool_name,
1878                        raw_input,
1879                        json_parse_error,
1880                    ),
1881                )));
1882            }
1883            UsageUpdate(usage) => {
1884                telemetry::event!(
1885                    "Agent Thread Completion Usage Updated",
1886                    thread_id = self.id.to_string(),
1887                    prompt_id = self.prompt_id.to_string(),
1888                    model = self.model.as_ref().map(|m| m.telemetry_id()),
1889                    model_provider = self.model.as_ref().map(|m| m.provider_id().to_string()),
1890                    input_tokens = usage.input_tokens,
1891                    output_tokens = usage.output_tokens,
1892                    cache_creation_input_tokens = usage.cache_creation_input_tokens,
1893                    cache_read_input_tokens = usage.cache_read_input_tokens,
1894                );
1895                self.update_token_usage(usage, cx);
1896            }
1897            Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()),
1898            Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()),
1899            Stop(StopReason::ToolUse | StopReason::EndTurn) => {}
1900            Started | Queued { .. } => {}
1901        }
1902
1903        Ok(None)
1904    }
1905
1906    fn handle_text_event(&mut self, new_text: String, event_stream: &ThreadEventStream) {
1907        event_stream.send_text(&new_text);
1908
1909        let last_message = self.pending_message();
1910        if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
1911            text.push_str(&new_text);
1912        } else {
1913            last_message
1914                .content
1915                .push(AgentMessageContent::Text(new_text));
1916        }
1917    }
1918
1919    fn handle_thinking_event(
1920        &mut self,
1921        new_text: String,
1922        new_signature: Option<String>,
1923        event_stream: &ThreadEventStream,
1924    ) {
1925        event_stream.send_thinking(&new_text);
1926
1927        let last_message = self.pending_message();
1928        if let Some(AgentMessageContent::Thinking { text, signature }) =
1929            last_message.content.last_mut()
1930        {
1931            text.push_str(&new_text);
1932            *signature = new_signature.or(signature.take());
1933        } else {
1934            last_message.content.push(AgentMessageContent::Thinking {
1935                text: new_text,
1936                signature: new_signature,
1937            });
1938        }
1939    }
1940
1941    fn handle_redacted_thinking_event(&mut self, data: String) {
1942        let last_message = self.pending_message();
1943        last_message
1944            .content
1945            .push(AgentMessageContent::RedactedThinking(data));
1946    }
1947
1948    fn handle_tool_use_event(
1949        &mut self,
1950        tool_use: LanguageModelToolUse,
1951        event_stream: &ThreadEventStream,
1952        cancellation_rx: watch::Receiver<bool>,
1953        cx: &mut Context<Self>,
1954    ) -> Option<Task<LanguageModelToolResult>> {
1955        cx.notify();
1956
1957        let tool = self.tool(tool_use.name.as_ref());
1958        let mut title = SharedString::from(&tool_use.name);
1959        let mut kind = acp::ToolKind::Other;
1960        if let Some(tool) = tool.as_ref() {
1961            title = tool.initial_title(tool_use.input.clone(), cx);
1962            kind = tool.kind();
1963        }
1964
1965        // Ensure the last message ends in the current tool use
1966        let last_message = self.pending_message();
1967        let push_new_tool_use = last_message.content.last_mut().is_none_or(|content| {
1968            if let AgentMessageContent::ToolUse(last_tool_use) = content {
1969                if last_tool_use.id == tool_use.id {
1970                    *last_tool_use = tool_use.clone();
1971                    false
1972                } else {
1973                    true
1974                }
1975            } else {
1976                true
1977            }
1978        });
1979
1980        if push_new_tool_use {
1981            event_stream.send_tool_call(
1982                &tool_use.id,
1983                &tool_use.name,
1984                title,
1985                kind,
1986                tool_use.input.clone(),
1987            );
1988            last_message
1989                .content
1990                .push(AgentMessageContent::ToolUse(tool_use.clone()));
1991        } else {
1992            event_stream.update_tool_call_fields(
1993                &tool_use.id,
1994                acp::ToolCallUpdateFields::new()
1995                    .title(title.as_str())
1996                    .kind(kind)
1997                    .raw_input(tool_use.input.clone()),
1998            );
1999        }
2000
2001        if !tool_use.is_input_complete {
2002            return None;
2003        }
2004
2005        let Some(tool) = tool else {
2006            let content = format!("No tool named {} exists", tool_use.name);
2007            return Some(Task::ready(LanguageModelToolResult {
2008                content: LanguageModelToolResultContent::Text(Arc::from(content)),
2009                tool_use_id: tool_use.id,
2010                tool_name: tool_use.name,
2011                is_error: true,
2012                output: None,
2013            }));
2014        };
2015
2016        let fs = self.project.read(cx).fs().clone();
2017        let tool_event_stream = ToolCallEventStream::new(
2018            tool_use.id.clone(),
2019            event_stream.clone(),
2020            Some(fs),
2021            cancellation_rx,
2022        );
2023        tool_event_stream.update_fields(
2024            acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
2025        );
2026        let supports_images = self.model().is_some_and(|model| model.supports_images());
2027        let tool_result = tool.run(tool_use.input, tool_event_stream, cx);
2028        log::debug!("Running tool {}", tool_use.name);
2029        Some(cx.foreground_executor().spawn(async move {
2030            let tool_result = tool_result.await.and_then(|output| {
2031                if let LanguageModelToolResultContent::Image(_) = &output.llm_output
2032                    && !supports_images
2033                {
2034                    return Err(anyhow!(
2035                        "Attempted to read an image, but this model doesn't support it.",
2036                    ));
2037                }
2038                Ok(output)
2039            });
2040
2041            match tool_result {
2042                Ok(output) => LanguageModelToolResult {
2043                    tool_use_id: tool_use.id,
2044                    tool_name: tool_use.name,
2045                    is_error: false,
2046                    content: output.llm_output,
2047                    output: Some(output.raw_output),
2048                },
2049                Err(error) => LanguageModelToolResult {
2050                    tool_use_id: tool_use.id,
2051                    tool_name: tool_use.name,
2052                    is_error: true,
2053                    content: LanguageModelToolResultContent::Text(Arc::from(error.to_string())),
2054                    output: Some(error.to_string().into()),
2055                },
2056            }
2057        }))
2058    }
2059
2060    fn handle_tool_use_json_parse_error_event(
2061        &mut self,
2062        tool_use_id: LanguageModelToolUseId,
2063        tool_name: Arc<str>,
2064        raw_input: Arc<str>,
2065        json_parse_error: String,
2066    ) -> LanguageModelToolResult {
2067        let tool_output = format!("Error parsing input JSON: {json_parse_error}");
2068        LanguageModelToolResult {
2069            tool_use_id,
2070            tool_name,
2071            is_error: true,
2072            content: LanguageModelToolResultContent::Text(tool_output.into()),
2073            output: Some(serde_json::Value::String(raw_input.to_string())),
2074        }
2075    }
2076
2077    pub fn title(&self) -> SharedString {
2078        self.title.clone().unwrap_or("New Thread".into())
2079    }
2080
2081    pub fn is_generating_summary(&self) -> bool {
2082        self.pending_summary_generation.is_some()
2083    }
2084
2085    pub fn is_generating_title(&self) -> bool {
2086        self.pending_title_generation.is_some()
2087    }
2088
2089    pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
2090        if let Some(summary) = self.summary.as_ref() {
2091            return Task::ready(Some(summary.clone())).shared();
2092        }
2093        if let Some(task) = self.pending_summary_generation.clone() {
2094            return task;
2095        }
2096        let Some(model) = self.summarization_model.clone() else {
2097            log::error!("No summarization model available");
2098            return Task::ready(None).shared();
2099        };
2100        let mut request = LanguageModelRequest {
2101            intent: Some(CompletionIntent::ThreadContextSummarization),
2102            temperature: AgentSettings::temperature_for_model(&model, cx),
2103            ..Default::default()
2104        };
2105
2106        for message in &self.messages {
2107            request.messages.extend(message.to_request());
2108        }
2109
2110        request.messages.push(LanguageModelRequestMessage {
2111            role: Role::User,
2112            content: vec![SUMMARIZE_THREAD_DETAILED_PROMPT.into()],
2113            cache: false,
2114            reasoning_details: None,
2115        });
2116
2117        let task = cx
2118            .spawn(async move |this, cx| {
2119                let mut summary = String::new();
2120                let mut messages = model.stream_completion(request, cx).await.log_err()?;
2121                while let Some(event) = messages.next().await {
2122                    let event = event.log_err()?;
2123                    let text = match event {
2124                        LanguageModelCompletionEvent::Text(text) => text,
2125                        _ => continue,
2126                    };
2127
2128                    let mut lines = text.lines();
2129                    summary.extend(lines.next());
2130                }
2131
2132                log::debug!("Setting summary: {}", summary);
2133                let summary = SharedString::from(summary);
2134
2135                this.update(cx, |this, cx| {
2136                    this.summary = Some(summary.clone());
2137                    this.pending_summary_generation = None;
2138                    cx.notify()
2139                })
2140                .ok()?;
2141
2142                Some(summary)
2143            })
2144            .shared();
2145        self.pending_summary_generation = Some(task.clone());
2146        task
2147    }
2148
2149    pub fn generate_title(&mut self, cx: &mut Context<Self>) {
2150        let Some(model) = self.summarization_model.clone() else {
2151            return;
2152        };
2153
2154        log::debug!(
2155            "Generating title with model: {:?}",
2156            self.summarization_model.as_ref().map(|model| model.name())
2157        );
2158        let mut request = LanguageModelRequest {
2159            intent: Some(CompletionIntent::ThreadSummarization),
2160            temperature: AgentSettings::temperature_for_model(&model, cx),
2161            ..Default::default()
2162        };
2163
2164        for message in &self.messages {
2165            request.messages.extend(message.to_request());
2166        }
2167
2168        request.messages.push(LanguageModelRequestMessage {
2169            role: Role::User,
2170            content: vec![SUMMARIZE_THREAD_PROMPT.into()],
2171            cache: false,
2172            reasoning_details: None,
2173        });
2174        self.pending_title_generation = Some(cx.spawn(async move |this, cx| {
2175            let mut title = String::new();
2176
2177            let generate = async {
2178                let mut messages = model.stream_completion(request, cx).await?;
2179                while let Some(event) = messages.next().await {
2180                    let event = event?;
2181                    let text = match event {
2182                        LanguageModelCompletionEvent::Text(text) => text,
2183                        _ => continue,
2184                    };
2185
2186                    let mut lines = text.lines();
2187                    title.extend(lines.next());
2188
2189                    // Stop if the LLM generated multiple lines.
2190                    if lines.next().is_some() {
2191                        break;
2192                    }
2193                }
2194                anyhow::Ok(())
2195            };
2196
2197            if generate.await.context("failed to generate title").is_ok() {
2198                _ = this.update(cx, |this, cx| this.set_title(title.into(), cx));
2199            }
2200            _ = this.update(cx, |this, _| this.pending_title_generation = None);
2201        }));
2202    }
2203
2204    pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
2205        self.pending_title_generation = None;
2206        if Some(&title) != self.title.as_ref() {
2207            self.title = Some(title);
2208            cx.emit(TitleUpdated);
2209            cx.notify();
2210        }
2211    }
2212
2213    fn clear_summary(&mut self) {
2214        self.summary = None;
2215        self.pending_summary_generation = None;
2216    }
2217
2218    fn last_user_message(&self) -> Option<&UserMessage> {
2219        self.messages
2220            .iter()
2221            .rev()
2222            .find_map(|message| match message {
2223                Message::User(user_message) => Some(user_message),
2224                Message::Agent(_) => None,
2225                Message::Resume => None,
2226            })
2227    }
2228
2229    fn pending_message(&mut self) -> &mut AgentMessage {
2230        self.pending_message.get_or_insert_default()
2231    }
2232
2233    fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
2234        let Some(mut message) = self.pending_message.take() else {
2235            return;
2236        };
2237
2238        if message.content.is_empty() {
2239            return;
2240        }
2241
2242        for content in &message.content {
2243            let AgentMessageContent::ToolUse(tool_use) = content else {
2244                continue;
2245            };
2246
2247            if !message.tool_results.contains_key(&tool_use.id) {
2248                message.tool_results.insert(
2249                    tool_use.id.clone(),
2250                    LanguageModelToolResult {
2251                        tool_use_id: tool_use.id.clone(),
2252                        tool_name: tool_use.name.clone(),
2253                        is_error: true,
2254                        content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
2255                        output: None,
2256                    },
2257                );
2258            }
2259        }
2260
2261        self.messages.push(Message::Agent(message));
2262        self.updated_at = Utc::now();
2263        self.clear_summary();
2264        cx.notify()
2265    }
2266
2267    pub(crate) fn build_completion_request(
2268        &self,
2269        completion_intent: CompletionIntent,
2270        cx: &App,
2271    ) -> Result<LanguageModelRequest> {
2272        let model = self.model().context("No language model configured")?;
2273        let tools = if let Some(turn) = self.running_turn.as_ref() {
2274            turn.tools
2275                .iter()
2276                .filter_map(|(tool_name, tool)| {
2277                    log::trace!("Including tool: {}", tool_name);
2278                    Some(LanguageModelRequestTool {
2279                        name: tool_name.to_string(),
2280                        description: tool.description().to_string(),
2281                        input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
2282                    })
2283                })
2284                .collect::<Vec<_>>()
2285        } else {
2286            Vec::new()
2287        };
2288
2289        log::debug!("Building completion request");
2290        log::debug!("Completion intent: {:?}", completion_intent);
2291
2292        let available_tools: Vec<_> = self
2293            .running_turn
2294            .as_ref()
2295            .map(|turn| turn.tools.keys().cloned().collect())
2296            .unwrap_or_default();
2297
2298        log::debug!("Request includes {} tools", available_tools.len());
2299        let messages = self.build_request_messages(available_tools, cx);
2300        log::debug!("Request will include {} messages", messages.len());
2301
2302        let request = LanguageModelRequest {
2303            thread_id: Some(self.id.to_string()),
2304            prompt_id: Some(self.prompt_id.to_string()),
2305            intent: Some(completion_intent),
2306            messages,
2307            tools,
2308            tool_choice: None,
2309            stop: Vec::new(),
2310            temperature: AgentSettings::temperature_for_model(model, cx),
2311            thinking_allowed: self.thinking_enabled,
2312        };
2313
2314        log::debug!("Completion request built successfully");
2315        Ok(request)
2316    }
2317
2318    fn enabled_tools(
2319        &self,
2320        profile: &AgentProfileSettings,
2321        model: &Arc<dyn LanguageModel>,
2322        cx: &App,
2323    ) -> BTreeMap<SharedString, Arc<dyn AnyAgentTool>> {
2324        fn truncate(tool_name: &SharedString) -> SharedString {
2325            if tool_name.len() > MAX_TOOL_NAME_LENGTH {
2326                let mut truncated = tool_name.to_string();
2327                truncated.truncate(MAX_TOOL_NAME_LENGTH);
2328                truncated.into()
2329            } else {
2330                tool_name.clone()
2331            }
2332        }
2333
2334        let use_streaming_edit_tool = false;
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", false) | ("edit_file", true) => None,
2352                        ("streaming_edit_file", true) => {
2353                            // Expose streaming tool as "edit_file"
2354                            Some((SharedString::from("edit_file"), tool.clone()))
2355                        }
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}