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