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