thread.rs

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