thread.rs

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