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