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                prompt_id = this.read_with(cx, |this, _| this.prompt_id.to_string())?,
1743                model = model.telemetry_id(),
1744                model_provider = model.provider_id().to_string(),
1745                attempt
1746            );
1747
1748            log::debug!("Calling model.stream_completion, attempt {}", attempt);
1749
1750            let (mut events, mut error) = match model.stream_completion(request, cx).await {
1751                Ok(events) => (events.fuse(), None),
1752                Err(err) => (stream::empty().boxed().fuse(), Some(err)),
1753            };
1754            let mut tool_results = FuturesUnordered::new();
1755            let mut cancelled = false;
1756            loop {
1757                // Race between getting the first event and cancellation
1758                let first_event = futures::select! {
1759                    event = events.next().fuse() => event,
1760                    _ = cancellation_rx.changed().fuse() => {
1761                        if *cancellation_rx.borrow() {
1762                            cancelled = true;
1763                            break;
1764                        }
1765                        continue;
1766                    }
1767                };
1768                let Some(first_event) = first_event else {
1769                    break;
1770                };
1771
1772                // Collect all immediately available events to process as a batch
1773                let mut batch = vec![first_event];
1774                while let Some(event) = events.next().now_or_never().flatten() {
1775                    batch.push(event);
1776                }
1777
1778                // Process the batch in a single update
1779                let batch_result = this.update(cx, |this, cx| {
1780                    let mut batch_tool_results = Vec::new();
1781                    let mut batch_error = None;
1782
1783                    for event in batch {
1784                        log::trace!("Received completion event: {:?}", event);
1785                        match event {
1786                            Ok(event) => {
1787                                match this.handle_completion_event(
1788                                    event,
1789                                    event_stream,
1790                                    cancellation_rx.clone(),
1791                                    cx,
1792                                ) {
1793                                    Ok(Some(task)) => batch_tool_results.push(task),
1794                                    Ok(None) => {}
1795                                    Err(err) => {
1796                                        batch_error = Some(err);
1797                                        break;
1798                                    }
1799                                }
1800                            }
1801                            Err(err) => {
1802                                batch_error = Some(err.into());
1803                                break;
1804                            }
1805                        }
1806                    }
1807
1808                    cx.notify();
1809                    (batch_tool_results, batch_error)
1810                })?;
1811
1812                tool_results.extend(batch_result.0);
1813                if let Some(err) = batch_result.1 {
1814                    error = Some(err.downcast()?);
1815                    break;
1816                }
1817            }
1818
1819            // Drop the stream to release the rate limit permit before tool execution.
1820            // The stream holds a semaphore guard that limits concurrent requests.
1821            // Without this, the permit would be held during potentially long-running
1822            // tool execution, which could cause deadlocks when tools spawn subagents
1823            // that need their own permits.
1824            drop(events);
1825
1826            let end_turn = tool_results.is_empty();
1827            while let Some(tool_result) = tool_results.next().await {
1828                log::debug!("Tool finished {:?}", tool_result);
1829
1830                event_stream.update_tool_call_fields(
1831                    &tool_result.tool_use_id,
1832                    acp::ToolCallUpdateFields::new()
1833                        .status(if tool_result.is_error {
1834                            acp::ToolCallStatus::Failed
1835                        } else {
1836                            acp::ToolCallStatus::Completed
1837                        })
1838                        .raw_output(tool_result.output.clone()),
1839                    None,
1840                );
1841                this.update(cx, |this, _cx| {
1842                    this.pending_message()
1843                        .tool_results
1844                        .insert(tool_result.tool_use_id.clone(), tool_result);
1845                })?;
1846            }
1847
1848            this.update(cx, |this, cx| {
1849                this.flush_pending_message(cx);
1850                if this.title.is_none() && this.pending_title_generation.is_none() {
1851                    this.generate_title(cx);
1852                }
1853            })?;
1854
1855            if cancelled {
1856                log::debug!("Turn cancelled by user, exiting");
1857                return Ok(());
1858            }
1859
1860            if let Some(error) = error {
1861                attempt += 1;
1862                let retry = this.update(cx, |this, cx| {
1863                    let user_store = this.user_store.read(cx);
1864                    this.handle_completion_error(error, attempt, user_store.plan())
1865                })??;
1866                let timer = cx.background_executor().timer(retry.duration);
1867                event_stream.send_retry(retry);
1868                timer.await;
1869                this.update(cx, |this, _cx| {
1870                    if let Some(Message::Agent(message)) = this.messages.last() {
1871                        if message.tool_results.is_empty() {
1872                            intent = CompletionIntent::UserPrompt;
1873                            this.messages.push(Message::Resume);
1874                        }
1875                    }
1876                })?;
1877            } else if end_turn {
1878                return Ok(());
1879            } else {
1880                let has_queued = this.update(cx, |this, _| this.has_queued_message())?;
1881                if has_queued {
1882                    log::debug!("Queued message found, ending turn at message boundary");
1883                    return Ok(());
1884                }
1885                intent = CompletionIntent::ToolResults;
1886                attempt = 0;
1887            }
1888        }
1889    }
1890
1891    fn handle_completion_error(
1892        &mut self,
1893        error: LanguageModelCompletionError,
1894        attempt: u8,
1895        plan: Option<Plan>,
1896    ) -> Result<acp_thread::RetryStatus> {
1897        let Some(model) = self.model.as_ref() else {
1898            return Err(anyhow!(error));
1899        };
1900
1901        let auto_retry = if model.provider_id() == ZED_CLOUD_PROVIDER_ID {
1902            plan.is_some()
1903        } else {
1904            true
1905        };
1906
1907        if !auto_retry {
1908            return Err(anyhow!(error));
1909        }
1910
1911        let Some(strategy) = Self::retry_strategy_for(&error) else {
1912            return Err(anyhow!(error));
1913        };
1914
1915        let max_attempts = match &strategy {
1916            RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
1917            RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
1918        };
1919
1920        if attempt > max_attempts {
1921            return Err(anyhow!(error));
1922        }
1923
1924        let delay = match &strategy {
1925            RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
1926                let delay_secs = initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
1927                Duration::from_secs(delay_secs)
1928            }
1929            RetryStrategy::Fixed { delay, .. } => *delay,
1930        };
1931        log::debug!("Retry attempt {attempt} with delay {delay:?}");
1932
1933        Ok(acp_thread::RetryStatus {
1934            last_error: error.to_string().into(),
1935            attempt: attempt as usize,
1936            max_attempts: max_attempts as usize,
1937            started_at: Instant::now(),
1938            duration: delay,
1939        })
1940    }
1941
1942    /// A helper method that's called on every streamed completion event.
1943    /// Returns an optional tool result task, which the main agentic loop will
1944    /// send back to the model when it resolves.
1945    fn handle_completion_event(
1946        &mut self,
1947        event: LanguageModelCompletionEvent,
1948        event_stream: &ThreadEventStream,
1949        cancellation_rx: watch::Receiver<bool>,
1950        cx: &mut Context<Self>,
1951    ) -> Result<Option<Task<LanguageModelToolResult>>> {
1952        log::trace!("Handling streamed completion event: {:?}", event);
1953        use LanguageModelCompletionEvent::*;
1954
1955        match event {
1956            StartMessage { .. } => {
1957                self.flush_pending_message(cx);
1958                self.pending_message = Some(AgentMessage::default());
1959            }
1960            Text(new_text) => self.handle_text_event(new_text, event_stream),
1961            Thinking { text, signature } => {
1962                self.handle_thinking_event(text, signature, event_stream)
1963            }
1964            RedactedThinking { data } => self.handle_redacted_thinking_event(data),
1965            ReasoningDetails(details) => {
1966                let last_message = self.pending_message();
1967                // Store the last non-empty reasoning_details (overwrites earlier ones)
1968                // This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
1969                if let serde_json::Value::Array(ref arr) = details {
1970                    if !arr.is_empty() {
1971                        last_message.reasoning_details = Some(details);
1972                    }
1973                } else {
1974                    last_message.reasoning_details = Some(details);
1975                }
1976            }
1977            ToolUse(tool_use) => {
1978                return Ok(self.handle_tool_use_event(tool_use, event_stream, cancellation_rx, cx));
1979            }
1980            ToolUseJsonParseError {
1981                id,
1982                tool_name,
1983                raw_input,
1984                json_parse_error,
1985            } => {
1986                return Ok(Some(Task::ready(
1987                    self.handle_tool_use_json_parse_error_event(
1988                        id,
1989                        tool_name,
1990                        raw_input,
1991                        json_parse_error,
1992                        event_stream,
1993                    ),
1994                )));
1995            }
1996            UsageUpdate(usage) => {
1997                telemetry::event!(
1998                    "Agent Thread Completion Usage Updated",
1999                    thread_id = self.id.to_string(),
2000                    prompt_id = self.prompt_id.to_string(),
2001                    model = self.model.as_ref().map(|m| m.telemetry_id()),
2002                    model_provider = self.model.as_ref().map(|m| m.provider_id().to_string()),
2003                    input_tokens = usage.input_tokens,
2004                    output_tokens = usage.output_tokens,
2005                    cache_creation_input_tokens = usage.cache_creation_input_tokens,
2006                    cache_read_input_tokens = usage.cache_read_input_tokens,
2007                );
2008                self.update_token_usage(usage, cx);
2009            }
2010            Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()),
2011            Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()),
2012            Stop(StopReason::ToolUse | StopReason::EndTurn) => {}
2013            Started | Queued { .. } => {}
2014        }
2015
2016        Ok(None)
2017    }
2018
2019    fn handle_text_event(&mut self, new_text: String, event_stream: &ThreadEventStream) {
2020        event_stream.send_text(&new_text);
2021
2022        let last_message = self.pending_message();
2023        if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
2024            text.push_str(&new_text);
2025        } else {
2026            last_message
2027                .content
2028                .push(AgentMessageContent::Text(new_text));
2029        }
2030    }
2031
2032    fn handle_thinking_event(
2033        &mut self,
2034        new_text: String,
2035        new_signature: Option<String>,
2036        event_stream: &ThreadEventStream,
2037    ) {
2038        event_stream.send_thinking(&new_text);
2039
2040        let last_message = self.pending_message();
2041        if let Some(AgentMessageContent::Thinking { text, signature }) =
2042            last_message.content.last_mut()
2043        {
2044            text.push_str(&new_text);
2045            *signature = new_signature.or(signature.take());
2046        } else {
2047            last_message.content.push(AgentMessageContent::Thinking {
2048                text: new_text,
2049                signature: new_signature,
2050            });
2051        }
2052    }
2053
2054    fn handle_redacted_thinking_event(&mut self, data: String) {
2055        let last_message = self.pending_message();
2056        last_message
2057            .content
2058            .push(AgentMessageContent::RedactedThinking(data));
2059    }
2060
2061    fn handle_tool_use_event(
2062        &mut self,
2063        tool_use: LanguageModelToolUse,
2064        event_stream: &ThreadEventStream,
2065        cancellation_rx: watch::Receiver<bool>,
2066        cx: &mut Context<Self>,
2067    ) -> Option<Task<LanguageModelToolResult>> {
2068        cx.notify();
2069
2070        let tool = self.tool(tool_use.name.as_ref());
2071        let mut title = SharedString::from(&tool_use.name);
2072        let mut kind = acp::ToolKind::Other;
2073        if let Some(tool) = tool.as_ref() {
2074            title = tool.initial_title(tool_use.input.clone(), cx);
2075            kind = tool.kind();
2076        }
2077
2078        self.send_or_update_tool_use(&tool_use, title, kind, event_stream);
2079
2080        let Some(tool) = tool else {
2081            let content = format!("No tool named {} exists", tool_use.name);
2082            return Some(Task::ready(LanguageModelToolResult {
2083                content: LanguageModelToolResultContent::Text(Arc::from(content)),
2084                tool_use_id: tool_use.id,
2085                tool_name: tool_use.name,
2086                is_error: true,
2087                output: None,
2088            }));
2089        };
2090
2091        if !tool_use.is_input_complete {
2092            if tool.supports_input_streaming() {
2093                let running_turn = self.running_turn.as_mut()?;
2094                if let Some(sender) = running_turn.streaming_tool_inputs.get(&tool_use.id) {
2095                    sender.send_partial(tool_use.input);
2096                    return None;
2097                }
2098
2099                let (sender, tool_input) = ToolInputSender::channel();
2100                sender.send_partial(tool_use.input);
2101                running_turn
2102                    .streaming_tool_inputs
2103                    .insert(tool_use.id.clone(), sender);
2104
2105                let tool = tool.clone();
2106                log::debug!("Running streaming tool {}", tool_use.name);
2107                return Some(self.run_tool(
2108                    tool,
2109                    tool_input,
2110                    tool_use.id,
2111                    tool_use.name,
2112                    event_stream,
2113                    cancellation_rx,
2114                    cx,
2115                ));
2116            } else {
2117                return None;
2118            }
2119        }
2120
2121        if let Some(sender) = self
2122            .running_turn
2123            .as_mut()?
2124            .streaming_tool_inputs
2125            .remove(&tool_use.id)
2126        {
2127            sender.send_final(tool_use.input);
2128            return None;
2129        }
2130
2131        log::debug!("Running tool {}", tool_use.name);
2132        let tool_input = ToolInput::ready(tool_use.input);
2133        Some(self.run_tool(
2134            tool,
2135            tool_input,
2136            tool_use.id,
2137            tool_use.name,
2138            event_stream,
2139            cancellation_rx,
2140            cx,
2141        ))
2142    }
2143
2144    fn run_tool(
2145        &self,
2146        tool: Arc<dyn AnyAgentTool>,
2147        tool_input: ToolInput<serde_json::Value>,
2148        tool_use_id: LanguageModelToolUseId,
2149        tool_name: Arc<str>,
2150        event_stream: &ThreadEventStream,
2151        cancellation_rx: watch::Receiver<bool>,
2152        cx: &mut Context<Self>,
2153    ) -> Task<LanguageModelToolResult> {
2154        let fs = self.project.read(cx).fs().clone();
2155        let tool_event_stream = ToolCallEventStream::new(
2156            tool_use_id.clone(),
2157            event_stream.clone(),
2158            Some(fs),
2159            cancellation_rx,
2160        );
2161        tool_event_stream.update_fields(
2162            acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
2163        );
2164        let supports_images = self.model().is_some_and(|model| model.supports_images());
2165        let tool_result = tool.run(tool_input, tool_event_stream, cx);
2166        cx.foreground_executor().spawn(async move {
2167            let (is_error, output) = match tool_result.await {
2168                Ok(mut output) => {
2169                    if let LanguageModelToolResultContent::Image(_) = &output.llm_output
2170                        && !supports_images
2171                    {
2172                        output = AgentToolOutput::from_error(
2173                            "Attempted to read an image, but this model doesn't support it.",
2174                        );
2175                        (true, output)
2176                    } else {
2177                        (false, output)
2178                    }
2179                }
2180                Err(output) => (true, output),
2181            };
2182
2183            LanguageModelToolResult {
2184                tool_use_id,
2185                tool_name,
2186                is_error,
2187                content: output.llm_output,
2188                output: Some(output.raw_output),
2189            }
2190        })
2191    }
2192
2193    fn handle_tool_use_json_parse_error_event(
2194        &mut self,
2195        tool_use_id: LanguageModelToolUseId,
2196        tool_name: Arc<str>,
2197        raw_input: Arc<str>,
2198        json_parse_error: String,
2199        event_stream: &ThreadEventStream,
2200    ) -> LanguageModelToolResult {
2201        let tool_use = LanguageModelToolUse {
2202            id: tool_use_id.clone(),
2203            name: tool_name.clone(),
2204            raw_input: raw_input.to_string(),
2205            input: serde_json::json!({}),
2206            is_input_complete: true,
2207            thought_signature: None,
2208        };
2209        self.send_or_update_tool_use(
2210            &tool_use,
2211            SharedString::from(&tool_use.name),
2212            acp::ToolKind::Other,
2213            event_stream,
2214        );
2215
2216        let tool_output = format!("Error parsing input JSON: {json_parse_error}");
2217        LanguageModelToolResult {
2218            tool_use_id,
2219            tool_name,
2220            is_error: true,
2221            content: LanguageModelToolResultContent::Text(tool_output.into()),
2222            output: Some(serde_json::Value::String(raw_input.to_string())),
2223        }
2224    }
2225
2226    fn send_or_update_tool_use(
2227        &mut self,
2228        tool_use: &LanguageModelToolUse,
2229        title: SharedString,
2230        kind: acp::ToolKind,
2231        event_stream: &ThreadEventStream,
2232    ) {
2233        // Ensure the last message ends in the current tool use
2234        let last_message = self.pending_message();
2235        let push_new_tool_use = last_message.content.last_mut().is_none_or(|content| {
2236            if let AgentMessageContent::ToolUse(last_tool_use) = content {
2237                if last_tool_use.id == tool_use.id {
2238                    *last_tool_use = tool_use.clone();
2239                    false
2240                } else {
2241                    true
2242                }
2243            } else {
2244                true
2245            }
2246        });
2247
2248        if push_new_tool_use {
2249            event_stream.send_tool_call(
2250                &tool_use.id,
2251                &tool_use.name,
2252                title,
2253                kind,
2254                tool_use.input.clone(),
2255            );
2256            last_message
2257                .content
2258                .push(AgentMessageContent::ToolUse(tool_use.clone()));
2259        } else {
2260            event_stream.update_tool_call_fields(
2261                &tool_use.id,
2262                acp::ToolCallUpdateFields::new()
2263                    .title(title.as_str())
2264                    .kind(kind)
2265                    .raw_input(tool_use.input.clone()),
2266                None,
2267            );
2268        }
2269    }
2270
2271    pub fn title(&self) -> SharedString {
2272        self.title.clone().unwrap_or("New Thread".into())
2273    }
2274
2275    pub fn is_generating_summary(&self) -> bool {
2276        self.pending_summary_generation.is_some()
2277    }
2278
2279    pub fn is_generating_title(&self) -> bool {
2280        self.pending_title_generation.is_some()
2281    }
2282
2283    pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
2284        if let Some(summary) = self.summary.as_ref() {
2285            return Task::ready(Some(summary.clone())).shared();
2286        }
2287        if let Some(task) = self.pending_summary_generation.clone() {
2288            return task;
2289        }
2290        let Some(model) = self.summarization_model.clone() else {
2291            log::error!("No summarization model available");
2292            return Task::ready(None).shared();
2293        };
2294        let mut request = LanguageModelRequest {
2295            intent: Some(CompletionIntent::ThreadContextSummarization),
2296            temperature: AgentSettings::temperature_for_model(&model, cx),
2297            ..Default::default()
2298        };
2299
2300        for message in &self.messages {
2301            request.messages.extend(message.to_request());
2302        }
2303
2304        request.messages.push(LanguageModelRequestMessage {
2305            role: Role::User,
2306            content: vec![SUMMARIZE_THREAD_DETAILED_PROMPT.into()],
2307            cache: false,
2308            reasoning_details: None,
2309        });
2310
2311        let task = cx
2312            .spawn(async move |this, cx| {
2313                let mut summary = String::new();
2314                let mut messages = model.stream_completion(request, cx).await.log_err()?;
2315                while let Some(event) = messages.next().await {
2316                    let event = event.log_err()?;
2317                    let text = match event {
2318                        LanguageModelCompletionEvent::Text(text) => text,
2319                        _ => continue,
2320                    };
2321
2322                    let mut lines = text.lines();
2323                    summary.extend(lines.next());
2324                }
2325
2326                log::debug!("Setting summary: {}", summary);
2327                let summary = SharedString::from(summary);
2328
2329                this.update(cx, |this, cx| {
2330                    this.summary = Some(summary.clone());
2331                    this.pending_summary_generation = None;
2332                    cx.notify()
2333                })
2334                .ok()?;
2335
2336                Some(summary)
2337            })
2338            .shared();
2339        self.pending_summary_generation = Some(task.clone());
2340        task
2341    }
2342
2343    pub fn generate_title(&mut self, cx: &mut Context<Self>) {
2344        let Some(model) = self.summarization_model.clone() else {
2345            return;
2346        };
2347
2348        log::debug!(
2349            "Generating title with model: {:?}",
2350            self.summarization_model.as_ref().map(|model| model.name())
2351        );
2352        let mut request = LanguageModelRequest {
2353            intent: Some(CompletionIntent::ThreadSummarization),
2354            temperature: AgentSettings::temperature_for_model(&model, cx),
2355            ..Default::default()
2356        };
2357
2358        for message in &self.messages {
2359            request.messages.extend(message.to_request());
2360        }
2361
2362        request.messages.push(LanguageModelRequestMessage {
2363            role: Role::User,
2364            content: vec![SUMMARIZE_THREAD_PROMPT.into()],
2365            cache: false,
2366            reasoning_details: None,
2367        });
2368        self.pending_title_generation = Some(cx.spawn(async move |this, cx| {
2369            let mut title = String::new();
2370
2371            let generate = async {
2372                let mut messages = model.stream_completion(request, cx).await?;
2373                while let Some(event) = messages.next().await {
2374                    let event = event?;
2375                    let text = match event {
2376                        LanguageModelCompletionEvent::Text(text) => text,
2377                        _ => continue,
2378                    };
2379
2380                    let mut lines = text.lines();
2381                    title.extend(lines.next());
2382
2383                    // Stop if the LLM generated multiple lines.
2384                    if lines.next().is_some() {
2385                        break;
2386                    }
2387                }
2388                anyhow::Ok(())
2389            };
2390
2391            if generate.await.context("failed to generate title").is_ok() {
2392                _ = this.update(cx, |this, cx| this.set_title(title.into(), cx));
2393            }
2394            _ = this.update(cx, |this, _| this.pending_title_generation = None);
2395        }));
2396    }
2397
2398    pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
2399        self.pending_title_generation = None;
2400        if Some(&title) != self.title.as_ref() {
2401            self.title = Some(title);
2402            cx.emit(TitleUpdated);
2403            cx.notify();
2404        }
2405    }
2406
2407    fn clear_summary(&mut self) {
2408        self.summary = None;
2409        self.pending_summary_generation = None;
2410    }
2411
2412    fn last_user_message(&self) -> Option<&UserMessage> {
2413        self.messages
2414            .iter()
2415            .rev()
2416            .find_map(|message| match message {
2417                Message::User(user_message) => Some(user_message),
2418                Message::Agent(_) => None,
2419                Message::Resume => None,
2420            })
2421    }
2422
2423    fn pending_message(&mut self) -> &mut AgentMessage {
2424        self.pending_message.get_or_insert_default()
2425    }
2426
2427    fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
2428        let Some(mut message) = self.pending_message.take() else {
2429            return;
2430        };
2431
2432        if message.content.is_empty() {
2433            return;
2434        }
2435
2436        for content in &message.content {
2437            let AgentMessageContent::ToolUse(tool_use) = content else {
2438                continue;
2439            };
2440
2441            if !message.tool_results.contains_key(&tool_use.id) {
2442                message.tool_results.insert(
2443                    tool_use.id.clone(),
2444                    LanguageModelToolResult {
2445                        tool_use_id: tool_use.id.clone(),
2446                        tool_name: tool_use.name.clone(),
2447                        is_error: true,
2448                        content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
2449                        output: None,
2450                    },
2451                );
2452            }
2453        }
2454
2455        self.messages.push(Message::Agent(message));
2456        self.updated_at = Utc::now();
2457        self.clear_summary();
2458        cx.notify()
2459    }
2460
2461    pub(crate) fn build_completion_request(
2462        &self,
2463        completion_intent: CompletionIntent,
2464        cx: &App,
2465    ) -> Result<LanguageModelRequest> {
2466        let model = self.model().context("No language model configured")?;
2467        let tools = if let Some(turn) = self.running_turn.as_ref() {
2468            turn.tools
2469                .iter()
2470                .filter_map(|(tool_name, tool)| {
2471                    log::trace!("Including tool: {}", tool_name);
2472                    Some(LanguageModelRequestTool {
2473                        name: tool_name.to_string(),
2474                        description: tool.description().to_string(),
2475                        input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
2476                        use_input_streaming: tool.supports_input_streaming(),
2477                    })
2478                })
2479                .collect::<Vec<_>>()
2480        } else {
2481            Vec::new()
2482        };
2483
2484        log::debug!("Building completion request");
2485        log::debug!("Completion intent: {:?}", completion_intent);
2486
2487        let available_tools: Vec<_> = self
2488            .running_turn
2489            .as_ref()
2490            .map(|turn| turn.tools.keys().cloned().collect())
2491            .unwrap_or_default();
2492
2493        log::debug!("Request includes {} tools", available_tools.len());
2494        let messages = self.build_request_messages(available_tools, cx);
2495        log::debug!("Request will include {} messages", messages.len());
2496
2497        let request = LanguageModelRequest {
2498            thread_id: Some(self.id.to_string()),
2499            prompt_id: Some(self.prompt_id.to_string()),
2500            intent: Some(completion_intent),
2501            messages,
2502            tools,
2503            tool_choice: None,
2504            stop: Vec::new(),
2505            temperature: AgentSettings::temperature_for_model(model, cx),
2506            thinking_allowed: self.thinking_enabled,
2507            thinking_effort: self.thinking_effort.clone(),
2508            speed: self.speed(),
2509        };
2510
2511        log::debug!("Completion request built successfully");
2512        Ok(request)
2513    }
2514
2515    fn enabled_tools(
2516        &self,
2517        profile: &AgentProfileSettings,
2518        model: &Arc<dyn LanguageModel>,
2519        cx: &App,
2520    ) -> BTreeMap<SharedString, Arc<dyn AnyAgentTool>> {
2521        fn truncate(tool_name: &SharedString) -> SharedString {
2522            if tool_name.len() > MAX_TOOL_NAME_LENGTH {
2523                let mut truncated = tool_name.to_string();
2524                truncated.truncate(MAX_TOOL_NAME_LENGTH);
2525                truncated.into()
2526            } else {
2527                tool_name.clone()
2528            }
2529        }
2530
2531        let use_streaming_edit_tool = cx.has_flag::<StreamingEditFileToolFeatureFlag>();
2532
2533        let mut tools = self
2534            .tools
2535            .iter()
2536            .filter_map(|(tool_name, tool)| {
2537                // For streaming_edit_file, check profile against "edit_file" since that's what users configure
2538                let profile_tool_name = if tool_name == StreamingEditFileTool::NAME {
2539                    EditFileTool::NAME
2540                } else {
2541                    tool_name.as_ref()
2542                };
2543
2544                if tool.supports_provider(&model.provider_id())
2545                    && profile.is_tool_enabled(profile_tool_name)
2546                {
2547                    match (tool_name.as_ref(), use_streaming_edit_tool) {
2548                        (StreamingEditFileTool::NAME, false) | (EditFileTool::NAME, true) => None,
2549                        (StreamingEditFileTool::NAME, true) => {
2550                            // Expose streaming tool as "edit_file"
2551                            Some((SharedString::from(EditFileTool::NAME), tool.clone()))
2552                        }
2553                        _ => Some((truncate(tool_name), tool.clone())),
2554                    }
2555                } else {
2556                    None
2557                }
2558            })
2559            .collect::<BTreeMap<_, _>>();
2560
2561        let mut context_server_tools = Vec::new();
2562        let mut seen_tools = tools.keys().cloned().collect::<HashSet<_>>();
2563        let mut duplicate_tool_names = HashSet::default();
2564        for (server_id, server_tools) in self.context_server_registry.read(cx).servers() {
2565            for (tool_name, tool) in server_tools {
2566                if profile.is_context_server_tool_enabled(&server_id.0, &tool_name) {
2567                    let tool_name = truncate(tool_name);
2568                    if !seen_tools.insert(tool_name.clone()) {
2569                        duplicate_tool_names.insert(tool_name.clone());
2570                    }
2571                    context_server_tools.push((server_id.clone(), tool_name, tool.clone()));
2572                }
2573            }
2574        }
2575
2576        // When there are duplicate tool names, disambiguate by prefixing them
2577        // with the server ID (converted to snake_case for API compatibility).
2578        // In the rare case there isn't enough space for the disambiguated tool
2579        // name, keep only the last tool with this name.
2580        for (server_id, tool_name, tool) in context_server_tools {
2581            if duplicate_tool_names.contains(&tool_name) {
2582                let available = MAX_TOOL_NAME_LENGTH.saturating_sub(tool_name.len());
2583                if available >= 2 {
2584                    let mut disambiguated = server_id.0.to_snake_case();
2585                    disambiguated.truncate(available - 1);
2586                    disambiguated.push('_');
2587                    disambiguated.push_str(&tool_name);
2588                    tools.insert(disambiguated.into(), tool.clone());
2589                } else {
2590                    tools.insert(tool_name, tool.clone());
2591                }
2592            } else {
2593                tools.insert(tool_name, tool.clone());
2594            }
2595        }
2596
2597        tools
2598    }
2599
2600    fn tool(&self, name: &str) -> Option<Arc<dyn AnyAgentTool>> {
2601        self.running_turn.as_ref()?.tools.get(name).cloned()
2602    }
2603
2604    pub fn has_tool(&self, name: &str) -> bool {
2605        self.running_turn
2606            .as_ref()
2607            .is_some_and(|turn| turn.tools.contains_key(name))
2608    }
2609
2610    #[cfg(any(test, feature = "test-support"))]
2611    pub fn has_registered_tool(&self, name: &str) -> bool {
2612        self.tools.contains_key(name)
2613    }
2614
2615    pub fn registered_tool_names(&self) -> Vec<SharedString> {
2616        self.tools.keys().cloned().collect()
2617    }
2618
2619    pub(crate) fn register_running_subagent(&mut self, subagent: WeakEntity<Thread>) {
2620        self.running_subagents.push(subagent);
2621    }
2622
2623    pub(crate) fn unregister_running_subagent(
2624        &mut self,
2625        subagent_session_id: &acp::SessionId,
2626        cx: &App,
2627    ) {
2628        self.running_subagents.retain(|s| {
2629            s.upgrade()
2630                .map_or(false, |s| s.read(cx).id() != subagent_session_id)
2631        });
2632    }
2633
2634    #[cfg(any(test, feature = "test-support"))]
2635    pub fn running_subagent_ids(&self, cx: &App) -> Vec<acp::SessionId> {
2636        self.running_subagents
2637            .iter()
2638            .filter_map(|s| s.upgrade().map(|s| s.read(cx).id().clone()))
2639            .collect()
2640    }
2641
2642    pub fn is_subagent(&self) -> bool {
2643        self.subagent_context.is_some()
2644    }
2645
2646    pub fn parent_thread_id(&self) -> Option<acp::SessionId> {
2647        self.subagent_context
2648            .as_ref()
2649            .map(|c| c.parent_thread_id.clone())
2650    }
2651
2652    pub fn depth(&self) -> u8 {
2653        self.subagent_context.as_ref().map(|c| c.depth).unwrap_or(0)
2654    }
2655
2656    #[cfg(any(test, feature = "test-support"))]
2657    pub fn set_subagent_context(&mut self, context: SubagentContext) {
2658        self.subagent_context = Some(context);
2659    }
2660
2661    pub fn is_turn_complete(&self) -> bool {
2662        self.running_turn.is_none()
2663    }
2664
2665    fn build_request_messages(
2666        &self,
2667        available_tools: Vec<SharedString>,
2668        cx: &App,
2669    ) -> Vec<LanguageModelRequestMessage> {
2670        log::trace!(
2671            "Building request messages from {} thread messages",
2672            self.messages.len()
2673        );
2674
2675        let system_prompt = SystemPromptTemplate {
2676            project: self.project_context.read(cx),
2677            available_tools,
2678            model_name: self.model.as_ref().map(|m| m.name().0.to_string()),
2679        }
2680        .render(&self.templates)
2681        .context("failed to build system prompt")
2682        .expect("Invalid template");
2683        let mut messages = vec![LanguageModelRequestMessage {
2684            role: Role::System,
2685            content: vec![system_prompt.into()],
2686            cache: false,
2687            reasoning_details: None,
2688        }];
2689        for message in &self.messages {
2690            messages.extend(message.to_request());
2691        }
2692
2693        if let Some(last_message) = messages.last_mut() {
2694            last_message.cache = true;
2695        }
2696
2697        if let Some(message) = self.pending_message.as_ref() {
2698            messages.extend(message.to_request());
2699        }
2700
2701        messages
2702    }
2703
2704    pub fn to_markdown(&self) -> String {
2705        let mut markdown = String::new();
2706        for (ix, message) in self.messages.iter().enumerate() {
2707            if ix > 0 {
2708                markdown.push('\n');
2709            }
2710            match message {
2711                Message::User(_) => markdown.push_str("## User\n\n"),
2712                Message::Agent(_) => markdown.push_str("## Assistant\n\n"),
2713                Message::Resume => {}
2714            }
2715            markdown.push_str(&message.to_markdown());
2716        }
2717
2718        if let Some(message) = self.pending_message.as_ref() {
2719            markdown.push_str("\n## Assistant\n\n");
2720            markdown.push_str(&message.to_markdown());
2721        }
2722
2723        markdown
2724    }
2725
2726    fn advance_prompt_id(&mut self) {
2727        self.prompt_id = PromptId::new();
2728    }
2729
2730    fn retry_strategy_for(error: &LanguageModelCompletionError) -> Option<RetryStrategy> {
2731        use LanguageModelCompletionError::*;
2732        use http_client::StatusCode;
2733
2734        // General strategy here:
2735        // - If retrying won't help (e.g. invalid API key or payload too large), return None so we don't retry at all.
2736        // - If it's a time-based issue (e.g. server overloaded, rate limit exceeded), retry up to 4 times with exponential backoff.
2737        // - If it's an issue that *might* be fixed by retrying (e.g. internal server error), retry up to 3 times.
2738        match error {
2739            HttpResponseError {
2740                status_code: StatusCode::TOO_MANY_REQUESTS,
2741                ..
2742            } => Some(RetryStrategy::ExponentialBackoff {
2743                initial_delay: BASE_RETRY_DELAY,
2744                max_attempts: MAX_RETRY_ATTEMPTS,
2745            }),
2746            ServerOverloaded { retry_after, .. } | RateLimitExceeded { retry_after, .. } => {
2747                Some(RetryStrategy::Fixed {
2748                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2749                    max_attempts: MAX_RETRY_ATTEMPTS,
2750                })
2751            }
2752            UpstreamProviderError {
2753                status,
2754                retry_after,
2755                ..
2756            } => match *status {
2757                StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
2758                    Some(RetryStrategy::Fixed {
2759                        delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2760                        max_attempts: MAX_RETRY_ATTEMPTS,
2761                    })
2762                }
2763                StatusCode::INTERNAL_SERVER_ERROR => Some(RetryStrategy::Fixed {
2764                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2765                    // Internal Server Error could be anything, retry up to 3 times.
2766                    max_attempts: 3,
2767                }),
2768                status => {
2769                    // There is no StatusCode variant for the unofficial HTTP 529 ("The service is overloaded"),
2770                    // but we frequently get them in practice. See https://http.dev/529
2771                    if status.as_u16() == 529 {
2772                        Some(RetryStrategy::Fixed {
2773                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2774                            max_attempts: MAX_RETRY_ATTEMPTS,
2775                        })
2776                    } else {
2777                        Some(RetryStrategy::Fixed {
2778                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2779                            max_attempts: 2,
2780                        })
2781                    }
2782                }
2783            },
2784            ApiInternalServerError { .. } => Some(RetryStrategy::Fixed {
2785                delay: BASE_RETRY_DELAY,
2786                max_attempts: 3,
2787            }),
2788            ApiReadResponseError { .. }
2789            | HttpSend { .. }
2790            | DeserializeResponse { .. }
2791            | BadRequestFormat { .. } => Some(RetryStrategy::Fixed {
2792                delay: BASE_RETRY_DELAY,
2793                max_attempts: 3,
2794            }),
2795            // Retrying these errors definitely shouldn't help.
2796            HttpResponseError {
2797                status_code:
2798                    StatusCode::PAYLOAD_TOO_LARGE | StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED,
2799                ..
2800            }
2801            | AuthenticationError { .. }
2802            | PermissionError { .. }
2803            | NoApiKey { .. }
2804            | ApiEndpointNotFound { .. }
2805            | PromptTooLarge { .. } => None,
2806            // These errors might be transient, so retry them
2807            SerializeRequest { .. } | BuildRequestBody { .. } | StreamEndedUnexpectedly { .. } => {
2808                Some(RetryStrategy::Fixed {
2809                    delay: BASE_RETRY_DELAY,
2810                    max_attempts: 1,
2811                })
2812            }
2813            // Retry all other 4xx and 5xx errors once.
2814            HttpResponseError { status_code, .. }
2815                if status_code.is_client_error() || status_code.is_server_error() =>
2816            {
2817                Some(RetryStrategy::Fixed {
2818                    delay: BASE_RETRY_DELAY,
2819                    max_attempts: 3,
2820                })
2821            }
2822            Other(err) if err.is::<language_model::PaymentRequiredError>() => {
2823                // Retrying won't help for Payment Required errors.
2824                None
2825            }
2826            // Conservatively assume that any other errors are non-retryable
2827            HttpResponseError { .. } | Other(..) => Some(RetryStrategy::Fixed {
2828                delay: BASE_RETRY_DELAY,
2829                max_attempts: 2,
2830            }),
2831        }
2832    }
2833}
2834
2835struct RunningTurn {
2836    /// Holds the task that handles agent interaction until the end of the turn.
2837    /// Survives across multiple requests as the model performs tool calls and
2838    /// we run tools, report their results.
2839    _task: Task<()>,
2840    /// The current event stream for the running turn. Used to report a final
2841    /// cancellation event if we cancel the turn.
2842    event_stream: ThreadEventStream,
2843    /// The tools that were enabled for this turn.
2844    tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
2845    /// Sender to signal tool cancellation. When cancel is called, this is
2846    /// set to true so all tools can detect user-initiated cancellation.
2847    cancellation_tx: watch::Sender<bool>,
2848    /// Senders for tools that support input streaming and have already been
2849    /// started but are still receiving input from the LLM.
2850    streaming_tool_inputs: HashMap<LanguageModelToolUseId, ToolInputSender>,
2851}
2852
2853impl RunningTurn {
2854    fn cancel(mut self) -> Task<()> {
2855        log::debug!("Cancelling in progress turn");
2856        self.cancellation_tx.send(true).ok();
2857        self.event_stream.send_canceled();
2858        self._task
2859    }
2860}
2861
2862pub struct TokenUsageUpdated(pub Option<acp_thread::TokenUsage>);
2863
2864impl EventEmitter<TokenUsageUpdated> for Thread {}
2865
2866pub struct TitleUpdated;
2867
2868impl EventEmitter<TitleUpdated> for Thread {}
2869
2870/// A channel-based wrapper that delivers tool input to a running tool.
2871///
2872/// For non-streaming tools, created via `ToolInput::ready()` so `.recv()` resolves immediately.
2873/// For streaming tools, partial JSON snapshots arrive via `.recv_partial()` as the LLM streams
2874/// them, followed by the final complete input available through `.recv()`.
2875pub struct ToolInput<T> {
2876    partial_rx: mpsc::UnboundedReceiver<serde_json::Value>,
2877    final_rx: oneshot::Receiver<serde_json::Value>,
2878    _phantom: PhantomData<T>,
2879}
2880
2881impl<T: DeserializeOwned> ToolInput<T> {
2882    #[cfg(any(test, feature = "test-support"))]
2883    pub fn resolved(input: impl Serialize) -> Self {
2884        let value = serde_json::to_value(input).expect("failed to serialize tool input");
2885        Self::ready(value)
2886    }
2887
2888    pub fn ready(value: serde_json::Value) -> Self {
2889        let (partial_tx, partial_rx) = mpsc::unbounded();
2890        drop(partial_tx);
2891        let (final_tx, final_rx) = oneshot::channel();
2892        final_tx.send(value).ok();
2893        Self {
2894            partial_rx,
2895            final_rx,
2896            _phantom: PhantomData,
2897        }
2898    }
2899
2900    #[cfg(any(test, feature = "test-support"))]
2901    pub fn test() -> (ToolInputSender, Self) {
2902        let (sender, input) = ToolInputSender::channel();
2903        (sender, input.cast())
2904    }
2905
2906    /// Wait for the final deserialized input, ignoring all partial updates.
2907    /// Non-streaming tools can use this to wait until the whole input is available.
2908    pub async fn recv(mut self) -> Result<T> {
2909        // Drain any remaining partials
2910        while self.partial_rx.next().await.is_some() {}
2911        let value = self
2912            .final_rx
2913            .await
2914            .map_err(|_| anyhow!("tool input sender was dropped before sending final input"))?;
2915        serde_json::from_value(value).map_err(Into::into)
2916    }
2917
2918    /// Returns the next partial JSON snapshot, or `None` when input is complete.
2919    /// Once this returns `None`, call `recv()` to get the final input.
2920    pub async fn recv_partial(&mut self) -> Option<serde_json::Value> {
2921        self.partial_rx.next().await
2922    }
2923
2924    fn cast<U: DeserializeOwned>(self) -> ToolInput<U> {
2925        ToolInput {
2926            partial_rx: self.partial_rx,
2927            final_rx: self.final_rx,
2928            _phantom: PhantomData,
2929        }
2930    }
2931}
2932
2933pub struct ToolInputSender {
2934    partial_tx: mpsc::UnboundedSender<serde_json::Value>,
2935    final_tx: Option<oneshot::Sender<serde_json::Value>>,
2936}
2937
2938impl ToolInputSender {
2939    pub(crate) fn channel() -> (Self, ToolInput<serde_json::Value>) {
2940        let (partial_tx, partial_rx) = mpsc::unbounded();
2941        let (final_tx, final_rx) = oneshot::channel();
2942        let sender = Self {
2943            partial_tx,
2944            final_tx: Some(final_tx),
2945        };
2946        let input = ToolInput {
2947            partial_rx,
2948            final_rx,
2949            _phantom: PhantomData,
2950        };
2951        (sender, input)
2952    }
2953
2954    pub(crate) fn send_partial(&self, value: serde_json::Value) {
2955        self.partial_tx.unbounded_send(value).ok();
2956    }
2957
2958    pub(crate) fn send_final(mut self, value: serde_json::Value) {
2959        // Close the partial channel so recv_partial() returns None
2960        self.partial_tx.close_channel();
2961        if let Some(final_tx) = self.final_tx.take() {
2962            final_tx.send(value).ok();
2963        }
2964    }
2965}
2966
2967pub trait AgentTool
2968where
2969    Self: 'static + Sized,
2970{
2971    type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
2972    type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
2973
2974    const NAME: &'static str;
2975
2976    fn description() -> SharedString {
2977        let schema = schemars::schema_for!(Self::Input);
2978        SharedString::new(
2979            schema
2980                .get("description")
2981                .and_then(|description| description.as_str())
2982                .unwrap_or_default(),
2983        )
2984    }
2985
2986    fn kind() -> acp::ToolKind;
2987
2988    /// The initial tool title to display. Can be updated during the tool run.
2989    fn initial_title(
2990        &self,
2991        input: Result<Self::Input, serde_json::Value>,
2992        cx: &mut App,
2993    ) -> SharedString;
2994
2995    /// Returns the JSON schema that describes the tool's input.
2996    fn input_schema(format: LanguageModelToolSchemaFormat) -> Schema {
2997        language_model::tool_schema::root_schema_for::<Self::Input>(format)
2998    }
2999
3000    /// Returns whether the tool supports streaming of tool use parameters.
3001    fn supports_input_streaming() -> bool {
3002        false
3003    }
3004
3005    /// Some tools rely on a provider for the underlying billing or other reasons.
3006    /// Allow the tool to check if they are compatible, or should be filtered out.
3007    fn supports_provider(_provider: &LanguageModelProviderId) -> bool {
3008        true
3009    }
3010
3011    /// Runs the tool with the provided input.
3012    ///
3013    /// Returns `Result<Self::Output, Self::Output>` rather than `Result<Self::Output, anyhow::Error>`
3014    /// because tool errors are sent back to the model as tool results. This means error output must
3015    /// be structured and readable by the agent — not an arbitrary `anyhow::Error`. Returning the
3016    /// same `Output` type for both success and failure lets tools provide structured data while
3017    /// still signaling whether the invocation succeeded or failed.
3018    fn run(
3019        self: Arc<Self>,
3020        input: ToolInput<Self::Input>,
3021        event_stream: ToolCallEventStream,
3022        cx: &mut App,
3023    ) -> Task<Result<Self::Output, Self::Output>>;
3024
3025    /// Emits events for a previous execution of the tool.
3026    fn replay(
3027        &self,
3028        _input: Self::Input,
3029        _output: Self::Output,
3030        _event_stream: ToolCallEventStream,
3031        _cx: &mut App,
3032    ) -> Result<()> {
3033        Ok(())
3034    }
3035
3036    fn erase(self) -> Arc<dyn AnyAgentTool> {
3037        Arc::new(Erased(Arc::new(self)))
3038    }
3039}
3040
3041pub struct Erased<T>(T);
3042
3043pub struct AgentToolOutput {
3044    pub llm_output: LanguageModelToolResultContent,
3045    pub raw_output: serde_json::Value,
3046}
3047
3048impl AgentToolOutput {
3049    pub fn from_error(message: impl Into<String>) -> Self {
3050        let message = message.into();
3051        let llm_output = LanguageModelToolResultContent::Text(Arc::from(message.as_str()));
3052        Self {
3053            raw_output: serde_json::Value::String(message),
3054            llm_output,
3055        }
3056    }
3057}
3058
3059pub trait AnyAgentTool {
3060    fn name(&self) -> SharedString;
3061    fn description(&self) -> SharedString;
3062    fn kind(&self) -> acp::ToolKind;
3063    fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString;
3064    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
3065    fn supports_input_streaming(&self) -> bool {
3066        false
3067    }
3068    fn supports_provider(&self, _provider: &LanguageModelProviderId) -> bool {
3069        true
3070    }
3071    /// See [`AgentTool::run`] for why this returns `Result<AgentToolOutput, AgentToolOutput>`.
3072    fn run(
3073        self: Arc<Self>,
3074        input: ToolInput<serde_json::Value>,
3075        event_stream: ToolCallEventStream,
3076        cx: &mut App,
3077    ) -> Task<Result<AgentToolOutput, AgentToolOutput>>;
3078    fn replay(
3079        &self,
3080        input: serde_json::Value,
3081        output: serde_json::Value,
3082        event_stream: ToolCallEventStream,
3083        cx: &mut App,
3084    ) -> Result<()>;
3085}
3086
3087impl<T> AnyAgentTool for Erased<Arc<T>>
3088where
3089    T: AgentTool,
3090{
3091    fn name(&self) -> SharedString {
3092        T::NAME.into()
3093    }
3094
3095    fn description(&self) -> SharedString {
3096        T::description()
3097    }
3098
3099    fn kind(&self) -> agent_client_protocol::ToolKind {
3100        T::kind()
3101    }
3102
3103    fn supports_input_streaming(&self) -> bool {
3104        T::supports_input_streaming()
3105    }
3106
3107    fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString {
3108        let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
3109        self.0.initial_title(parsed_input, _cx)
3110    }
3111
3112    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
3113        let mut json = serde_json::to_value(T::input_schema(format))?;
3114        language_model::tool_schema::adapt_schema_to_format(&mut json, format)?;
3115        Ok(json)
3116    }
3117
3118    fn supports_provider(&self, provider: &LanguageModelProviderId) -> bool {
3119        T::supports_provider(provider)
3120    }
3121
3122    fn run(
3123        self: Arc<Self>,
3124        input: ToolInput<serde_json::Value>,
3125        event_stream: ToolCallEventStream,
3126        cx: &mut App,
3127    ) -> Task<Result<AgentToolOutput, AgentToolOutput>> {
3128        let tool_input: ToolInput<T::Input> = input.cast();
3129        let task = self.0.clone().run(tool_input, event_stream, cx);
3130        cx.spawn(async move |_cx| match task.await {
3131            Ok(output) => {
3132                let raw_output = serde_json::to_value(&output).map_err(|e| {
3133                    AgentToolOutput::from_error(format!("Failed to serialize tool output: {e}"))
3134                })?;
3135                Ok(AgentToolOutput {
3136                    llm_output: output.into(),
3137                    raw_output,
3138                })
3139            }
3140            Err(error_output) => {
3141                let raw_output = serde_json::to_value(&error_output).unwrap_or_else(|e| {
3142                    log::error!("Failed to serialize tool error output: {e}");
3143                    serde_json::Value::Null
3144                });
3145                Err(AgentToolOutput {
3146                    llm_output: error_output.into(),
3147                    raw_output,
3148                })
3149            }
3150        })
3151    }
3152
3153    fn replay(
3154        &self,
3155        input: serde_json::Value,
3156        output: serde_json::Value,
3157        event_stream: ToolCallEventStream,
3158        cx: &mut App,
3159    ) -> Result<()> {
3160        let input = serde_json::from_value(input)?;
3161        let output = serde_json::from_value(output)?;
3162        self.0.replay(input, output, event_stream, cx)
3163    }
3164}
3165
3166#[derive(Clone)]
3167struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
3168
3169impl ThreadEventStream {
3170    fn send_user_message(&self, message: &UserMessage) {
3171        self.0
3172            .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
3173            .ok();
3174    }
3175
3176    fn send_text(&self, text: &str) {
3177        self.0
3178            .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
3179            .ok();
3180    }
3181
3182    fn send_thinking(&self, text: &str) {
3183        self.0
3184            .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
3185            .ok();
3186    }
3187
3188    fn send_tool_call(
3189        &self,
3190        id: &LanguageModelToolUseId,
3191        tool_name: &str,
3192        title: SharedString,
3193        kind: acp::ToolKind,
3194        input: serde_json::Value,
3195    ) {
3196        self.0
3197            .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
3198                id,
3199                tool_name,
3200                title.to_string(),
3201                kind,
3202                input,
3203            ))))
3204            .ok();
3205    }
3206
3207    fn initial_tool_call(
3208        id: &LanguageModelToolUseId,
3209        tool_name: &str,
3210        title: String,
3211        kind: acp::ToolKind,
3212        input: serde_json::Value,
3213    ) -> acp::ToolCall {
3214        acp::ToolCall::new(id.to_string(), title)
3215            .kind(kind)
3216            .raw_input(input)
3217            .meta(acp_thread::meta_with_tool_name(tool_name))
3218    }
3219
3220    fn update_tool_call_fields(
3221        &self,
3222        tool_use_id: &LanguageModelToolUseId,
3223        fields: acp::ToolCallUpdateFields,
3224        meta: Option<acp::Meta>,
3225    ) {
3226        self.0
3227            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3228                acp::ToolCallUpdate::new(tool_use_id.to_string(), fields)
3229                    .meta(meta)
3230                    .into(),
3231            )))
3232            .ok();
3233    }
3234
3235    fn send_retry(&self, status: acp_thread::RetryStatus) {
3236        self.0.unbounded_send(Ok(ThreadEvent::Retry(status))).ok();
3237    }
3238
3239    fn send_stop(&self, reason: acp::StopReason) {
3240        self.0.unbounded_send(Ok(ThreadEvent::Stop(reason))).ok();
3241    }
3242
3243    fn send_canceled(&self) {
3244        self.0
3245            .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))
3246            .ok();
3247    }
3248
3249    fn send_error(&self, error: impl Into<anyhow::Error>) {
3250        self.0.unbounded_send(Err(error.into())).ok();
3251    }
3252}
3253
3254#[derive(Clone)]
3255pub struct ToolCallEventStream {
3256    tool_use_id: LanguageModelToolUseId,
3257    stream: ThreadEventStream,
3258    fs: Option<Arc<dyn Fs>>,
3259    cancellation_rx: watch::Receiver<bool>,
3260}
3261
3262impl ToolCallEventStream {
3263    #[cfg(any(test, feature = "test-support"))]
3264    pub fn test() -> (Self, ToolCallEventStreamReceiver) {
3265        let (stream, receiver, _cancellation_tx) = Self::test_with_cancellation();
3266        (stream, receiver)
3267    }
3268
3269    #[cfg(any(test, feature = "test-support"))]
3270    pub fn test_with_cancellation() -> (Self, ToolCallEventStreamReceiver, watch::Sender<bool>) {
3271        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
3272        let (cancellation_tx, cancellation_rx) = watch::channel(false);
3273
3274        let stream = ToolCallEventStream::new(
3275            "test_id".into(),
3276            ThreadEventStream(events_tx),
3277            None,
3278            cancellation_rx,
3279        );
3280
3281        (
3282            stream,
3283            ToolCallEventStreamReceiver(events_rx),
3284            cancellation_tx,
3285        )
3286    }
3287
3288    /// Signal cancellation for this event stream. Only available in tests.
3289    #[cfg(any(test, feature = "test-support"))]
3290    pub fn signal_cancellation_with_sender(cancellation_tx: &mut watch::Sender<bool>) {
3291        cancellation_tx.send(true).ok();
3292    }
3293
3294    fn new(
3295        tool_use_id: LanguageModelToolUseId,
3296        stream: ThreadEventStream,
3297        fs: Option<Arc<dyn Fs>>,
3298        cancellation_rx: watch::Receiver<bool>,
3299    ) -> Self {
3300        Self {
3301            tool_use_id,
3302            stream,
3303            fs,
3304            cancellation_rx,
3305        }
3306    }
3307
3308    /// Returns a future that resolves when the user cancels the tool call.
3309    /// Tools should select on this alongside their main work to detect user cancellation.
3310    pub fn cancelled_by_user(&self) -> impl std::future::Future<Output = ()> + '_ {
3311        let mut rx = self.cancellation_rx.clone();
3312        async move {
3313            loop {
3314                if *rx.borrow() {
3315                    return;
3316                }
3317                if rx.changed().await.is_err() {
3318                    // Sender dropped, will never be cancelled
3319                    std::future::pending::<()>().await;
3320                }
3321            }
3322        }
3323    }
3324
3325    /// Returns true if the user has cancelled this tool call.
3326    /// This is useful for checking cancellation state after an operation completes,
3327    /// to determine if the completion was due to user cancellation.
3328    pub fn was_cancelled_by_user(&self) -> bool {
3329        *self.cancellation_rx.clone().borrow()
3330    }
3331
3332    pub fn tool_use_id(&self) -> &LanguageModelToolUseId {
3333        &self.tool_use_id
3334    }
3335
3336    pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
3337        self.stream
3338            .update_tool_call_fields(&self.tool_use_id, fields, None);
3339    }
3340
3341    pub fn update_fields_with_meta(
3342        &self,
3343        fields: acp::ToolCallUpdateFields,
3344        meta: Option<acp::Meta>,
3345    ) {
3346        self.stream
3347            .update_tool_call_fields(&self.tool_use_id, fields, meta);
3348    }
3349
3350    pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
3351        self.stream
3352            .0
3353            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3354                acp_thread::ToolCallUpdateDiff {
3355                    id: acp::ToolCallId::new(self.tool_use_id.to_string()),
3356                    diff,
3357                }
3358                .into(),
3359            )))
3360            .ok();
3361    }
3362
3363    pub fn subagent_spawned(&self, id: acp::SessionId) {
3364        self.stream
3365            .0
3366            .unbounded_send(Ok(ThreadEvent::SubagentSpawned(id)))
3367            .ok();
3368    }
3369
3370    /// Authorize a third-party tool (e.g., MCP tool from a context server).
3371    ///
3372    /// Unlike built-in tools, third-party tools don't support pattern-based permissions.
3373    /// They only support `default` (allow/deny/confirm) per tool.
3374    ///
3375    /// Uses the dropdown authorization flow with two granularities:
3376    /// - "Always for <display_name> MCP tool" → sets `tools.<tool_id>.default = "allow"` or "deny"
3377    /// - "Only this time" → allow/deny once
3378    pub fn authorize_third_party_tool(
3379        &self,
3380        title: impl Into<String>,
3381        tool_id: String,
3382        display_name: String,
3383        cx: &mut App,
3384    ) -> Task<Result<()>> {
3385        let settings = agent_settings::AgentSettings::get_global(cx);
3386
3387        let decision = decide_permission_from_settings(&tool_id, &[String::new()], &settings);
3388
3389        match decision {
3390            ToolPermissionDecision::Allow => return Task::ready(Ok(())),
3391            ToolPermissionDecision::Deny(reason) => return Task::ready(Err(anyhow!(reason))),
3392            ToolPermissionDecision::Confirm => {}
3393        }
3394
3395        let (response_tx, response_rx) = oneshot::channel();
3396        if let Err(error) = self
3397            .stream
3398            .0
3399            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3400                ToolCallAuthorization {
3401                    tool_call: acp::ToolCallUpdate::new(
3402                        self.tool_use_id.to_string(),
3403                        acp::ToolCallUpdateFields::new().title(title.into()),
3404                    ),
3405                    options: acp_thread::PermissionOptions::Dropdown(vec![
3406                        acp_thread::PermissionOptionChoice {
3407                            allow: acp::PermissionOption::new(
3408                                acp::PermissionOptionId::new(format!(
3409                                    "always_allow_mcp:{}",
3410                                    tool_id
3411                                )),
3412                                format!("Always for {} MCP tool", display_name),
3413                                acp::PermissionOptionKind::AllowAlways,
3414                            ),
3415                            deny: acp::PermissionOption::new(
3416                                acp::PermissionOptionId::new(format!(
3417                                    "always_deny_mcp:{}",
3418                                    tool_id
3419                                )),
3420                                format!("Always for {} MCP tool", display_name),
3421                                acp::PermissionOptionKind::RejectAlways,
3422                            ),
3423                        },
3424                        acp_thread::PermissionOptionChoice {
3425                            allow: acp::PermissionOption::new(
3426                                acp::PermissionOptionId::new("allow"),
3427                                "Only this time",
3428                                acp::PermissionOptionKind::AllowOnce,
3429                            ),
3430                            deny: acp::PermissionOption::new(
3431                                acp::PermissionOptionId::new("deny"),
3432                                "Only this time",
3433                                acp::PermissionOptionKind::RejectOnce,
3434                            ),
3435                        },
3436                    ]),
3437                    response: response_tx,
3438                    context: None,
3439                },
3440            )))
3441        {
3442            log::error!("Failed to send tool call authorization: {error}");
3443            return Task::ready(Err(anyhow!(
3444                "Failed to send tool call authorization: {error}"
3445            )));
3446        }
3447
3448        let fs = self.fs.clone();
3449        cx.spawn(async move |cx| {
3450            let response_str = response_rx.await?.0.to_string();
3451
3452            if response_str == format!("always_allow_mcp:{}", tool_id) {
3453                if let Some(fs) = fs.clone() {
3454                    cx.update(|cx| {
3455                        update_settings_file(fs, cx, move |settings, _| {
3456                            settings
3457                                .agent
3458                                .get_or_insert_default()
3459                                .set_tool_default_permission(&tool_id, ToolPermissionMode::Allow);
3460                        });
3461                    });
3462                }
3463                return Ok(());
3464            }
3465            if response_str == format!("always_deny_mcp:{}", tool_id) {
3466                if let Some(fs) = fs.clone() {
3467                    cx.update(|cx| {
3468                        update_settings_file(fs, cx, move |settings, _| {
3469                            settings
3470                                .agent
3471                                .get_or_insert_default()
3472                                .set_tool_default_permission(&tool_id, ToolPermissionMode::Deny);
3473                        });
3474                    });
3475                }
3476                return Err(anyhow!("Permission to run tool denied by user"));
3477            }
3478
3479            if response_str == "allow" {
3480                return Ok(());
3481            }
3482
3483            Err(anyhow!("Permission to run tool denied by user"))
3484        })
3485    }
3486
3487    pub fn authorize(
3488        &self,
3489        title: impl Into<String>,
3490        context: ToolPermissionContext,
3491        cx: &mut App,
3492    ) -> Task<Result<()>> {
3493        use settings::ToolPermissionMode;
3494
3495        let options = context.build_permission_options();
3496
3497        let (response_tx, response_rx) = oneshot::channel();
3498        if let Err(error) = self
3499            .stream
3500            .0
3501            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3502                ToolCallAuthorization {
3503                    tool_call: acp::ToolCallUpdate::new(
3504                        self.tool_use_id.to_string(),
3505                        acp::ToolCallUpdateFields::new().title(title.into()),
3506                    ),
3507                    options,
3508                    response: response_tx,
3509                    context: Some(context),
3510                },
3511            )))
3512        {
3513            log::error!("Failed to send tool call authorization: {error}");
3514            return Task::ready(Err(anyhow!(
3515                "Failed to send tool call authorization: {error}"
3516            )));
3517        }
3518
3519        let fs = self.fs.clone();
3520        cx.spawn(async move |cx| {
3521            let response_str = response_rx.await?.0.to_string();
3522
3523            // Handle "always allow tool" - e.g., "always_allow:terminal"
3524            if let Some(tool) = response_str.strip_prefix("always_allow:") {
3525                if let Some(fs) = fs.clone() {
3526                    let tool = tool.to_string();
3527                    cx.update(|cx| {
3528                        update_settings_file(fs, cx, move |settings, _| {
3529                            settings
3530                                .agent
3531                                .get_or_insert_default()
3532                                .set_tool_default_permission(&tool, ToolPermissionMode::Allow);
3533                        });
3534                    });
3535                }
3536                return Ok(());
3537            }
3538
3539            // Handle "always deny tool" - e.g., "always_deny:terminal"
3540            if let Some(tool) = response_str.strip_prefix("always_deny:") {
3541                if let Some(fs) = fs.clone() {
3542                    let tool = tool.to_string();
3543                    cx.update(|cx| {
3544                        update_settings_file(fs, cx, move |settings, _| {
3545                            settings
3546                                .agent
3547                                .get_or_insert_default()
3548                                .set_tool_default_permission(&tool, ToolPermissionMode::Deny);
3549                        });
3550                    });
3551                }
3552                return Err(anyhow!("Permission to run tool denied by user"));
3553            }
3554
3555            // Handle "always allow pattern" - e.g., "always_allow_pattern:mcp:server:tool\n^cargo\s"
3556            if let Some(rest) = response_str.strip_prefix("always_allow_pattern:") {
3557                if let Some((pattern_tool_name, pattern)) = rest.split_once('\n') {
3558                    let pattern_tool_name = pattern_tool_name.to_string();
3559                    let pattern = pattern.to_string();
3560                    if let Some(fs) = fs.clone() {
3561                        cx.update(|cx| {
3562                            update_settings_file(fs, cx, move |settings, _| {
3563                                settings
3564                                    .agent
3565                                    .get_or_insert_default()
3566                                    .add_tool_allow_pattern(&pattern_tool_name, pattern);
3567                            });
3568                        });
3569                    }
3570                } else {
3571                    log::error!("Failed to parse always allow pattern: missing newline separator in '{rest}'");
3572                }
3573                return Ok(());
3574            }
3575
3576            // Handle "always deny pattern" - e.g., "always_deny_pattern:mcp:server:tool\n^cargo\s"
3577            if let Some(rest) = response_str.strip_prefix("always_deny_pattern:") {
3578                if let Some((pattern_tool_name, pattern)) = rest.split_once('\n') {
3579                    let pattern_tool_name = pattern_tool_name.to_string();
3580                    let pattern = pattern.to_string();
3581                    if let Some(fs) = fs.clone() {
3582                        cx.update(|cx| {
3583                            update_settings_file(fs, cx, move |settings, _| {
3584                                settings
3585                                    .agent
3586                                    .get_or_insert_default()
3587                                    .add_tool_deny_pattern(&pattern_tool_name, pattern);
3588                            });
3589                        });
3590                    }
3591                } else {
3592                    log::error!("Failed to parse always deny pattern: missing newline separator in '{rest}'");
3593                }
3594                return Err(anyhow!("Permission to run tool denied by user"));
3595            }
3596
3597            // Handle simple "allow" (allow once)
3598            if response_str == "allow" {
3599                return Ok(());
3600            }
3601
3602            // Handle simple "deny" (deny once)
3603            Err(anyhow!("Permission to run tool denied by user"))
3604        })
3605    }
3606}
3607
3608#[cfg(any(test, feature = "test-support"))]
3609pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
3610
3611#[cfg(any(test, feature = "test-support"))]
3612impl ToolCallEventStreamReceiver {
3613    pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
3614        let event = self.0.next().await;
3615        if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
3616            auth
3617        } else {
3618            panic!("Expected ToolCallAuthorization but got: {:?}", event);
3619        }
3620    }
3621
3622    pub async fn expect_update_fields(&mut self) -> acp::ToolCallUpdateFields {
3623        let event = self.0.next().await;
3624        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
3625            update,
3626        )))) = event
3627        {
3628            update.fields
3629        } else {
3630            panic!("Expected update fields but got: {:?}", event);
3631        }
3632    }
3633
3634    pub async fn expect_diff(&mut self) -> Entity<acp_thread::Diff> {
3635        let event = self.0.next().await;
3636        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateDiff(
3637            update,
3638        )))) = event
3639        {
3640            update.diff
3641        } else {
3642            panic!("Expected diff but got: {:?}", event);
3643        }
3644    }
3645
3646    pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
3647        let event = self.0.next().await;
3648        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
3649            update,
3650        )))) = event
3651        {
3652            update.terminal
3653        } else {
3654            panic!("Expected terminal but got: {:?}", event);
3655        }
3656    }
3657}
3658
3659#[cfg(any(test, feature = "test-support"))]
3660impl std::ops::Deref for ToolCallEventStreamReceiver {
3661    type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
3662
3663    fn deref(&self) -> &Self::Target {
3664        &self.0
3665    }
3666}
3667
3668#[cfg(any(test, feature = "test-support"))]
3669impl std::ops::DerefMut for ToolCallEventStreamReceiver {
3670    fn deref_mut(&mut self) -> &mut Self::Target {
3671        &mut self.0
3672    }
3673}
3674
3675impl From<&str> for UserMessageContent {
3676    fn from(text: &str) -> Self {
3677        Self::Text(text.into())
3678    }
3679}
3680
3681impl From<String> for UserMessageContent {
3682    fn from(text: String) -> Self {
3683        Self::Text(text)
3684    }
3685}
3686
3687impl UserMessageContent {
3688    pub fn from_content_block(value: acp::ContentBlock, path_style: PathStyle) -> Self {
3689        match value {
3690            acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
3691            acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
3692            acp::ContentBlock::Audio(_) => {
3693                // TODO
3694                Self::Text("[audio]".to_string())
3695            }
3696            acp::ContentBlock::ResourceLink(resource_link) => {
3697                match MentionUri::parse(&resource_link.uri, path_style) {
3698                    Ok(uri) => Self::Mention {
3699                        uri,
3700                        content: String::new(),
3701                    },
3702                    Err(err) => {
3703                        log::error!("Failed to parse mention link: {}", err);
3704                        Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
3705                    }
3706                }
3707            }
3708            acp::ContentBlock::Resource(resource) => match resource.resource {
3709                acp::EmbeddedResourceResource::TextResourceContents(resource) => {
3710                    match MentionUri::parse(&resource.uri, path_style) {
3711                        Ok(uri) => Self::Mention {
3712                            uri,
3713                            content: resource.text,
3714                        },
3715                        Err(err) => {
3716                            log::error!("Failed to parse mention link: {}", err);
3717                            Self::Text(
3718                                MarkdownCodeBlock {
3719                                    tag: &resource.uri,
3720                                    text: &resource.text,
3721                                }
3722                                .to_string(),
3723                            )
3724                        }
3725                    }
3726                }
3727                acp::EmbeddedResourceResource::BlobResourceContents(_) => {
3728                    // TODO
3729                    Self::Text("[blob]".to_string())
3730                }
3731                other => {
3732                    log::warn!("Unexpected content type: {:?}", other);
3733                    Self::Text("[unknown]".to_string())
3734                }
3735            },
3736            other => {
3737                log::warn!("Unexpected content type: {:?}", other);
3738                Self::Text("[unknown]".to_string())
3739            }
3740        }
3741    }
3742}
3743
3744impl From<UserMessageContent> for acp::ContentBlock {
3745    fn from(content: UserMessageContent) -> Self {
3746        match content {
3747            UserMessageContent::Text(text) => text.into(),
3748            UserMessageContent::Image(image) => {
3749                acp::ContentBlock::Image(acp::ImageContent::new(image.source, "image/png"))
3750            }
3751            UserMessageContent::Mention { uri, content } => acp::ContentBlock::Resource(
3752                acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(
3753                    acp::TextResourceContents::new(content, uri.to_uri().to_string()),
3754                )),
3755            ),
3756        }
3757    }
3758}
3759
3760fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
3761    LanguageModelImage {
3762        source: image_content.data.into(),
3763        size: None,
3764    }
3765}
3766
3767#[cfg(test)]
3768mod tests {
3769    use super::*;
3770    use gpui::TestAppContext;
3771    use language_model::LanguageModelToolUseId;
3772    use serde_json::json;
3773    use std::sync::Arc;
3774
3775    async fn setup_thread_for_test(cx: &mut TestAppContext) -> (Entity<Thread>, ThreadEventStream) {
3776        cx.update(|cx| {
3777            let settings_store = settings::SettingsStore::test(cx);
3778            cx.set_global(settings_store);
3779        });
3780
3781        let fs = fs::FakeFs::new(cx.background_executor.clone());
3782        let templates = Templates::new();
3783        let project = Project::test(fs.clone(), [], cx).await;
3784
3785        cx.update(|cx| {
3786            let project_context = cx.new(|_cx| prompt_store::ProjectContext::default());
3787            let context_server_store = project.read(cx).context_server_store();
3788            let context_server_registry =
3789                cx.new(|cx| ContextServerRegistry::new(context_server_store, cx));
3790
3791            let thread = cx.new(|cx| {
3792                Thread::new(
3793                    project,
3794                    project_context,
3795                    context_server_registry,
3796                    templates,
3797                    None,
3798                    cx,
3799                )
3800            });
3801
3802            let (event_tx, _event_rx) = mpsc::unbounded();
3803            let event_stream = ThreadEventStream(event_tx);
3804
3805            (thread, event_stream)
3806        })
3807    }
3808
3809    #[gpui::test]
3810    async fn test_handle_tool_use_json_parse_error_adds_tool_use_to_content(
3811        cx: &mut TestAppContext,
3812    ) {
3813        let (thread, event_stream) = setup_thread_for_test(cx).await;
3814
3815        cx.update(|cx| {
3816            thread.update(cx, |thread, _cx| {
3817                let tool_use_id = LanguageModelToolUseId::from("test_tool_id");
3818                let tool_name: Arc<str> = Arc::from("test_tool");
3819                let raw_input: Arc<str> = Arc::from("{invalid json");
3820                let json_parse_error = "expected value at line 1 column 1".to_string();
3821
3822                // Call the function under test
3823                let result = thread.handle_tool_use_json_parse_error_event(
3824                    tool_use_id.clone(),
3825                    tool_name.clone(),
3826                    raw_input.clone(),
3827                    json_parse_error,
3828                    &event_stream,
3829                );
3830
3831                // Verify the result is an error
3832                assert!(result.is_error);
3833                assert_eq!(result.tool_use_id, tool_use_id);
3834                assert_eq!(result.tool_name, tool_name);
3835                assert!(matches!(
3836                    result.content,
3837                    LanguageModelToolResultContent::Text(_)
3838                ));
3839
3840                // Verify the tool use was added to the message content
3841                {
3842                    let last_message = thread.pending_message();
3843                    assert_eq!(
3844                        last_message.content.len(),
3845                        1,
3846                        "Should have one tool_use in content"
3847                    );
3848
3849                    match &last_message.content[0] {
3850                        AgentMessageContent::ToolUse(tool_use) => {
3851                            assert_eq!(tool_use.id, tool_use_id);
3852                            assert_eq!(tool_use.name, tool_name);
3853                            assert_eq!(tool_use.raw_input, raw_input.to_string());
3854                            assert!(tool_use.is_input_complete);
3855                            // Should fall back to empty object for invalid JSON
3856                            assert_eq!(tool_use.input, json!({}));
3857                        }
3858                        _ => panic!("Expected ToolUse content"),
3859                    }
3860                }
3861
3862                // Insert the tool result (simulating what the caller does)
3863                thread
3864                    .pending_message()
3865                    .tool_results
3866                    .insert(result.tool_use_id.clone(), result);
3867
3868                // Verify the tool result was added
3869                let last_message = thread.pending_message();
3870                assert_eq!(
3871                    last_message.tool_results.len(),
3872                    1,
3873                    "Should have one tool_result"
3874                );
3875                assert!(last_message.tool_results.contains_key(&tool_use_id));
3876            });
3877        });
3878    }
3879}