thread.rs

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