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