thread.rs

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