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 clear_queued_messages(&mut self) {
1292        self.queued_messages.clear();
1293    }
1294
1295    fn has_queued_messages(&self) -> bool {
1296        !self.queued_messages.is_empty()
1297    }
1298
1299    fn update_token_usage(&mut self, update: language_model::TokenUsage, cx: &mut Context<Self>) {
1300        let Some(last_user_message) = self.last_user_message() else {
1301            return;
1302        };
1303
1304        self.request_token_usage
1305            .insert(last_user_message.id.clone(), update);
1306        cx.emit(TokenUsageUpdated(self.latest_token_usage()));
1307        cx.notify();
1308    }
1309
1310    pub fn truncate(&mut self, message_id: UserMessageId, cx: &mut Context<Self>) -> Result<()> {
1311        self.cancel(cx).detach();
1312        // Clear pending message since cancel will try to flush it asynchronously,
1313        // and we don't want that content to be added after we truncate
1314        self.pending_message.take();
1315        let Some(position) = self.messages.iter().position(
1316            |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
1317        ) else {
1318            return Err(anyhow!("Message not found"));
1319        };
1320
1321        for message in self.messages.drain(position..) {
1322            match message {
1323                Message::User(message) => {
1324                    self.request_token_usage.remove(&message.id);
1325                }
1326                Message::Agent(_) | Message::Resume => {}
1327            }
1328        }
1329        self.clear_summary();
1330        cx.notify();
1331        Ok(())
1332    }
1333
1334    pub fn latest_request_token_usage(&self) -> Option<language_model::TokenUsage> {
1335        let last_user_message = self.last_user_message()?;
1336        let tokens = self.request_token_usage.get(&last_user_message.id)?;
1337        Some(*tokens)
1338    }
1339
1340    pub fn latest_token_usage(&self) -> Option<acp_thread::TokenUsage> {
1341        let usage = self.latest_request_token_usage()?;
1342        let model = self.model.clone()?;
1343        Some(acp_thread::TokenUsage {
1344            max_tokens: model.max_token_count(),
1345            used_tokens: usage.total_tokens(),
1346            input_tokens: usage.input_tokens,
1347            output_tokens: usage.output_tokens,
1348        })
1349    }
1350
1351    /// Get the total input token count as of the message before the given message.
1352    ///
1353    /// Returns `None` if:
1354    /// - `target_id` is the first message (no previous message)
1355    /// - The previous message hasn't received a response yet (no usage data)
1356    /// - `target_id` is not found in the messages
1357    pub fn tokens_before_message(&self, target_id: &UserMessageId) -> Option<u64> {
1358        let mut previous_user_message_id: Option<&UserMessageId> = None;
1359
1360        for message in &self.messages {
1361            if let Message::User(user_msg) = message {
1362                if &user_msg.id == target_id {
1363                    let prev_id = previous_user_message_id?;
1364                    let usage = self.request_token_usage.get(prev_id)?;
1365                    return Some(usage.input_tokens);
1366                }
1367                previous_user_message_id = Some(&user_msg.id);
1368            }
1369        }
1370        None
1371    }
1372
1373    /// Look up the active profile and resolve its preferred model if one is configured.
1374    fn resolve_profile_model(
1375        profile_id: &AgentProfileId,
1376        cx: &mut Context<Self>,
1377    ) -> Option<Arc<dyn LanguageModel>> {
1378        let selection = AgentSettings::get_global(cx)
1379            .profiles
1380            .get(profile_id)?
1381            .default_model
1382            .clone()?;
1383        Self::resolve_model_from_selection(&selection, cx)
1384    }
1385
1386    /// Translate a stored model selection into the configured model from the registry.
1387    fn resolve_model_from_selection(
1388        selection: &LanguageModelSelection,
1389        cx: &mut Context<Self>,
1390    ) -> Option<Arc<dyn LanguageModel>> {
1391        let selected = SelectedModel {
1392            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
1393            model: LanguageModelId::from(selection.model.clone()),
1394        };
1395        LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1396            registry
1397                .select_model(&selected, cx)
1398                .map(|configured| configured.model)
1399        })
1400    }
1401
1402    pub fn resume(
1403        &mut self,
1404        cx: &mut Context<Self>,
1405    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1406        self.messages.push(Message::Resume);
1407        cx.notify();
1408
1409        log::debug!("Total messages in thread: {}", self.messages.len());
1410        self.run_turn(cx)
1411    }
1412
1413    /// Sending a message results in the model streaming a response, which could include tool calls.
1414    /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
1415    /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
1416    pub fn send<T>(
1417        &mut self,
1418        id: UserMessageId,
1419        content: impl IntoIterator<Item = T>,
1420        cx: &mut Context<Self>,
1421    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
1422    where
1423        T: Into<UserMessageContent>,
1424    {
1425        let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
1426        log::debug!("Thread::send content: {:?}", content);
1427
1428        self.messages
1429            .push(Message::User(UserMessage { id, content }));
1430        cx.notify();
1431
1432        self.send_existing(cx)
1433    }
1434
1435    pub fn send_existing(
1436        &mut self,
1437        cx: &mut Context<Self>,
1438    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1439        let model = self.model().context("No language model configured")?;
1440
1441        log::info!("Thread::send called with model: {}", model.name().0);
1442        self.advance_prompt_id();
1443
1444        log::debug!("Total messages in thread: {}", self.messages.len());
1445        self.run_turn(cx)
1446    }
1447
1448    pub fn push_acp_user_block(
1449        &mut self,
1450        id: UserMessageId,
1451        blocks: impl IntoIterator<Item = acp::ContentBlock>,
1452        path_style: PathStyle,
1453        cx: &mut Context<Self>,
1454    ) {
1455        let content = blocks
1456            .into_iter()
1457            .map(|block| UserMessageContent::from_content_block(block, path_style))
1458            .collect::<Vec<_>>();
1459        self.messages
1460            .push(Message::User(UserMessage { id, content }));
1461        cx.notify();
1462    }
1463
1464    pub fn push_acp_agent_block(&mut self, block: acp::ContentBlock, cx: &mut Context<Self>) {
1465        let text = match block {
1466            acp::ContentBlock::Text(text_content) => text_content.text,
1467            acp::ContentBlock::Image(_) => "[image]".to_string(),
1468            acp::ContentBlock::Audio(_) => "[audio]".to_string(),
1469            acp::ContentBlock::ResourceLink(resource_link) => resource_link.uri,
1470            acp::ContentBlock::Resource(resource) => match resource.resource {
1471                acp::EmbeddedResourceResource::TextResourceContents(resource) => resource.uri,
1472                acp::EmbeddedResourceResource::BlobResourceContents(resource) => resource.uri,
1473                _ => "[resource]".to_string(),
1474            },
1475            _ => "[unknown]".to_string(),
1476        };
1477
1478        self.messages.push(Message::Agent(AgentMessage {
1479            content: vec![AgentMessageContent::Text(text)],
1480            ..Default::default()
1481        }));
1482        cx.notify();
1483    }
1484
1485    #[cfg(feature = "eval")]
1486    pub fn proceed(
1487        &mut self,
1488        cx: &mut Context<Self>,
1489    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1490        self.run_turn(cx)
1491    }
1492
1493    fn run_turn(
1494        &mut self,
1495        cx: &mut Context<Self>,
1496    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1497        // Flush the old pending message synchronously before cancelling,
1498        // to avoid a race where the detached cancel task might flush the NEW
1499        // turn's pending message instead of the old one.
1500        self.flush_pending_message(cx);
1501        self.cancel(cx).detach();
1502
1503        let model = self.model.clone().context("No language model configured")?;
1504        let profile = AgentSettings::get_global(cx)
1505            .profiles
1506            .get(&self.profile_id)
1507            .context("Profile not found")?;
1508        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1509        let event_stream = ThreadEventStream(events_tx);
1510        let message_ix = self.messages.len().saturating_sub(1);
1511        self.clear_summary();
1512        let (cancellation_tx, mut cancellation_rx) = watch::channel(false);
1513        self.running_turn = Some(RunningTurn {
1514            event_stream: event_stream.clone(),
1515            tools: self.enabled_tools(profile, &model, cx),
1516            cancellation_tx,
1517            _task: cx.spawn(async move |this, cx| {
1518                log::debug!("Starting agent turn execution");
1519
1520                let turn_result = Self::run_turn_internal(
1521                    &this,
1522                    model,
1523                    &event_stream,
1524                    cancellation_rx.clone(),
1525                    cx,
1526                )
1527                .await;
1528
1529                // Check if we were cancelled - if so, cancel() already took running_turn
1530                // and we shouldn't touch it (it might be a NEW turn now)
1531                let was_cancelled = *cancellation_rx.borrow();
1532                if was_cancelled {
1533                    log::debug!("Turn was cancelled, skipping cleanup");
1534                    return;
1535                }
1536
1537                _ = this.update(cx, |this, cx| this.flush_pending_message(cx));
1538
1539                match turn_result {
1540                    Ok(()) => {
1541                        log::debug!("Turn execution completed");
1542                        event_stream.send_stop(acp::StopReason::EndTurn);
1543                    }
1544                    Err(error) => {
1545                        log::error!("Turn execution failed: {:?}", error);
1546                        match error.downcast::<CompletionError>() {
1547                            Ok(CompletionError::Refusal) => {
1548                                event_stream.send_stop(acp::StopReason::Refusal);
1549                                _ = this.update(cx, |this, _| this.messages.truncate(message_ix));
1550                            }
1551                            Ok(CompletionError::MaxTokens) => {
1552                                event_stream.send_stop(acp::StopReason::MaxTokens);
1553                            }
1554                            Ok(CompletionError::Other(error)) | Err(error) => {
1555                                event_stream.send_error(error);
1556                            }
1557                        }
1558                    }
1559                }
1560
1561                _ = this.update(cx, |this, _| this.running_turn.take());
1562            }),
1563        });
1564        Ok(events_rx)
1565    }
1566
1567    async fn run_turn_internal(
1568        this: &WeakEntity<Self>,
1569        model: Arc<dyn LanguageModel>,
1570        event_stream: &ThreadEventStream,
1571        mut cancellation_rx: watch::Receiver<bool>,
1572        cx: &mut AsyncApp,
1573    ) -> Result<()> {
1574        let mut attempt = 0;
1575        let mut intent = CompletionIntent::UserPrompt;
1576        loop {
1577            let request =
1578                this.update(cx, |this, cx| this.build_completion_request(intent, cx))??;
1579
1580            telemetry::event!(
1581                "Agent Thread Completion",
1582                thread_id = this.read_with(cx, |this, _| this.id.to_string())?,
1583                prompt_id = this.read_with(cx, |this, _| this.prompt_id.to_string())?,
1584                model = model.telemetry_id(),
1585                model_provider = model.provider_id().to_string(),
1586                attempt
1587            );
1588
1589            log::debug!("Calling model.stream_completion, attempt {}", attempt);
1590
1591            let (mut events, mut error) = match model.stream_completion(request, cx).await {
1592                Ok(events) => (events.fuse(), None),
1593                Err(err) => (stream::empty().boxed().fuse(), Some(err)),
1594            };
1595            let mut tool_results = FuturesUnordered::new();
1596            let mut cancelled = false;
1597            loop {
1598                // Race between getting the first event and cancellation
1599                let first_event = futures::select! {
1600                    event = events.next().fuse() => event,
1601                    _ = cancellation_rx.changed().fuse() => {
1602                        if *cancellation_rx.borrow() {
1603                            cancelled = true;
1604                            break;
1605                        }
1606                        continue;
1607                    }
1608                };
1609                let Some(first_event) = first_event else {
1610                    break;
1611                };
1612
1613                // Collect all immediately available events to process as a batch
1614                let mut batch = vec![first_event];
1615                while let Some(event) = events.next().now_or_never().flatten() {
1616                    batch.push(event);
1617                }
1618
1619                // Process the batch in a single update
1620                let batch_result = this.update(cx, |this, cx| {
1621                    let mut batch_tool_results = Vec::new();
1622                    let mut batch_error = None;
1623
1624                    for event in batch {
1625                        log::trace!("Received completion event: {:?}", event);
1626                        match event {
1627                            Ok(event) => {
1628                                match this.handle_completion_event(
1629                                    event,
1630                                    event_stream,
1631                                    cancellation_rx.clone(),
1632                                    cx,
1633                                ) {
1634                                    Ok(Some(task)) => batch_tool_results.push(task),
1635                                    Ok(None) => {}
1636                                    Err(err) => {
1637                                        batch_error = Some(err);
1638                                        break;
1639                                    }
1640                                }
1641                            }
1642                            Err(err) => {
1643                                batch_error = Some(err.into());
1644                                break;
1645                            }
1646                        }
1647                    }
1648
1649                    cx.notify();
1650                    (batch_tool_results, batch_error)
1651                })?;
1652
1653                tool_results.extend(batch_result.0);
1654                if let Some(err) = batch_result.1 {
1655                    error = Some(err.downcast()?);
1656                    break;
1657                }
1658            }
1659
1660            let end_turn = tool_results.is_empty();
1661            while let Some(tool_result) = tool_results.next().await {
1662                log::debug!("Tool finished {:?}", tool_result);
1663
1664                event_stream.update_tool_call_fields(
1665                    &tool_result.tool_use_id,
1666                    acp::ToolCallUpdateFields::new()
1667                        .status(if tool_result.is_error {
1668                            acp::ToolCallStatus::Failed
1669                        } else {
1670                            acp::ToolCallStatus::Completed
1671                        })
1672                        .raw_output(tool_result.output.clone()),
1673                );
1674                this.update(cx, |this, _cx| {
1675                    this.pending_message()
1676                        .tool_results
1677                        .insert(tool_result.tool_use_id.clone(), tool_result);
1678                })?;
1679            }
1680
1681            this.update(cx, |this, cx| {
1682                this.flush_pending_message(cx);
1683                if this.title.is_none() && this.pending_title_generation.is_none() {
1684                    this.generate_title(cx);
1685                }
1686            })?;
1687
1688            if cancelled {
1689                log::debug!("Turn cancelled by user, exiting");
1690                return Ok(());
1691            }
1692
1693            if let Some(error) = error {
1694                attempt += 1;
1695                let retry = this.update(cx, |this, cx| {
1696                    let user_store = this.user_store.read(cx);
1697                    this.handle_completion_error(error, attempt, user_store.plan())
1698                })??;
1699                let timer = cx.background_executor().timer(retry.duration);
1700                event_stream.send_retry(retry);
1701                timer.await;
1702                this.update(cx, |this, _cx| {
1703                    if let Some(Message::Agent(message)) = this.messages.last() {
1704                        if message.tool_results.is_empty() {
1705                            intent = CompletionIntent::UserPrompt;
1706                            this.messages.push(Message::Resume);
1707                        }
1708                    }
1709                })?;
1710            } else if end_turn {
1711                return Ok(());
1712            } else {
1713                let has_queued = this.update(cx, |this, _| this.has_queued_messages())?;
1714                if has_queued {
1715                    log::debug!("Queued message found, ending turn at message boundary");
1716                    return Ok(());
1717                }
1718                intent = CompletionIntent::ToolResults;
1719                attempt = 0;
1720            }
1721        }
1722    }
1723
1724    fn handle_completion_error(
1725        &mut self,
1726        error: LanguageModelCompletionError,
1727        attempt: u8,
1728        plan: Option<Plan>,
1729    ) -> Result<acp_thread::RetryStatus> {
1730        let Some(model) = self.model.as_ref() else {
1731            return Err(anyhow!(error));
1732        };
1733
1734        let auto_retry = if model.provider_id() == ZED_CLOUD_PROVIDER_ID {
1735            match plan {
1736                Some(Plan::V2(_)) => true,
1737                None => false,
1738            }
1739        } else {
1740            true
1741        };
1742
1743        if !auto_retry {
1744            return Err(anyhow!(error));
1745        }
1746
1747        let Some(strategy) = Self::retry_strategy_for(&error) else {
1748            return Err(anyhow!(error));
1749        };
1750
1751        let max_attempts = match &strategy {
1752            RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
1753            RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
1754        };
1755
1756        if attempt > max_attempts {
1757            return Err(anyhow!(error));
1758        }
1759
1760        let delay = match &strategy {
1761            RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
1762                let delay_secs = initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
1763                Duration::from_secs(delay_secs)
1764            }
1765            RetryStrategy::Fixed { delay, .. } => *delay,
1766        };
1767        log::debug!("Retry attempt {attempt} with delay {delay:?}");
1768
1769        Ok(acp_thread::RetryStatus {
1770            last_error: error.to_string().into(),
1771            attempt: attempt as usize,
1772            max_attempts: max_attempts as usize,
1773            started_at: Instant::now(),
1774            duration: delay,
1775        })
1776    }
1777
1778    /// A helper method that's called on every streamed completion event.
1779    /// Returns an optional tool result task, which the main agentic loop will
1780    /// send back to the model when it resolves.
1781    fn handle_completion_event(
1782        &mut self,
1783        event: LanguageModelCompletionEvent,
1784        event_stream: &ThreadEventStream,
1785        cancellation_rx: watch::Receiver<bool>,
1786        cx: &mut Context<Self>,
1787    ) -> Result<Option<Task<LanguageModelToolResult>>> {
1788        log::trace!("Handling streamed completion event: {:?}", event);
1789        use LanguageModelCompletionEvent::*;
1790
1791        match event {
1792            StartMessage { .. } => {
1793                self.flush_pending_message(cx);
1794                self.pending_message = Some(AgentMessage::default());
1795            }
1796            Text(new_text) => self.handle_text_event(new_text, event_stream),
1797            Thinking { text, signature } => {
1798                self.handle_thinking_event(text, signature, event_stream)
1799            }
1800            RedactedThinking { data } => self.handle_redacted_thinking_event(data),
1801            ReasoningDetails(details) => {
1802                let last_message = self.pending_message();
1803                // Store the last non-empty reasoning_details (overwrites earlier ones)
1804                // This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
1805                if let serde_json::Value::Array(ref arr) = details {
1806                    if !arr.is_empty() {
1807                        last_message.reasoning_details = Some(details);
1808                    }
1809                } else {
1810                    last_message.reasoning_details = Some(details);
1811                }
1812            }
1813            ToolUse(tool_use) => {
1814                return Ok(self.handle_tool_use_event(tool_use, event_stream, cancellation_rx, cx));
1815            }
1816            ToolUseJsonParseError {
1817                id,
1818                tool_name,
1819                raw_input,
1820                json_parse_error,
1821            } => {
1822                return Ok(Some(Task::ready(
1823                    self.handle_tool_use_json_parse_error_event(
1824                        id,
1825                        tool_name,
1826                        raw_input,
1827                        json_parse_error,
1828                    ),
1829                )));
1830            }
1831            UsageUpdate(usage) => {
1832                telemetry::event!(
1833                    "Agent Thread Completion Usage Updated",
1834                    thread_id = self.id.to_string(),
1835                    prompt_id = self.prompt_id.to_string(),
1836                    model = self.model.as_ref().map(|m| m.telemetry_id()),
1837                    model_provider = self.model.as_ref().map(|m| m.provider_id().to_string()),
1838                    input_tokens = usage.input_tokens,
1839                    output_tokens = usage.output_tokens,
1840                    cache_creation_input_tokens = usage.cache_creation_input_tokens,
1841                    cache_read_input_tokens = usage.cache_read_input_tokens,
1842                );
1843                self.update_token_usage(usage, cx);
1844            }
1845            Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()),
1846            Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()),
1847            Stop(StopReason::ToolUse | StopReason::EndTurn) => {}
1848            Started | Queued { .. } => {}
1849        }
1850
1851        Ok(None)
1852    }
1853
1854    fn handle_text_event(&mut self, new_text: String, event_stream: &ThreadEventStream) {
1855        event_stream.send_text(&new_text);
1856
1857        let last_message = self.pending_message();
1858        if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
1859            text.push_str(&new_text);
1860        } else {
1861            last_message
1862                .content
1863                .push(AgentMessageContent::Text(new_text));
1864        }
1865    }
1866
1867    fn handle_thinking_event(
1868        &mut self,
1869        new_text: String,
1870        new_signature: Option<String>,
1871        event_stream: &ThreadEventStream,
1872    ) {
1873        event_stream.send_thinking(&new_text);
1874
1875        let last_message = self.pending_message();
1876        if let Some(AgentMessageContent::Thinking { text, signature }) =
1877            last_message.content.last_mut()
1878        {
1879            text.push_str(&new_text);
1880            *signature = new_signature.or(signature.take());
1881        } else {
1882            last_message.content.push(AgentMessageContent::Thinking {
1883                text: new_text,
1884                signature: new_signature,
1885            });
1886        }
1887    }
1888
1889    fn handle_redacted_thinking_event(&mut self, data: String) {
1890        let last_message = self.pending_message();
1891        last_message
1892            .content
1893            .push(AgentMessageContent::RedactedThinking(data));
1894    }
1895
1896    fn handle_tool_use_event(
1897        &mut self,
1898        tool_use: LanguageModelToolUse,
1899        event_stream: &ThreadEventStream,
1900        cancellation_rx: watch::Receiver<bool>,
1901        cx: &mut Context<Self>,
1902    ) -> Option<Task<LanguageModelToolResult>> {
1903        cx.notify();
1904
1905        let tool = self.tool(tool_use.name.as_ref());
1906        let mut title = SharedString::from(&tool_use.name);
1907        let mut kind = acp::ToolKind::Other;
1908        if let Some(tool) = tool.as_ref() {
1909            title = tool.initial_title(tool_use.input.clone(), cx);
1910            kind = tool.kind();
1911        }
1912
1913        // Ensure the last message ends in the current tool use
1914        let last_message = self.pending_message();
1915        let push_new_tool_use = last_message.content.last_mut().is_none_or(|content| {
1916            if let AgentMessageContent::ToolUse(last_tool_use) = content {
1917                if last_tool_use.id == tool_use.id {
1918                    *last_tool_use = tool_use.clone();
1919                    false
1920                } else {
1921                    true
1922                }
1923            } else {
1924                true
1925            }
1926        });
1927
1928        if push_new_tool_use {
1929            event_stream.send_tool_call(
1930                &tool_use.id,
1931                &tool_use.name,
1932                title,
1933                kind,
1934                tool_use.input.clone(),
1935            );
1936            last_message
1937                .content
1938                .push(AgentMessageContent::ToolUse(tool_use.clone()));
1939        } else {
1940            event_stream.update_tool_call_fields(
1941                &tool_use.id,
1942                acp::ToolCallUpdateFields::new()
1943                    .title(title.as_str())
1944                    .kind(kind)
1945                    .raw_input(tool_use.input.clone()),
1946            );
1947        }
1948
1949        if !tool_use.is_input_complete {
1950            return None;
1951        }
1952
1953        let Some(tool) = tool else {
1954            let content = format!("No tool named {} exists", tool_use.name);
1955            return Some(Task::ready(LanguageModelToolResult {
1956                content: LanguageModelToolResultContent::Text(Arc::from(content)),
1957                tool_use_id: tool_use.id,
1958                tool_name: tool_use.name,
1959                is_error: true,
1960                output: None,
1961            }));
1962        };
1963
1964        let fs = self.project.read(cx).fs().clone();
1965        let tool_event_stream = ToolCallEventStream::new(
1966            tool_use.id.clone(),
1967            event_stream.clone(),
1968            Some(fs),
1969            cancellation_rx,
1970        );
1971        tool_event_stream.update_fields(
1972            acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
1973        );
1974        let supports_images = self.model().is_some_and(|model| model.supports_images());
1975        let tool_result = tool.run(tool_use.input, tool_event_stream, cx);
1976        log::debug!("Running tool {}", tool_use.name);
1977        Some(cx.foreground_executor().spawn(async move {
1978            let tool_result = tool_result.await.and_then(|output| {
1979                if let LanguageModelToolResultContent::Image(_) = &output.llm_output
1980                    && !supports_images
1981                {
1982                    return Err(anyhow!(
1983                        "Attempted to read an image, but this model doesn't support it.",
1984                    ));
1985                }
1986                Ok(output)
1987            });
1988
1989            match tool_result {
1990                Ok(output) => LanguageModelToolResult {
1991                    tool_use_id: tool_use.id,
1992                    tool_name: tool_use.name,
1993                    is_error: false,
1994                    content: output.llm_output,
1995                    output: Some(output.raw_output),
1996                },
1997                Err(error) => LanguageModelToolResult {
1998                    tool_use_id: tool_use.id,
1999                    tool_name: tool_use.name,
2000                    is_error: true,
2001                    content: LanguageModelToolResultContent::Text(Arc::from(error.to_string())),
2002                    output: Some(error.to_string().into()),
2003                },
2004            }
2005        }))
2006    }
2007
2008    fn handle_tool_use_json_parse_error_event(
2009        &mut self,
2010        tool_use_id: LanguageModelToolUseId,
2011        tool_name: Arc<str>,
2012        raw_input: Arc<str>,
2013        json_parse_error: String,
2014    ) -> LanguageModelToolResult {
2015        let tool_output = format!("Error parsing input JSON: {json_parse_error}");
2016        LanguageModelToolResult {
2017            tool_use_id,
2018            tool_name,
2019            is_error: true,
2020            content: LanguageModelToolResultContent::Text(tool_output.into()),
2021            output: Some(serde_json::Value::String(raw_input.to_string())),
2022        }
2023    }
2024
2025    pub fn title(&self) -> SharedString {
2026        self.title.clone().unwrap_or("New Thread".into())
2027    }
2028
2029    pub fn is_generating_summary(&self) -> bool {
2030        self.pending_summary_generation.is_some()
2031    }
2032
2033    pub fn is_generating_title(&self) -> bool {
2034        self.pending_title_generation.is_some()
2035    }
2036
2037    pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
2038        if let Some(summary) = self.summary.as_ref() {
2039            return Task::ready(Some(summary.clone())).shared();
2040        }
2041        if let Some(task) = self.pending_summary_generation.clone() {
2042            return task;
2043        }
2044        let Some(model) = self.summarization_model.clone() else {
2045            log::error!("No summarization model available");
2046            return Task::ready(None).shared();
2047        };
2048        let mut request = LanguageModelRequest {
2049            intent: Some(CompletionIntent::ThreadContextSummarization),
2050            temperature: AgentSettings::temperature_for_model(&model, cx),
2051            ..Default::default()
2052        };
2053
2054        for message in &self.messages {
2055            request.messages.extend(message.to_request());
2056        }
2057
2058        request.messages.push(LanguageModelRequestMessage {
2059            role: Role::User,
2060            content: vec![SUMMARIZE_THREAD_DETAILED_PROMPT.into()],
2061            cache: false,
2062            reasoning_details: None,
2063        });
2064
2065        let task = cx
2066            .spawn(async move |this, cx| {
2067                let mut summary = String::new();
2068                let mut messages = model.stream_completion(request, cx).await.log_err()?;
2069                while let Some(event) = messages.next().await {
2070                    let event = event.log_err()?;
2071                    let text = match event {
2072                        LanguageModelCompletionEvent::Text(text) => text,
2073                        _ => continue,
2074                    };
2075
2076                    let mut lines = text.lines();
2077                    summary.extend(lines.next());
2078                }
2079
2080                log::debug!("Setting summary: {}", summary);
2081                let summary = SharedString::from(summary);
2082
2083                this.update(cx, |this, cx| {
2084                    this.summary = Some(summary.clone());
2085                    this.pending_summary_generation = None;
2086                    cx.notify()
2087                })
2088                .ok()?;
2089
2090                Some(summary)
2091            })
2092            .shared();
2093        self.pending_summary_generation = Some(task.clone());
2094        task
2095    }
2096
2097    pub fn generate_title(&mut self, cx: &mut Context<Self>) {
2098        let Some(model) = self.summarization_model.clone() else {
2099            return;
2100        };
2101
2102        log::debug!(
2103            "Generating title with model: {:?}",
2104            self.summarization_model.as_ref().map(|model| model.name())
2105        );
2106        let mut request = LanguageModelRequest {
2107            intent: Some(CompletionIntent::ThreadSummarization),
2108            temperature: AgentSettings::temperature_for_model(&model, cx),
2109            ..Default::default()
2110        };
2111
2112        for message in &self.messages {
2113            request.messages.extend(message.to_request());
2114        }
2115
2116        request.messages.push(LanguageModelRequestMessage {
2117            role: Role::User,
2118            content: vec![SUMMARIZE_THREAD_PROMPT.into()],
2119            cache: false,
2120            reasoning_details: None,
2121        });
2122        self.pending_title_generation = Some(cx.spawn(async move |this, cx| {
2123            let mut title = String::new();
2124
2125            let generate = async {
2126                let mut messages = model.stream_completion(request, cx).await?;
2127                while let Some(event) = messages.next().await {
2128                    let event = event?;
2129                    let text = match event {
2130                        LanguageModelCompletionEvent::Text(text) => text,
2131                        _ => continue,
2132                    };
2133
2134                    let mut lines = text.lines();
2135                    title.extend(lines.next());
2136
2137                    // Stop if the LLM generated multiple lines.
2138                    if lines.next().is_some() {
2139                        break;
2140                    }
2141                }
2142                anyhow::Ok(())
2143            };
2144
2145            if generate.await.context("failed to generate title").is_ok() {
2146                _ = this.update(cx, |this, cx| this.set_title(title.into(), cx));
2147            }
2148            _ = this.update(cx, |this, _| this.pending_title_generation = None);
2149        }));
2150    }
2151
2152    pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
2153        self.pending_title_generation = None;
2154        if Some(&title) != self.title.as_ref() {
2155            self.title = Some(title);
2156            cx.emit(TitleUpdated);
2157            cx.notify();
2158        }
2159    }
2160
2161    fn clear_summary(&mut self) {
2162        self.summary = None;
2163        self.pending_summary_generation = None;
2164    }
2165
2166    fn last_user_message(&self) -> Option<&UserMessage> {
2167        self.messages
2168            .iter()
2169            .rev()
2170            .find_map(|message| match message {
2171                Message::User(user_message) => Some(user_message),
2172                Message::Agent(_) => None,
2173                Message::Resume => None,
2174            })
2175    }
2176
2177    fn pending_message(&mut self) -> &mut AgentMessage {
2178        self.pending_message.get_or_insert_default()
2179    }
2180
2181    fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
2182        let Some(mut message) = self.pending_message.take() else {
2183            return;
2184        };
2185
2186        if message.content.is_empty() {
2187            return;
2188        }
2189
2190        for content in &message.content {
2191            let AgentMessageContent::ToolUse(tool_use) = content else {
2192                continue;
2193            };
2194
2195            if !message.tool_results.contains_key(&tool_use.id) {
2196                message.tool_results.insert(
2197                    tool_use.id.clone(),
2198                    LanguageModelToolResult {
2199                        tool_use_id: tool_use.id.clone(),
2200                        tool_name: tool_use.name.clone(),
2201                        is_error: true,
2202                        content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
2203                        output: None,
2204                    },
2205                );
2206            }
2207        }
2208
2209        self.messages.push(Message::Agent(message));
2210        self.updated_at = Utc::now();
2211        self.clear_summary();
2212        cx.notify()
2213    }
2214
2215    pub(crate) fn build_completion_request(
2216        &self,
2217        completion_intent: CompletionIntent,
2218        cx: &App,
2219    ) -> Result<LanguageModelRequest> {
2220        let model = self.model().context("No language model configured")?;
2221        let tools = if let Some(turn) = self.running_turn.as_ref() {
2222            turn.tools
2223                .iter()
2224                .filter_map(|(tool_name, tool)| {
2225                    log::trace!("Including tool: {}", tool_name);
2226                    Some(LanguageModelRequestTool {
2227                        name: tool_name.to_string(),
2228                        description: tool.description().to_string(),
2229                        input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
2230                    })
2231                })
2232                .collect::<Vec<_>>()
2233        } else {
2234            Vec::new()
2235        };
2236
2237        log::debug!("Building completion request");
2238        log::debug!("Completion intent: {:?}", completion_intent);
2239
2240        let available_tools: Vec<_> = self
2241            .running_turn
2242            .as_ref()
2243            .map(|turn| turn.tools.keys().cloned().collect())
2244            .unwrap_or_default();
2245
2246        log::debug!("Request includes {} tools", available_tools.len());
2247        let messages = self.build_request_messages(available_tools, cx);
2248        log::debug!("Request will include {} messages", messages.len());
2249
2250        let request = LanguageModelRequest {
2251            thread_id: Some(self.id.to_string()),
2252            prompt_id: Some(self.prompt_id.to_string()),
2253            intent: Some(completion_intent),
2254            messages,
2255            tools,
2256            tool_choice: None,
2257            stop: Vec::new(),
2258            temperature: AgentSettings::temperature_for_model(model, cx),
2259            thinking_allowed: true,
2260        };
2261
2262        log::debug!("Completion request built successfully");
2263        Ok(request)
2264    }
2265
2266    fn enabled_tools(
2267        &self,
2268        profile: &AgentProfileSettings,
2269        model: &Arc<dyn LanguageModel>,
2270        cx: &App,
2271    ) -> BTreeMap<SharedString, Arc<dyn AnyAgentTool>> {
2272        fn truncate(tool_name: &SharedString) -> SharedString {
2273            if tool_name.len() > MAX_TOOL_NAME_LENGTH {
2274                let mut truncated = tool_name.to_string();
2275                truncated.truncate(MAX_TOOL_NAME_LENGTH);
2276                truncated.into()
2277            } else {
2278                tool_name.clone()
2279            }
2280        }
2281
2282        let mut tools = self
2283            .tools
2284            .iter()
2285            .filter_map(|(tool_name, tool)| {
2286                if tool.supports_provider(&model.provider_id())
2287                    && profile.is_tool_enabled(tool_name)
2288                {
2289                    Some((truncate(tool_name), tool.clone()))
2290                } else {
2291                    None
2292                }
2293            })
2294            .collect::<BTreeMap<_, _>>();
2295
2296        let mut context_server_tools = Vec::new();
2297        let mut seen_tools = tools.keys().cloned().collect::<HashSet<_>>();
2298        let mut duplicate_tool_names = HashSet::default();
2299        for (server_id, server_tools) in self.context_server_registry.read(cx).servers() {
2300            for (tool_name, tool) in server_tools {
2301                if profile.is_context_server_tool_enabled(&server_id.0, &tool_name) {
2302                    let tool_name = truncate(tool_name);
2303                    if !seen_tools.insert(tool_name.clone()) {
2304                        duplicate_tool_names.insert(tool_name.clone());
2305                    }
2306                    context_server_tools.push((server_id.clone(), tool_name, tool.clone()));
2307                }
2308            }
2309        }
2310
2311        // When there are duplicate tool names, disambiguate by prefixing them
2312        // with the server ID. In the rare case there isn't enough space for the
2313        // disambiguated tool name, keep only the last tool with this name.
2314        for (server_id, tool_name, tool) in context_server_tools {
2315            if duplicate_tool_names.contains(&tool_name) {
2316                let available = MAX_TOOL_NAME_LENGTH.saturating_sub(tool_name.len());
2317                if available >= 2 {
2318                    let mut disambiguated = server_id.0.to_string();
2319                    disambiguated.truncate(available - 1);
2320                    disambiguated.push('_');
2321                    disambiguated.push_str(&tool_name);
2322                    tools.insert(disambiguated.into(), tool.clone());
2323                } else {
2324                    tools.insert(tool_name, tool.clone());
2325                }
2326            } else {
2327                tools.insert(tool_name, tool.clone());
2328            }
2329        }
2330
2331        tools
2332    }
2333
2334    fn tool(&self, name: &str) -> Option<Arc<dyn AnyAgentTool>> {
2335        self.running_turn.as_ref()?.tools.get(name).cloned()
2336    }
2337
2338    pub fn has_tool(&self, name: &str) -> bool {
2339        self.running_turn
2340            .as_ref()
2341            .is_some_and(|turn| turn.tools.contains_key(name))
2342    }
2343
2344    #[cfg(any(test, feature = "test-support"))]
2345    pub fn has_registered_tool(&self, name: &str) -> bool {
2346        self.tools.contains_key(name)
2347    }
2348
2349    pub fn registered_tool_names(&self) -> Vec<SharedString> {
2350        self.tools.keys().cloned().collect()
2351    }
2352
2353    pub fn register_running_subagent(&mut self, subagent: WeakEntity<Thread>) {
2354        self.running_subagents.push(subagent);
2355    }
2356
2357    pub fn unregister_running_subagent(&mut self, subagent: &WeakEntity<Thread>) {
2358        self.running_subagents
2359            .retain(|s| s.entity_id() != subagent.entity_id());
2360    }
2361
2362    pub fn running_subagent_count(&self) -> usize {
2363        self.running_subagents
2364            .iter()
2365            .filter(|s| s.upgrade().is_some())
2366            .count()
2367    }
2368
2369    pub fn is_subagent(&self) -> bool {
2370        self.subagent_context.is_some()
2371    }
2372
2373    pub fn depth(&self) -> u8 {
2374        self.subagent_context.as_ref().map(|c| c.depth).unwrap_or(0)
2375    }
2376
2377    pub fn is_turn_complete(&self) -> bool {
2378        self.running_turn.is_none()
2379    }
2380
2381    pub fn submit_user_message(
2382        &mut self,
2383        content: impl Into<String>,
2384        cx: &mut Context<Self>,
2385    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
2386        let content = content.into();
2387        self.messages.push(Message::User(UserMessage {
2388            id: UserMessageId::new(),
2389            content: vec![UserMessageContent::Text(content)],
2390        }));
2391        cx.notify();
2392        self.send_existing(cx)
2393    }
2394
2395    pub fn interrupt_for_summary(
2396        &mut self,
2397        cx: &mut Context<Self>,
2398    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
2399        let context = self
2400            .subagent_context
2401            .as_ref()
2402            .context("Not a subagent thread")?;
2403        let prompt = context.context_low_prompt.clone();
2404        self.cancel(cx).detach();
2405        self.submit_user_message(prompt, cx)
2406    }
2407
2408    pub fn request_final_summary(
2409        &mut self,
2410        cx: &mut Context<Self>,
2411    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
2412        let context = self
2413            .subagent_context
2414            .as_ref()
2415            .context("Not a subagent thread")?;
2416        let prompt = context.summary_prompt.clone();
2417        self.submit_user_message(prompt, cx)
2418    }
2419
2420    fn build_request_messages(
2421        &self,
2422        available_tools: Vec<SharedString>,
2423        cx: &App,
2424    ) -> Vec<LanguageModelRequestMessage> {
2425        log::trace!(
2426            "Building request messages from {} thread messages",
2427            self.messages.len()
2428        );
2429
2430        let system_prompt = SystemPromptTemplate {
2431            project: self.project_context.read(cx),
2432            available_tools,
2433            model_name: self.model.as_ref().map(|m| m.name().0.to_string()),
2434        }
2435        .render(&self.templates)
2436        .context("failed to build system prompt")
2437        .expect("Invalid template");
2438        let mut messages = vec![LanguageModelRequestMessage {
2439            role: Role::System,
2440            content: vec![system_prompt.into()],
2441            cache: false,
2442            reasoning_details: None,
2443        }];
2444        for message in &self.messages {
2445            messages.extend(message.to_request());
2446        }
2447
2448        if let Some(last_message) = messages.last_mut() {
2449            last_message.cache = true;
2450        }
2451
2452        if let Some(message) = self.pending_message.as_ref() {
2453            messages.extend(message.to_request());
2454        }
2455
2456        messages
2457    }
2458
2459    pub fn to_markdown(&self) -> String {
2460        let mut markdown = String::new();
2461        for (ix, message) in self.messages.iter().enumerate() {
2462            if ix > 0 {
2463                markdown.push('\n');
2464            }
2465            markdown.push_str(&message.to_markdown());
2466        }
2467
2468        if let Some(message) = self.pending_message.as_ref() {
2469            markdown.push('\n');
2470            markdown.push_str(&message.to_markdown());
2471        }
2472
2473        markdown
2474    }
2475
2476    fn advance_prompt_id(&mut self) {
2477        self.prompt_id = PromptId::new();
2478    }
2479
2480    fn retry_strategy_for(error: &LanguageModelCompletionError) -> Option<RetryStrategy> {
2481        use LanguageModelCompletionError::*;
2482        use http_client::StatusCode;
2483
2484        // General strategy here:
2485        // - If retrying won't help (e.g. invalid API key or payload too large), return None so we don't retry at all.
2486        // - If it's a time-based issue (e.g. server overloaded, rate limit exceeded), retry up to 4 times with exponential backoff.
2487        // - If it's an issue that *might* be fixed by retrying (e.g. internal server error), retry up to 3 times.
2488        match error {
2489            HttpResponseError {
2490                status_code: StatusCode::TOO_MANY_REQUESTS,
2491                ..
2492            } => Some(RetryStrategy::ExponentialBackoff {
2493                initial_delay: BASE_RETRY_DELAY,
2494                max_attempts: MAX_RETRY_ATTEMPTS,
2495            }),
2496            ServerOverloaded { retry_after, .. } | RateLimitExceeded { retry_after, .. } => {
2497                Some(RetryStrategy::Fixed {
2498                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2499                    max_attempts: MAX_RETRY_ATTEMPTS,
2500                })
2501            }
2502            UpstreamProviderError {
2503                status,
2504                retry_after,
2505                ..
2506            } => match *status {
2507                StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
2508                    Some(RetryStrategy::Fixed {
2509                        delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2510                        max_attempts: MAX_RETRY_ATTEMPTS,
2511                    })
2512                }
2513                StatusCode::INTERNAL_SERVER_ERROR => Some(RetryStrategy::Fixed {
2514                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2515                    // Internal Server Error could be anything, retry up to 3 times.
2516                    max_attempts: 3,
2517                }),
2518                status => {
2519                    // There is no StatusCode variant for the unofficial HTTP 529 ("The service is overloaded"),
2520                    // but we frequently get them in practice. See https://http.dev/529
2521                    if status.as_u16() == 529 {
2522                        Some(RetryStrategy::Fixed {
2523                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2524                            max_attempts: MAX_RETRY_ATTEMPTS,
2525                        })
2526                    } else {
2527                        Some(RetryStrategy::Fixed {
2528                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2529                            max_attempts: 2,
2530                        })
2531                    }
2532                }
2533            },
2534            ApiInternalServerError { .. } => Some(RetryStrategy::Fixed {
2535                delay: BASE_RETRY_DELAY,
2536                max_attempts: 3,
2537            }),
2538            ApiReadResponseError { .. }
2539            | HttpSend { .. }
2540            | DeserializeResponse { .. }
2541            | BadRequestFormat { .. } => Some(RetryStrategy::Fixed {
2542                delay: BASE_RETRY_DELAY,
2543                max_attempts: 3,
2544            }),
2545            // Retrying these errors definitely shouldn't help.
2546            HttpResponseError {
2547                status_code:
2548                    StatusCode::PAYLOAD_TOO_LARGE | StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED,
2549                ..
2550            }
2551            | AuthenticationError { .. }
2552            | PermissionError { .. }
2553            | NoApiKey { .. }
2554            | ApiEndpointNotFound { .. }
2555            | PromptTooLarge { .. } => None,
2556            // These errors might be transient, so retry them
2557            SerializeRequest { .. } | BuildRequestBody { .. } => Some(RetryStrategy::Fixed {
2558                delay: BASE_RETRY_DELAY,
2559                max_attempts: 1,
2560            }),
2561            // Retry all other 4xx and 5xx errors once.
2562            HttpResponseError { status_code, .. }
2563                if status_code.is_client_error() || status_code.is_server_error() =>
2564            {
2565                Some(RetryStrategy::Fixed {
2566                    delay: BASE_RETRY_DELAY,
2567                    max_attempts: 3,
2568                })
2569            }
2570            Other(err) if err.is::<language_model::PaymentRequiredError>() => {
2571                // Retrying won't help for Payment Required errors.
2572                None
2573            }
2574            // Conservatively assume that any other errors are non-retryable
2575            HttpResponseError { .. } | Other(..) => Some(RetryStrategy::Fixed {
2576                delay: BASE_RETRY_DELAY,
2577                max_attempts: 2,
2578            }),
2579        }
2580    }
2581}
2582
2583struct RunningTurn {
2584    /// Holds the task that handles agent interaction until the end of the turn.
2585    /// Survives across multiple requests as the model performs tool calls and
2586    /// we run tools, report their results.
2587    _task: Task<()>,
2588    /// The current event stream for the running turn. Used to report a final
2589    /// cancellation event if we cancel the turn.
2590    event_stream: ThreadEventStream,
2591    /// The tools that were enabled for this turn.
2592    tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
2593    /// Sender to signal tool cancellation. When cancel is called, this is
2594    /// set to true so all tools can detect user-initiated cancellation.
2595    cancellation_tx: watch::Sender<bool>,
2596}
2597
2598impl RunningTurn {
2599    fn cancel(mut self) -> Task<()> {
2600        log::debug!("Cancelling in progress turn");
2601        self.cancellation_tx.send(true).ok();
2602        self.event_stream.send_canceled();
2603        self._task
2604    }
2605}
2606
2607pub struct TokenUsageUpdated(pub Option<acp_thread::TokenUsage>);
2608
2609impl EventEmitter<TokenUsageUpdated> for Thread {}
2610
2611pub struct TitleUpdated;
2612
2613impl EventEmitter<TitleUpdated> for Thread {}
2614
2615pub trait AgentTool
2616where
2617    Self: 'static + Sized,
2618{
2619    type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
2620    type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
2621
2622    fn name() -> &'static str;
2623
2624    fn description() -> SharedString {
2625        let schema = schemars::schema_for!(Self::Input);
2626        SharedString::new(
2627            schema
2628                .get("description")
2629                .and_then(|description| description.as_str())
2630                .unwrap_or_default(),
2631        )
2632    }
2633
2634    fn kind() -> acp::ToolKind;
2635
2636    /// The initial tool title to display. Can be updated during the tool run.
2637    fn initial_title(
2638        &self,
2639        input: Result<Self::Input, serde_json::Value>,
2640        cx: &mut App,
2641    ) -> SharedString;
2642
2643    /// Returns the JSON schema that describes the tool's input.
2644    fn input_schema(format: LanguageModelToolSchemaFormat) -> Schema {
2645        language_model::tool_schema::root_schema_for::<Self::Input>(format)
2646    }
2647
2648    /// Some tools rely on a provider for the underlying billing or other reasons.
2649    /// Allow the tool to check if they are compatible, or should be filtered out.
2650    fn supports_provider(_provider: &LanguageModelProviderId) -> bool {
2651        true
2652    }
2653
2654    /// Runs the tool with the provided input.
2655    fn run(
2656        self: Arc<Self>,
2657        input: Self::Input,
2658        event_stream: ToolCallEventStream,
2659        cx: &mut App,
2660    ) -> Task<Result<Self::Output>>;
2661
2662    /// Emits events for a previous execution of the tool.
2663    fn replay(
2664        &self,
2665        _input: Self::Input,
2666        _output: Self::Output,
2667        _event_stream: ToolCallEventStream,
2668        _cx: &mut App,
2669    ) -> Result<()> {
2670        Ok(())
2671    }
2672
2673    fn erase(self) -> Arc<dyn AnyAgentTool> {
2674        Arc::new(Erased(Arc::new(self)))
2675    }
2676}
2677
2678pub struct Erased<T>(T);
2679
2680pub struct AgentToolOutput {
2681    pub llm_output: LanguageModelToolResultContent,
2682    pub raw_output: serde_json::Value,
2683}
2684
2685pub trait AnyAgentTool {
2686    fn name(&self) -> SharedString;
2687    fn description(&self) -> SharedString;
2688    fn kind(&self) -> acp::ToolKind;
2689    fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString;
2690    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
2691    fn supports_provider(&self, _provider: &LanguageModelProviderId) -> bool {
2692        true
2693    }
2694    fn run(
2695        self: Arc<Self>,
2696        input: serde_json::Value,
2697        event_stream: ToolCallEventStream,
2698        cx: &mut App,
2699    ) -> Task<Result<AgentToolOutput>>;
2700    fn replay(
2701        &self,
2702        input: serde_json::Value,
2703        output: serde_json::Value,
2704        event_stream: ToolCallEventStream,
2705        cx: &mut App,
2706    ) -> Result<()>;
2707}
2708
2709impl<T> AnyAgentTool for Erased<Arc<T>>
2710where
2711    T: AgentTool,
2712{
2713    fn name(&self) -> SharedString {
2714        T::name().into()
2715    }
2716
2717    fn description(&self) -> SharedString {
2718        T::description()
2719    }
2720
2721    fn kind(&self) -> agent_client_protocol::ToolKind {
2722        T::kind()
2723    }
2724
2725    fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString {
2726        let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
2727        self.0.initial_title(parsed_input, _cx)
2728    }
2729
2730    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
2731        let mut json = serde_json::to_value(T::input_schema(format))?;
2732        language_model::tool_schema::adapt_schema_to_format(&mut json, format)?;
2733        Ok(json)
2734    }
2735
2736    fn supports_provider(&self, provider: &LanguageModelProviderId) -> bool {
2737        T::supports_provider(provider)
2738    }
2739
2740    fn run(
2741        self: Arc<Self>,
2742        input: serde_json::Value,
2743        event_stream: ToolCallEventStream,
2744        cx: &mut App,
2745    ) -> Task<Result<AgentToolOutput>> {
2746        cx.spawn(async move |cx| {
2747            let input = serde_json::from_value(input)?;
2748            let output = cx
2749                .update(|cx| self.0.clone().run(input, event_stream, cx))
2750                .await?;
2751            let raw_output = serde_json::to_value(&output)?;
2752            Ok(AgentToolOutput {
2753                llm_output: output.into(),
2754                raw_output,
2755            })
2756        })
2757    }
2758
2759    fn replay(
2760        &self,
2761        input: serde_json::Value,
2762        output: serde_json::Value,
2763        event_stream: ToolCallEventStream,
2764        cx: &mut App,
2765    ) -> Result<()> {
2766        let input = serde_json::from_value(input)?;
2767        let output = serde_json::from_value(output)?;
2768        self.0.replay(input, output, event_stream, cx)
2769    }
2770}
2771
2772#[derive(Clone)]
2773struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
2774
2775impl ThreadEventStream {
2776    fn send_user_message(&self, message: &UserMessage) {
2777        self.0
2778            .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
2779            .ok();
2780    }
2781
2782    fn send_text(&self, text: &str) {
2783        self.0
2784            .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
2785            .ok();
2786    }
2787
2788    fn send_thinking(&self, text: &str) {
2789        self.0
2790            .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
2791            .ok();
2792    }
2793
2794    fn send_tool_call(
2795        &self,
2796        id: &LanguageModelToolUseId,
2797        tool_name: &str,
2798        title: SharedString,
2799        kind: acp::ToolKind,
2800        input: serde_json::Value,
2801    ) {
2802        self.0
2803            .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
2804                id,
2805                tool_name,
2806                title.to_string(),
2807                kind,
2808                input,
2809            ))))
2810            .ok();
2811    }
2812
2813    fn initial_tool_call(
2814        id: &LanguageModelToolUseId,
2815        tool_name: &str,
2816        title: String,
2817        kind: acp::ToolKind,
2818        input: serde_json::Value,
2819    ) -> acp::ToolCall {
2820        acp::ToolCall::new(id.to_string(), title)
2821            .kind(kind)
2822            .raw_input(input)
2823            .meta(acp_thread::meta_with_tool_name(tool_name))
2824    }
2825
2826    fn update_tool_call_fields(
2827        &self,
2828        tool_use_id: &LanguageModelToolUseId,
2829        fields: acp::ToolCallUpdateFields,
2830    ) {
2831        self.0
2832            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
2833                acp::ToolCallUpdate::new(tool_use_id.to_string(), fields).into(),
2834            )))
2835            .ok();
2836    }
2837
2838    fn send_retry(&self, status: acp_thread::RetryStatus) {
2839        self.0.unbounded_send(Ok(ThreadEvent::Retry(status))).ok();
2840    }
2841
2842    fn send_stop(&self, reason: acp::StopReason) {
2843        self.0.unbounded_send(Ok(ThreadEvent::Stop(reason))).ok();
2844    }
2845
2846    fn send_canceled(&self) {
2847        self.0
2848            .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))
2849            .ok();
2850    }
2851
2852    fn send_error(&self, error: impl Into<anyhow::Error>) {
2853        self.0.unbounded_send(Err(error.into())).ok();
2854    }
2855}
2856
2857#[derive(Clone)]
2858pub struct ToolCallEventStream {
2859    tool_use_id: LanguageModelToolUseId,
2860    stream: ThreadEventStream,
2861    fs: Option<Arc<dyn Fs>>,
2862    cancellation_rx: watch::Receiver<bool>,
2863}
2864
2865impl ToolCallEventStream {
2866    #[cfg(any(test, feature = "test-support"))]
2867    pub fn test() -> (Self, ToolCallEventStreamReceiver) {
2868        let (stream, receiver, _cancellation_tx) = Self::test_with_cancellation();
2869        (stream, receiver)
2870    }
2871
2872    #[cfg(any(test, feature = "test-support"))]
2873    pub fn test_with_cancellation() -> (Self, ToolCallEventStreamReceiver, watch::Sender<bool>) {
2874        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
2875        let (cancellation_tx, cancellation_rx) = watch::channel(false);
2876
2877        let stream = ToolCallEventStream::new(
2878            "test_id".into(),
2879            ThreadEventStream(events_tx),
2880            None,
2881            cancellation_rx,
2882        );
2883
2884        (
2885            stream,
2886            ToolCallEventStreamReceiver(events_rx),
2887            cancellation_tx,
2888        )
2889    }
2890
2891    /// Signal cancellation for this event stream. Only available in tests.
2892    #[cfg(any(test, feature = "test-support"))]
2893    pub fn signal_cancellation_with_sender(cancellation_tx: &mut watch::Sender<bool>) {
2894        cancellation_tx.send(true).ok();
2895    }
2896
2897    fn new(
2898        tool_use_id: LanguageModelToolUseId,
2899        stream: ThreadEventStream,
2900        fs: Option<Arc<dyn Fs>>,
2901        cancellation_rx: watch::Receiver<bool>,
2902    ) -> Self {
2903        Self {
2904            tool_use_id,
2905            stream,
2906            fs,
2907            cancellation_rx,
2908        }
2909    }
2910
2911    /// Returns a future that resolves when the user cancels the tool call.
2912    /// Tools should select on this alongside their main work to detect user cancellation.
2913    pub fn cancelled_by_user(&self) -> impl std::future::Future<Output = ()> + '_ {
2914        let mut rx = self.cancellation_rx.clone();
2915        async move {
2916            loop {
2917                if *rx.borrow() {
2918                    return;
2919                }
2920                if rx.changed().await.is_err() {
2921                    // Sender dropped, will never be cancelled
2922                    std::future::pending::<()>().await;
2923                }
2924            }
2925        }
2926    }
2927
2928    /// Returns true if the user has cancelled this tool call.
2929    /// This is useful for checking cancellation state after an operation completes,
2930    /// to determine if the completion was due to user cancellation.
2931    pub fn was_cancelled_by_user(&self) -> bool {
2932        *self.cancellation_rx.clone().borrow()
2933    }
2934
2935    pub fn tool_use_id(&self) -> &LanguageModelToolUseId {
2936        &self.tool_use_id
2937    }
2938
2939    pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
2940        self.stream
2941            .update_tool_call_fields(&self.tool_use_id, fields);
2942    }
2943
2944    pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
2945        self.stream
2946            .0
2947            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
2948                acp_thread::ToolCallUpdateDiff {
2949                    id: acp::ToolCallId::new(self.tool_use_id.to_string()),
2950                    diff,
2951                }
2952                .into(),
2953            )))
2954            .ok();
2955    }
2956
2957    pub fn update_subagent_thread(&self, thread: Entity<acp_thread::AcpThread>) {
2958        self.stream
2959            .0
2960            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
2961                acp_thread::ToolCallUpdateSubagentThread {
2962                    id: acp::ToolCallId::new(self.tool_use_id.to_string()),
2963                    thread,
2964                }
2965                .into(),
2966            )))
2967            .ok();
2968    }
2969
2970    /// Authorize a third-party tool (e.g., MCP tool from a context server).
2971    ///
2972    /// Unlike built-in tools, third-party tools don't support pattern-based permissions.
2973    /// They only support `default_mode` (allow/deny/confirm) per tool.
2974    ///
2975    /// Uses the dropdown authorization flow with two granularities:
2976    /// - "Always for <display_name> MCP tool" → sets `tools.<tool_id>.default_mode = "allow"` or "deny"
2977    /// - "Only this time" → allow/deny once
2978    pub fn authorize_third_party_tool(
2979        &self,
2980        title: impl Into<String>,
2981        tool_id: String,
2982        display_name: String,
2983        cx: &mut App,
2984    ) -> Task<Result<()>> {
2985        let settings = agent_settings::AgentSettings::get_global(cx);
2986
2987        let decision = decide_permission_from_settings(&tool_id, "", &settings);
2988
2989        match decision {
2990            ToolPermissionDecision::Allow => return Task::ready(Ok(())),
2991            ToolPermissionDecision::Deny(reason) => return Task::ready(Err(anyhow!(reason))),
2992            ToolPermissionDecision::Confirm => {}
2993        }
2994
2995        let (response_tx, response_rx) = oneshot::channel();
2996        self.stream
2997            .0
2998            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
2999                ToolCallAuthorization {
3000                    tool_call: acp::ToolCallUpdate::new(
3001                        self.tool_use_id.to_string(),
3002                        acp::ToolCallUpdateFields::new().title(title.into()),
3003                    ),
3004                    options: acp_thread::PermissionOptions::Dropdown(vec![
3005                        acp_thread::PermissionOptionChoice {
3006                            allow: acp::PermissionOption::new(
3007                                acp::PermissionOptionId::new(format!(
3008                                    "always_allow_mcp:{}",
3009                                    tool_id
3010                                )),
3011                                format!("Always for {} MCP tool", display_name),
3012                                acp::PermissionOptionKind::AllowAlways,
3013                            ),
3014                            deny: acp::PermissionOption::new(
3015                                acp::PermissionOptionId::new(format!(
3016                                    "always_deny_mcp:{}",
3017                                    tool_id
3018                                )),
3019                                format!("Always for {} MCP tool", display_name),
3020                                acp::PermissionOptionKind::RejectAlways,
3021                            ),
3022                        },
3023                        acp_thread::PermissionOptionChoice {
3024                            allow: acp::PermissionOption::new(
3025                                acp::PermissionOptionId::new("allow"),
3026                                "Only this time",
3027                                acp::PermissionOptionKind::AllowOnce,
3028                            ),
3029                            deny: acp::PermissionOption::new(
3030                                acp::PermissionOptionId::new("deny"),
3031                                "Only this time",
3032                                acp::PermissionOptionKind::RejectOnce,
3033                            ),
3034                        },
3035                    ]),
3036                    response: response_tx,
3037                    context: None,
3038                },
3039            )))
3040            .ok();
3041
3042        let fs = self.fs.clone();
3043        cx.spawn(async move |cx| {
3044            let response_str = response_rx.await?.0.to_string();
3045
3046            if response_str == format!("always_allow_mcp:{}", tool_id) {
3047                if let Some(fs) = fs.clone() {
3048                    cx.update(|cx| {
3049                        update_settings_file(fs, cx, move |settings, _| {
3050                            settings
3051                                .agent
3052                                .get_or_insert_default()
3053                                .set_tool_default_mode(&tool_id, ToolPermissionMode::Allow);
3054                        });
3055                    });
3056                }
3057                return Ok(());
3058            }
3059            if response_str == format!("always_deny_mcp:{}", tool_id) {
3060                if let Some(fs) = fs.clone() {
3061                    cx.update(|cx| {
3062                        update_settings_file(fs, cx, move |settings, _| {
3063                            settings
3064                                .agent
3065                                .get_or_insert_default()
3066                                .set_tool_default_mode(&tool_id, ToolPermissionMode::Deny);
3067                        });
3068                    });
3069                }
3070                return Err(anyhow!("Permission to run tool denied by user"));
3071            }
3072
3073            if response_str == "allow" {
3074                return Ok(());
3075            }
3076
3077            Err(anyhow!("Permission to run tool denied by user"))
3078        })
3079    }
3080
3081    pub fn authorize(
3082        &self,
3083        title: impl Into<String>,
3084        context: ToolPermissionContext,
3085        cx: &mut App,
3086    ) -> Task<Result<()>> {
3087        use settings::ToolPermissionMode;
3088
3089        let options = context.build_permission_options();
3090
3091        let (response_tx, response_rx) = oneshot::channel();
3092        self.stream
3093            .0
3094            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3095                ToolCallAuthorization {
3096                    tool_call: acp::ToolCallUpdate::new(
3097                        self.tool_use_id.to_string(),
3098                        acp::ToolCallUpdateFields::new().title(title.into()),
3099                    ),
3100                    options,
3101                    response: response_tx,
3102                    context: Some(context),
3103                },
3104            )))
3105            .ok();
3106
3107        let fs = self.fs.clone();
3108        cx.spawn(async move |cx| {
3109            let response_str = response_rx.await?.0.to_string();
3110
3111            // Handle "always allow tool" - e.g., "always_allow:terminal"
3112            if let Some(tool) = response_str.strip_prefix("always_allow:") {
3113                if let Some(fs) = fs.clone() {
3114                    let tool = tool.to_string();
3115                    cx.update(|cx| {
3116                        update_settings_file(fs, cx, move |settings, _| {
3117                            settings
3118                                .agent
3119                                .get_or_insert_default()
3120                                .set_tool_default_mode(&tool, ToolPermissionMode::Allow);
3121                        });
3122                    });
3123                }
3124                return Ok(());
3125            }
3126
3127            // Handle "always deny tool" - e.g., "always_deny:terminal"
3128            if let Some(tool) = response_str.strip_prefix("always_deny:") {
3129                if let Some(fs) = fs.clone() {
3130                    let tool = tool.to_string();
3131                    cx.update(|cx| {
3132                        update_settings_file(fs, cx, move |settings, _| {
3133                            settings
3134                                .agent
3135                                .get_or_insert_default()
3136                                .set_tool_default_mode(&tool, ToolPermissionMode::Deny);
3137                        });
3138                    });
3139                }
3140                return Err(anyhow!("Permission to run tool denied by user"));
3141            }
3142
3143            // Handle "always allow pattern" - e.g., "always_allow_pattern:terminal:^cargo\s"
3144            if response_str.starts_with("always_allow_pattern:") {
3145                let parts: Vec<&str> = response_str.splitn(3, ':').collect();
3146                if parts.len() == 3 {
3147                    let pattern_tool_name = parts[1].to_string();
3148                    let pattern = parts[2].to_string();
3149                    if let Some(fs) = fs.clone() {
3150                        cx.update(|cx| {
3151                            update_settings_file(fs, cx, move |settings, _| {
3152                                settings
3153                                    .agent
3154                                    .get_or_insert_default()
3155                                    .add_tool_allow_pattern(&pattern_tool_name, pattern);
3156                            });
3157                        });
3158                    }
3159                }
3160                return Ok(());
3161            }
3162
3163            // Handle "always deny pattern" - e.g., "always_deny_pattern:terminal:^cargo\s"
3164            if response_str.starts_with("always_deny_pattern:") {
3165                let parts: Vec<&str> = response_str.splitn(3, ':').collect();
3166                if parts.len() == 3 {
3167                    let pattern_tool_name = parts[1].to_string();
3168                    let pattern = parts[2].to_string();
3169                    if let Some(fs) = fs.clone() {
3170                        cx.update(|cx| {
3171                            update_settings_file(fs, cx, move |settings, _| {
3172                                settings
3173                                    .agent
3174                                    .get_or_insert_default()
3175                                    .add_tool_deny_pattern(&pattern_tool_name, pattern);
3176                            });
3177                        });
3178                    }
3179                }
3180                return Err(anyhow!("Permission to run tool denied by user"));
3181            }
3182
3183            // Handle simple "allow" (allow once)
3184            if response_str == "allow" {
3185                return Ok(());
3186            }
3187
3188            // Handle simple "deny" (deny once)
3189            Err(anyhow!("Permission to run tool denied by user"))
3190        })
3191    }
3192}
3193
3194#[cfg(any(test, feature = "test-support"))]
3195pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
3196
3197#[cfg(any(test, feature = "test-support"))]
3198impl ToolCallEventStreamReceiver {
3199    pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
3200        let event = self.0.next().await;
3201        if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
3202            auth
3203        } else {
3204            panic!("Expected ToolCallAuthorization but got: {:?}", event);
3205        }
3206    }
3207
3208    pub async fn expect_update_fields(&mut self) -> acp::ToolCallUpdateFields {
3209        let event = self.0.next().await;
3210        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
3211            update,
3212        )))) = event
3213        {
3214            update.fields
3215        } else {
3216            panic!("Expected update fields but got: {:?}", event);
3217        }
3218    }
3219
3220    pub async fn expect_diff(&mut self) -> Entity<acp_thread::Diff> {
3221        let event = self.0.next().await;
3222        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateDiff(
3223            update,
3224        )))) = event
3225        {
3226            update.diff
3227        } else {
3228            panic!("Expected diff but got: {:?}", event);
3229        }
3230    }
3231
3232    pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
3233        let event = self.0.next().await;
3234        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
3235            update,
3236        )))) = event
3237        {
3238            update.terminal
3239        } else {
3240            panic!("Expected terminal but got: {:?}", event);
3241        }
3242    }
3243}
3244
3245#[cfg(any(test, feature = "test-support"))]
3246impl std::ops::Deref for ToolCallEventStreamReceiver {
3247    type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
3248
3249    fn deref(&self) -> &Self::Target {
3250        &self.0
3251    }
3252}
3253
3254#[cfg(any(test, feature = "test-support"))]
3255impl std::ops::DerefMut for ToolCallEventStreamReceiver {
3256    fn deref_mut(&mut self) -> &mut Self::Target {
3257        &mut self.0
3258    }
3259}
3260
3261impl From<&str> for UserMessageContent {
3262    fn from(text: &str) -> Self {
3263        Self::Text(text.into())
3264    }
3265}
3266
3267impl UserMessageContent {
3268    pub fn from_content_block(value: acp::ContentBlock, path_style: PathStyle) -> Self {
3269        match value {
3270            acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
3271            acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
3272            acp::ContentBlock::Audio(_) => {
3273                // TODO
3274                Self::Text("[audio]".to_string())
3275            }
3276            acp::ContentBlock::ResourceLink(resource_link) => {
3277                match MentionUri::parse(&resource_link.uri, path_style) {
3278                    Ok(uri) => Self::Mention {
3279                        uri,
3280                        content: String::new(),
3281                    },
3282                    Err(err) => {
3283                        log::error!("Failed to parse mention link: {}", err);
3284                        Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
3285                    }
3286                }
3287            }
3288            acp::ContentBlock::Resource(resource) => match resource.resource {
3289                acp::EmbeddedResourceResource::TextResourceContents(resource) => {
3290                    match MentionUri::parse(&resource.uri, path_style) {
3291                        Ok(uri) => Self::Mention {
3292                            uri,
3293                            content: resource.text,
3294                        },
3295                        Err(err) => {
3296                            log::error!("Failed to parse mention link: {}", err);
3297                            Self::Text(
3298                                MarkdownCodeBlock {
3299                                    tag: &resource.uri,
3300                                    text: &resource.text,
3301                                }
3302                                .to_string(),
3303                            )
3304                        }
3305                    }
3306                }
3307                acp::EmbeddedResourceResource::BlobResourceContents(_) => {
3308                    // TODO
3309                    Self::Text("[blob]".to_string())
3310                }
3311                other => {
3312                    log::warn!("Unexpected content type: {:?}", other);
3313                    Self::Text("[unknown]".to_string())
3314                }
3315            },
3316            other => {
3317                log::warn!("Unexpected content type: {:?}", other);
3318                Self::Text("[unknown]".to_string())
3319            }
3320        }
3321    }
3322}
3323
3324impl From<UserMessageContent> for acp::ContentBlock {
3325    fn from(content: UserMessageContent) -> Self {
3326        match content {
3327            UserMessageContent::Text(text) => text.into(),
3328            UserMessageContent::Image(image) => {
3329                acp::ContentBlock::Image(acp::ImageContent::new(image.source, "image/png"))
3330            }
3331            UserMessageContent::Mention { uri, content } => acp::ContentBlock::Resource(
3332                acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(
3333                    acp::TextResourceContents::new(content, uri.to_uri().to_string()),
3334                )),
3335            ),
3336        }
3337    }
3338}
3339
3340fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
3341    LanguageModelImage {
3342        source: image_content.data.into(),
3343        size: None,
3344    }
3345}