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