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