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