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