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