thread.rs

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