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