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