thread.rs

   1use crate::{
   2    ContextServerRegistry, CopyPathTool, CreateDirectoryTool, DbLanguageModel, DbThread,
   3    DeletePathTool, DiagnosticsTool, EditFileTool, FetchTool, FindPathTool, GrepTool,
   4    ListDirectoryTool, MovePathTool, NowTool, OpenTool, ProjectSnapshot, ReadFileTool,
   5    RestoreFileFromDiskTool, SaveFileTool, SpawnAgentTool, StreamingEditFileTool,
   6    SystemPromptTemplate, Template, Templates, TerminalTool, ToolPermissionDecision,
   7    UpdatePlanTool, WebSearchTool, decide_permission_from_settings,
   8};
   9use acp_thread::{MentionUri, UserMessageId};
  10use action_log::ActionLog;
  11use feature_flags::{
  12    FeatureFlagAppExt as _, StreamingEditFileToolFeatureFlag, UpdatePlanToolFeatureFlag,
  13};
  14
  15use agent_client_protocol as acp;
  16use agent_settings::{
  17    AgentProfileId, AgentSettings, SUMMARIZE_THREAD_DETAILED_PROMPT, SUMMARIZE_THREAD_PROMPT,
  18};
  19use anyhow::{Context as _, Result, anyhow};
  20use chrono::{DateTime, Utc};
  21use client::UserStore;
  22use cloud_api_types::Plan;
  23use collections::{HashMap, HashSet, IndexMap};
  24use fs::Fs;
  25use futures::{
  26    FutureExt,
  27    channel::{mpsc, oneshot},
  28    future::Shared,
  29    stream::FuturesUnordered,
  30};
  31use futures::{StreamExt, stream};
  32use gpui::{
  33    App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task, WeakEntity,
  34};
  35use heck::ToSnakeCase as _;
  36use language_model::{
  37    CompletionIntent, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
  38    LanguageModelId, LanguageModelImage, LanguageModelProviderId, LanguageModelRegistry,
  39    LanguageModelRequest, LanguageModelRequestMessage, LanguageModelRequestTool,
  40    LanguageModelToolResult, LanguageModelToolResultContent, LanguageModelToolSchemaFormat,
  41    LanguageModelToolUse, LanguageModelToolUseId, Role, SelectedModel, Speed, StopReason,
  42    TokenUsage, ZED_CLOUD_PROVIDER_ID,
  43};
  44use project::Project;
  45use prompt_store::ProjectContext;
  46use schemars::{JsonSchema, Schema};
  47use serde::de::DeserializeOwned;
  48use serde::{Deserialize, Serialize};
  49use settings::{LanguageModelSelection, Settings, ToolPermissionMode, update_settings_file};
  50use std::{
  51    collections::BTreeMap,
  52    marker::PhantomData,
  53    ops::RangeInclusive,
  54    path::Path,
  55    rc::Rc,
  56    sync::Arc,
  57    time::{Duration, Instant},
  58};
  59use std::{fmt::Write, path::PathBuf};
  60use util::{ResultExt, debug_panic, markdown::MarkdownCodeBlock, paths::PathStyle};
  61use uuid::Uuid;
  62
  63const TOOL_CANCELED_MESSAGE: &str = "Tool canceled by user";
  64pub const MAX_TOOL_NAME_LENGTH: usize = 64;
  65pub const MAX_SUBAGENT_DEPTH: u8 = 1;
  66
  67/// Context passed to a subagent thread for lifecycle management
  68#[derive(Clone, Debug, Serialize, Deserialize)]
  69pub struct SubagentContext {
  70    /// ID of the parent thread
  71    pub parent_thread_id: acp::SessionId,
  72
  73    /// Current depth level (0 = root agent, 1 = first-level subagent, etc.)
  74    pub depth: u8,
  75}
  76
  77/// The ID of the user prompt that initiated a request.
  78///
  79/// This equates to the user physically submitting a message to the model (e.g., by pressing the Enter key).
  80#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
  81pub struct PromptId(Arc<str>);
  82
  83impl PromptId {
  84    pub fn new() -> Self {
  85        Self(Uuid::new_v4().to_string().into())
  86    }
  87}
  88
  89impl std::fmt::Display for PromptId {
  90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  91        write!(f, "{}", self.0)
  92    }
  93}
  94
  95pub(crate) const MAX_RETRY_ATTEMPTS: u8 = 4;
  96pub(crate) const BASE_RETRY_DELAY: Duration = Duration::from_secs(5);
  97
  98#[derive(Debug, Clone)]
  99enum RetryStrategy {
 100    ExponentialBackoff {
 101        initial_delay: Duration,
 102        max_attempts: u8,
 103    },
 104    Fixed {
 105        delay: Duration,
 106        max_attempts: u8,
 107    },
 108}
 109
 110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 111pub enum Message {
 112    User(UserMessage),
 113    Agent(AgentMessage),
 114    Resume,
 115}
 116
 117impl Message {
 118    pub fn as_agent_message(&self) -> Option<&AgentMessage> {
 119        match self {
 120            Message::Agent(agent_message) => Some(agent_message),
 121            _ => None,
 122        }
 123    }
 124
 125    pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
 126        match self {
 127            Message::User(message) => {
 128                if message.content.is_empty() {
 129                    vec![]
 130                } else {
 131                    vec![message.to_request()]
 132                }
 133            }
 134            Message::Agent(message) => message.to_request(),
 135            Message::Resume => vec![LanguageModelRequestMessage {
 136                role: Role::User,
 137                content: vec!["Continue where you left off".into()],
 138                cache: false,
 139                reasoning_details: None,
 140            }],
 141        }
 142    }
 143
 144    pub fn to_markdown(&self) -> String {
 145        match self {
 146            Message::User(message) => message.to_markdown(),
 147            Message::Agent(message) => message.to_markdown(),
 148            Message::Resume => "[resume]\n".into(),
 149        }
 150    }
 151
 152    pub fn role(&self) -> Role {
 153        match self {
 154            Message::User(_) | Message::Resume => Role::User,
 155            Message::Agent(_) => Role::Assistant,
 156        }
 157    }
 158}
 159
 160#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 161pub struct UserMessage {
 162    pub id: UserMessageId,
 163    pub content: Vec<UserMessageContent>,
 164}
 165
 166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 167pub enum UserMessageContent {
 168    Text(String),
 169    Mention { uri: MentionUri, content: String },
 170    Image(LanguageModelImage),
 171}
 172
 173impl UserMessage {
 174    pub fn to_markdown(&self) -> String {
 175        let mut markdown = String::new();
 176
 177        for content in &self.content {
 178            match content {
 179                UserMessageContent::Text(text) => {
 180                    markdown.push_str(text);
 181                    markdown.push('\n');
 182                }
 183                UserMessageContent::Image(_) => {
 184                    markdown.push_str("<image />\n");
 185                }
 186                UserMessageContent::Mention { uri, content } => {
 187                    if !content.is_empty() {
 188                        let _ = writeln!(&mut markdown, "{}\n\n{}", uri.as_link(), content);
 189                    } else {
 190                        let _ = writeln!(&mut markdown, "{}", uri.as_link());
 191                    }
 192                }
 193            }
 194        }
 195
 196        markdown
 197    }
 198
 199    fn to_request(&self) -> LanguageModelRequestMessage {
 200        let mut message = LanguageModelRequestMessage {
 201            role: Role::User,
 202            content: Vec::with_capacity(self.content.len()),
 203            cache: false,
 204            reasoning_details: None,
 205        };
 206
 207        const OPEN_CONTEXT: &str = "<context>\n\
 208            The following items were attached by the user. \
 209            They are up-to-date and don't need to be re-read.\n\n";
 210
 211        const OPEN_FILES_TAG: &str = "<files>";
 212        const OPEN_DIRECTORIES_TAG: &str = "<directories>";
 213        const OPEN_SYMBOLS_TAG: &str = "<symbols>";
 214        const OPEN_SELECTIONS_TAG: &str = "<selections>";
 215        const OPEN_THREADS_TAG: &str = "<threads>";
 216        const OPEN_FETCH_TAG: &str = "<fetched_urls>";
 217        const OPEN_RULES_TAG: &str =
 218            "<rules>\nThe user has specified the following rules that should be applied:\n";
 219        const OPEN_DIAGNOSTICS_TAG: &str = "<diagnostics>";
 220        const OPEN_DIFFS_TAG: &str = "<diffs>";
 221        const MERGE_CONFLICT_TAG: &str = "<merge_conflicts>";
 222
 223        let mut file_context = OPEN_FILES_TAG.to_string();
 224        let mut directory_context = OPEN_DIRECTORIES_TAG.to_string();
 225        let mut symbol_context = OPEN_SYMBOLS_TAG.to_string();
 226        let mut selection_context = OPEN_SELECTIONS_TAG.to_string();
 227        let mut thread_context = OPEN_THREADS_TAG.to_string();
 228        let mut fetch_context = OPEN_FETCH_TAG.to_string();
 229        let mut rules_context = OPEN_RULES_TAG.to_string();
 230        let mut diagnostics_context = OPEN_DIAGNOSTICS_TAG.to_string();
 231        let mut diffs_context = OPEN_DIFFS_TAG.to_string();
 232        let mut merge_conflict_context = MERGE_CONFLICT_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::Rule { .. } => {
 298                            write!(
 299                                &mut rules_context,
 300                                "\n{}",
 301                                MarkdownCodeBlock {
 302                                    tag: "",
 303                                    text: content
 304                                }
 305                            )
 306                            .ok();
 307                        }
 308                        MentionUri::Fetch { url } => {
 309                            write!(&mut fetch_context, "\nFetch: {}\n\n{}", url, content).ok();
 310                        }
 311                        MentionUri::Diagnostics { .. } => {
 312                            write!(&mut diagnostics_context, "\n{}\n", content).ok();
 313                        }
 314                        MentionUri::TerminalSelection { .. } => {
 315                            write!(
 316                                &mut selection_context,
 317                                "\n{}",
 318                                MarkdownCodeBlock {
 319                                    tag: "console",
 320                                    text: content
 321                                }
 322                            )
 323                            .ok();
 324                        }
 325                        MentionUri::GitDiff { base_ref } => {
 326                            write!(
 327                                &mut diffs_context,
 328                                "\nBranch diff against {}:\n{}",
 329                                base_ref,
 330                                MarkdownCodeBlock {
 331                                    tag: "diff",
 332                                    text: content
 333                                }
 334                            )
 335                            .ok();
 336                        }
 337                        MentionUri::MergeConflict { file_path } => {
 338                            write!(
 339                                &mut merge_conflict_context,
 340                                "\nMerge conflict in {}:\n{}",
 341                                file_path,
 342                                MarkdownCodeBlock {
 343                                    tag: "diff",
 344                                    text: content
 345                                }
 346                            )
 347                            .ok();
 348                        }
 349                    }
 350
 351                    language_model::MessageContent::Text(uri.as_link().to_string())
 352                }
 353            };
 354
 355            message.content.push(chunk);
 356        }
 357
 358        let len_before_context = message.content.len();
 359
 360        if file_context.len() > OPEN_FILES_TAG.len() {
 361            file_context.push_str("</files>\n");
 362            message
 363                .content
 364                .push(language_model::MessageContent::Text(file_context));
 365        }
 366
 367        if directory_context.len() > OPEN_DIRECTORIES_TAG.len() {
 368            directory_context.push_str("</directories>\n");
 369            message
 370                .content
 371                .push(language_model::MessageContent::Text(directory_context));
 372        }
 373
 374        if symbol_context.len() > OPEN_SYMBOLS_TAG.len() {
 375            symbol_context.push_str("</symbols>\n");
 376            message
 377                .content
 378                .push(language_model::MessageContent::Text(symbol_context));
 379        }
 380
 381        if selection_context.len() > OPEN_SELECTIONS_TAG.len() {
 382            selection_context.push_str("</selections>\n");
 383            message
 384                .content
 385                .push(language_model::MessageContent::Text(selection_context));
 386        }
 387
 388        if diffs_context.len() > OPEN_DIFFS_TAG.len() {
 389            diffs_context.push_str("</diffs>\n");
 390            message
 391                .content
 392                .push(language_model::MessageContent::Text(diffs_context));
 393        }
 394
 395        if thread_context.len() > OPEN_THREADS_TAG.len() {
 396            thread_context.push_str("</threads>\n");
 397            message
 398                .content
 399                .push(language_model::MessageContent::Text(thread_context));
 400        }
 401
 402        if fetch_context.len() > OPEN_FETCH_TAG.len() {
 403            fetch_context.push_str("</fetched_urls>\n");
 404            message
 405                .content
 406                .push(language_model::MessageContent::Text(fetch_context));
 407        }
 408
 409        if rules_context.len() > OPEN_RULES_TAG.len() {
 410            rules_context.push_str("</user_rules>\n");
 411            message
 412                .content
 413                .push(language_model::MessageContent::Text(rules_context));
 414        }
 415
 416        if diagnostics_context.len() > OPEN_DIAGNOSTICS_TAG.len() {
 417            diagnostics_context.push_str("</diagnostics>\n");
 418            message
 419                .content
 420                .push(language_model::MessageContent::Text(diagnostics_context));
 421        }
 422
 423        if merge_conflict_context.len() > MERGE_CONFLICT_TAG.len() {
 424            merge_conflict_context.push_str("</merge_conflicts>\n");
 425            message
 426                .content
 427                .push(language_model::MessageContent::Text(merge_conflict_context));
 428        }
 429
 430        if message.content.len() > len_before_context {
 431            message.content.insert(
 432                len_before_context,
 433                language_model::MessageContent::Text(OPEN_CONTEXT.into()),
 434            );
 435            message
 436                .content
 437                .push(language_model::MessageContent::Text("</context>".into()));
 438        }
 439
 440        message
 441    }
 442}
 443
 444fn codeblock_tag(full_path: &Path, line_range: Option<&RangeInclusive<u32>>) -> String {
 445    let mut result = String::new();
 446
 447    if let Some(extension) = full_path.extension().and_then(|ext| ext.to_str()) {
 448        let _ = write!(result, "{} ", extension);
 449    }
 450
 451    let _ = write!(result, "{}", full_path.display());
 452
 453    if let Some(range) = line_range {
 454        if range.start() == range.end() {
 455            let _ = write!(result, ":{}", range.start() + 1);
 456        } else {
 457            let _ = write!(result, ":{}-{}", range.start() + 1, range.end() + 1);
 458        }
 459    }
 460
 461    result
 462}
 463
 464impl AgentMessage {
 465    pub fn to_markdown(&self) -> String {
 466        let mut markdown = String::new();
 467
 468        for content in &self.content {
 469            match content {
 470                AgentMessageContent::Text(text) => {
 471                    markdown.push_str(text);
 472                    markdown.push('\n');
 473                }
 474                AgentMessageContent::Thinking { text, .. } => {
 475                    markdown.push_str("<think>");
 476                    markdown.push_str(text);
 477                    markdown.push_str("</think>\n");
 478                }
 479                AgentMessageContent::RedactedThinking(_) => {
 480                    markdown.push_str("<redacted_thinking />\n")
 481                }
 482                AgentMessageContent::ToolUse(tool_use) => {
 483                    markdown.push_str(&format!(
 484                        "**Tool Use**: {} (ID: {})\n",
 485                        tool_use.name, tool_use.id
 486                    ));
 487                    markdown.push_str(&format!(
 488                        "{}\n",
 489                        MarkdownCodeBlock {
 490                            tag: "json",
 491                            text: &format!("{:#}", tool_use.input)
 492                        }
 493                    ));
 494                }
 495            }
 496        }
 497
 498        for tool_result in self.tool_results.values() {
 499            markdown.push_str(&format!(
 500                "**Tool Result**: {} (ID: {})\n\n",
 501                tool_result.tool_name, tool_result.tool_use_id
 502            ));
 503            if tool_result.is_error {
 504                markdown.push_str("**ERROR:**\n");
 505            }
 506
 507            match &tool_result.content {
 508                LanguageModelToolResultContent::Text(text) => {
 509                    writeln!(markdown, "{text}\n").ok();
 510                }
 511                LanguageModelToolResultContent::Image(_) => {
 512                    writeln!(markdown, "<image />\n").ok();
 513                }
 514            }
 515
 516            if let Some(output) = tool_result.output.as_ref() {
 517                writeln!(
 518                    markdown,
 519                    "**Debug Output**:\n\n```json\n{}\n```\n",
 520                    serde_json::to_string_pretty(output).unwrap()
 521                )
 522                .unwrap();
 523            }
 524        }
 525
 526        markdown
 527    }
 528
 529    pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
 530        let mut assistant_message = LanguageModelRequestMessage {
 531            role: Role::Assistant,
 532            content: Vec::with_capacity(self.content.len()),
 533            cache: false,
 534            reasoning_details: self.reasoning_details.clone(),
 535        };
 536        for chunk in &self.content {
 537            match chunk {
 538                AgentMessageContent::Text(text) => {
 539                    assistant_message
 540                        .content
 541                        .push(language_model::MessageContent::Text(text.clone()));
 542                }
 543                AgentMessageContent::Thinking { text, signature } => {
 544                    assistant_message
 545                        .content
 546                        .push(language_model::MessageContent::Thinking {
 547                            text: text.clone(),
 548                            signature: signature.clone(),
 549                        });
 550                }
 551                AgentMessageContent::RedactedThinking(value) => {
 552                    assistant_message.content.push(
 553                        language_model::MessageContent::RedactedThinking(value.clone()),
 554                    );
 555                }
 556                AgentMessageContent::ToolUse(tool_use) => {
 557                    if self.tool_results.contains_key(&tool_use.id) {
 558                        assistant_message
 559                            .content
 560                            .push(language_model::MessageContent::ToolUse(tool_use.clone()));
 561                    }
 562                }
 563            };
 564        }
 565
 566        let mut user_message = LanguageModelRequestMessage {
 567            role: Role::User,
 568            content: Vec::new(),
 569            cache: false,
 570            reasoning_details: None,
 571        };
 572
 573        for tool_result in self.tool_results.values() {
 574            let mut tool_result = tool_result.clone();
 575            // Surprisingly, the API fails if we return an empty string here.
 576            // It thinks we are sending a tool use without a tool result.
 577            if tool_result.content.is_empty() {
 578                tool_result.content = "<Tool returned an empty string>".into();
 579            }
 580            user_message
 581                .content
 582                .push(language_model::MessageContent::ToolResult(tool_result));
 583        }
 584
 585        let mut messages = Vec::new();
 586        if !assistant_message.content.is_empty() {
 587            messages.push(assistant_message);
 588        }
 589        if !user_message.content.is_empty() {
 590            messages.push(user_message);
 591        }
 592        messages
 593    }
 594}
 595
 596#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 597pub struct AgentMessage {
 598    pub content: Vec<AgentMessageContent>,
 599    pub tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
 600    pub reasoning_details: Option<serde_json::Value>,
 601}
 602
 603#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 604pub enum AgentMessageContent {
 605    Text(String),
 606    Thinking {
 607        text: String,
 608        signature: Option<String>,
 609    },
 610    RedactedThinking(String),
 611    ToolUse(LanguageModelToolUse),
 612}
 613
 614pub trait TerminalHandle {
 615    fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId>;
 616    fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse>;
 617    fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>>;
 618    fn kill(&self, cx: &AsyncApp) -> Result<()>;
 619    fn was_stopped_by_user(&self, cx: &AsyncApp) -> Result<bool>;
 620}
 621
 622pub trait SubagentHandle {
 623    /// The session ID of this subagent thread
 624    fn id(&self) -> acp::SessionId;
 625    /// The current number of entries in the thread.
 626    /// Useful for knowing where the next turn will begin
 627    fn num_entries(&self, cx: &App) -> usize;
 628    /// Runs a turn for a given message and returns both the response and the index of that output message.
 629    fn send(&self, message: String, cx: &AsyncApp) -> Task<Result<String>>;
 630}
 631
 632pub trait ThreadEnvironment {
 633    fn create_terminal(
 634        &self,
 635        command: String,
 636        cwd: Option<PathBuf>,
 637        output_byte_limit: Option<u64>,
 638        cx: &mut AsyncApp,
 639    ) -> Task<Result<Rc<dyn TerminalHandle>>>;
 640
 641    fn create_subagent(&self, label: String, cx: &mut App) -> Result<Rc<dyn SubagentHandle>>;
 642
 643    fn resume_subagent(
 644        &self,
 645        _session_id: acp::SessionId,
 646        _cx: &mut App,
 647    ) -> Result<Rc<dyn SubagentHandle>> {
 648        Err(anyhow::anyhow!(
 649            "Resuming subagent sessions is not supported"
 650        ))
 651    }
 652}
 653
 654#[derive(Debug)]
 655pub enum ThreadEvent {
 656    UserMessage(UserMessage),
 657    AgentText(String),
 658    AgentThinking(String),
 659    ToolCall(acp::ToolCall),
 660    ToolCallUpdate(acp_thread::ToolCallUpdate),
 661    Plan(acp::Plan),
 662    ToolCallAuthorization(ToolCallAuthorization),
 663    SubagentSpawned(acp::SessionId),
 664    Retry(acp_thread::RetryStatus),
 665    Stop(acp::StopReason),
 666}
 667
 668#[derive(Debug)]
 669pub struct NewTerminal {
 670    pub command: String,
 671    pub output_byte_limit: Option<u64>,
 672    pub cwd: Option<PathBuf>,
 673    pub response: oneshot::Sender<Result<Entity<acp_thread::Terminal>>>,
 674}
 675
 676#[derive(Debug, Clone)]
 677pub struct ToolPermissionContext {
 678    pub tool_name: String,
 679    pub input_values: Vec<String>,
 680    pub scope: ToolPermissionScope,
 681}
 682
 683#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 684pub enum ToolPermissionScope {
 685    ToolInput,
 686    SymlinkTarget,
 687}
 688
 689impl ToolPermissionContext {
 690    pub fn new(tool_name: impl Into<String>, input_values: Vec<String>) -> Self {
 691        Self {
 692            tool_name: tool_name.into(),
 693            input_values,
 694            scope: ToolPermissionScope::ToolInput,
 695        }
 696    }
 697
 698    pub fn symlink_target(tool_name: impl Into<String>, target_paths: Vec<String>) -> Self {
 699        Self {
 700            tool_name: tool_name.into(),
 701            input_values: target_paths,
 702            scope: ToolPermissionScope::SymlinkTarget,
 703        }
 704    }
 705
 706    /// Builds the permission options for this tool context.
 707    ///
 708    /// This is the canonical source for permission option generation.
 709    /// Tests should use this function rather than manually constructing options.
 710    ///
 711    /// # Shell Compatibility for Terminal Tool
 712    ///
 713    /// For the terminal tool, "Always allow" options are only shown when the user's
 714    /// shell supports POSIX-like command chaining syntax (`&&`, `||`, `;`, `|`).
 715    ///
 716    /// **Why this matters:** When a user sets up an "always allow" pattern like `^cargo`,
 717    /// we need to parse the command to extract all sub-commands and verify that EVERY
 718    /// sub-command matches the pattern. Otherwise, an attacker could craft a command like
 719    /// `cargo build && rm -rf /` that would bypass the security check.
 720    ///
 721    /// **Supported shells:** Posix (sh, bash, dash, zsh), Fish 3.0+, PowerShell 7+/Pwsh,
 722    /// Cmd, Xonsh, Csh, Tcsh
 723    ///
 724    /// **Unsupported shells:** Nushell (uses `and`/`or` keywords), Elvish (uses `and`/`or`
 725    /// keywords), Rc (Plan 9 shell - no `&&`/`||` operators)
 726    ///
 727    /// For unsupported shells, we hide the "Always allow" UI options entirely, and if
 728    /// the user has `always_allow` rules configured in settings, `ToolPermissionDecision::from_input`
 729    /// will return a `Deny` with an explanatory error message.
 730    pub fn build_permission_options(&self) -> acp_thread::PermissionOptions {
 731        use crate::pattern_extraction::*;
 732        use util::shell::ShellKind;
 733
 734        let tool_name = &self.tool_name;
 735        let input_values = &self.input_values;
 736        if self.scope == ToolPermissionScope::SymlinkTarget {
 737            return acp_thread::PermissionOptions::Flat(vec![
 738                acp::PermissionOption::new(
 739                    acp::PermissionOptionId::new("allow"),
 740                    "Yes",
 741                    acp::PermissionOptionKind::AllowOnce,
 742                ),
 743                acp::PermissionOption::new(
 744                    acp::PermissionOptionId::new("deny"),
 745                    "No",
 746                    acp::PermissionOptionKind::RejectOnce,
 747                ),
 748            ]);
 749        }
 750
 751        // Check if the user's shell supports POSIX-like command chaining.
 752        // See the doc comment above for the full explanation of why this is needed.
 753        let shell_supports_always_allow = if tool_name == TerminalTool::NAME {
 754            ShellKind::system().supports_posix_chaining()
 755        } else {
 756            true
 757        };
 758
 759        // For terminal commands with multiple pipeline commands, use DropdownWithPatterns
 760        // to let users individually select which command patterns to always allow.
 761        if tool_name == TerminalTool::NAME && shell_supports_always_allow {
 762            if let Some(input) = input_values.first() {
 763                let all_patterns = extract_all_terminal_patterns(input);
 764                if all_patterns.len() > 1 {
 765                    let mut choices = Vec::new();
 766                    choices.push(acp_thread::PermissionOptionChoice {
 767                        allow: acp::PermissionOption::new(
 768                            acp::PermissionOptionId::new(format!("always_allow:{}", tool_name)),
 769                            format!("Always for {}", tool_name.replace('_', " ")),
 770                            acp::PermissionOptionKind::AllowAlways,
 771                        ),
 772                        deny: acp::PermissionOption::new(
 773                            acp::PermissionOptionId::new(format!("always_deny:{}", tool_name)),
 774                            format!("Always for {}", tool_name.replace('_', " ")),
 775                            acp::PermissionOptionKind::RejectAlways,
 776                        ),
 777                        sub_patterns: vec![],
 778                    });
 779                    choices.push(acp_thread::PermissionOptionChoice {
 780                        allow: acp::PermissionOption::new(
 781                            acp::PermissionOptionId::new("allow"),
 782                            "Only this time",
 783                            acp::PermissionOptionKind::AllowOnce,
 784                        ),
 785                        deny: acp::PermissionOption::new(
 786                            acp::PermissionOptionId::new("deny"),
 787                            "Only this time",
 788                            acp::PermissionOptionKind::RejectOnce,
 789                        ),
 790                        sub_patterns: vec![],
 791                    });
 792                    return acp_thread::PermissionOptions::DropdownWithPatterns {
 793                        choices,
 794                        patterns: all_patterns,
 795                        tool_name: tool_name.clone(),
 796                    };
 797                }
 798            }
 799        }
 800
 801        let extract_for_value = |value: &str| -> (Option<String>, Option<String>) {
 802            if tool_name == TerminalTool::NAME {
 803                (
 804                    extract_terminal_pattern(value),
 805                    extract_terminal_pattern_display(value),
 806                )
 807            } else if tool_name == CopyPathTool::NAME
 808                || tool_name == MovePathTool::NAME
 809                || tool_name == EditFileTool::NAME
 810                || tool_name == DeletePathTool::NAME
 811                || tool_name == CreateDirectoryTool::NAME
 812                || tool_name == SaveFileTool::NAME
 813            {
 814                (
 815                    extract_path_pattern(value),
 816                    extract_path_pattern_display(value),
 817                )
 818            } else if tool_name == FetchTool::NAME {
 819                (
 820                    extract_url_pattern(value),
 821                    extract_url_pattern_display(value),
 822                )
 823            } else {
 824                (None, None)
 825            }
 826        };
 827
 828        // Extract patterns from all input values. Only offer a pattern-specific
 829        // "always allow/deny" button when every value produces the same pattern.
 830        let (pattern, pattern_display) = match input_values.as_slice() {
 831            [single] => extract_for_value(single),
 832            _ => {
 833                let mut iter = input_values.iter().map(|v| extract_for_value(v));
 834                match iter.next() {
 835                    Some(first) => {
 836                        if iter.all(|pair| pair.0 == first.0) {
 837                            first
 838                        } else {
 839                            (None, None)
 840                        }
 841                    }
 842                    None => (None, None),
 843                }
 844            }
 845        };
 846
 847        let mut choices = Vec::new();
 848
 849        let mut push_choice =
 850            |label: String, allow_id, deny_id, allow_kind, deny_kind, sub_patterns: Vec<String>| {
 851                choices.push(acp_thread::PermissionOptionChoice {
 852                    allow: acp::PermissionOption::new(
 853                        acp::PermissionOptionId::new(allow_id),
 854                        label.clone(),
 855                        allow_kind,
 856                    ),
 857                    deny: acp::PermissionOption::new(
 858                        acp::PermissionOptionId::new(deny_id),
 859                        label,
 860                        deny_kind,
 861                    ),
 862                    sub_patterns,
 863                });
 864            };
 865
 866        if shell_supports_always_allow {
 867            push_choice(
 868                format!("Always for {}", tool_name.replace('_', " ")),
 869                format!("always_allow:{}", tool_name),
 870                format!("always_deny:{}", tool_name),
 871                acp::PermissionOptionKind::AllowAlways,
 872                acp::PermissionOptionKind::RejectAlways,
 873                vec![],
 874            );
 875
 876            if let (Some(pattern), Some(display)) = (pattern, pattern_display) {
 877                let button_text = if tool_name == TerminalTool::NAME {
 878                    format!("Always for `{}` commands", display)
 879                } else {
 880                    format!("Always for `{}`", display)
 881                };
 882                push_choice(
 883                    button_text,
 884                    format!("always_allow:{}", tool_name),
 885                    format!("always_deny:{}", tool_name),
 886                    acp::PermissionOptionKind::AllowAlways,
 887                    acp::PermissionOptionKind::RejectAlways,
 888                    vec![pattern],
 889                );
 890            }
 891        }
 892
 893        push_choice(
 894            "Only this time".to_string(),
 895            "allow".to_string(),
 896            "deny".to_string(),
 897            acp::PermissionOptionKind::AllowOnce,
 898            acp::PermissionOptionKind::RejectOnce,
 899            vec![],
 900        );
 901
 902        acp_thread::PermissionOptions::Dropdown(choices)
 903    }
 904}
 905
 906#[derive(Debug)]
 907pub struct ToolCallAuthorization {
 908    pub tool_call: acp::ToolCallUpdate,
 909    pub options: acp_thread::PermissionOptions,
 910    pub response: oneshot::Sender<acp_thread::SelectedPermissionOutcome>,
 911    pub context: Option<ToolPermissionContext>,
 912}
 913
 914#[derive(Debug, thiserror::Error)]
 915enum CompletionError {
 916    #[error("max tokens")]
 917    MaxTokens,
 918    #[error("refusal")]
 919    Refusal,
 920    #[error(transparent)]
 921    Other(#[from] anyhow::Error),
 922}
 923
 924pub struct Thread {
 925    id: acp::SessionId,
 926    prompt_id: PromptId,
 927    updated_at: DateTime<Utc>,
 928    title: Option<SharedString>,
 929    pending_title_generation: Option<Task<()>>,
 930    pending_summary_generation: Option<Shared<Task<Option<SharedString>>>>,
 931    summary: Option<SharedString>,
 932    messages: Vec<Message>,
 933    user_store: Entity<UserStore>,
 934    /// Holds the task that handles agent interaction until the end of the turn.
 935    /// Survives across multiple requests as the model performs tool calls and
 936    /// we run tools, report their results.
 937    running_turn: Option<RunningTurn>,
 938    /// Flag indicating the UI has a queued message waiting to be sent.
 939    /// Used to signal that the turn should end at the next message boundary.
 940    has_queued_message: bool,
 941    pending_message: Option<AgentMessage>,
 942    pub(crate) tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
 943    request_token_usage: HashMap<UserMessageId, language_model::TokenUsage>,
 944    #[allow(unused)]
 945    cumulative_token_usage: TokenUsage,
 946    #[allow(unused)]
 947    initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
 948    pub(crate) context_server_registry: Entity<ContextServerRegistry>,
 949    profile_id: AgentProfileId,
 950    project_context: Entity<ProjectContext>,
 951    pub(crate) templates: Arc<Templates>,
 952    model: Option<Arc<dyn LanguageModel>>,
 953    summarization_model: Option<Arc<dyn LanguageModel>>,
 954    thinking_enabled: bool,
 955    thinking_effort: Option<String>,
 956    speed: Option<Speed>,
 957    prompt_capabilities_tx: watch::Sender<acp::PromptCapabilities>,
 958    pub(crate) prompt_capabilities_rx: watch::Receiver<acp::PromptCapabilities>,
 959    pub(crate) project: Entity<Project>,
 960    pub(crate) action_log: Entity<ActionLog>,
 961    /// True if this thread was imported from a shared thread and can be synced.
 962    imported: bool,
 963    /// If this is a subagent thread, contains context about the parent
 964    subagent_context: Option<SubagentContext>,
 965    /// The user's unsent prompt text, persisted so it can be restored when reloading the thread.
 966    draft_prompt: Option<Vec<acp::ContentBlock>>,
 967    ui_scroll_position: Option<gpui::ListOffset>,
 968    /// Weak references to running subagent threads for cancellation propagation
 969    running_subagents: Vec<WeakEntity<Thread>>,
 970}
 971
 972impl Thread {
 973    fn prompt_capabilities(model: Option<&dyn LanguageModel>) -> acp::PromptCapabilities {
 974        let image = model.map_or(true, |model| model.supports_images());
 975        acp::PromptCapabilities::new()
 976            .image(image)
 977            .embedded_context(true)
 978    }
 979
 980    pub fn new_subagent(parent_thread: &Entity<Thread>, cx: &mut Context<Self>) -> Self {
 981        let project = parent_thread.read(cx).project.clone();
 982        let project_context = parent_thread.read(cx).project_context.clone();
 983        let context_server_registry = parent_thread.read(cx).context_server_registry.clone();
 984        let templates = parent_thread.read(cx).templates.clone();
 985        let model = parent_thread.read(cx).model().cloned();
 986        let parent_action_log = parent_thread.read(cx).action_log().clone();
 987        let action_log =
 988            cx.new(|_cx| ActionLog::new(project.clone()).with_linked_action_log(parent_action_log));
 989        let mut thread = Self::new_internal(
 990            project,
 991            project_context,
 992            context_server_registry,
 993            templates,
 994            model,
 995            action_log,
 996            cx,
 997        );
 998        thread.subagent_context = Some(SubagentContext {
 999            parent_thread_id: parent_thread.read(cx).id().clone(),
1000            depth: parent_thread.read(cx).depth() + 1,
1001        });
1002        thread.inherit_parent_settings(parent_thread, cx);
1003        thread
1004    }
1005
1006    pub fn new(
1007        project: Entity<Project>,
1008        project_context: Entity<ProjectContext>,
1009        context_server_registry: Entity<ContextServerRegistry>,
1010        templates: Arc<Templates>,
1011        model: Option<Arc<dyn LanguageModel>>,
1012        cx: &mut Context<Self>,
1013    ) -> Self {
1014        Self::new_internal(
1015            project.clone(),
1016            project_context,
1017            context_server_registry,
1018            templates,
1019            model,
1020            cx.new(|_cx| ActionLog::new(project)),
1021            cx,
1022        )
1023    }
1024
1025    fn new_internal(
1026        project: Entity<Project>,
1027        project_context: Entity<ProjectContext>,
1028        context_server_registry: Entity<ContextServerRegistry>,
1029        templates: Arc<Templates>,
1030        model: Option<Arc<dyn LanguageModel>>,
1031        action_log: Entity<ActionLog>,
1032        cx: &mut Context<Self>,
1033    ) -> Self {
1034        let settings = AgentSettings::get_global(cx);
1035        let profile_id = settings.default_profile.clone();
1036        let enable_thinking = settings
1037            .default_model
1038            .as_ref()
1039            .is_some_and(|model| model.enable_thinking);
1040        let thinking_effort = settings
1041            .default_model
1042            .as_ref()
1043            .and_then(|model| model.effort.clone());
1044        let (prompt_capabilities_tx, prompt_capabilities_rx) =
1045            watch::channel(Self::prompt_capabilities(model.as_deref()));
1046        Self {
1047            id: acp::SessionId::new(uuid::Uuid::new_v4().to_string()),
1048            prompt_id: PromptId::new(),
1049            updated_at: Utc::now(),
1050            title: None,
1051            pending_title_generation: None,
1052            pending_summary_generation: None,
1053            summary: None,
1054            messages: Vec::new(),
1055            user_store: project.read(cx).user_store(),
1056            running_turn: None,
1057            has_queued_message: false,
1058            pending_message: None,
1059            tools: BTreeMap::default(),
1060            request_token_usage: HashMap::default(),
1061            cumulative_token_usage: TokenUsage::default(),
1062            initial_project_snapshot: {
1063                let project_snapshot = Self::project_snapshot(project.clone(), cx);
1064                cx.foreground_executor()
1065                    .spawn(async move { Some(project_snapshot.await) })
1066                    .shared()
1067            },
1068            context_server_registry,
1069            profile_id,
1070            project_context,
1071            templates,
1072            model,
1073            summarization_model: None,
1074            thinking_enabled: enable_thinking,
1075            speed: None,
1076            thinking_effort,
1077            prompt_capabilities_tx,
1078            prompt_capabilities_rx,
1079            project,
1080            action_log,
1081            imported: false,
1082            subagent_context: None,
1083            draft_prompt: None,
1084            ui_scroll_position: None,
1085            running_subagents: Vec::new(),
1086        }
1087    }
1088
1089    /// Copies runtime-mutable settings from the parent thread so that
1090    /// subagents start with the same configuration the user selected.
1091    /// Every property that `set_*` propagates to `running_subagents`
1092    /// should be inherited here as well.
1093    fn inherit_parent_settings(&mut self, parent_thread: &Entity<Thread>, cx: &mut Context<Self>) {
1094        let parent = parent_thread.read(cx);
1095        self.speed = parent.speed;
1096        self.thinking_enabled = parent.thinking_enabled;
1097        self.thinking_effort = parent.thinking_effort.clone();
1098        self.summarization_model = parent.summarization_model.clone();
1099        self.profile_id = parent.profile_id.clone();
1100    }
1101
1102    pub fn id(&self) -> &acp::SessionId {
1103        &self.id
1104    }
1105
1106    /// Returns true if this thread was imported from a shared thread.
1107    pub fn is_imported(&self) -> bool {
1108        self.imported
1109    }
1110
1111    pub fn replay(
1112        &mut self,
1113        cx: &mut Context<Self>,
1114    ) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {
1115        let (tx, rx) = mpsc::unbounded();
1116        let stream = ThreadEventStream(tx);
1117        for message in &self.messages {
1118            match message {
1119                Message::User(user_message) => stream.send_user_message(user_message),
1120                Message::Agent(assistant_message) => {
1121                    for content in &assistant_message.content {
1122                        match content {
1123                            AgentMessageContent::Text(text) => stream.send_text(text),
1124                            AgentMessageContent::Thinking { text, .. } => {
1125                                stream.send_thinking(text)
1126                            }
1127                            AgentMessageContent::RedactedThinking(_) => {}
1128                            AgentMessageContent::ToolUse(tool_use) => {
1129                                self.replay_tool_call(
1130                                    tool_use,
1131                                    assistant_message.tool_results.get(&tool_use.id),
1132                                    &stream,
1133                                    cx,
1134                                );
1135                            }
1136                        }
1137                    }
1138                }
1139                Message::Resume => {}
1140            }
1141        }
1142        rx
1143    }
1144
1145    fn replay_tool_call(
1146        &self,
1147        tool_use: &LanguageModelToolUse,
1148        tool_result: Option<&LanguageModelToolResult>,
1149        stream: &ThreadEventStream,
1150        cx: &mut Context<Self>,
1151    ) {
1152        // Extract saved output and status first, so they're available even if tool is not found
1153        let output = tool_result
1154            .as_ref()
1155            .and_then(|result| result.output.clone());
1156        let status = tool_result
1157            .as_ref()
1158            .map_or(acp::ToolCallStatus::Failed, |result| {
1159                if result.is_error {
1160                    acp::ToolCallStatus::Failed
1161                } else {
1162                    acp::ToolCallStatus::Completed
1163                }
1164            });
1165
1166        let tool = self.tools.get(tool_use.name.as_ref()).cloned().or_else(|| {
1167            self.context_server_registry
1168                .read(cx)
1169                .servers()
1170                .find_map(|(_, tools)| {
1171                    if let Some(tool) = tools.get(tool_use.name.as_ref()) {
1172                        Some(tool.clone())
1173                    } else {
1174                        None
1175                    }
1176                })
1177        });
1178
1179        let Some(tool) = tool else {
1180            // Tool not found (e.g., MCP server not connected after restart),
1181            // but still display the saved result if available.
1182            // We need to send both ToolCall and ToolCallUpdate events because the UI
1183            // only converts raw_output to displayable content in update_fields, not from_acp.
1184            stream
1185                .0
1186                .unbounded_send(Ok(ThreadEvent::ToolCall(
1187                    acp::ToolCall::new(tool_use.id.to_string(), tool_use.name.to_string())
1188                        .status(status)
1189                        .raw_input(tool_use.input.clone()),
1190                )))
1191                .ok();
1192            stream.update_tool_call_fields(
1193                &tool_use.id,
1194                acp::ToolCallUpdateFields::new()
1195                    .status(status)
1196                    .raw_output(output),
1197                None,
1198            );
1199            return;
1200        };
1201
1202        let title = tool.initial_title(tool_use.input.clone(), cx);
1203        let kind = tool.kind();
1204        stream.send_tool_call(
1205            &tool_use.id,
1206            &tool_use.name,
1207            title,
1208            kind,
1209            tool_use.input.clone(),
1210        );
1211
1212        if let Some(output) = output.clone() {
1213            // For replay, we use a dummy cancellation receiver since the tool already completed
1214            let (_cancellation_tx, cancellation_rx) = watch::channel(false);
1215            let tool_event_stream = ToolCallEventStream::new(
1216                tool_use.id.clone(),
1217                stream.clone(),
1218                Some(self.project.read(cx).fs().clone()),
1219                cancellation_rx,
1220            );
1221            tool.replay(tool_use.input.clone(), output, tool_event_stream, cx)
1222                .log_err();
1223        }
1224
1225        stream.update_tool_call_fields(
1226            &tool_use.id,
1227            acp::ToolCallUpdateFields::new()
1228                .status(status)
1229                .raw_output(output),
1230            None,
1231        );
1232    }
1233
1234    pub fn from_db(
1235        id: acp::SessionId,
1236        db_thread: DbThread,
1237        project: Entity<Project>,
1238        project_context: Entity<ProjectContext>,
1239        context_server_registry: Entity<ContextServerRegistry>,
1240        templates: Arc<Templates>,
1241        cx: &mut Context<Self>,
1242    ) -> Self {
1243        let settings = AgentSettings::get_global(cx);
1244        let profile_id = db_thread
1245            .profile
1246            .unwrap_or_else(|| settings.default_profile.clone());
1247
1248        let mut model = LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1249            db_thread
1250                .model
1251                .and_then(|model| {
1252                    let model = SelectedModel {
1253                        provider: model.provider.clone().into(),
1254                        model: model.model.into(),
1255                    };
1256                    registry.select_model(&model, cx)
1257                })
1258                .or_else(|| registry.default_model())
1259                .map(|model| model.model)
1260        });
1261
1262        if model.is_none() {
1263            model = Self::resolve_profile_model(&profile_id, cx);
1264        }
1265        if model.is_none() {
1266            model = LanguageModelRegistry::global(cx).update(cx, |registry, _cx| {
1267                registry.default_model().map(|model| model.model)
1268            });
1269        }
1270
1271        let (prompt_capabilities_tx, prompt_capabilities_rx) =
1272            watch::channel(Self::prompt_capabilities(model.as_deref()));
1273
1274        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1275
1276        Self {
1277            id,
1278            prompt_id: PromptId::new(),
1279            title: if db_thread.title.is_empty() {
1280                None
1281            } else {
1282                Some(db_thread.title.clone())
1283            },
1284            pending_title_generation: None,
1285            pending_summary_generation: None,
1286            summary: db_thread.detailed_summary,
1287            messages: db_thread.messages,
1288            user_store: project.read(cx).user_store(),
1289            running_turn: None,
1290            has_queued_message: false,
1291            pending_message: None,
1292            tools: BTreeMap::default(),
1293            request_token_usage: db_thread.request_token_usage.clone(),
1294            cumulative_token_usage: db_thread.cumulative_token_usage,
1295            initial_project_snapshot: Task::ready(db_thread.initial_project_snapshot).shared(),
1296            context_server_registry,
1297            profile_id,
1298            project_context,
1299            templates,
1300            model,
1301            summarization_model: None,
1302            thinking_enabled: db_thread.thinking_enabled,
1303            thinking_effort: db_thread.thinking_effort,
1304            speed: db_thread.speed,
1305            project,
1306            action_log,
1307            updated_at: db_thread.updated_at,
1308            prompt_capabilities_tx,
1309            prompt_capabilities_rx,
1310            imported: db_thread.imported,
1311            subagent_context: db_thread.subagent_context,
1312            draft_prompt: db_thread.draft_prompt,
1313            ui_scroll_position: db_thread.ui_scroll_position.map(|sp| gpui::ListOffset {
1314                item_ix: sp.item_ix,
1315                offset_in_item: gpui::px(sp.offset_in_item),
1316            }),
1317            running_subagents: Vec::new(),
1318        }
1319    }
1320
1321    pub fn to_db(&self, cx: &App) -> Task<DbThread> {
1322        let initial_project_snapshot = self.initial_project_snapshot.clone();
1323        let mut thread = DbThread {
1324            title: self.title().unwrap_or_default(),
1325            messages: self.messages.clone(),
1326            updated_at: self.updated_at,
1327            detailed_summary: self.summary.clone(),
1328            initial_project_snapshot: None,
1329            cumulative_token_usage: self.cumulative_token_usage,
1330            request_token_usage: self.request_token_usage.clone(),
1331            model: self.model.as_ref().map(|model| DbLanguageModel {
1332                provider: model.provider_id().to_string(),
1333                model: model.id().0.to_string(),
1334            }),
1335            profile: Some(self.profile_id.clone()),
1336            imported: self.imported,
1337            subagent_context: self.subagent_context.clone(),
1338            speed: self.speed,
1339            thinking_enabled: self.thinking_enabled,
1340            thinking_effort: self.thinking_effort.clone(),
1341            draft_prompt: self.draft_prompt.clone(),
1342            ui_scroll_position: self.ui_scroll_position.map(|lo| {
1343                crate::db::SerializedScrollPosition {
1344                    item_ix: lo.item_ix,
1345                    offset_in_item: lo.offset_in_item.as_f32(),
1346                }
1347            }),
1348        };
1349
1350        cx.background_spawn(async move {
1351            let initial_project_snapshot = initial_project_snapshot.await;
1352            thread.initial_project_snapshot = initial_project_snapshot;
1353            thread
1354        })
1355    }
1356
1357    /// Create a snapshot of the current project state including git information and unsaved buffers.
1358    fn project_snapshot(
1359        project: Entity<Project>,
1360        cx: &mut Context<Self>,
1361    ) -> Task<Arc<ProjectSnapshot>> {
1362        let task = project::telemetry_snapshot::TelemetrySnapshot::new(&project, cx);
1363        cx.spawn(async move |_, _| {
1364            let snapshot = task.await;
1365
1366            Arc::new(ProjectSnapshot {
1367                worktree_snapshots: snapshot.worktree_snapshots,
1368                timestamp: Utc::now(),
1369            })
1370        })
1371    }
1372
1373    pub fn project_context(&self) -> &Entity<ProjectContext> {
1374        &self.project_context
1375    }
1376
1377    pub fn project(&self) -> &Entity<Project> {
1378        &self.project
1379    }
1380
1381    pub fn action_log(&self) -> &Entity<ActionLog> {
1382        &self.action_log
1383    }
1384
1385    pub fn is_empty(&self) -> bool {
1386        self.messages.is_empty() && self.title.is_none()
1387    }
1388
1389    pub fn draft_prompt(&self) -> Option<&[acp::ContentBlock]> {
1390        self.draft_prompt.as_deref()
1391    }
1392
1393    pub fn set_draft_prompt(&mut self, prompt: Option<Vec<acp::ContentBlock>>) {
1394        self.draft_prompt = prompt;
1395    }
1396
1397    pub fn ui_scroll_position(&self) -> Option<gpui::ListOffset> {
1398        self.ui_scroll_position
1399    }
1400
1401    pub fn set_ui_scroll_position(&mut self, position: Option<gpui::ListOffset>) {
1402        self.ui_scroll_position = position;
1403    }
1404
1405    pub fn model(&self) -> Option<&Arc<dyn LanguageModel>> {
1406        self.model.as_ref()
1407    }
1408
1409    pub fn set_model(&mut self, model: Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
1410        let old_usage = self.latest_token_usage();
1411        self.model = Some(model.clone());
1412        let new_caps = Self::prompt_capabilities(self.model.as_deref());
1413        let new_usage = self.latest_token_usage();
1414        if old_usage != new_usage {
1415            cx.emit(TokenUsageUpdated(new_usage));
1416        }
1417        self.prompt_capabilities_tx.send(new_caps).log_err();
1418
1419        for subagent in &self.running_subagents {
1420            subagent
1421                .update(cx, |thread, cx| thread.set_model(model.clone(), cx))
1422                .ok();
1423        }
1424
1425        cx.notify()
1426    }
1427
1428    pub fn summarization_model(&self) -> Option<&Arc<dyn LanguageModel>> {
1429        self.summarization_model.as_ref()
1430    }
1431
1432    pub fn set_summarization_model(
1433        &mut self,
1434        model: Option<Arc<dyn LanguageModel>>,
1435        cx: &mut Context<Self>,
1436    ) {
1437        self.summarization_model = model.clone();
1438
1439        for subagent in &self.running_subagents {
1440            subagent
1441                .update(cx, |thread, cx| {
1442                    thread.set_summarization_model(model.clone(), cx)
1443                })
1444                .ok();
1445        }
1446        cx.notify()
1447    }
1448
1449    pub fn thinking_enabled(&self) -> bool {
1450        self.thinking_enabled
1451    }
1452
1453    pub fn set_thinking_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
1454        self.thinking_enabled = enabled;
1455
1456        for subagent in &self.running_subagents {
1457            subagent
1458                .update(cx, |thread, cx| thread.set_thinking_enabled(enabled, cx))
1459                .ok();
1460        }
1461        cx.notify();
1462    }
1463
1464    pub fn thinking_effort(&self) -> Option<&String> {
1465        self.thinking_effort.as_ref()
1466    }
1467
1468    pub fn set_thinking_effort(&mut self, effort: Option<String>, cx: &mut Context<Self>) {
1469        self.thinking_effort = effort.clone();
1470
1471        for subagent in &self.running_subagents {
1472            subagent
1473                .update(cx, |thread, cx| {
1474                    thread.set_thinking_effort(effort.clone(), cx)
1475                })
1476                .ok();
1477        }
1478        cx.notify();
1479    }
1480
1481    pub fn speed(&self) -> Option<Speed> {
1482        self.speed
1483    }
1484
1485    pub fn set_speed(&mut self, speed: Speed, cx: &mut Context<Self>) {
1486        self.speed = Some(speed);
1487
1488        for subagent in &self.running_subagents {
1489            subagent
1490                .update(cx, |thread, cx| thread.set_speed(speed, cx))
1491                .ok();
1492        }
1493        cx.notify();
1494    }
1495
1496    pub fn last_message(&self) -> Option<&Message> {
1497        self.messages.last()
1498    }
1499
1500    #[cfg(any(test, feature = "test-support"))]
1501    pub fn last_received_or_pending_message(&self) -> Option<Message> {
1502        if let Some(message) = self.pending_message.clone() {
1503            Some(Message::Agent(message))
1504        } else {
1505            self.messages.last().cloned()
1506        }
1507    }
1508
1509    pub fn add_default_tools(
1510        &mut self,
1511        environment: Rc<dyn ThreadEnvironment>,
1512        cx: &mut Context<Self>,
1513    ) {
1514        // Only update the agent location for the root thread, not for subagents.
1515        let update_agent_location = self.parent_thread_id().is_none();
1516
1517        let language_registry = self.project.read(cx).languages().clone();
1518        self.add_tool(CopyPathTool::new(self.project.clone()));
1519        self.add_tool(CreateDirectoryTool::new(self.project.clone()));
1520        self.add_tool(DeletePathTool::new(
1521            self.project.clone(),
1522            self.action_log.clone(),
1523        ));
1524        self.add_tool(DiagnosticsTool::new(self.project.clone()));
1525        self.add_tool(EditFileTool::new(
1526            self.project.clone(),
1527            cx.weak_entity(),
1528            language_registry.clone(),
1529            Templates::new(),
1530        ));
1531        self.add_tool(StreamingEditFileTool::new(
1532            self.project.clone(),
1533            cx.weak_entity(),
1534            self.action_log.clone(),
1535            language_registry,
1536        ));
1537        self.add_tool(FetchTool::new(self.project.read(cx).client().http_client()));
1538        self.add_tool(FindPathTool::new(self.project.clone()));
1539        self.add_tool(GrepTool::new(self.project.clone()));
1540        self.add_tool(ListDirectoryTool::new(self.project.clone()));
1541        self.add_tool(MovePathTool::new(self.project.clone()));
1542        self.add_tool(NowTool);
1543        self.add_tool(OpenTool::new(self.project.clone()));
1544        if cx.has_flag::<UpdatePlanToolFeatureFlag>() {
1545            self.add_tool(UpdatePlanTool);
1546        }
1547        self.add_tool(ReadFileTool::new(
1548            self.project.clone(),
1549            self.action_log.clone(),
1550            update_agent_location,
1551        ));
1552        self.add_tool(SaveFileTool::new(self.project.clone()));
1553        self.add_tool(RestoreFileFromDiskTool::new(self.project.clone()));
1554        self.add_tool(TerminalTool::new(self.project.clone(), environment.clone()));
1555        self.add_tool(WebSearchTool);
1556
1557        if self.depth() < MAX_SUBAGENT_DEPTH {
1558            self.add_tool(SpawnAgentTool::new(environment));
1559        }
1560    }
1561
1562    pub fn add_tool<T: AgentTool>(&mut self, tool: T) {
1563        debug_assert!(
1564            !self.tools.contains_key(T::NAME),
1565            "Duplicate tool name: {}",
1566            T::NAME,
1567        );
1568        self.tools.insert(T::NAME.into(), tool.erase());
1569    }
1570
1571    #[cfg(any(test, feature = "test-support"))]
1572    pub fn remove_tool(&mut self, name: &str) -> bool {
1573        self.tools.remove(name).is_some()
1574    }
1575
1576    pub fn profile(&self) -> &AgentProfileId {
1577        &self.profile_id
1578    }
1579
1580    pub fn set_profile(&mut self, profile_id: AgentProfileId, cx: &mut Context<Self>) {
1581        if self.profile_id == profile_id {
1582            return;
1583        }
1584
1585        self.profile_id = profile_id.clone();
1586
1587        // Swap to the profile's preferred model when available.
1588        if let Some(model) = Self::resolve_profile_model(&self.profile_id, cx) {
1589            self.set_model(model, cx);
1590        }
1591
1592        for subagent in &self.running_subagents {
1593            subagent
1594                .update(cx, |thread, cx| thread.set_profile(profile_id.clone(), cx))
1595                .ok();
1596        }
1597    }
1598
1599    pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
1600        for subagent in self.running_subagents.drain(..) {
1601            if let Some(subagent) = subagent.upgrade() {
1602                subagent.update(cx, |thread, cx| thread.cancel(cx)).detach();
1603            }
1604        }
1605
1606        let Some(running_turn) = self.running_turn.take() else {
1607            self.flush_pending_message(cx);
1608            return Task::ready(());
1609        };
1610
1611        let turn_task = running_turn.cancel();
1612
1613        cx.spawn(async move |this, cx| {
1614            turn_task.await;
1615            this.update(cx, |this, cx| {
1616                this.flush_pending_message(cx);
1617            })
1618            .ok();
1619        })
1620    }
1621
1622    pub fn set_has_queued_message(&mut self, has_queued: bool) {
1623        self.has_queued_message = has_queued;
1624    }
1625
1626    pub fn has_queued_message(&self) -> bool {
1627        self.has_queued_message
1628    }
1629
1630    fn update_token_usage(&mut self, update: language_model::TokenUsage, cx: &mut Context<Self>) {
1631        let Some(last_user_message) = self.last_user_message() else {
1632            return;
1633        };
1634
1635        self.request_token_usage
1636            .insert(last_user_message.id.clone(), update);
1637        cx.emit(TokenUsageUpdated(self.latest_token_usage()));
1638        cx.notify();
1639    }
1640
1641    pub fn truncate(&mut self, message_id: UserMessageId, cx: &mut Context<Self>) -> Result<()> {
1642        self.cancel(cx).detach();
1643        // Clear pending message since cancel will try to flush it asynchronously,
1644        // and we don't want that content to be added after we truncate
1645        self.pending_message.take();
1646        let Some(position) = self.messages.iter().position(
1647            |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
1648        ) else {
1649            return Err(anyhow!("Message not found"));
1650        };
1651
1652        for message in self.messages.drain(position..) {
1653            match message {
1654                Message::User(message) => {
1655                    self.request_token_usage.remove(&message.id);
1656                }
1657                Message::Agent(_) | Message::Resume => {}
1658            }
1659        }
1660        self.clear_summary();
1661        cx.notify();
1662        Ok(())
1663    }
1664
1665    pub fn latest_request_token_usage(&self) -> Option<language_model::TokenUsage> {
1666        let last_user_message = self.last_user_message()?;
1667        let tokens = self.request_token_usage.get(&last_user_message.id)?;
1668        Some(*tokens)
1669    }
1670
1671    pub fn latest_token_usage(&self) -> Option<acp_thread::TokenUsage> {
1672        let usage = self.latest_request_token_usage()?;
1673        let model = self.model.clone()?;
1674        Some(acp_thread::TokenUsage {
1675            max_tokens: model.max_token_count(),
1676            max_output_tokens: model.max_output_tokens(),
1677            used_tokens: usage.total_tokens(),
1678            input_tokens: usage.input_tokens,
1679            output_tokens: usage.output_tokens,
1680        })
1681    }
1682
1683    /// Get the total input token count as of the message before the given message.
1684    ///
1685    /// Returns `None` if:
1686    /// - `target_id` is the first message (no previous message)
1687    /// - The previous message hasn't received a response yet (no usage data)
1688    /// - `target_id` is not found in the messages
1689    pub fn tokens_before_message(&self, target_id: &UserMessageId) -> Option<u64> {
1690        let mut previous_user_message_id: Option<&UserMessageId> = None;
1691
1692        for message in &self.messages {
1693            if let Message::User(user_msg) = message {
1694                if &user_msg.id == target_id {
1695                    let prev_id = previous_user_message_id?;
1696                    let usage = self.request_token_usage.get(prev_id)?;
1697                    return Some(usage.input_tokens);
1698                }
1699                previous_user_message_id = Some(&user_msg.id);
1700            }
1701        }
1702        None
1703    }
1704
1705    /// Look up the active profile and resolve its preferred model if one is configured.
1706    fn resolve_profile_model(
1707        profile_id: &AgentProfileId,
1708        cx: &mut Context<Self>,
1709    ) -> Option<Arc<dyn LanguageModel>> {
1710        let selection = AgentSettings::get_global(cx)
1711            .profiles
1712            .get(profile_id)?
1713            .default_model
1714            .clone()?;
1715        Self::resolve_model_from_selection(&selection, cx)
1716    }
1717
1718    /// Translate a stored model selection into the configured model from the registry.
1719    fn resolve_model_from_selection(
1720        selection: &LanguageModelSelection,
1721        cx: &mut Context<Self>,
1722    ) -> Option<Arc<dyn LanguageModel>> {
1723        let selected = SelectedModel {
1724            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
1725            model: LanguageModelId::from(selection.model.clone()),
1726        };
1727        LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1728            registry
1729                .select_model(&selected, cx)
1730                .map(|configured| configured.model)
1731        })
1732    }
1733
1734    pub fn resume(
1735        &mut self,
1736        cx: &mut Context<Self>,
1737    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1738        self.messages.push(Message::Resume);
1739        cx.notify();
1740
1741        log::debug!("Total messages in thread: {}", self.messages.len());
1742        self.run_turn(cx)
1743    }
1744
1745    /// Sending a message results in the model streaming a response, which could include tool calls.
1746    /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
1747    /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
1748    pub fn send<T>(
1749        &mut self,
1750        id: UserMessageId,
1751        content: impl IntoIterator<Item = T>,
1752        cx: &mut Context<Self>,
1753    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
1754    where
1755        T: Into<UserMessageContent>,
1756    {
1757        let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
1758        log::debug!("Thread::send content: {:?}", content);
1759
1760        self.messages
1761            .push(Message::User(UserMessage { id, content }));
1762        cx.notify();
1763
1764        self.send_existing(cx)
1765    }
1766
1767    pub fn send_existing(
1768        &mut self,
1769        cx: &mut Context<Self>,
1770    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1771        let model = self.model().context("No language model configured")?;
1772
1773        log::info!("Thread::send called with model: {}", model.name().0);
1774        self.advance_prompt_id();
1775
1776        log::debug!("Total messages in thread: {}", self.messages.len());
1777        self.run_turn(cx)
1778    }
1779
1780    pub fn push_acp_user_block(
1781        &mut self,
1782        id: UserMessageId,
1783        blocks: impl IntoIterator<Item = acp::ContentBlock>,
1784        path_style: PathStyle,
1785        cx: &mut Context<Self>,
1786    ) {
1787        let content = blocks
1788            .into_iter()
1789            .map(|block| UserMessageContent::from_content_block(block, path_style))
1790            .collect::<Vec<_>>();
1791        self.messages
1792            .push(Message::User(UserMessage { id, content }));
1793        cx.notify();
1794    }
1795
1796    pub fn push_acp_agent_block(&mut self, block: acp::ContentBlock, cx: &mut Context<Self>) {
1797        let text = match block {
1798            acp::ContentBlock::Text(text_content) => text_content.text,
1799            acp::ContentBlock::Image(_) => "[image]".to_string(),
1800            acp::ContentBlock::Audio(_) => "[audio]".to_string(),
1801            acp::ContentBlock::ResourceLink(resource_link) => resource_link.uri,
1802            acp::ContentBlock::Resource(resource) => match resource.resource {
1803                acp::EmbeddedResourceResource::TextResourceContents(resource) => resource.uri,
1804                acp::EmbeddedResourceResource::BlobResourceContents(resource) => resource.uri,
1805                _ => "[resource]".to_string(),
1806            },
1807            _ => "[unknown]".to_string(),
1808        };
1809
1810        self.messages.push(Message::Agent(AgentMessage {
1811            content: vec![AgentMessageContent::Text(text)],
1812            ..Default::default()
1813        }));
1814        cx.notify();
1815    }
1816
1817    fn run_turn(
1818        &mut self,
1819        cx: &mut Context<Self>,
1820    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1821        // Flush the old pending message synchronously before cancelling,
1822        // to avoid a race where the detached cancel task might flush the NEW
1823        // turn's pending message instead of the old one.
1824        self.flush_pending_message(cx);
1825        self.cancel(cx).detach();
1826
1827        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1828        let event_stream = ThreadEventStream(events_tx);
1829        let message_ix = self.messages.len().saturating_sub(1);
1830        self.clear_summary();
1831        let (cancellation_tx, mut cancellation_rx) = watch::channel(false);
1832        self.running_turn = Some(RunningTurn {
1833            event_stream: event_stream.clone(),
1834            tools: self.enabled_tools(cx),
1835            cancellation_tx,
1836            streaming_tool_inputs: HashMap::default(),
1837            _task: cx.spawn(async move |this, cx| {
1838                log::debug!("Starting agent turn execution");
1839
1840                let turn_result =
1841                    Self::run_turn_internal(&this, &event_stream, cancellation_rx.clone(), cx)
1842                        .await;
1843
1844                // Check if we were cancelled - if so, cancel() already took running_turn
1845                // and we shouldn't touch it (it might be a NEW turn now)
1846                let was_cancelled = *cancellation_rx.borrow();
1847                if was_cancelled {
1848                    log::debug!("Turn was cancelled, skipping cleanup");
1849                    return;
1850                }
1851
1852                _ = this.update(cx, |this, cx| this.flush_pending_message(cx));
1853
1854                match turn_result {
1855                    Ok(()) => {
1856                        log::debug!("Turn execution completed");
1857                        event_stream.send_stop(acp::StopReason::EndTurn);
1858                    }
1859                    Err(error) => {
1860                        log::error!("Turn execution failed: {:?}", error);
1861                        match error.downcast::<CompletionError>() {
1862                            Ok(CompletionError::Refusal) => {
1863                                event_stream.send_stop(acp::StopReason::Refusal);
1864                                _ = this.update(cx, |this, _| this.messages.truncate(message_ix));
1865                            }
1866                            Ok(CompletionError::MaxTokens) => {
1867                                event_stream.send_stop(acp::StopReason::MaxTokens);
1868                            }
1869                            Ok(CompletionError::Other(error)) | Err(error) => {
1870                                event_stream.send_error(error);
1871                            }
1872                        }
1873                    }
1874                }
1875
1876                _ = this.update(cx, |this, _| this.running_turn.take());
1877            }),
1878        });
1879        Ok(events_rx)
1880    }
1881
1882    async fn run_turn_internal(
1883        this: &WeakEntity<Self>,
1884        event_stream: &ThreadEventStream,
1885        mut cancellation_rx: watch::Receiver<bool>,
1886        cx: &mut AsyncApp,
1887    ) -> Result<()> {
1888        let mut attempt = 0;
1889        let mut intent = CompletionIntent::UserPrompt;
1890        loop {
1891            // Re-read the model and refresh tools on each iteration so that
1892            // mid-turn changes (e.g. the user switches model, toggles tools,
1893            // or changes profile) take effect between tool-call rounds.
1894            let (model, request) = this.update(cx, |this, cx| {
1895                let model = this.model.clone().context("No language model configured")?;
1896                this.refresh_turn_tools(cx);
1897                let request = this.build_completion_request(intent, cx)?;
1898                anyhow::Ok((model, request))
1899            })??;
1900
1901            telemetry::event!(
1902                "Agent Thread Completion",
1903                thread_id = this.read_with(cx, |this, _| this.id.to_string())?,
1904                parent_thread_id = this.read_with(cx, |this, _| this
1905                    .parent_thread_id()
1906                    .map(|id| id.to_string()))?,
1907                prompt_id = this.read_with(cx, |this, _| this.prompt_id.to_string())?,
1908                model = model.telemetry_id(),
1909                model_provider = model.provider_id().to_string(),
1910                attempt
1911            );
1912
1913            log::debug!("Calling model.stream_completion, attempt {}", attempt);
1914
1915            let (mut events, mut error) = match model.stream_completion(request, cx).await {
1916                Ok(events) => (events.fuse(), None),
1917                Err(err) => (stream::empty().boxed().fuse(), Some(err)),
1918            };
1919            let mut tool_results: FuturesUnordered<Task<LanguageModelToolResult>> =
1920                FuturesUnordered::new();
1921            let mut early_tool_results: Vec<LanguageModelToolResult> = Vec::new();
1922            let mut cancelled = false;
1923            loop {
1924                // Race between getting the first event, tool completion, and cancellation.
1925                let first_event = futures::select! {
1926                    event = events.next().fuse() => event,
1927                    tool_result = futures::StreamExt::select_next_some(&mut tool_results) => {
1928                        let is_error = tool_result.is_error;
1929                        let is_still_streaming = this
1930                            .read_with(cx, |this, _cx| {
1931                                this.running_turn
1932                                    .as_ref()
1933                                    .and_then(|turn| turn.streaming_tool_inputs.get(&tool_result.tool_use_id))
1934                                    .map_or(false, |inputs| !inputs.has_received_final())
1935                            })
1936                            .unwrap_or(false);
1937
1938                        early_tool_results.push(tool_result);
1939
1940                        // Only break if the tool errored and we are still
1941                        // streaming the input of the tool. If the tool errored
1942                        // but we are no longer streaming its input (i.e. there
1943                        // are parallel tool calls) we want to continue
1944                        // processing those tool inputs.
1945                        if is_error && is_still_streaming {
1946                            break;
1947                        }
1948                        continue;
1949                    }
1950                    _ = cancellation_rx.changed().fuse() => {
1951                        if *cancellation_rx.borrow() {
1952                            cancelled = true;
1953                            break;
1954                        }
1955                        continue;
1956                    }
1957                };
1958                let Some(first_event) = first_event else {
1959                    break;
1960                };
1961
1962                // Collect all immediately available events to process as a batch
1963                let mut batch = vec![first_event];
1964                while let Some(event) = events.next().now_or_never().flatten() {
1965                    batch.push(event);
1966                }
1967
1968                // Process the batch in a single update
1969                let batch_result = this.update(cx, |this, cx| {
1970                    let mut batch_tool_results = Vec::new();
1971                    let mut batch_error = None;
1972
1973                    for event in batch {
1974                        log::trace!("Received completion event: {:?}", event);
1975                        match event {
1976                            Ok(event) => {
1977                                match this.handle_completion_event(
1978                                    event,
1979                                    event_stream,
1980                                    cancellation_rx.clone(),
1981                                    cx,
1982                                ) {
1983                                    Ok(Some(task)) => batch_tool_results.push(task),
1984                                    Ok(None) => {}
1985                                    Err(err) => {
1986                                        batch_error = Some(err);
1987                                        break;
1988                                    }
1989                                }
1990                            }
1991                            Err(err) => {
1992                                batch_error = Some(err.into());
1993                                break;
1994                            }
1995                        }
1996                    }
1997
1998                    cx.notify();
1999                    (batch_tool_results, batch_error)
2000                })?;
2001
2002                tool_results.extend(batch_result.0);
2003                if let Some(err) = batch_result.1 {
2004                    error = Some(err.downcast()?);
2005                    break;
2006                }
2007            }
2008
2009            // Drop the stream to release the rate limit permit before tool execution.
2010            // The stream holds a semaphore guard that limits concurrent requests.
2011            // Without this, the permit would be held during potentially long-running
2012            // tool execution, which could cause deadlocks when tools spawn subagents
2013            // that need their own permits.
2014            drop(events);
2015
2016            // Drop streaming tool input senders that never received their final input.
2017            // This prevents deadlock when the LLM stream ends (e.g. because of an error)
2018            // before sending a tool use with `is_input_complete: true`.
2019            this.update(cx, |this, _cx| {
2020                if let Some(running_turn) = this.running_turn.as_mut() {
2021                    if running_turn.streaming_tool_inputs.is_empty() {
2022                        return;
2023                    }
2024                    log::warn!("Dropping partial tool inputs because the stream ended");
2025                    running_turn.streaming_tool_inputs.drain();
2026                }
2027            })?;
2028
2029            let end_turn = tool_results.is_empty() && early_tool_results.is_empty();
2030
2031            for tool_result in early_tool_results {
2032                Self::process_tool_result(this, event_stream, cx, tool_result)?;
2033            }
2034            while let Some(tool_result) = tool_results.next().await {
2035                Self::process_tool_result(this, event_stream, cx, tool_result)?;
2036            }
2037
2038            this.update(cx, |this, cx| {
2039                this.flush_pending_message(cx);
2040                if this.title.is_none() && this.pending_title_generation.is_none() {
2041                    this.generate_title(cx);
2042                }
2043            })?;
2044
2045            if cancelled {
2046                log::debug!("Turn cancelled by user, exiting");
2047                return Ok(());
2048            }
2049
2050            if let Some(error) = error {
2051                attempt += 1;
2052                let retry = this.update(cx, |this, cx| {
2053                    let user_store = this.user_store.read(cx);
2054                    this.handle_completion_error(error, attempt, user_store.plan())
2055                })??;
2056                let timer = cx.background_executor().timer(retry.duration);
2057                event_stream.send_retry(retry);
2058                futures::select! {
2059                    _ = timer.fuse() => {}
2060                    _ = cancellation_rx.changed().fuse() => {
2061                        if *cancellation_rx.borrow() {
2062                            log::debug!("Turn cancelled during retry delay, exiting");
2063                            return Ok(());
2064                        }
2065                    }
2066                }
2067                this.update(cx, |this, _cx| {
2068                    if let Some(Message::Agent(message)) = this.messages.last() {
2069                        if message.tool_results.is_empty() {
2070                            intent = CompletionIntent::UserPrompt;
2071                            this.messages.push(Message::Resume);
2072                        }
2073                    }
2074                })?;
2075            } else if end_turn {
2076                return Ok(());
2077            } else {
2078                let has_queued = this.update(cx, |this, _| this.has_queued_message())?;
2079                if has_queued {
2080                    log::debug!("Queued message found, ending turn at message boundary");
2081                    return Ok(());
2082                }
2083                intent = CompletionIntent::ToolResults;
2084                attempt = 0;
2085            }
2086        }
2087    }
2088
2089    fn process_tool_result(
2090        this: &WeakEntity<Thread>,
2091        event_stream: &ThreadEventStream,
2092        cx: &mut AsyncApp,
2093        tool_result: LanguageModelToolResult,
2094    ) -> Result<(), anyhow::Error> {
2095        log::debug!("Tool finished {:?}", tool_result);
2096
2097        event_stream.update_tool_call_fields(
2098            &tool_result.tool_use_id,
2099            acp::ToolCallUpdateFields::new()
2100                .status(if tool_result.is_error {
2101                    acp::ToolCallStatus::Failed
2102                } else {
2103                    acp::ToolCallStatus::Completed
2104                })
2105                .raw_output(tool_result.output.clone()),
2106            None,
2107        );
2108        this.update(cx, |this, _cx| {
2109            this.pending_message()
2110                .tool_results
2111                .insert(tool_result.tool_use_id.clone(), tool_result)
2112        })?;
2113        Ok(())
2114    }
2115
2116    fn handle_completion_error(
2117        &mut self,
2118        error: LanguageModelCompletionError,
2119        attempt: u8,
2120        plan: Option<Plan>,
2121    ) -> Result<acp_thread::RetryStatus> {
2122        let Some(model) = self.model.as_ref() else {
2123            return Err(anyhow!(error));
2124        };
2125
2126        let auto_retry = if model.provider_id() == ZED_CLOUD_PROVIDER_ID {
2127            plan.is_some()
2128        } else {
2129            true
2130        };
2131
2132        if !auto_retry {
2133            return Err(anyhow!(error));
2134        }
2135
2136        let Some(strategy) = Self::retry_strategy_for(&error) else {
2137            return Err(anyhow!(error));
2138        };
2139
2140        let max_attempts = match &strategy {
2141            RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
2142            RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
2143        };
2144
2145        if attempt > max_attempts {
2146            return Err(anyhow!(error));
2147        }
2148
2149        let delay = match &strategy {
2150            RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
2151                let delay_secs = initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
2152                Duration::from_secs(delay_secs)
2153            }
2154            RetryStrategy::Fixed { delay, .. } => *delay,
2155        };
2156        log::debug!("Retry attempt {attempt} with delay {delay:?}");
2157
2158        Ok(acp_thread::RetryStatus {
2159            last_error: error.to_string().into(),
2160            attempt: attempt as usize,
2161            max_attempts: max_attempts as usize,
2162            started_at: Instant::now(),
2163            duration: delay,
2164        })
2165    }
2166
2167    /// A helper method that's called on every streamed completion event.
2168    /// Returns an optional tool result task, which the main agentic loop will
2169    /// send back to the model when it resolves.
2170    fn handle_completion_event(
2171        &mut self,
2172        event: LanguageModelCompletionEvent,
2173        event_stream: &ThreadEventStream,
2174        cancellation_rx: watch::Receiver<bool>,
2175        cx: &mut Context<Self>,
2176    ) -> Result<Option<Task<LanguageModelToolResult>>> {
2177        log::trace!("Handling streamed completion event: {:?}", event);
2178        use LanguageModelCompletionEvent::*;
2179
2180        match event {
2181            StartMessage { .. } => {
2182                self.flush_pending_message(cx);
2183                self.pending_message = Some(AgentMessage::default());
2184            }
2185            Text(new_text) => self.handle_text_event(new_text, event_stream),
2186            Thinking { text, signature } => {
2187                self.handle_thinking_event(text, signature, event_stream)
2188            }
2189            RedactedThinking { data } => self.handle_redacted_thinking_event(data),
2190            ReasoningDetails(details) => {
2191                let last_message = self.pending_message();
2192                // Store the last non-empty reasoning_details (overwrites earlier ones)
2193                // This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
2194                if let serde_json::Value::Array(ref arr) = details {
2195                    if !arr.is_empty() {
2196                        last_message.reasoning_details = Some(details);
2197                    }
2198                } else {
2199                    last_message.reasoning_details = Some(details);
2200                }
2201            }
2202            ToolUse(tool_use) => {
2203                return Ok(self.handle_tool_use_event(tool_use, event_stream, cancellation_rx, cx));
2204            }
2205            ToolUseJsonParseError {
2206                id,
2207                tool_name,
2208                raw_input,
2209                json_parse_error,
2210            } => {
2211                return Ok(self.handle_tool_use_json_parse_error_event(
2212                    id,
2213                    tool_name,
2214                    raw_input,
2215                    json_parse_error,
2216                    event_stream,
2217                    cancellation_rx,
2218                    cx,
2219                ));
2220            }
2221            UsageUpdate(usage) => {
2222                telemetry::event!(
2223                    "Agent Thread Completion Usage Updated",
2224                    thread_id = self.id.to_string(),
2225                    parent_thread_id = self.parent_thread_id().map(|id| id.to_string()),
2226                    prompt_id = self.prompt_id.to_string(),
2227                    model = self.model.as_ref().map(|m| m.telemetry_id()),
2228                    model_provider = self.model.as_ref().map(|m| m.provider_id().to_string()),
2229                    input_tokens = usage.input_tokens,
2230                    output_tokens = usage.output_tokens,
2231                    cache_creation_input_tokens = usage.cache_creation_input_tokens,
2232                    cache_read_input_tokens = usage.cache_read_input_tokens,
2233                );
2234                self.update_token_usage(usage, cx);
2235            }
2236            Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()),
2237            Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()),
2238            Stop(StopReason::ToolUse | StopReason::EndTurn) => {}
2239            Started | Queued { .. } => {}
2240        }
2241
2242        Ok(None)
2243    }
2244
2245    fn handle_text_event(&mut self, new_text: String, event_stream: &ThreadEventStream) {
2246        event_stream.send_text(&new_text);
2247
2248        let last_message = self.pending_message();
2249        if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
2250            text.push_str(&new_text);
2251        } else {
2252            last_message
2253                .content
2254                .push(AgentMessageContent::Text(new_text));
2255        }
2256    }
2257
2258    fn handle_thinking_event(
2259        &mut self,
2260        new_text: String,
2261        new_signature: Option<String>,
2262        event_stream: &ThreadEventStream,
2263    ) {
2264        event_stream.send_thinking(&new_text);
2265
2266        let last_message = self.pending_message();
2267        if let Some(AgentMessageContent::Thinking { text, signature }) =
2268            last_message.content.last_mut()
2269        {
2270            text.push_str(&new_text);
2271            *signature = new_signature.or(signature.take());
2272        } else {
2273            last_message.content.push(AgentMessageContent::Thinking {
2274                text: new_text,
2275                signature: new_signature,
2276            });
2277        }
2278    }
2279
2280    fn handle_redacted_thinking_event(&mut self, data: String) {
2281        let last_message = self.pending_message();
2282        last_message
2283            .content
2284            .push(AgentMessageContent::RedactedThinking(data));
2285    }
2286
2287    fn handle_tool_use_event(
2288        &mut self,
2289        tool_use: LanguageModelToolUse,
2290        event_stream: &ThreadEventStream,
2291        cancellation_rx: watch::Receiver<bool>,
2292        cx: &mut Context<Self>,
2293    ) -> Option<Task<LanguageModelToolResult>> {
2294        cx.notify();
2295
2296        let tool = self.tool(tool_use.name.as_ref());
2297        let mut title = SharedString::from(&tool_use.name);
2298        let mut kind = acp::ToolKind::Other;
2299        if let Some(tool) = tool.as_ref() {
2300            title = tool.initial_title(tool_use.input.clone(), cx);
2301            kind = tool.kind();
2302        }
2303
2304        self.send_or_update_tool_use(&tool_use, title, kind, event_stream);
2305
2306        let Some(tool) = tool else {
2307            let content = format!("No tool named {} exists", tool_use.name);
2308            return Some(Task::ready(LanguageModelToolResult {
2309                content: LanguageModelToolResultContent::Text(Arc::from(content)),
2310                tool_use_id: tool_use.id,
2311                tool_name: tool_use.name,
2312                is_error: true,
2313                output: None,
2314            }));
2315        };
2316
2317        if !tool_use.is_input_complete {
2318            if tool.supports_input_streaming() {
2319                let running_turn = self.running_turn.as_mut()?;
2320                if let Some(sender) = running_turn.streaming_tool_inputs.get_mut(&tool_use.id) {
2321                    sender.send_partial(tool_use.input);
2322                    return None;
2323                }
2324
2325                let (mut sender, tool_input) = ToolInputSender::channel();
2326                sender.send_partial(tool_use.input);
2327                running_turn
2328                    .streaming_tool_inputs
2329                    .insert(tool_use.id.clone(), sender);
2330
2331                let tool = tool.clone();
2332                log::debug!("Running streaming tool {}", tool_use.name);
2333                return Some(self.run_tool(
2334                    tool,
2335                    tool_input,
2336                    tool_use.id,
2337                    tool_use.name,
2338                    event_stream,
2339                    cancellation_rx,
2340                    cx,
2341                ));
2342            } else {
2343                return None;
2344            }
2345        }
2346
2347        if let Some(mut sender) = self
2348            .running_turn
2349            .as_mut()?
2350            .streaming_tool_inputs
2351            .remove(&tool_use.id)
2352        {
2353            sender.send_full(tool_use.input);
2354            return None;
2355        }
2356
2357        log::debug!("Running tool {}", tool_use.name);
2358        let tool_input = ToolInput::ready(tool_use.input);
2359        Some(self.run_tool(
2360            tool,
2361            tool_input,
2362            tool_use.id,
2363            tool_use.name,
2364            event_stream,
2365            cancellation_rx,
2366            cx,
2367        ))
2368    }
2369
2370    fn run_tool(
2371        &self,
2372        tool: Arc<dyn AnyAgentTool>,
2373        tool_input: ToolInput<serde_json::Value>,
2374        tool_use_id: LanguageModelToolUseId,
2375        tool_name: Arc<str>,
2376        event_stream: &ThreadEventStream,
2377        cancellation_rx: watch::Receiver<bool>,
2378        cx: &mut Context<Self>,
2379    ) -> Task<LanguageModelToolResult> {
2380        let fs = self.project.read(cx).fs().clone();
2381        let tool_event_stream = ToolCallEventStream::new(
2382            tool_use_id.clone(),
2383            event_stream.clone(),
2384            Some(fs),
2385            cancellation_rx,
2386        );
2387        tool_event_stream.update_fields(
2388            acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
2389        );
2390        let supports_images = self.model().is_some_and(|model| model.supports_images());
2391        let tool_result = tool.run(tool_input, tool_event_stream, cx);
2392        cx.foreground_executor().spawn(async move {
2393            let (is_error, output) = match tool_result.await {
2394                Ok(mut output) => {
2395                    if let LanguageModelToolResultContent::Image(_) = &output.llm_output
2396                        && !supports_images
2397                    {
2398                        output = AgentToolOutput::from_error(
2399                            "Attempted to read an image, but this model doesn't support it.",
2400                        );
2401                        (true, output)
2402                    } else {
2403                        (false, output)
2404                    }
2405                }
2406                Err(output) => (true, output),
2407            };
2408
2409            LanguageModelToolResult {
2410                tool_use_id,
2411                tool_name,
2412                is_error,
2413                content: output.llm_output,
2414                output: Some(output.raw_output),
2415            }
2416        })
2417    }
2418
2419    fn handle_tool_use_json_parse_error_event(
2420        &mut self,
2421        tool_use_id: LanguageModelToolUseId,
2422        tool_name: Arc<str>,
2423        raw_input: Arc<str>,
2424        json_parse_error: String,
2425        event_stream: &ThreadEventStream,
2426        cancellation_rx: watch::Receiver<bool>,
2427        cx: &mut Context<Self>,
2428    ) -> Option<Task<LanguageModelToolResult>> {
2429        let tool_use = LanguageModelToolUse {
2430            id: tool_use_id,
2431            name: tool_name,
2432            raw_input: raw_input.to_string(),
2433            input: serde_json::json!({}),
2434            is_input_complete: true,
2435            thought_signature: None,
2436        };
2437        self.send_or_update_tool_use(
2438            &tool_use,
2439            SharedString::from(&tool_use.name),
2440            acp::ToolKind::Other,
2441            event_stream,
2442        );
2443
2444        let tool = self.tool(tool_use.name.as_ref());
2445
2446        let Some(tool) = tool else {
2447            let content = format!("No tool named {} exists", tool_use.name);
2448            return Some(Task::ready(LanguageModelToolResult {
2449                content: LanguageModelToolResultContent::Text(Arc::from(content)),
2450                tool_use_id: tool_use.id,
2451                tool_name: tool_use.name,
2452                is_error: true,
2453                output: None,
2454            }));
2455        };
2456
2457        let error_message = format!("Error parsing input JSON: {json_parse_error}");
2458
2459        if tool.supports_input_streaming()
2460            && let Some(mut sender) = self
2461                .running_turn
2462                .as_mut()?
2463                .streaming_tool_inputs
2464                .remove(&tool_use.id)
2465        {
2466            sender.send_invalid_json(error_message);
2467            return None;
2468        }
2469
2470        log::debug!("Running tool {}. Received invalid JSON", tool_use.name);
2471        let tool_input = ToolInput::invalid_json(error_message);
2472        Some(self.run_tool(
2473            tool,
2474            tool_input,
2475            tool_use.id,
2476            tool_use.name,
2477            event_stream,
2478            cancellation_rx,
2479            cx,
2480        ))
2481    }
2482
2483    fn send_or_update_tool_use(
2484        &mut self,
2485        tool_use: &LanguageModelToolUse,
2486        title: SharedString,
2487        kind: acp::ToolKind,
2488        event_stream: &ThreadEventStream,
2489    ) {
2490        // Ensure the last message ends in the current tool use
2491        let last_message = self.pending_message();
2492
2493        let has_tool_use = last_message.content.iter_mut().rev().any(|content| {
2494            if let AgentMessageContent::ToolUse(last_tool_use) = content {
2495                if last_tool_use.id == tool_use.id {
2496                    *last_tool_use = tool_use.clone();
2497                    return true;
2498                }
2499            }
2500            false
2501        });
2502
2503        if !has_tool_use {
2504            event_stream.send_tool_call(
2505                &tool_use.id,
2506                &tool_use.name,
2507                title,
2508                kind,
2509                tool_use.input.clone(),
2510            );
2511            last_message
2512                .content
2513                .push(AgentMessageContent::ToolUse(tool_use.clone()));
2514        } else {
2515            event_stream.update_tool_call_fields(
2516                &tool_use.id,
2517                acp::ToolCallUpdateFields::new()
2518                    .title(title.as_str())
2519                    .kind(kind)
2520                    .raw_input(tool_use.input.clone()),
2521                None,
2522            );
2523        }
2524    }
2525
2526    pub fn title(&self) -> Option<SharedString> {
2527        self.title.clone()
2528    }
2529
2530    pub fn is_generating_summary(&self) -> bool {
2531        self.pending_summary_generation.is_some()
2532    }
2533
2534    pub fn is_generating_title(&self) -> bool {
2535        self.pending_title_generation.is_some()
2536    }
2537
2538    pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
2539        if let Some(summary) = self.summary.as_ref() {
2540            return Task::ready(Some(summary.clone())).shared();
2541        }
2542        if let Some(task) = self.pending_summary_generation.clone() {
2543            return task;
2544        }
2545        let Some(model) = self.summarization_model.clone() else {
2546            log::error!("No summarization model available");
2547            return Task::ready(None).shared();
2548        };
2549        let mut request = LanguageModelRequest {
2550            intent: Some(CompletionIntent::ThreadContextSummarization),
2551            temperature: AgentSettings::temperature_for_model(&model, cx),
2552            ..Default::default()
2553        };
2554
2555        for message in &self.messages {
2556            request.messages.extend(message.to_request());
2557        }
2558
2559        request.messages.push(LanguageModelRequestMessage {
2560            role: Role::User,
2561            content: vec![SUMMARIZE_THREAD_DETAILED_PROMPT.into()],
2562            cache: false,
2563            reasoning_details: None,
2564        });
2565
2566        let task = cx
2567            .spawn(async move |this, cx| {
2568                let mut summary = String::new();
2569                let mut messages = model.stream_completion(request, cx).await.log_err()?;
2570                while let Some(event) = messages.next().await {
2571                    let event = event.log_err()?;
2572                    let text = match event {
2573                        LanguageModelCompletionEvent::Text(text) => text,
2574                        _ => continue,
2575                    };
2576
2577                    let mut lines = text.lines();
2578                    summary.extend(lines.next());
2579                }
2580
2581                log::debug!("Setting summary: {}", summary);
2582                let summary = SharedString::from(summary);
2583
2584                this.update(cx, |this, cx| {
2585                    this.summary = Some(summary.clone());
2586                    this.pending_summary_generation = None;
2587                    cx.notify()
2588                })
2589                .ok()?;
2590
2591                Some(summary)
2592            })
2593            .shared();
2594        self.pending_summary_generation = Some(task.clone());
2595        task
2596    }
2597
2598    pub fn generate_title(&mut self, cx: &mut Context<Self>) {
2599        let Some(model) = self.summarization_model.clone() else {
2600            return;
2601        };
2602
2603        log::debug!(
2604            "Generating title with model: {:?}",
2605            self.summarization_model.as_ref().map(|model| model.name())
2606        );
2607        let mut request = LanguageModelRequest {
2608            intent: Some(CompletionIntent::ThreadSummarization),
2609            temperature: AgentSettings::temperature_for_model(&model, cx),
2610            ..Default::default()
2611        };
2612
2613        for message in &self.messages {
2614            request.messages.extend(message.to_request());
2615        }
2616
2617        request.messages.push(LanguageModelRequestMessage {
2618            role: Role::User,
2619            content: vec![SUMMARIZE_THREAD_PROMPT.into()],
2620            cache: false,
2621            reasoning_details: None,
2622        });
2623        self.pending_title_generation = Some(cx.spawn(async move |this, cx| {
2624            let mut title = String::new();
2625
2626            let generate = async {
2627                let mut messages = model.stream_completion(request, cx).await?;
2628                while let Some(event) = messages.next().await {
2629                    let event = event?;
2630                    let text = match event {
2631                        LanguageModelCompletionEvent::Text(text) => text,
2632                        _ => continue,
2633                    };
2634
2635                    let mut lines = text.lines();
2636                    title.extend(lines.next());
2637
2638                    // Stop if the LLM generated multiple lines.
2639                    if lines.next().is_some() {
2640                        break;
2641                    }
2642                }
2643                anyhow::Ok(())
2644            };
2645
2646            if generate
2647                .await
2648                .context("failed to generate thread title")
2649                .log_err()
2650                .is_some()
2651            {
2652                _ = this.update(cx, |this, cx| this.set_title(title.into(), cx));
2653            } else {
2654                // Emit TitleUpdated even on failure so that the propagation
2655                // chain (agent::Thread → NativeAgent → AcpThread) fires and
2656                // clears any provisional title that was set before the turn.
2657                _ = this.update(cx, |_, cx| {
2658                    cx.emit(TitleUpdated);
2659                    cx.notify();
2660                });
2661            }
2662            _ = this.update(cx, |this, _| this.pending_title_generation = None);
2663        }));
2664    }
2665
2666    pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
2667        self.pending_title_generation = None;
2668        if Some(&title) != self.title.as_ref() {
2669            self.title = Some(title);
2670            cx.emit(TitleUpdated);
2671            cx.notify();
2672        }
2673    }
2674
2675    fn clear_summary(&mut self) {
2676        self.summary = None;
2677        self.pending_summary_generation = None;
2678    }
2679
2680    fn last_user_message(&self) -> Option<&UserMessage> {
2681        self.messages
2682            .iter()
2683            .rev()
2684            .find_map(|message| match message {
2685                Message::User(user_message) => Some(user_message),
2686                Message::Agent(_) => None,
2687                Message::Resume => None,
2688            })
2689    }
2690
2691    fn pending_message(&mut self) -> &mut AgentMessage {
2692        self.pending_message.get_or_insert_default()
2693    }
2694
2695    fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
2696        let Some(mut message) = self.pending_message.take() else {
2697            return;
2698        };
2699
2700        if message.content.is_empty() {
2701            return;
2702        }
2703
2704        for content in &message.content {
2705            let AgentMessageContent::ToolUse(tool_use) = content else {
2706                continue;
2707            };
2708
2709            if !message.tool_results.contains_key(&tool_use.id) {
2710                message.tool_results.insert(
2711                    tool_use.id.clone(),
2712                    LanguageModelToolResult {
2713                        tool_use_id: tool_use.id.clone(),
2714                        tool_name: tool_use.name.clone(),
2715                        is_error: true,
2716                        content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
2717                        output: None,
2718                    },
2719                );
2720            }
2721        }
2722
2723        self.messages.push(Message::Agent(message));
2724        self.updated_at = Utc::now();
2725        self.clear_summary();
2726        cx.notify()
2727    }
2728
2729    pub(crate) fn build_completion_request(
2730        &self,
2731        completion_intent: CompletionIntent,
2732        cx: &App,
2733    ) -> Result<LanguageModelRequest> {
2734        let completion_intent =
2735            if self.is_subagent() && completion_intent == CompletionIntent::UserPrompt {
2736                CompletionIntent::Subagent
2737            } else {
2738                completion_intent
2739            };
2740
2741        let model = self.model().context("No language model configured")?;
2742        let tools = if let Some(turn) = self.running_turn.as_ref() {
2743            turn.tools
2744                .iter()
2745                .filter_map(|(tool_name, tool)| {
2746                    log::trace!("Including tool: {}", tool_name);
2747                    Some(LanguageModelRequestTool {
2748                        name: tool_name.to_string(),
2749                        description: tool.description().to_string(),
2750                        input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
2751                        use_input_streaming: tool.supports_input_streaming(),
2752                    })
2753                })
2754                .collect::<Vec<_>>()
2755        } else {
2756            Vec::new()
2757        };
2758
2759        log::debug!("Building completion request");
2760        log::debug!("Completion intent: {:?}", completion_intent);
2761
2762        let available_tools: Vec<_> = self
2763            .running_turn
2764            .as_ref()
2765            .map(|turn| turn.tools.keys().cloned().collect())
2766            .unwrap_or_default();
2767
2768        log::debug!("Request includes {} tools", available_tools.len());
2769        let messages = self.build_request_messages(available_tools, cx);
2770        log::debug!("Request will include {} messages", messages.len());
2771
2772        let request = LanguageModelRequest {
2773            thread_id: Some(self.id.to_string()),
2774            prompt_id: Some(self.prompt_id.to_string()),
2775            intent: Some(completion_intent),
2776            messages,
2777            tools,
2778            tool_choice: None,
2779            stop: Vec::new(),
2780            temperature: AgentSettings::temperature_for_model(model, cx),
2781            thinking_allowed: self.thinking_enabled,
2782            thinking_effort: self.thinking_effort.clone(),
2783            speed: self.speed(),
2784        };
2785
2786        log::debug!("Completion request built successfully");
2787        Ok(request)
2788    }
2789
2790    fn enabled_tools(&self, cx: &App) -> BTreeMap<SharedString, Arc<dyn AnyAgentTool>> {
2791        let Some(model) = self.model.as_ref() else {
2792            return BTreeMap::new();
2793        };
2794        let Some(profile) = AgentSettings::get_global(cx).profiles.get(&self.profile_id) else {
2795            return BTreeMap::new();
2796        };
2797        fn truncate(tool_name: &SharedString) -> SharedString {
2798            if tool_name.len() > MAX_TOOL_NAME_LENGTH {
2799                let mut truncated = tool_name.to_string();
2800                truncated.truncate(MAX_TOOL_NAME_LENGTH);
2801                truncated.into()
2802            } else {
2803                tool_name.clone()
2804            }
2805        }
2806
2807        let use_streaming_edit_tool =
2808            cx.has_flag::<StreamingEditFileToolFeatureFlag>() && model.supports_streaming_tools();
2809
2810        let mut tools = self
2811            .tools
2812            .iter()
2813            .filter_map(|(tool_name, tool)| {
2814                // For streaming_edit_file, check profile against "edit_file" since that's what users configure
2815                let profile_tool_name = if tool_name == StreamingEditFileTool::NAME {
2816                    EditFileTool::NAME
2817                } else {
2818                    tool_name.as_ref()
2819                };
2820
2821                if tool.supports_provider(&model.provider_id())
2822                    && profile.is_tool_enabled(profile_tool_name)
2823                {
2824                    match (tool_name.as_ref(), use_streaming_edit_tool) {
2825                        (StreamingEditFileTool::NAME, false) | (EditFileTool::NAME, true) => None,
2826                        (StreamingEditFileTool::NAME, true) => {
2827                            // Expose streaming tool as "edit_file"
2828                            Some((SharedString::from(EditFileTool::NAME), tool.clone()))
2829                        }
2830                        _ => Some((truncate(tool_name), tool.clone())),
2831                    }
2832                } else {
2833                    None
2834                }
2835            })
2836            .collect::<BTreeMap<_, _>>();
2837
2838        let mut context_server_tools = Vec::new();
2839        let mut seen_tools = tools.keys().cloned().collect::<HashSet<_>>();
2840        let mut duplicate_tool_names = HashSet::default();
2841        for (server_id, server_tools) in self.context_server_registry.read(cx).servers() {
2842            for (tool_name, tool) in server_tools {
2843                if profile.is_context_server_tool_enabled(&server_id.0, &tool_name) {
2844                    let tool_name = truncate(tool_name);
2845                    if !seen_tools.insert(tool_name.clone()) {
2846                        duplicate_tool_names.insert(tool_name.clone());
2847                    }
2848                    context_server_tools.push((server_id.clone(), tool_name, tool.clone()));
2849                }
2850            }
2851        }
2852
2853        // When there are duplicate tool names, disambiguate by prefixing them
2854        // with the server ID (converted to snake_case for API compatibility).
2855        // In the rare case there isn't enough space for the disambiguated tool
2856        // name, keep only the last tool with this name.
2857        for (server_id, tool_name, tool) in context_server_tools {
2858            if duplicate_tool_names.contains(&tool_name) {
2859                let available = MAX_TOOL_NAME_LENGTH.saturating_sub(tool_name.len());
2860                if available >= 2 {
2861                    let mut disambiguated = server_id.0.to_snake_case();
2862                    disambiguated.truncate(available - 1);
2863                    disambiguated.push('_');
2864                    disambiguated.push_str(&tool_name);
2865                    tools.insert(disambiguated.into(), tool.clone());
2866                } else {
2867                    tools.insert(tool_name, tool.clone());
2868                }
2869            } else {
2870                tools.insert(tool_name, tool.clone());
2871            }
2872        }
2873
2874        tools
2875    }
2876
2877    fn refresh_turn_tools(&mut self, cx: &App) {
2878        let tools = self.enabled_tools(cx);
2879        if let Some(turn) = self.running_turn.as_mut() {
2880            turn.tools = tools;
2881        }
2882    }
2883
2884    fn tool(&self, name: &str) -> Option<Arc<dyn AnyAgentTool>> {
2885        self.running_turn.as_ref()?.tools.get(name).cloned()
2886    }
2887
2888    pub fn has_tool(&self, name: &str) -> bool {
2889        self.running_turn
2890            .as_ref()
2891            .is_some_and(|turn| turn.tools.contains_key(name))
2892    }
2893
2894    #[cfg(any(test, feature = "test-support"))]
2895    pub fn has_registered_tool(&self, name: &str) -> bool {
2896        self.tools.contains_key(name)
2897    }
2898
2899    pub fn registered_tool_names(&self) -> Vec<SharedString> {
2900        self.tools.keys().cloned().collect()
2901    }
2902
2903    pub(crate) fn register_running_subagent(&mut self, subagent: WeakEntity<Thread>) {
2904        self.running_subagents.push(subagent);
2905    }
2906
2907    pub(crate) fn unregister_running_subagent(
2908        &mut self,
2909        subagent_session_id: &acp::SessionId,
2910        cx: &App,
2911    ) {
2912        self.running_subagents.retain(|s| {
2913            s.upgrade()
2914                .map_or(false, |s| s.read(cx).id() != subagent_session_id)
2915        });
2916    }
2917
2918    #[cfg(any(test, feature = "test-support"))]
2919    pub fn running_subagent_ids(&self, cx: &App) -> Vec<acp::SessionId> {
2920        self.running_subagents
2921            .iter()
2922            .filter_map(|s| s.upgrade().map(|s| s.read(cx).id().clone()))
2923            .collect()
2924    }
2925
2926    pub fn is_subagent(&self) -> bool {
2927        self.subagent_context.is_some()
2928    }
2929
2930    pub fn parent_thread_id(&self) -> Option<acp::SessionId> {
2931        self.subagent_context
2932            .as_ref()
2933            .map(|c| c.parent_thread_id.clone())
2934    }
2935
2936    pub fn depth(&self) -> u8 {
2937        self.subagent_context.as_ref().map(|c| c.depth).unwrap_or(0)
2938    }
2939
2940    #[cfg(any(test, feature = "test-support"))]
2941    pub fn set_subagent_context(&mut self, context: SubagentContext) {
2942        self.subagent_context = Some(context);
2943    }
2944
2945    pub fn is_turn_complete(&self) -> bool {
2946        self.running_turn.is_none()
2947    }
2948
2949    fn build_request_messages(
2950        &self,
2951        available_tools: Vec<SharedString>,
2952        cx: &App,
2953    ) -> Vec<LanguageModelRequestMessage> {
2954        log::trace!(
2955            "Building request messages from {} thread messages",
2956            self.messages.len()
2957        );
2958
2959        let system_prompt = SystemPromptTemplate {
2960            project: self.project_context.read(cx),
2961            available_tools,
2962            model_name: self.model.as_ref().map(|m| m.name().0.to_string()),
2963        }
2964        .render(&self.templates)
2965        .context("failed to build system prompt")
2966        .expect("Invalid template");
2967        let mut messages = vec![LanguageModelRequestMessage {
2968            role: Role::System,
2969            content: vec![system_prompt.into()],
2970            cache: false,
2971            reasoning_details: None,
2972        }];
2973        for message in &self.messages {
2974            messages.extend(message.to_request());
2975        }
2976
2977        if let Some(last_message) = messages.last_mut() {
2978            last_message.cache = true;
2979        }
2980
2981        if let Some(message) = self.pending_message.as_ref() {
2982            messages.extend(message.to_request());
2983        }
2984
2985        messages
2986    }
2987
2988    pub fn to_markdown(&self) -> String {
2989        let mut markdown = String::new();
2990        for (ix, message) in self.messages.iter().enumerate() {
2991            if ix > 0 {
2992                markdown.push('\n');
2993            }
2994            match message {
2995                Message::User(_) => markdown.push_str("## User\n\n"),
2996                Message::Agent(_) => markdown.push_str("## Assistant\n\n"),
2997                Message::Resume => {}
2998            }
2999            markdown.push_str(&message.to_markdown());
3000        }
3001
3002        if let Some(message) = self.pending_message.as_ref() {
3003            markdown.push_str("\n## Assistant\n\n");
3004            markdown.push_str(&message.to_markdown());
3005        }
3006
3007        markdown
3008    }
3009
3010    fn advance_prompt_id(&mut self) {
3011        self.prompt_id = PromptId::new();
3012    }
3013
3014    fn retry_strategy_for(error: &LanguageModelCompletionError) -> Option<RetryStrategy> {
3015        use LanguageModelCompletionError::*;
3016        use http_client::StatusCode;
3017
3018        // General strategy here:
3019        // - If retrying won't help (e.g. invalid API key or payload too large), return None so we don't retry at all.
3020        // - If it's a time-based issue (e.g. server overloaded, rate limit exceeded), retry up to 4 times with exponential backoff.
3021        // - If it's an issue that *might* be fixed by retrying (e.g. internal server error), retry up to 3 times.
3022        match error {
3023            HttpResponseError {
3024                status_code: StatusCode::TOO_MANY_REQUESTS,
3025                ..
3026            } => Some(RetryStrategy::ExponentialBackoff {
3027                initial_delay: BASE_RETRY_DELAY,
3028                max_attempts: MAX_RETRY_ATTEMPTS,
3029            }),
3030            ServerOverloaded { retry_after, .. } | RateLimitExceeded { retry_after, .. } => {
3031                Some(RetryStrategy::Fixed {
3032                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
3033                    max_attempts: MAX_RETRY_ATTEMPTS,
3034                })
3035            }
3036            UpstreamProviderError {
3037                status,
3038                retry_after,
3039                ..
3040            } => match *status {
3041                StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
3042                    Some(RetryStrategy::Fixed {
3043                        delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
3044                        max_attempts: MAX_RETRY_ATTEMPTS,
3045                    })
3046                }
3047                StatusCode::INTERNAL_SERVER_ERROR => Some(RetryStrategy::Fixed {
3048                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
3049                    // Internal Server Error could be anything, retry up to 3 times.
3050                    max_attempts: 3,
3051                }),
3052                status => {
3053                    // There is no StatusCode variant for the unofficial HTTP 529 ("The service is overloaded"),
3054                    // but we frequently get them in practice. See https://http.dev/529
3055                    if status.as_u16() == 529 {
3056                        Some(RetryStrategy::Fixed {
3057                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
3058                            max_attempts: MAX_RETRY_ATTEMPTS,
3059                        })
3060                    } else {
3061                        Some(RetryStrategy::Fixed {
3062                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
3063                            max_attempts: 2,
3064                        })
3065                    }
3066                }
3067            },
3068            ApiInternalServerError { .. } => Some(RetryStrategy::Fixed {
3069                delay: BASE_RETRY_DELAY,
3070                max_attempts: 3,
3071            }),
3072            ApiReadResponseError { .. }
3073            | HttpSend { .. }
3074            | DeserializeResponse { .. }
3075            | BadRequestFormat { .. } => Some(RetryStrategy::Fixed {
3076                delay: BASE_RETRY_DELAY,
3077                max_attempts: 3,
3078            }),
3079            // Retrying these errors definitely shouldn't help.
3080            HttpResponseError {
3081                status_code:
3082                    StatusCode::PAYLOAD_TOO_LARGE | StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED,
3083                ..
3084            }
3085            | AuthenticationError { .. }
3086            | PermissionError { .. }
3087            | NoApiKey { .. }
3088            | ApiEndpointNotFound { .. }
3089            | PromptTooLarge { .. } => None,
3090            // These errors might be transient, so retry them
3091            SerializeRequest { .. } | BuildRequestBody { .. } | StreamEndedUnexpectedly { .. } => {
3092                Some(RetryStrategy::Fixed {
3093                    delay: BASE_RETRY_DELAY,
3094                    max_attempts: 1,
3095                })
3096            }
3097            // Retry all other 4xx and 5xx errors once.
3098            HttpResponseError { status_code, .. }
3099                if status_code.is_client_error() || status_code.is_server_error() =>
3100            {
3101                Some(RetryStrategy::Fixed {
3102                    delay: BASE_RETRY_DELAY,
3103                    max_attempts: 3,
3104                })
3105            }
3106            Other(err) if err.is::<language_model::PaymentRequiredError>() => {
3107                // Retrying won't help for Payment Required errors.
3108                None
3109            }
3110            // Conservatively assume that any other errors are non-retryable
3111            HttpResponseError { .. } | Other(..) => Some(RetryStrategy::Fixed {
3112                delay: BASE_RETRY_DELAY,
3113                max_attempts: 2,
3114            }),
3115        }
3116    }
3117}
3118
3119struct RunningTurn {
3120    /// Holds the task that handles agent interaction until the end of the turn.
3121    /// Survives across multiple requests as the model performs tool calls and
3122    /// we run tools, report their results.
3123    _task: Task<()>,
3124    /// The current event stream for the running turn. Used to report a final
3125    /// cancellation event if we cancel the turn.
3126    event_stream: ThreadEventStream,
3127    /// The tools that are enabled for the current iteration of the turn.
3128    /// Refreshed at the start of each iteration via `refresh_turn_tools`.
3129    tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
3130    /// Sender to signal tool cancellation. When cancel is called, this is
3131    /// set to true so all tools can detect user-initiated cancellation.
3132    cancellation_tx: watch::Sender<bool>,
3133    /// Senders for tools that support input streaming and have already been
3134    /// started but are still receiving input from the LLM.
3135    streaming_tool_inputs: HashMap<LanguageModelToolUseId, ToolInputSender>,
3136}
3137
3138impl RunningTurn {
3139    fn cancel(mut self) -> Task<()> {
3140        log::debug!("Cancelling in progress turn");
3141        self.cancellation_tx.send(true).ok();
3142        self.event_stream.send_canceled();
3143        self._task
3144    }
3145}
3146
3147pub struct TokenUsageUpdated(pub Option<acp_thread::TokenUsage>);
3148
3149impl EventEmitter<TokenUsageUpdated> for Thread {}
3150
3151pub struct TitleUpdated;
3152
3153impl EventEmitter<TitleUpdated> for Thread {}
3154
3155/// A channel-based wrapper that delivers tool input to a running tool.
3156///
3157/// For non-streaming tools, created via `ToolInput::ready()` so `.recv()` resolves immediately.
3158/// For streaming tools, partial JSON snapshots arrive via `.recv_partial()` as the LLM streams
3159/// them, followed by the final complete input available through `.recv()`.
3160pub struct ToolInput<T> {
3161    rx: mpsc::UnboundedReceiver<ToolInputPayload<serde_json::Value>>,
3162    _phantom: PhantomData<T>,
3163}
3164
3165impl<T: DeserializeOwned> ToolInput<T> {
3166    #[cfg(any(test, feature = "test-support"))]
3167    pub fn resolved(input: impl Serialize) -> Self {
3168        let value = serde_json::to_value(input).expect("failed to serialize tool input");
3169        Self::ready(value)
3170    }
3171
3172    pub fn ready(value: serde_json::Value) -> Self {
3173        let (tx, rx) = mpsc::unbounded();
3174        tx.unbounded_send(ToolInputPayload::Full(value)).ok();
3175        Self {
3176            rx,
3177            _phantom: PhantomData,
3178        }
3179    }
3180
3181    pub fn invalid_json(error_message: String) -> Self {
3182        let (tx, rx) = mpsc::unbounded();
3183        tx.unbounded_send(ToolInputPayload::InvalidJson { error_message })
3184            .ok();
3185        Self {
3186            rx,
3187            _phantom: PhantomData,
3188        }
3189    }
3190
3191    #[cfg(any(test, feature = "test-support"))]
3192    pub fn test() -> (ToolInputSender, Self) {
3193        let (sender, input) = ToolInputSender::channel();
3194        (sender, input.cast())
3195    }
3196
3197    /// Wait for the final deserialized input, ignoring all partial updates.
3198    /// Non-streaming tools can use this to wait until the whole input is available.
3199    pub async fn recv(mut self) -> Result<T> {
3200        while let Ok(value) = self.next().await {
3201            match value {
3202                ToolInputPayload::Full(value) => return Ok(value),
3203                ToolInputPayload::Partial(_) => {}
3204                ToolInputPayload::InvalidJson { error_message } => {
3205                    return Err(anyhow!(error_message));
3206                }
3207            }
3208        }
3209        Err(anyhow!("tool input was not fully received"))
3210    }
3211
3212    pub async fn next(&mut self) -> Result<ToolInputPayload<T>> {
3213        let value = self
3214            .rx
3215            .next()
3216            .await
3217            .ok_or_else(|| anyhow!("tool input was not fully received"))?;
3218
3219        Ok(match value {
3220            ToolInputPayload::Partial(payload) => ToolInputPayload::Partial(payload),
3221            ToolInputPayload::Full(payload) => {
3222                ToolInputPayload::Full(serde_json::from_value(payload)?)
3223            }
3224            ToolInputPayload::InvalidJson { error_message } => {
3225                ToolInputPayload::InvalidJson { error_message }
3226            }
3227        })
3228    }
3229
3230    fn cast<U: DeserializeOwned>(self) -> ToolInput<U> {
3231        ToolInput {
3232            rx: self.rx,
3233            _phantom: PhantomData,
3234        }
3235    }
3236}
3237
3238pub enum ToolInputPayload<T> {
3239    Partial(serde_json::Value),
3240    Full(T),
3241    InvalidJson { error_message: String },
3242}
3243
3244pub struct ToolInputSender {
3245    has_received_final: bool,
3246    tx: mpsc::UnboundedSender<ToolInputPayload<serde_json::Value>>,
3247}
3248
3249impl ToolInputSender {
3250    pub(crate) fn channel() -> (Self, ToolInput<serde_json::Value>) {
3251        let (tx, rx) = mpsc::unbounded();
3252        let sender = Self {
3253            tx,
3254            has_received_final: false,
3255        };
3256        let input = ToolInput {
3257            rx,
3258            _phantom: PhantomData,
3259        };
3260        (sender, input)
3261    }
3262
3263    pub(crate) fn has_received_final(&self) -> bool {
3264        self.has_received_final
3265    }
3266
3267    pub fn send_partial(&mut self, payload: serde_json::Value) {
3268        self.tx
3269            .unbounded_send(ToolInputPayload::Partial(payload))
3270            .ok();
3271    }
3272
3273    pub fn send_full(&mut self, payload: serde_json::Value) {
3274        self.has_received_final = true;
3275        self.tx.unbounded_send(ToolInputPayload::Full(payload)).ok();
3276    }
3277
3278    pub fn send_invalid_json(&mut self, error_message: String) {
3279        self.has_received_final = true;
3280        self.tx
3281            .unbounded_send(ToolInputPayload::InvalidJson { error_message })
3282            .ok();
3283    }
3284}
3285
3286pub trait AgentTool
3287where
3288    Self: 'static + Sized,
3289{
3290    type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
3291    type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
3292
3293    const NAME: &'static str;
3294
3295    fn description() -> SharedString {
3296        let schema = schemars::schema_for!(Self::Input);
3297        SharedString::new(
3298            schema
3299                .get("description")
3300                .and_then(|description| description.as_str())
3301                .unwrap_or_default(),
3302        )
3303    }
3304
3305    fn kind() -> acp::ToolKind;
3306
3307    /// The initial tool title to display. Can be updated during the tool run.
3308    fn initial_title(
3309        &self,
3310        input: Result<Self::Input, serde_json::Value>,
3311        cx: &mut App,
3312    ) -> SharedString;
3313
3314    /// Returns the JSON schema that describes the tool's input.
3315    fn input_schema(format: LanguageModelToolSchemaFormat) -> Schema {
3316        language_model::tool_schema::root_schema_for::<Self::Input>(format)
3317    }
3318
3319    /// Returns whether the tool supports streaming of tool use parameters.
3320    fn supports_input_streaming() -> bool {
3321        false
3322    }
3323
3324    /// Some tools rely on a provider for the underlying billing or other reasons.
3325    /// Allow the tool to check if they are compatible, or should be filtered out.
3326    fn supports_provider(_provider: &LanguageModelProviderId) -> bool {
3327        true
3328    }
3329
3330    /// Runs the tool with the provided input.
3331    ///
3332    /// Returns `Result<Self::Output, Self::Output>` rather than `Result<Self::Output, anyhow::Error>`
3333    /// because tool errors are sent back to the model as tool results. This means error output must
3334    /// be structured and readable by the agent — not an arbitrary `anyhow::Error`. Returning the
3335    /// same `Output` type for both success and failure lets tools provide structured data while
3336    /// still signaling whether the invocation succeeded or failed.
3337    fn run(
3338        self: Arc<Self>,
3339        input: ToolInput<Self::Input>,
3340        event_stream: ToolCallEventStream,
3341        cx: &mut App,
3342    ) -> Task<Result<Self::Output, Self::Output>>;
3343
3344    /// Emits events for a previous execution of the tool.
3345    fn replay(
3346        &self,
3347        _input: Self::Input,
3348        _output: Self::Output,
3349        _event_stream: ToolCallEventStream,
3350        _cx: &mut App,
3351    ) -> Result<()> {
3352        Ok(())
3353    }
3354
3355    fn erase(self) -> Arc<dyn AnyAgentTool> {
3356        Arc::new(Erased(Arc::new(self)))
3357    }
3358}
3359
3360pub struct Erased<T>(T);
3361
3362pub struct AgentToolOutput {
3363    pub llm_output: LanguageModelToolResultContent,
3364    pub raw_output: serde_json::Value,
3365}
3366
3367impl AgentToolOutput {
3368    pub fn from_error(message: impl Into<String>) -> Self {
3369        let message = message.into();
3370        let llm_output = LanguageModelToolResultContent::Text(Arc::from(message.as_str()));
3371        Self {
3372            raw_output: serde_json::Value::String(message),
3373            llm_output,
3374        }
3375    }
3376}
3377
3378pub trait AnyAgentTool {
3379    fn name(&self) -> SharedString;
3380    fn description(&self) -> SharedString;
3381    fn kind(&self) -> acp::ToolKind;
3382    fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString;
3383    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
3384    fn supports_input_streaming(&self) -> bool {
3385        false
3386    }
3387    fn supports_provider(&self, _provider: &LanguageModelProviderId) -> bool {
3388        true
3389    }
3390    /// See [`AgentTool::run`] for why this returns `Result<AgentToolOutput, AgentToolOutput>`.
3391    fn run(
3392        self: Arc<Self>,
3393        input: ToolInput<serde_json::Value>,
3394        event_stream: ToolCallEventStream,
3395        cx: &mut App,
3396    ) -> Task<Result<AgentToolOutput, AgentToolOutput>>;
3397    fn replay(
3398        &self,
3399        input: serde_json::Value,
3400        output: serde_json::Value,
3401        event_stream: ToolCallEventStream,
3402        cx: &mut App,
3403    ) -> Result<()>;
3404}
3405
3406impl<T> AnyAgentTool for Erased<Arc<T>>
3407where
3408    T: AgentTool,
3409{
3410    fn name(&self) -> SharedString {
3411        T::NAME.into()
3412    }
3413
3414    fn description(&self) -> SharedString {
3415        T::description()
3416    }
3417
3418    fn kind(&self) -> agent_client_protocol::ToolKind {
3419        T::kind()
3420    }
3421
3422    fn supports_input_streaming(&self) -> bool {
3423        T::supports_input_streaming()
3424    }
3425
3426    fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString {
3427        let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
3428        self.0.initial_title(parsed_input, _cx)
3429    }
3430
3431    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
3432        let mut json = serde_json::to_value(T::input_schema(format))?;
3433        language_model::tool_schema::adapt_schema_to_format(&mut json, format)?;
3434        Ok(json)
3435    }
3436
3437    fn supports_provider(&self, provider: &LanguageModelProviderId) -> bool {
3438        T::supports_provider(provider)
3439    }
3440
3441    fn run(
3442        self: Arc<Self>,
3443        input: ToolInput<serde_json::Value>,
3444        event_stream: ToolCallEventStream,
3445        cx: &mut App,
3446    ) -> Task<Result<AgentToolOutput, AgentToolOutput>> {
3447        let tool_input: ToolInput<T::Input> = input.cast();
3448        let task = self.0.clone().run(tool_input, event_stream, cx);
3449        cx.spawn(async move |_cx| match task.await {
3450            Ok(output) => {
3451                let raw_output = serde_json::to_value(&output).map_err(|e| {
3452                    AgentToolOutput::from_error(format!("Failed to serialize tool output: {e}"))
3453                })?;
3454                Ok(AgentToolOutput {
3455                    llm_output: output.into(),
3456                    raw_output,
3457                })
3458            }
3459            Err(error_output) => {
3460                let raw_output = serde_json::to_value(&error_output).unwrap_or_else(|e| {
3461                    log::error!("Failed to serialize tool error output: {e}");
3462                    serde_json::Value::Null
3463                });
3464                Err(AgentToolOutput {
3465                    llm_output: error_output.into(),
3466                    raw_output,
3467                })
3468            }
3469        })
3470    }
3471
3472    fn replay(
3473        &self,
3474        input: serde_json::Value,
3475        output: serde_json::Value,
3476        event_stream: ToolCallEventStream,
3477        cx: &mut App,
3478    ) -> Result<()> {
3479        let input = serde_json::from_value(input)?;
3480        let output = serde_json::from_value(output)?;
3481        self.0.replay(input, output, event_stream, cx)
3482    }
3483}
3484
3485#[derive(Clone)]
3486struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
3487
3488impl ThreadEventStream {
3489    fn send_user_message(&self, message: &UserMessage) {
3490        self.0
3491            .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
3492            .ok();
3493    }
3494
3495    fn send_text(&self, text: &str) {
3496        self.0
3497            .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
3498            .ok();
3499    }
3500
3501    fn send_thinking(&self, text: &str) {
3502        self.0
3503            .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
3504            .ok();
3505    }
3506
3507    fn send_tool_call(
3508        &self,
3509        id: &LanguageModelToolUseId,
3510        tool_name: &str,
3511        title: SharedString,
3512        kind: acp::ToolKind,
3513        input: serde_json::Value,
3514    ) {
3515        self.0
3516            .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
3517                id,
3518                tool_name,
3519                title.to_string(),
3520                kind,
3521                input,
3522            ))))
3523            .ok();
3524    }
3525
3526    fn initial_tool_call(
3527        id: &LanguageModelToolUseId,
3528        tool_name: &str,
3529        title: String,
3530        kind: acp::ToolKind,
3531        input: serde_json::Value,
3532    ) -> acp::ToolCall {
3533        acp::ToolCall::new(id.to_string(), title)
3534            .kind(kind)
3535            .raw_input(input)
3536            .meta(acp_thread::meta_with_tool_name(tool_name))
3537    }
3538
3539    fn update_tool_call_fields(
3540        &self,
3541        tool_use_id: &LanguageModelToolUseId,
3542        fields: acp::ToolCallUpdateFields,
3543        meta: Option<acp::Meta>,
3544    ) {
3545        self.0
3546            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3547                acp::ToolCallUpdate::new(tool_use_id.to_string(), fields)
3548                    .meta(meta)
3549                    .into(),
3550            )))
3551            .ok();
3552    }
3553
3554    fn send_plan(&self, plan: acp::Plan) {
3555        self.0.unbounded_send(Ok(ThreadEvent::Plan(plan))).ok();
3556    }
3557
3558    fn send_retry(&self, status: acp_thread::RetryStatus) {
3559        self.0.unbounded_send(Ok(ThreadEvent::Retry(status))).ok();
3560    }
3561
3562    fn send_stop(&self, reason: acp::StopReason) {
3563        self.0.unbounded_send(Ok(ThreadEvent::Stop(reason))).ok();
3564    }
3565
3566    fn send_canceled(&self) {
3567        self.0
3568            .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))
3569            .ok();
3570    }
3571
3572    fn send_error(&self, error: impl Into<anyhow::Error>) {
3573        self.0.unbounded_send(Err(error.into())).ok();
3574    }
3575}
3576
3577#[derive(Clone)]
3578pub struct ToolCallEventStream {
3579    tool_use_id: LanguageModelToolUseId,
3580    stream: ThreadEventStream,
3581    fs: Option<Arc<dyn Fs>>,
3582    cancellation_rx: watch::Receiver<bool>,
3583}
3584
3585impl ToolCallEventStream {
3586    #[cfg(any(test, feature = "test-support"))]
3587    pub fn test() -> (Self, ToolCallEventStreamReceiver) {
3588        let (stream, receiver, _cancellation_tx) = Self::test_with_cancellation();
3589        (stream, receiver)
3590    }
3591
3592    #[cfg(any(test, feature = "test-support"))]
3593    pub fn test_with_cancellation() -> (Self, ToolCallEventStreamReceiver, watch::Sender<bool>) {
3594        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
3595        let (cancellation_tx, cancellation_rx) = watch::channel(false);
3596
3597        let stream = ToolCallEventStream::new(
3598            "test_id".into(),
3599            ThreadEventStream(events_tx),
3600            None,
3601            cancellation_rx,
3602        );
3603
3604        (
3605            stream,
3606            ToolCallEventStreamReceiver(events_rx),
3607            cancellation_tx,
3608        )
3609    }
3610
3611    /// Signal cancellation for this event stream. Only available in tests.
3612    #[cfg(any(test, feature = "test-support"))]
3613    pub fn signal_cancellation_with_sender(cancellation_tx: &mut watch::Sender<bool>) {
3614        cancellation_tx.send(true).ok();
3615    }
3616
3617    fn new(
3618        tool_use_id: LanguageModelToolUseId,
3619        stream: ThreadEventStream,
3620        fs: Option<Arc<dyn Fs>>,
3621        cancellation_rx: watch::Receiver<bool>,
3622    ) -> Self {
3623        Self {
3624            tool_use_id,
3625            stream,
3626            fs,
3627            cancellation_rx,
3628        }
3629    }
3630
3631    /// Returns a future that resolves when the user cancels the tool call.
3632    /// Tools should select on this alongside their main work to detect user cancellation.
3633    pub fn cancelled_by_user(&self) -> impl std::future::Future<Output = ()> + '_ {
3634        let mut rx = self.cancellation_rx.clone();
3635        async move {
3636            loop {
3637                if *rx.borrow() {
3638                    return;
3639                }
3640                if rx.changed().await.is_err() {
3641                    // Sender dropped, will never be cancelled
3642                    std::future::pending::<()>().await;
3643                }
3644            }
3645        }
3646    }
3647
3648    /// Returns true if the user has cancelled this tool call.
3649    /// This is useful for checking cancellation state after an operation completes,
3650    /// to determine if the completion was due to user cancellation.
3651    pub fn was_cancelled_by_user(&self) -> bool {
3652        *self.cancellation_rx.clone().borrow()
3653    }
3654
3655    pub fn tool_use_id(&self) -> &LanguageModelToolUseId {
3656        &self.tool_use_id
3657    }
3658
3659    pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
3660        self.stream
3661            .update_tool_call_fields(&self.tool_use_id, fields, None);
3662    }
3663
3664    pub fn update_fields_with_meta(
3665        &self,
3666        fields: acp::ToolCallUpdateFields,
3667        meta: Option<acp::Meta>,
3668    ) {
3669        self.stream
3670            .update_tool_call_fields(&self.tool_use_id, fields, meta);
3671    }
3672
3673    pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
3674        self.stream
3675            .0
3676            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3677                acp_thread::ToolCallUpdateDiff {
3678                    id: acp::ToolCallId::new(self.tool_use_id.to_string()),
3679                    diff,
3680                }
3681                .into(),
3682            )))
3683            .ok();
3684    }
3685
3686    pub fn subagent_spawned(&self, id: acp::SessionId) {
3687        self.stream
3688            .0
3689            .unbounded_send(Ok(ThreadEvent::SubagentSpawned(id)))
3690            .ok();
3691    }
3692
3693    pub fn update_plan(&self, plan: acp::Plan) {
3694        self.stream.send_plan(plan);
3695    }
3696
3697    /// Authorize a third-party tool (e.g., MCP tool from a context server).
3698    ///
3699    /// Unlike built-in tools, third-party tools don't support pattern-based permissions.
3700    /// They only support `default` (allow/deny/confirm) per tool.
3701    ///
3702    /// Uses the dropdown authorization flow with two granularities:
3703    /// - "Always for <display_name> MCP tool" → sets `tools.<tool_id>.default = "allow"` or "deny"
3704    /// - "Only this time" → allow/deny once
3705    pub fn authorize_third_party_tool(
3706        &self,
3707        title: impl Into<String>,
3708        tool_id: String,
3709        display_name: String,
3710        cx: &mut App,
3711    ) -> Task<Result<()>> {
3712        let settings = agent_settings::AgentSettings::get_global(cx);
3713
3714        let decision = decide_permission_from_settings(&tool_id, &[String::new()], &settings);
3715
3716        match decision {
3717            ToolPermissionDecision::Allow => return Task::ready(Ok(())),
3718            ToolPermissionDecision::Deny(reason) => return Task::ready(Err(anyhow!(reason))),
3719            ToolPermissionDecision::Confirm => {}
3720        }
3721
3722        let (response_tx, response_rx) = oneshot::channel();
3723        if let Err(error) = self
3724            .stream
3725            .0
3726            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3727                ToolCallAuthorization {
3728                    tool_call: acp::ToolCallUpdate::new(
3729                        self.tool_use_id.to_string(),
3730                        acp::ToolCallUpdateFields::new().title(title.into()),
3731                    ),
3732                    options: acp_thread::PermissionOptions::Dropdown(vec![
3733                        acp_thread::PermissionOptionChoice {
3734                            allow: acp::PermissionOption::new(
3735                                acp::PermissionOptionId::new(format!(
3736                                    "always_allow_mcp:{}",
3737                                    tool_id
3738                                )),
3739                                format!("Always for {} MCP tool", display_name),
3740                                acp::PermissionOptionKind::AllowAlways,
3741                            ),
3742                            deny: acp::PermissionOption::new(
3743                                acp::PermissionOptionId::new(format!(
3744                                    "always_deny_mcp:{}",
3745                                    tool_id
3746                                )),
3747                                format!("Always for {} MCP tool", display_name),
3748                                acp::PermissionOptionKind::RejectAlways,
3749                            ),
3750                            sub_patterns: vec![],
3751                        },
3752                        acp_thread::PermissionOptionChoice {
3753                            allow: acp::PermissionOption::new(
3754                                acp::PermissionOptionId::new("allow"),
3755                                "Only this time",
3756                                acp::PermissionOptionKind::AllowOnce,
3757                            ),
3758                            deny: acp::PermissionOption::new(
3759                                acp::PermissionOptionId::new("deny"),
3760                                "Only this time",
3761                                acp::PermissionOptionKind::RejectOnce,
3762                            ),
3763                            sub_patterns: vec![],
3764                        },
3765                    ]),
3766                    response: response_tx,
3767                    context: None,
3768                },
3769            )))
3770        {
3771            log::error!("Failed to send tool call authorization: {error}");
3772            return Task::ready(Err(anyhow!(
3773                "Failed to send tool call authorization: {error}"
3774            )));
3775        }
3776
3777        let fs = self.fs.clone();
3778        cx.spawn(async move |cx| {
3779            let outcome = response_rx.await?;
3780            let is_allow = Self::persist_permission_outcome(&outcome, fs, &cx);
3781            if is_allow {
3782                Ok(())
3783            } else {
3784                Err(anyhow!("Permission to run tool denied by user"))
3785            }
3786        })
3787    }
3788
3789    pub fn authorize(
3790        &self,
3791        title: impl Into<String>,
3792        context: ToolPermissionContext,
3793        cx: &mut App,
3794    ) -> Task<Result<()>> {
3795        let options = context.build_permission_options();
3796
3797        let (response_tx, response_rx) = oneshot::channel();
3798        if let Err(error) = self
3799            .stream
3800            .0
3801            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3802                ToolCallAuthorization {
3803                    tool_call: acp::ToolCallUpdate::new(
3804                        self.tool_use_id.to_string(),
3805                        acp::ToolCallUpdateFields::new().title(title.into()),
3806                    ),
3807                    options,
3808                    response: response_tx,
3809                    context: Some(context),
3810                },
3811            )))
3812        {
3813            log::error!("Failed to send tool call authorization: {error}");
3814            return Task::ready(Err(anyhow!(
3815                "Failed to send tool call authorization: {error}"
3816            )));
3817        }
3818
3819        let fs = self.fs.clone();
3820        cx.spawn(async move |cx| {
3821            let outcome = response_rx.await?;
3822            let is_allow = Self::persist_permission_outcome(&outcome, fs, &cx);
3823            if is_allow {
3824                Ok(())
3825            } else {
3826                Err(anyhow!("Permission to run tool denied by user"))
3827            }
3828        })
3829    }
3830
3831    /// Interprets a `SelectedPermissionOutcome` and persists any settings changes.
3832    /// Returns `true` if the tool call should be allowed, `false` if denied.
3833    fn persist_permission_outcome(
3834        outcome: &acp_thread::SelectedPermissionOutcome,
3835        fs: Option<Arc<dyn Fs>>,
3836        cx: &AsyncApp,
3837    ) -> bool {
3838        let option_id = outcome.option_id.0.as_ref();
3839
3840        let always_permission = option_id
3841            .strip_prefix("always_allow:")
3842            .map(|tool| (tool, ToolPermissionMode::Allow))
3843            .or_else(|| {
3844                option_id
3845                    .strip_prefix("always_deny:")
3846                    .map(|tool| (tool, ToolPermissionMode::Deny))
3847            })
3848            .or_else(|| {
3849                option_id
3850                    .strip_prefix("always_allow_mcp:")
3851                    .map(|tool| (tool, ToolPermissionMode::Allow))
3852            })
3853            .or_else(|| {
3854                option_id
3855                    .strip_prefix("always_deny_mcp:")
3856                    .map(|tool| (tool, ToolPermissionMode::Deny))
3857            });
3858
3859        if let Some((tool, mode)) = always_permission {
3860            let params = outcome.params.as_ref();
3861            Self::persist_always_permission(tool, mode, params, fs, cx);
3862            return mode == ToolPermissionMode::Allow;
3863        }
3864
3865        // Handle simple "allow" / "deny" (once, no persistence)
3866        if option_id == "allow" || option_id == "deny" {
3867            debug_assert!(
3868                outcome.params.is_none(),
3869                "unexpected params for once-only permission"
3870            );
3871            return option_id == "allow";
3872        }
3873
3874        debug_assert!(false, "unexpected permission option_id: {option_id}");
3875        false
3876    }
3877
3878    /// Persists an "always allow" or "always deny" permission, using sub_patterns
3879    /// from params when present.
3880    fn persist_always_permission(
3881        tool: &str,
3882        mode: ToolPermissionMode,
3883        params: Option<&acp_thread::SelectedPermissionParams>,
3884        fs: Option<Arc<dyn Fs>>,
3885        cx: &AsyncApp,
3886    ) {
3887        let Some(fs) = fs else {
3888            return;
3889        };
3890
3891        match params {
3892            Some(acp_thread::SelectedPermissionParams::Terminal {
3893                patterns: sub_patterns,
3894            }) => {
3895                debug_assert!(
3896                    !sub_patterns.is_empty(),
3897                    "empty sub_patterns for tool {tool} — callers should pass None instead"
3898                );
3899                let tool = tool.to_string();
3900                let sub_patterns = sub_patterns.clone();
3901                cx.update(|cx| {
3902                    update_settings_file(fs, cx, move |settings, _| {
3903                        let agent = settings.agent.get_or_insert_default();
3904                        for pattern in sub_patterns {
3905                            match mode {
3906                                ToolPermissionMode::Allow => {
3907                                    agent.add_tool_allow_pattern(&tool, pattern);
3908                                }
3909                                ToolPermissionMode::Deny => {
3910                                    agent.add_tool_deny_pattern(&tool, pattern);
3911                                }
3912                                // If there's no matching pattern this will
3913                                // default to confirm, so falling through is
3914                                // fine here.
3915                                ToolPermissionMode::Confirm => (),
3916                            }
3917                        }
3918                    });
3919                });
3920            }
3921            None => {
3922                let tool = tool.to_string();
3923                cx.update(|cx| {
3924                    update_settings_file(fs, cx, move |settings, _| {
3925                        settings
3926                            .agent
3927                            .get_or_insert_default()
3928                            .set_tool_default_permission(&tool, mode);
3929                    });
3930                });
3931            }
3932        }
3933    }
3934}
3935
3936#[cfg(any(test, feature = "test-support"))]
3937pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
3938
3939#[cfg(any(test, feature = "test-support"))]
3940impl ToolCallEventStreamReceiver {
3941    pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
3942        let event = self.0.next().await;
3943        if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
3944            auth
3945        } else {
3946            panic!("Expected ToolCallAuthorization but got: {:?}", event);
3947        }
3948    }
3949
3950    pub async fn expect_update_fields(&mut self) -> acp::ToolCallUpdateFields {
3951        let event = self.0.next().await;
3952        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
3953            update,
3954        )))) = event
3955        {
3956            update.fields
3957        } else {
3958            panic!("Expected update fields but got: {:?}", event);
3959        }
3960    }
3961
3962    pub async fn expect_diff(&mut self) -> Entity<acp_thread::Diff> {
3963        let event = self.0.next().await;
3964        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateDiff(
3965            update,
3966        )))) = event
3967        {
3968            update.diff
3969        } else {
3970            panic!("Expected diff but got: {:?}", event);
3971        }
3972    }
3973
3974    pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
3975        let event = self.0.next().await;
3976        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
3977            update,
3978        )))) = event
3979        {
3980            update.terminal
3981        } else {
3982            panic!("Expected terminal but got: {:?}", event);
3983        }
3984    }
3985
3986    pub async fn expect_plan(&mut self) -> acp::Plan {
3987        let event = self.0.next().await;
3988        if let Some(Ok(ThreadEvent::Plan(plan))) = event {
3989            plan
3990        } else {
3991            panic!("Expected plan but got: {:?}", event);
3992        }
3993    }
3994}
3995
3996#[cfg(any(test, feature = "test-support"))]
3997impl std::ops::Deref for ToolCallEventStreamReceiver {
3998    type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
3999
4000    fn deref(&self) -> &Self::Target {
4001        &self.0
4002    }
4003}
4004
4005#[cfg(any(test, feature = "test-support"))]
4006impl std::ops::DerefMut for ToolCallEventStreamReceiver {
4007    fn deref_mut(&mut self) -> &mut Self::Target {
4008        &mut self.0
4009    }
4010}
4011
4012impl From<&str> for UserMessageContent {
4013    fn from(text: &str) -> Self {
4014        Self::Text(text.into())
4015    }
4016}
4017
4018impl From<String> for UserMessageContent {
4019    fn from(text: String) -> Self {
4020        Self::Text(text)
4021    }
4022}
4023
4024impl UserMessageContent {
4025    pub fn from_content_block(value: acp::ContentBlock, path_style: PathStyle) -> Self {
4026        match value {
4027            acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
4028            acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
4029            acp::ContentBlock::Audio(_) => {
4030                // TODO
4031                Self::Text("[audio]".to_string())
4032            }
4033            acp::ContentBlock::ResourceLink(resource_link) => {
4034                match MentionUri::parse(&resource_link.uri, path_style) {
4035                    Ok(uri) => Self::Mention {
4036                        uri,
4037                        content: String::new(),
4038                    },
4039                    Err(err) => {
4040                        log::error!("Failed to parse mention link: {}", err);
4041                        Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
4042                    }
4043                }
4044            }
4045            acp::ContentBlock::Resource(resource) => match resource.resource {
4046                acp::EmbeddedResourceResource::TextResourceContents(resource) => {
4047                    match MentionUri::parse(&resource.uri, path_style) {
4048                        Ok(uri) => Self::Mention {
4049                            uri,
4050                            content: resource.text,
4051                        },
4052                        Err(err) => {
4053                            log::error!("Failed to parse mention link: {}", err);
4054                            Self::Text(
4055                                MarkdownCodeBlock {
4056                                    tag: &resource.uri,
4057                                    text: &resource.text,
4058                                }
4059                                .to_string(),
4060                            )
4061                        }
4062                    }
4063                }
4064                acp::EmbeddedResourceResource::BlobResourceContents(_) => {
4065                    // TODO
4066                    Self::Text("[blob]".to_string())
4067                }
4068                other => {
4069                    log::warn!("Unexpected content type: {:?}", other);
4070                    Self::Text("[unknown]".to_string())
4071                }
4072            },
4073            other => {
4074                log::warn!("Unexpected content type: {:?}", other);
4075                Self::Text("[unknown]".to_string())
4076            }
4077        }
4078    }
4079}
4080
4081impl From<UserMessageContent> for acp::ContentBlock {
4082    fn from(content: UserMessageContent) -> Self {
4083        match content {
4084            UserMessageContent::Text(text) => text.into(),
4085            UserMessageContent::Image(image) => {
4086                acp::ContentBlock::Image(acp::ImageContent::new(image.source, "image/png"))
4087            }
4088            UserMessageContent::Mention { uri, content } => acp::ContentBlock::Resource(
4089                acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(
4090                    acp::TextResourceContents::new(content, uri.to_uri().to_string()),
4091                )),
4092            ),
4093        }
4094    }
4095}
4096
4097fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
4098    LanguageModelImage {
4099        source: image_content.data.into(),
4100        size: None,
4101    }
4102}
4103
4104#[cfg(test)]
4105mod tests {
4106    use super::*;
4107    use gpui::TestAppContext;
4108    use language_model::LanguageModelToolUseId;
4109    use language_model::fake_provider::FakeLanguageModel;
4110    use serde_json::json;
4111    use std::sync::Arc;
4112
4113    async fn setup_thread_for_test(cx: &mut TestAppContext) -> (Entity<Thread>, ThreadEventStream) {
4114        cx.update(|cx| {
4115            let settings_store = settings::SettingsStore::test(cx);
4116            cx.set_global(settings_store);
4117        });
4118
4119        let fs = fs::FakeFs::new(cx.background_executor.clone());
4120        let templates = Templates::new();
4121        let project = Project::test(fs.clone(), [], cx).await;
4122
4123        cx.update(|cx| {
4124            let project_context = cx.new(|_cx| prompt_store::ProjectContext::default());
4125            let context_server_store = project.read(cx).context_server_store();
4126            let context_server_registry =
4127                cx.new(|cx| ContextServerRegistry::new(context_server_store, cx));
4128
4129            let thread = cx.new(|cx| {
4130                Thread::new(
4131                    project,
4132                    project_context,
4133                    context_server_registry,
4134                    templates,
4135                    None,
4136                    cx,
4137                )
4138            });
4139
4140            let (event_tx, _event_rx) = mpsc::unbounded();
4141            let event_stream = ThreadEventStream(event_tx);
4142
4143            (thread, event_stream)
4144        })
4145    }
4146
4147    fn setup_parent_with_subagents(
4148        cx: &mut TestAppContext,
4149        parent: &Entity<Thread>,
4150        count: usize,
4151    ) -> Vec<Entity<Thread>> {
4152        cx.update(|cx| {
4153            let mut subagents = Vec::new();
4154            for _ in 0..count {
4155                let subagent = cx.new(|cx| Thread::new_subagent(parent, cx));
4156                parent.update(cx, |thread, _cx| {
4157                    thread.register_running_subagent(subagent.downgrade());
4158                });
4159                subagents.push(subagent);
4160            }
4161            subagents
4162        })
4163    }
4164
4165    #[gpui::test]
4166    async fn test_set_model_propagates_to_subagents(cx: &mut TestAppContext) {
4167        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4168        let subagents = setup_parent_with_subagents(cx, &parent, 2);
4169
4170        let new_model: Arc<dyn LanguageModel> = Arc::new(FakeLanguageModel::with_id_and_thinking(
4171            "test-provider",
4172            "new-model",
4173            "New Model",
4174            false,
4175        ));
4176
4177        cx.update(|cx| {
4178            parent.update(cx, |thread, cx| {
4179                thread.set_model(new_model, cx);
4180            });
4181
4182            for subagent in &subagents {
4183                let subagent_model_id = subagent.read(cx).model().unwrap().id();
4184                assert_eq!(
4185                    subagent_model_id.0.as_ref(),
4186                    "new-model",
4187                    "Subagent model should match parent model after set_model"
4188                );
4189            }
4190        });
4191    }
4192
4193    #[gpui::test]
4194    async fn test_set_summarization_model_propagates_to_subagents(cx: &mut TestAppContext) {
4195        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4196        let subagents = setup_parent_with_subagents(cx, &parent, 2);
4197
4198        let summary_model: Arc<dyn LanguageModel> =
4199            Arc::new(FakeLanguageModel::with_id_and_thinking(
4200                "test-provider",
4201                "summary-model",
4202                "Summary Model",
4203                false,
4204            ));
4205
4206        cx.update(|cx| {
4207            parent.update(cx, |thread, cx| {
4208                thread.set_summarization_model(Some(summary_model), cx);
4209            });
4210
4211            for subagent in &subagents {
4212                let subagent_summary_id = subagent.read(cx).summarization_model().unwrap().id();
4213                assert_eq!(
4214                    subagent_summary_id.0.as_ref(),
4215                    "summary-model",
4216                    "Subagent summarization model should match parent after set_summarization_model"
4217                );
4218            }
4219        });
4220    }
4221
4222    #[gpui::test]
4223    async fn test_set_thinking_enabled_propagates_to_subagents(cx: &mut TestAppContext) {
4224        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4225        let subagents = setup_parent_with_subagents(cx, &parent, 2);
4226
4227        cx.update(|cx| {
4228            parent.update(cx, |thread, cx| {
4229                thread.set_thinking_enabled(true, cx);
4230            });
4231
4232            for subagent in &subagents {
4233                assert!(
4234                    subagent.read(cx).thinking_enabled(),
4235                    "Subagent thinking should be enabled after parent enables it"
4236                );
4237            }
4238
4239            parent.update(cx, |thread, cx| {
4240                thread.set_thinking_enabled(false, cx);
4241            });
4242
4243            for subagent in &subagents {
4244                assert!(
4245                    !subagent.read(cx).thinking_enabled(),
4246                    "Subagent thinking should be disabled after parent disables it"
4247                );
4248            }
4249        });
4250    }
4251
4252    #[gpui::test]
4253    async fn test_set_thinking_effort_propagates_to_subagents(cx: &mut TestAppContext) {
4254        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4255        let subagents = setup_parent_with_subagents(cx, &parent, 2);
4256
4257        cx.update(|cx| {
4258            parent.update(cx, |thread, cx| {
4259                thread.set_thinking_effort(Some("high".to_string()), cx);
4260            });
4261
4262            for subagent in &subagents {
4263                assert_eq!(
4264                    subagent.read(cx).thinking_effort().map(|s| s.as_str()),
4265                    Some("high"),
4266                    "Subagent thinking effort should match parent"
4267                );
4268            }
4269
4270            parent.update(cx, |thread, cx| {
4271                thread.set_thinking_effort(None, cx);
4272            });
4273
4274            for subagent in &subagents {
4275                assert_eq!(
4276                    subagent.read(cx).thinking_effort(),
4277                    None,
4278                    "Subagent thinking effort should be None after parent clears it"
4279                );
4280            }
4281        });
4282    }
4283
4284    #[gpui::test]
4285    async fn test_subagent_inherits_settings_at_creation(cx: &mut TestAppContext) {
4286        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4287
4288        cx.update(|cx| {
4289            parent.update(cx, |thread, cx| {
4290                thread.set_speed(Speed::Fast, cx);
4291                thread.set_thinking_enabled(true, cx);
4292                thread.set_thinking_effort(Some("high".to_string()), cx);
4293                thread.set_profile(AgentProfileId("custom-profile".into()), cx);
4294            });
4295        });
4296
4297        let subagents = setup_parent_with_subagents(cx, &parent, 1);
4298
4299        cx.update(|cx| {
4300            let sub = subagents[0].read(cx);
4301            assert_eq!(sub.speed(), Some(Speed::Fast));
4302            assert!(sub.thinking_enabled());
4303            assert_eq!(sub.thinking_effort().map(|s| s.as_str()), Some("high"));
4304            assert_eq!(sub.profile(), &AgentProfileId("custom-profile".into()));
4305        });
4306    }
4307
4308    #[gpui::test]
4309    async fn test_set_speed_propagates_to_subagents(cx: &mut TestAppContext) {
4310        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4311        let subagents = setup_parent_with_subagents(cx, &parent, 2);
4312
4313        cx.update(|cx| {
4314            parent.update(cx, |thread, cx| {
4315                thread.set_speed(Speed::Fast, cx);
4316            });
4317
4318            for subagent in &subagents {
4319                assert_eq!(
4320                    subagent.read(cx).speed(),
4321                    Some(Speed::Fast),
4322                    "Subagent speed should match parent after set_speed"
4323                );
4324            }
4325        });
4326    }
4327
4328    #[gpui::test]
4329    async fn test_dropped_subagent_does_not_panic(cx: &mut TestAppContext) {
4330        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4331        let subagents = setup_parent_with_subagents(cx, &parent, 1);
4332
4333        // Drop the subagent so the WeakEntity can no longer be upgraded
4334        drop(subagents);
4335
4336        // Should not panic even though the subagent was dropped
4337        cx.update(|cx| {
4338            parent.update(cx, |thread, cx| {
4339                thread.set_thinking_enabled(true, cx);
4340                thread.set_speed(Speed::Fast, cx);
4341                thread.set_thinking_effort(Some("high".to_string()), cx);
4342            });
4343        });
4344    }
4345
4346    #[gpui::test]
4347    async fn test_handle_tool_use_json_parse_error_adds_tool_use_to_content(
4348        cx: &mut TestAppContext,
4349    ) {
4350        let (thread, event_stream) = setup_thread_for_test(cx).await;
4351
4352        let tool_use_id = LanguageModelToolUseId::from("test_tool_id");
4353        let tool_name: Arc<str> = Arc::from("test_tool");
4354        let raw_input: Arc<str> = Arc::from("{invalid json");
4355        let json_parse_error = "expected value at line 1 column 1".to_string();
4356
4357        let (_cancellation_tx, cancellation_rx) = watch::channel(false);
4358
4359        let result = cx
4360            .update(|cx| {
4361                thread.update(cx, |thread, cx| {
4362                    // Call the function under test
4363                    thread
4364                        .handle_tool_use_json_parse_error_event(
4365                            tool_use_id.clone(),
4366                            tool_name.clone(),
4367                            raw_input.clone(),
4368                            json_parse_error,
4369                            &event_stream,
4370                            cancellation_rx,
4371                            cx,
4372                        )
4373                        .unwrap()
4374                })
4375            })
4376            .await;
4377
4378        // Verify the result is an error
4379        assert!(result.is_error);
4380        assert_eq!(result.tool_use_id, tool_use_id);
4381        assert_eq!(result.tool_name, tool_name);
4382        assert!(matches!(
4383            result.content,
4384            LanguageModelToolResultContent::Text(_)
4385        ));
4386
4387        thread.update(cx, |thread, _cx| {
4388            // Verify the tool use was added to the message content
4389            {
4390                let last_message = thread.pending_message();
4391                assert_eq!(
4392                    last_message.content.len(),
4393                    1,
4394                    "Should have one tool_use in content"
4395                );
4396
4397                match &last_message.content[0] {
4398                    AgentMessageContent::ToolUse(tool_use) => {
4399                        assert_eq!(tool_use.id, tool_use_id);
4400                        assert_eq!(tool_use.name, tool_name);
4401                        assert_eq!(tool_use.raw_input, raw_input.to_string());
4402                        assert!(tool_use.is_input_complete);
4403                        // Should fall back to empty object for invalid JSON
4404                        assert_eq!(tool_use.input, json!({}));
4405                    }
4406                    _ => panic!("Expected ToolUse content"),
4407                }
4408            }
4409
4410            // Insert the tool result (simulating what the caller does)
4411            thread
4412                .pending_message()
4413                .tool_results
4414                .insert(result.tool_use_id.clone(), result);
4415
4416            // Verify the tool result was added
4417            let last_message = thread.pending_message();
4418            assert_eq!(
4419                last_message.tool_results.len(),
4420                1,
4421                "Should have one tool_result"
4422            );
4423            assert!(last_message.tool_results.contains_key(&tool_use_id));
4424        })
4425    }
4426}