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 speed = settings
1045            .default_model
1046            .as_ref()
1047            .and_then(|model| model.speed);
1048        let (prompt_capabilities_tx, prompt_capabilities_rx) =
1049            watch::channel(Self::prompt_capabilities(model.as_deref()));
1050        Self {
1051            id: acp::SessionId::new(uuid::Uuid::new_v4().to_string()),
1052            prompt_id: PromptId::new(),
1053            updated_at: Utc::now(),
1054            title: None,
1055            pending_title_generation: None,
1056            pending_summary_generation: None,
1057            summary: None,
1058            messages: Vec::new(),
1059            user_store: project.read(cx).user_store(),
1060            running_turn: None,
1061            has_queued_message: false,
1062            pending_message: None,
1063            tools: BTreeMap::default(),
1064            request_token_usage: HashMap::default(),
1065            cumulative_token_usage: TokenUsage::default(),
1066            initial_project_snapshot: {
1067                let project_snapshot = Self::project_snapshot(project.clone(), cx);
1068                cx.foreground_executor()
1069                    .spawn(async move { Some(project_snapshot.await) })
1070                    .shared()
1071            },
1072            context_server_registry,
1073            profile_id,
1074            project_context,
1075            templates,
1076            model,
1077            summarization_model: None,
1078            thinking_enabled: enable_thinking,
1079            speed,
1080            thinking_effort,
1081            prompt_capabilities_tx,
1082            prompt_capabilities_rx,
1083            project,
1084            action_log,
1085            imported: false,
1086            subagent_context: None,
1087            draft_prompt: None,
1088            ui_scroll_position: None,
1089            running_subagents: Vec::new(),
1090        }
1091    }
1092
1093    /// Copies runtime-mutable settings from the parent thread so that
1094    /// subagents start with the same configuration the user selected.
1095    /// Every property that `set_*` propagates to `running_subagents`
1096    /// should be inherited here as well.
1097    fn inherit_parent_settings(&mut self, parent_thread: &Entity<Thread>, cx: &mut Context<Self>) {
1098        let parent = parent_thread.read(cx);
1099        self.speed = parent.speed;
1100        self.thinking_enabled = parent.thinking_enabled;
1101        self.thinking_effort = parent.thinking_effort.clone();
1102        self.summarization_model = parent.summarization_model.clone();
1103        self.profile_id = parent.profile_id.clone();
1104    }
1105
1106    pub fn id(&self) -> &acp::SessionId {
1107        &self.id
1108    }
1109
1110    /// Returns true if this thread was imported from a shared thread.
1111    pub fn is_imported(&self) -> bool {
1112        self.imported
1113    }
1114
1115    pub fn replay(
1116        &mut self,
1117        cx: &mut Context<Self>,
1118    ) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {
1119        let (tx, rx) = mpsc::unbounded();
1120        let stream = ThreadEventStream(tx);
1121        for message in &self.messages {
1122            match message {
1123                Message::User(user_message) => stream.send_user_message(user_message),
1124                Message::Agent(assistant_message) => {
1125                    for content in &assistant_message.content {
1126                        match content {
1127                            AgentMessageContent::Text(text) => stream.send_text(text),
1128                            AgentMessageContent::Thinking { text, .. } => {
1129                                stream.send_thinking(text)
1130                            }
1131                            AgentMessageContent::RedactedThinking(_) => {}
1132                            AgentMessageContent::ToolUse(tool_use) => {
1133                                self.replay_tool_call(
1134                                    tool_use,
1135                                    assistant_message.tool_results.get(&tool_use.id),
1136                                    &stream,
1137                                    cx,
1138                                );
1139                            }
1140                        }
1141                    }
1142                }
1143                Message::Resume => {}
1144            }
1145        }
1146        rx
1147    }
1148
1149    fn replay_tool_call(
1150        &self,
1151        tool_use: &LanguageModelToolUse,
1152        tool_result: Option<&LanguageModelToolResult>,
1153        stream: &ThreadEventStream,
1154        cx: &mut Context<Self>,
1155    ) {
1156        // Extract saved output and status first, so they're available even if tool is not found
1157        let output = tool_result
1158            .as_ref()
1159            .and_then(|result| result.output.clone());
1160        let status = tool_result
1161            .as_ref()
1162            .map_or(acp::ToolCallStatus::Failed, |result| {
1163                if result.is_error {
1164                    acp::ToolCallStatus::Failed
1165                } else {
1166                    acp::ToolCallStatus::Completed
1167                }
1168            });
1169
1170        let tool = self.tools.get(tool_use.name.as_ref()).cloned().or_else(|| {
1171            self.context_server_registry
1172                .read(cx)
1173                .servers()
1174                .find_map(|(_, tools)| {
1175                    if let Some(tool) = tools.get(tool_use.name.as_ref()) {
1176                        Some(tool.clone())
1177                    } else {
1178                        None
1179                    }
1180                })
1181        });
1182
1183        let Some(tool) = tool else {
1184            // Tool not found (e.g., MCP server not connected after restart),
1185            // but still display the saved result if available.
1186            // We need to send both ToolCall and ToolCallUpdate events because the UI
1187            // only converts raw_output to displayable content in update_fields, not from_acp.
1188            stream
1189                .0
1190                .unbounded_send(Ok(ThreadEvent::ToolCall(
1191                    acp::ToolCall::new(tool_use.id.to_string(), tool_use.name.to_string())
1192                        .status(status)
1193                        .raw_input(tool_use.input.clone()),
1194                )))
1195                .ok();
1196            stream.update_tool_call_fields(
1197                &tool_use.id,
1198                acp::ToolCallUpdateFields::new()
1199                    .status(status)
1200                    .raw_output(output),
1201                None,
1202            );
1203            return;
1204        };
1205
1206        let title = tool.initial_title(tool_use.input.clone(), cx);
1207        let kind = tool.kind();
1208        stream.send_tool_call(
1209            &tool_use.id,
1210            &tool_use.name,
1211            title,
1212            kind,
1213            tool_use.input.clone(),
1214        );
1215
1216        if let Some(output) = output.clone() {
1217            // For replay, we use a dummy cancellation receiver since the tool already completed
1218            let (_cancellation_tx, cancellation_rx) = watch::channel(false);
1219            let tool_event_stream = ToolCallEventStream::new(
1220                tool_use.id.clone(),
1221                stream.clone(),
1222                Some(self.project.read(cx).fs().clone()),
1223                cancellation_rx,
1224            );
1225            tool.replay(tool_use.input.clone(), output, tool_event_stream, cx)
1226                .log_err();
1227        }
1228
1229        stream.update_tool_call_fields(
1230            &tool_use.id,
1231            acp::ToolCallUpdateFields::new()
1232                .status(status)
1233                .raw_output(output),
1234            None,
1235        );
1236    }
1237
1238    pub fn from_db(
1239        id: acp::SessionId,
1240        db_thread: DbThread,
1241        project: Entity<Project>,
1242        project_context: Entity<ProjectContext>,
1243        context_server_registry: Entity<ContextServerRegistry>,
1244        templates: Arc<Templates>,
1245        cx: &mut Context<Self>,
1246    ) -> Self {
1247        let settings = AgentSettings::get_global(cx);
1248        let profile_id = db_thread
1249            .profile
1250            .unwrap_or_else(|| settings.default_profile.clone());
1251
1252        let mut model = LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1253            db_thread
1254                .model
1255                .and_then(|model| {
1256                    let model = SelectedModel {
1257                        provider: model.provider.clone().into(),
1258                        model: model.model.into(),
1259                    };
1260                    registry.select_model(&model, cx)
1261                })
1262                .or_else(|| registry.default_model())
1263                .map(|model| model.model)
1264        });
1265
1266        if model.is_none() {
1267            model = Self::resolve_profile_model(&profile_id, cx);
1268        }
1269        if model.is_none() {
1270            model = LanguageModelRegistry::global(cx).update(cx, |registry, _cx| {
1271                registry.default_model().map(|model| model.model)
1272            });
1273        }
1274
1275        let (prompt_capabilities_tx, prompt_capabilities_rx) =
1276            watch::channel(Self::prompt_capabilities(model.as_deref()));
1277
1278        let action_log = cx.new(|_| ActionLog::new(project.clone()));
1279
1280        Self {
1281            id,
1282            prompt_id: PromptId::new(),
1283            title: if db_thread.title.is_empty() {
1284                None
1285            } else {
1286                Some(db_thread.title.clone())
1287            },
1288            pending_title_generation: None,
1289            pending_summary_generation: None,
1290            summary: db_thread.detailed_summary,
1291            messages: db_thread.messages,
1292            user_store: project.read(cx).user_store(),
1293            running_turn: None,
1294            has_queued_message: false,
1295            pending_message: None,
1296            tools: BTreeMap::default(),
1297            request_token_usage: db_thread.request_token_usage.clone(),
1298            cumulative_token_usage: db_thread.cumulative_token_usage,
1299            initial_project_snapshot: Task::ready(db_thread.initial_project_snapshot).shared(),
1300            context_server_registry,
1301            profile_id,
1302            project_context,
1303            templates,
1304            model,
1305            summarization_model: None,
1306            thinking_enabled: db_thread.thinking_enabled,
1307            thinking_effort: db_thread.thinking_effort,
1308            speed: db_thread.speed,
1309            project,
1310            action_log,
1311            updated_at: db_thread.updated_at,
1312            prompt_capabilities_tx,
1313            prompt_capabilities_rx,
1314            imported: db_thread.imported,
1315            subagent_context: db_thread.subagent_context,
1316            draft_prompt: db_thread.draft_prompt,
1317            ui_scroll_position: db_thread.ui_scroll_position.map(|sp| gpui::ListOffset {
1318                item_ix: sp.item_ix,
1319                offset_in_item: gpui::px(sp.offset_in_item),
1320            }),
1321            running_subagents: Vec::new(),
1322        }
1323    }
1324
1325    pub fn to_db(&self, cx: &App) -> Task<DbThread> {
1326        let initial_project_snapshot = self.initial_project_snapshot.clone();
1327        let mut thread = DbThread {
1328            title: self.title().unwrap_or_default(),
1329            messages: self.messages.clone(),
1330            updated_at: self.updated_at,
1331            detailed_summary: self.summary.clone(),
1332            initial_project_snapshot: None,
1333            cumulative_token_usage: self.cumulative_token_usage,
1334            request_token_usage: self.request_token_usage.clone(),
1335            model: self.model.as_ref().map(|model| DbLanguageModel {
1336                provider: model.provider_id().to_string(),
1337                model: model.id().0.to_string(),
1338            }),
1339            profile: Some(self.profile_id.clone()),
1340            imported: self.imported,
1341            subagent_context: self.subagent_context.clone(),
1342            speed: self.speed,
1343            thinking_enabled: self.thinking_enabled,
1344            thinking_effort: self.thinking_effort.clone(),
1345            draft_prompt: self.draft_prompt.clone(),
1346            ui_scroll_position: self.ui_scroll_position.map(|lo| {
1347                crate::db::SerializedScrollPosition {
1348                    item_ix: lo.item_ix,
1349                    offset_in_item: lo.offset_in_item.as_f32(),
1350                }
1351            }),
1352        };
1353
1354        cx.background_spawn(async move {
1355            let initial_project_snapshot = initial_project_snapshot.await;
1356            thread.initial_project_snapshot = initial_project_snapshot;
1357            thread
1358        })
1359    }
1360
1361    /// Create a snapshot of the current project state including git information and unsaved buffers.
1362    fn project_snapshot(
1363        project: Entity<Project>,
1364        cx: &mut Context<Self>,
1365    ) -> Task<Arc<ProjectSnapshot>> {
1366        let task = project::telemetry_snapshot::TelemetrySnapshot::new(&project, cx);
1367        cx.spawn(async move |_, _| {
1368            let snapshot = task.await;
1369
1370            Arc::new(ProjectSnapshot {
1371                worktree_snapshots: snapshot.worktree_snapshots,
1372                timestamp: Utc::now(),
1373            })
1374        })
1375    }
1376
1377    pub fn project_context(&self) -> &Entity<ProjectContext> {
1378        &self.project_context
1379    }
1380
1381    pub fn project(&self) -> &Entity<Project> {
1382        &self.project
1383    }
1384
1385    pub fn action_log(&self) -> &Entity<ActionLog> {
1386        &self.action_log
1387    }
1388
1389    pub fn is_empty(&self) -> bool {
1390        self.messages.is_empty() && self.title.is_none()
1391    }
1392
1393    pub fn draft_prompt(&self) -> Option<&[acp::ContentBlock]> {
1394        self.draft_prompt.as_deref()
1395    }
1396
1397    pub fn set_draft_prompt(&mut self, prompt: Option<Vec<acp::ContentBlock>>) {
1398        self.draft_prompt = prompt;
1399    }
1400
1401    pub fn ui_scroll_position(&self) -> Option<gpui::ListOffset> {
1402        self.ui_scroll_position
1403    }
1404
1405    pub fn set_ui_scroll_position(&mut self, position: Option<gpui::ListOffset>) {
1406        self.ui_scroll_position = position;
1407    }
1408
1409    pub fn model(&self) -> Option<&Arc<dyn LanguageModel>> {
1410        self.model.as_ref()
1411    }
1412
1413    pub fn set_model(&mut self, model: Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
1414        let old_usage = self.latest_token_usage();
1415        self.model = Some(model.clone());
1416        let new_caps = Self::prompt_capabilities(self.model.as_deref());
1417        let new_usage = self.latest_token_usage();
1418        if old_usage != new_usage {
1419            cx.emit(TokenUsageUpdated(new_usage));
1420        }
1421        self.prompt_capabilities_tx.send(new_caps).log_err();
1422
1423        for subagent in &self.running_subagents {
1424            subagent
1425                .update(cx, |thread, cx| thread.set_model(model.clone(), cx))
1426                .ok();
1427        }
1428
1429        cx.notify()
1430    }
1431
1432    pub fn summarization_model(&self) -> Option<&Arc<dyn LanguageModel>> {
1433        self.summarization_model.as_ref()
1434    }
1435
1436    pub fn set_summarization_model(
1437        &mut self,
1438        model: Option<Arc<dyn LanguageModel>>,
1439        cx: &mut Context<Self>,
1440    ) {
1441        self.summarization_model = model.clone();
1442
1443        for subagent in &self.running_subagents {
1444            subagent
1445                .update(cx, |thread, cx| {
1446                    thread.set_summarization_model(model.clone(), cx)
1447                })
1448                .ok();
1449        }
1450        cx.notify()
1451    }
1452
1453    pub fn thinking_enabled(&self) -> bool {
1454        self.thinking_enabled
1455    }
1456
1457    pub fn set_thinking_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
1458        self.thinking_enabled = enabled;
1459
1460        for subagent in &self.running_subagents {
1461            subagent
1462                .update(cx, |thread, cx| thread.set_thinking_enabled(enabled, cx))
1463                .ok();
1464        }
1465        cx.notify();
1466    }
1467
1468    pub fn thinking_effort(&self) -> Option<&String> {
1469        self.thinking_effort.as_ref()
1470    }
1471
1472    pub fn set_thinking_effort(&mut self, effort: Option<String>, cx: &mut Context<Self>) {
1473        self.thinking_effort = effort.clone();
1474
1475        for subagent in &self.running_subagents {
1476            subagent
1477                .update(cx, |thread, cx| {
1478                    thread.set_thinking_effort(effort.clone(), cx)
1479                })
1480                .ok();
1481        }
1482        cx.notify();
1483    }
1484
1485    pub fn speed(&self) -> Option<Speed> {
1486        self.speed
1487    }
1488
1489    pub fn set_speed(&mut self, speed: Speed, cx: &mut Context<Self>) {
1490        self.speed = Some(speed);
1491
1492        for subagent in &self.running_subagents {
1493            subagent
1494                .update(cx, |thread, cx| thread.set_speed(speed, cx))
1495                .ok();
1496        }
1497        cx.notify();
1498    }
1499
1500    pub fn last_message(&self) -> Option<&Message> {
1501        self.messages.last()
1502    }
1503
1504    #[cfg(any(test, feature = "test-support"))]
1505    pub fn last_received_or_pending_message(&self) -> Option<Message> {
1506        if let Some(message) = self.pending_message.clone() {
1507            Some(Message::Agent(message))
1508        } else {
1509            self.messages.last().cloned()
1510        }
1511    }
1512
1513    pub fn add_default_tools(
1514        &mut self,
1515        environment: Rc<dyn ThreadEnvironment>,
1516        cx: &mut Context<Self>,
1517    ) {
1518        // Only update the agent location for the root thread, not for subagents.
1519        let update_agent_location = self.parent_thread_id().is_none();
1520
1521        let language_registry = self.project.read(cx).languages().clone();
1522        self.add_tool(CopyPathTool::new(self.project.clone()));
1523        self.add_tool(CreateDirectoryTool::new(self.project.clone()));
1524        self.add_tool(DeletePathTool::new(
1525            self.project.clone(),
1526            self.action_log.clone(),
1527        ));
1528        self.add_tool(DiagnosticsTool::new(self.project.clone()));
1529        self.add_tool(EditFileTool::new(
1530            self.project.clone(),
1531            cx.weak_entity(),
1532            language_registry.clone(),
1533            Templates::new(),
1534        ));
1535        self.add_tool(StreamingEditFileTool::new(
1536            self.project.clone(),
1537            cx.weak_entity(),
1538            self.action_log.clone(),
1539            language_registry,
1540        ));
1541        self.add_tool(FetchTool::new(self.project.read(cx).client().http_client()));
1542        self.add_tool(FindPathTool::new(self.project.clone()));
1543        self.add_tool(GrepTool::new(self.project.clone()));
1544        self.add_tool(ListDirectoryTool::new(self.project.clone()));
1545        self.add_tool(MovePathTool::new(self.project.clone()));
1546        self.add_tool(NowTool);
1547        self.add_tool(OpenTool::new(self.project.clone()));
1548        if cx.has_flag::<UpdatePlanToolFeatureFlag>() {
1549            self.add_tool(UpdatePlanTool);
1550        }
1551        self.add_tool(ReadFileTool::new(
1552            self.project.clone(),
1553            self.action_log.clone(),
1554            update_agent_location,
1555        ));
1556        self.add_tool(SaveFileTool::new(self.project.clone()));
1557        self.add_tool(RestoreFileFromDiskTool::new(self.project.clone()));
1558        self.add_tool(TerminalTool::new(self.project.clone(), environment.clone()));
1559        self.add_tool(WebSearchTool);
1560
1561        if self.depth() < MAX_SUBAGENT_DEPTH {
1562            self.add_tool(SpawnAgentTool::new(environment));
1563        }
1564    }
1565
1566    pub fn add_tool<T: AgentTool>(&mut self, tool: T) {
1567        debug_assert!(
1568            !self.tools.contains_key(T::NAME),
1569            "Duplicate tool name: {}",
1570            T::NAME,
1571        );
1572        self.tools.insert(T::NAME.into(), tool.erase());
1573    }
1574
1575    #[cfg(any(test, feature = "test-support"))]
1576    pub fn remove_tool(&mut self, name: &str) -> bool {
1577        self.tools.remove(name).is_some()
1578    }
1579
1580    pub fn profile(&self) -> &AgentProfileId {
1581        &self.profile_id
1582    }
1583
1584    pub fn set_profile(&mut self, profile_id: AgentProfileId, cx: &mut Context<Self>) {
1585        if self.profile_id == profile_id {
1586            return;
1587        }
1588
1589        self.profile_id = profile_id.clone();
1590
1591        // Swap to the profile's preferred model when available.
1592        if let Some(model) = Self::resolve_profile_model(&self.profile_id, cx) {
1593            self.set_model(model, cx);
1594        }
1595
1596        for subagent in &self.running_subagents {
1597            subagent
1598                .update(cx, |thread, cx| thread.set_profile(profile_id.clone(), cx))
1599                .ok();
1600        }
1601    }
1602
1603    pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
1604        for subagent in self.running_subagents.drain(..) {
1605            if let Some(subagent) = subagent.upgrade() {
1606                subagent.update(cx, |thread, cx| thread.cancel(cx)).detach();
1607            }
1608        }
1609
1610        let Some(running_turn) = self.running_turn.take() else {
1611            self.flush_pending_message(cx);
1612            return Task::ready(());
1613        };
1614
1615        let turn_task = running_turn.cancel();
1616
1617        cx.spawn(async move |this, cx| {
1618            turn_task.await;
1619            this.update(cx, |this, cx| {
1620                this.flush_pending_message(cx);
1621            })
1622            .ok();
1623        })
1624    }
1625
1626    pub fn set_has_queued_message(&mut self, has_queued: bool) {
1627        self.has_queued_message = has_queued;
1628    }
1629
1630    pub fn has_queued_message(&self) -> bool {
1631        self.has_queued_message
1632    }
1633
1634    fn update_token_usage(&mut self, update: language_model::TokenUsage, cx: &mut Context<Self>) {
1635        let Some(last_user_message) = self.last_user_message() else {
1636            return;
1637        };
1638
1639        self.request_token_usage
1640            .insert(last_user_message.id.clone(), update);
1641        cx.emit(TokenUsageUpdated(self.latest_token_usage()));
1642        cx.notify();
1643    }
1644
1645    pub fn truncate(&mut self, message_id: UserMessageId, cx: &mut Context<Self>) -> Result<()> {
1646        self.cancel(cx).detach();
1647        // Clear pending message since cancel will try to flush it asynchronously,
1648        // and we don't want that content to be added after we truncate
1649        self.pending_message.take();
1650        let Some(position) = self.messages.iter().position(
1651            |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
1652        ) else {
1653            return Err(anyhow!("Message not found"));
1654        };
1655
1656        for message in self.messages.drain(position..) {
1657            match message {
1658                Message::User(message) => {
1659                    self.request_token_usage.remove(&message.id);
1660                }
1661                Message::Agent(_) | Message::Resume => {}
1662            }
1663        }
1664        self.clear_summary();
1665        cx.notify();
1666        Ok(())
1667    }
1668
1669    pub fn latest_request_token_usage(&self) -> Option<language_model::TokenUsage> {
1670        let last_user_message = self.last_user_message()?;
1671        let tokens = self.request_token_usage.get(&last_user_message.id)?;
1672        Some(*tokens)
1673    }
1674
1675    pub fn latest_token_usage(&self) -> Option<acp_thread::TokenUsage> {
1676        let usage = self.latest_request_token_usage()?;
1677        let model = self.model.clone()?;
1678        Some(acp_thread::TokenUsage {
1679            max_tokens: model.max_token_count(),
1680            max_output_tokens: model.max_output_tokens(),
1681            used_tokens: usage.total_tokens(),
1682            input_tokens: usage.input_tokens,
1683            output_tokens: usage.output_tokens,
1684        })
1685    }
1686
1687    /// Get the total input token count as of the message before the given message.
1688    ///
1689    /// Returns `None` if:
1690    /// - `target_id` is the first message (no previous message)
1691    /// - The previous message hasn't received a response yet (no usage data)
1692    /// - `target_id` is not found in the messages
1693    pub fn tokens_before_message(&self, target_id: &UserMessageId) -> Option<u64> {
1694        let mut previous_user_message_id: Option<&UserMessageId> = None;
1695
1696        for message in &self.messages {
1697            if let Message::User(user_msg) = message {
1698                if &user_msg.id == target_id {
1699                    let prev_id = previous_user_message_id?;
1700                    let usage = self.request_token_usage.get(prev_id)?;
1701                    return Some(usage.input_tokens);
1702                }
1703                previous_user_message_id = Some(&user_msg.id);
1704            }
1705        }
1706        None
1707    }
1708
1709    /// Look up the active profile and resolve its preferred model if one is configured.
1710    fn resolve_profile_model(
1711        profile_id: &AgentProfileId,
1712        cx: &mut Context<Self>,
1713    ) -> Option<Arc<dyn LanguageModel>> {
1714        let selection = AgentSettings::get_global(cx)
1715            .profiles
1716            .get(profile_id)?
1717            .default_model
1718            .clone()?;
1719        Self::resolve_model_from_selection(&selection, cx)
1720    }
1721
1722    /// Translate a stored model selection into the configured model from the registry.
1723    fn resolve_model_from_selection(
1724        selection: &LanguageModelSelection,
1725        cx: &mut Context<Self>,
1726    ) -> Option<Arc<dyn LanguageModel>> {
1727        let selected = SelectedModel {
1728            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
1729            model: LanguageModelId::from(selection.model.clone()),
1730        };
1731        LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1732            registry
1733                .select_model(&selected, cx)
1734                .map(|configured| configured.model)
1735        })
1736    }
1737
1738    pub fn resume(
1739        &mut self,
1740        cx: &mut Context<Self>,
1741    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1742        self.messages.push(Message::Resume);
1743        cx.notify();
1744
1745        log::debug!("Total messages in thread: {}", self.messages.len());
1746        self.run_turn(cx)
1747    }
1748
1749    /// Sending a message results in the model streaming a response, which could include tool calls.
1750    /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
1751    /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
1752    pub fn send<T>(
1753        &mut self,
1754        id: UserMessageId,
1755        content: impl IntoIterator<Item = T>,
1756        cx: &mut Context<Self>,
1757    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
1758    where
1759        T: Into<UserMessageContent>,
1760    {
1761        let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
1762        log::debug!("Thread::send content: {:?}", content);
1763
1764        self.messages
1765            .push(Message::User(UserMessage { id, content }));
1766        cx.notify();
1767
1768        self.send_existing(cx)
1769    }
1770
1771    pub fn send_existing(
1772        &mut self,
1773        cx: &mut Context<Self>,
1774    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1775        let model = self.model().context("No language model configured")?;
1776
1777        log::info!("Thread::send called with model: {}", model.name().0);
1778        self.advance_prompt_id();
1779
1780        log::debug!("Total messages in thread: {}", self.messages.len());
1781        self.run_turn(cx)
1782    }
1783
1784    pub fn push_acp_user_block(
1785        &mut self,
1786        id: UserMessageId,
1787        blocks: impl IntoIterator<Item = acp::ContentBlock>,
1788        path_style: PathStyle,
1789        cx: &mut Context<Self>,
1790    ) {
1791        let content = blocks
1792            .into_iter()
1793            .map(|block| UserMessageContent::from_content_block(block, path_style))
1794            .collect::<Vec<_>>();
1795        self.messages
1796            .push(Message::User(UserMessage { id, content }));
1797        cx.notify();
1798    }
1799
1800    pub fn push_acp_agent_block(&mut self, block: acp::ContentBlock, cx: &mut Context<Self>) {
1801        let text = match block {
1802            acp::ContentBlock::Text(text_content) => text_content.text,
1803            acp::ContentBlock::Image(_) => "[image]".to_string(),
1804            acp::ContentBlock::Audio(_) => "[audio]".to_string(),
1805            acp::ContentBlock::ResourceLink(resource_link) => resource_link.uri,
1806            acp::ContentBlock::Resource(resource) => match resource.resource {
1807                acp::EmbeddedResourceResource::TextResourceContents(resource) => resource.uri,
1808                acp::EmbeddedResourceResource::BlobResourceContents(resource) => resource.uri,
1809                _ => "[resource]".to_string(),
1810            },
1811            _ => "[unknown]".to_string(),
1812        };
1813
1814        self.messages.push(Message::Agent(AgentMessage {
1815            content: vec![AgentMessageContent::Text(text)],
1816            ..Default::default()
1817        }));
1818        cx.notify();
1819    }
1820
1821    fn run_turn(
1822        &mut self,
1823        cx: &mut Context<Self>,
1824    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1825        // Flush the old pending message synchronously before cancelling,
1826        // to avoid a race where the detached cancel task might flush the NEW
1827        // turn's pending message instead of the old one.
1828        self.flush_pending_message(cx);
1829        self.cancel(cx).detach();
1830
1831        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1832        let event_stream = ThreadEventStream(events_tx);
1833        let message_ix = self.messages.len().saturating_sub(1);
1834        self.clear_summary();
1835        let (cancellation_tx, mut cancellation_rx) = watch::channel(false);
1836        self.running_turn = Some(RunningTurn {
1837            event_stream: event_stream.clone(),
1838            tools: self.enabled_tools(cx),
1839            cancellation_tx,
1840            streaming_tool_inputs: HashMap::default(),
1841            _task: cx.spawn(async move |this, cx| {
1842                log::debug!("Starting agent turn execution");
1843
1844                let turn_result =
1845                    Self::run_turn_internal(&this, &event_stream, cancellation_rx.clone(), cx)
1846                        .await;
1847
1848                // Check if we were cancelled - if so, cancel() already took running_turn
1849                // and we shouldn't touch it (it might be a NEW turn now)
1850                let was_cancelled = *cancellation_rx.borrow();
1851                if was_cancelled {
1852                    log::debug!("Turn was cancelled, skipping cleanup");
1853                    return;
1854                }
1855
1856                _ = this.update(cx, |this, cx| this.flush_pending_message(cx));
1857
1858                match turn_result {
1859                    Ok(()) => {
1860                        log::debug!("Turn execution completed");
1861                        event_stream.send_stop(acp::StopReason::EndTurn);
1862                    }
1863                    Err(error) => {
1864                        log::error!("Turn execution failed: {:?}", error);
1865                        match error.downcast::<CompletionError>() {
1866                            Ok(CompletionError::Refusal) => {
1867                                event_stream.send_stop(acp::StopReason::Refusal);
1868                                _ = this.update(cx, |this, _| this.messages.truncate(message_ix));
1869                            }
1870                            Ok(CompletionError::MaxTokens) => {
1871                                event_stream.send_stop(acp::StopReason::MaxTokens);
1872                            }
1873                            Ok(CompletionError::Other(error)) | Err(error) => {
1874                                event_stream.send_error(error);
1875                            }
1876                        }
1877                    }
1878                }
1879
1880                _ = this.update(cx, |this, _| this.running_turn.take());
1881            }),
1882        });
1883        Ok(events_rx)
1884    }
1885
1886    async fn run_turn_internal(
1887        this: &WeakEntity<Self>,
1888        event_stream: &ThreadEventStream,
1889        mut cancellation_rx: watch::Receiver<bool>,
1890        cx: &mut AsyncApp,
1891    ) -> Result<()> {
1892        let mut attempt = 0;
1893        let mut intent = CompletionIntent::UserPrompt;
1894        loop {
1895            // Re-read the model and refresh tools on each iteration so that
1896            // mid-turn changes (e.g. the user switches model, toggles tools,
1897            // or changes profile) take effect between tool-call rounds.
1898            let (model, request) = this.update(cx, |this, cx| {
1899                let model = this.model.clone().context("No language model configured")?;
1900                this.refresh_turn_tools(cx);
1901                let request = this.build_completion_request(intent, cx)?;
1902                anyhow::Ok((model, request))
1903            })??;
1904
1905            telemetry::event!(
1906                "Agent Thread Completion",
1907                thread_id = this.read_with(cx, |this, _| this.id.to_string())?,
1908                parent_thread_id = this.read_with(cx, |this, _| this
1909                    .parent_thread_id()
1910                    .map(|id| id.to_string()))?,
1911                prompt_id = this.read_with(cx, |this, _| this.prompt_id.to_string())?,
1912                model = model.telemetry_id(),
1913                model_provider = model.provider_id().to_string(),
1914                attempt
1915            );
1916
1917            log::debug!("Calling model.stream_completion, attempt {}", attempt);
1918
1919            let (mut events, mut error) = match model.stream_completion(request, cx).await {
1920                Ok(events) => (events.fuse(), None),
1921                Err(err) => (stream::empty().boxed().fuse(), Some(err)),
1922            };
1923            let mut tool_results: FuturesUnordered<Task<LanguageModelToolResult>> =
1924                FuturesUnordered::new();
1925            let mut early_tool_results: Vec<LanguageModelToolResult> = Vec::new();
1926            let mut cancelled = false;
1927            loop {
1928                // Race between getting the first event, tool completion, and cancellation.
1929                let first_event = futures::select! {
1930                    event = events.next().fuse() => event,
1931                    tool_result = futures::StreamExt::select_next_some(&mut tool_results) => {
1932                        let is_error = tool_result.is_error;
1933                        let is_still_streaming = this
1934                            .read_with(cx, |this, _cx| {
1935                                this.running_turn
1936                                    .as_ref()
1937                                    .and_then(|turn| turn.streaming_tool_inputs.get(&tool_result.tool_use_id))
1938                                    .map_or(false, |inputs| !inputs.has_received_final())
1939                            })
1940                            .unwrap_or(false);
1941
1942                        early_tool_results.push(tool_result);
1943
1944                        // Only break if the tool errored and we are still
1945                        // streaming the input of the tool. If the tool errored
1946                        // but we are no longer streaming its input (i.e. there
1947                        // are parallel tool calls) we want to continue
1948                        // processing those tool inputs.
1949                        if is_error && is_still_streaming {
1950                            break;
1951                        }
1952                        continue;
1953                    }
1954                    _ = cancellation_rx.changed().fuse() => {
1955                        if *cancellation_rx.borrow() {
1956                            cancelled = true;
1957                            break;
1958                        }
1959                        continue;
1960                    }
1961                };
1962                let Some(first_event) = first_event else {
1963                    break;
1964                };
1965
1966                // Collect all immediately available events to process as a batch
1967                let mut batch = vec![first_event];
1968                while let Some(event) = events.next().now_or_never().flatten() {
1969                    batch.push(event);
1970                }
1971
1972                // Process the batch in a single update
1973                let batch_result = this.update(cx, |this, cx| {
1974                    let mut batch_tool_results = Vec::new();
1975                    let mut batch_error = None;
1976
1977                    for event in batch {
1978                        log::trace!("Received completion event: {:?}", event);
1979                        match event {
1980                            Ok(event) => {
1981                                match this.handle_completion_event(
1982                                    event,
1983                                    event_stream,
1984                                    cancellation_rx.clone(),
1985                                    cx,
1986                                ) {
1987                                    Ok(Some(task)) => batch_tool_results.push(task),
1988                                    Ok(None) => {}
1989                                    Err(err) => {
1990                                        batch_error = Some(err);
1991                                        break;
1992                                    }
1993                                }
1994                            }
1995                            Err(err) => {
1996                                batch_error = Some(err.into());
1997                                break;
1998                            }
1999                        }
2000                    }
2001
2002                    cx.notify();
2003                    (batch_tool_results, batch_error)
2004                })?;
2005
2006                tool_results.extend(batch_result.0);
2007                if let Some(err) = batch_result.1 {
2008                    error = Some(err.downcast()?);
2009                    break;
2010                }
2011            }
2012
2013            // Drop the stream to release the rate limit permit before tool execution.
2014            // The stream holds a semaphore guard that limits concurrent requests.
2015            // Without this, the permit would be held during potentially long-running
2016            // tool execution, which could cause deadlocks when tools spawn subagents
2017            // that need their own permits.
2018            drop(events);
2019
2020            // Drop streaming tool input senders that never received their final input.
2021            // This prevents deadlock when the LLM stream ends (e.g. because of an error)
2022            // before sending a tool use with `is_input_complete: true`.
2023            this.update(cx, |this, _cx| {
2024                if let Some(running_turn) = this.running_turn.as_mut() {
2025                    if running_turn.streaming_tool_inputs.is_empty() {
2026                        return;
2027                    }
2028                    log::warn!("Dropping partial tool inputs because the stream ended");
2029                    running_turn.streaming_tool_inputs.drain();
2030                }
2031            })?;
2032
2033            let end_turn = tool_results.is_empty() && early_tool_results.is_empty();
2034
2035            for tool_result in early_tool_results {
2036                Self::process_tool_result(this, event_stream, cx, tool_result)?;
2037            }
2038            while let Some(tool_result) = tool_results.next().await {
2039                Self::process_tool_result(this, event_stream, cx, tool_result)?;
2040            }
2041
2042            this.update(cx, |this, cx| {
2043                this.flush_pending_message(cx);
2044                if this.title.is_none() && this.pending_title_generation.is_none() {
2045                    this.generate_title(cx);
2046                }
2047            })?;
2048
2049            if cancelled {
2050                log::debug!("Turn cancelled by user, exiting");
2051                return Ok(());
2052            }
2053
2054            if let Some(error) = error {
2055                attempt += 1;
2056                let retry = this.update(cx, |this, cx| {
2057                    let user_store = this.user_store.read(cx);
2058                    this.handle_completion_error(error, attempt, user_store.plan())
2059                })??;
2060                let timer = cx.background_executor().timer(retry.duration);
2061                event_stream.send_retry(retry);
2062                futures::select! {
2063                    _ = timer.fuse() => {}
2064                    _ = cancellation_rx.changed().fuse() => {
2065                        if *cancellation_rx.borrow() {
2066                            log::debug!("Turn cancelled during retry delay, exiting");
2067                            return Ok(());
2068                        }
2069                    }
2070                }
2071                this.update(cx, |this, _cx| {
2072                    if let Some(Message::Agent(message)) = this.messages.last() {
2073                        if message.tool_results.is_empty() {
2074                            intent = CompletionIntent::UserPrompt;
2075                            this.messages.push(Message::Resume);
2076                        }
2077                    }
2078                })?;
2079            } else if end_turn {
2080                return Ok(());
2081            } else {
2082                let has_queued = this.update(cx, |this, _| this.has_queued_message())?;
2083                if has_queued {
2084                    log::debug!("Queued message found, ending turn at message boundary");
2085                    return Ok(());
2086                }
2087                intent = CompletionIntent::ToolResults;
2088                attempt = 0;
2089            }
2090        }
2091    }
2092
2093    fn process_tool_result(
2094        this: &WeakEntity<Thread>,
2095        event_stream: &ThreadEventStream,
2096        cx: &mut AsyncApp,
2097        tool_result: LanguageModelToolResult,
2098    ) -> Result<(), anyhow::Error> {
2099        log::debug!("Tool finished {:?}", tool_result);
2100
2101        event_stream.update_tool_call_fields(
2102            &tool_result.tool_use_id,
2103            acp::ToolCallUpdateFields::new()
2104                .status(if tool_result.is_error {
2105                    acp::ToolCallStatus::Failed
2106                } else {
2107                    acp::ToolCallStatus::Completed
2108                })
2109                .raw_output(tool_result.output.clone()),
2110            None,
2111        );
2112        this.update(cx, |this, _cx| {
2113            this.pending_message()
2114                .tool_results
2115                .insert(tool_result.tool_use_id.clone(), tool_result)
2116        })?;
2117        Ok(())
2118    }
2119
2120    fn handle_completion_error(
2121        &mut self,
2122        error: LanguageModelCompletionError,
2123        attempt: u8,
2124        plan: Option<Plan>,
2125    ) -> Result<acp_thread::RetryStatus> {
2126        let Some(model) = self.model.as_ref() else {
2127            return Err(anyhow!(error));
2128        };
2129
2130        let auto_retry = if model.provider_id() == ZED_CLOUD_PROVIDER_ID {
2131            plan.is_some()
2132        } else {
2133            true
2134        };
2135
2136        if !auto_retry {
2137            return Err(anyhow!(error));
2138        }
2139
2140        let Some(strategy) = Self::retry_strategy_for(&error) else {
2141            return Err(anyhow!(error));
2142        };
2143
2144        let max_attempts = match &strategy {
2145            RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
2146            RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
2147        };
2148
2149        if attempt > max_attempts {
2150            return Err(anyhow!(error));
2151        }
2152
2153        let delay = match &strategy {
2154            RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
2155                let delay_secs = initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
2156                Duration::from_secs(delay_secs)
2157            }
2158            RetryStrategy::Fixed { delay, .. } => *delay,
2159        };
2160        log::debug!("Retry attempt {attempt} with delay {delay:?}");
2161
2162        Ok(acp_thread::RetryStatus {
2163            last_error: error.to_string().into(),
2164            attempt: attempt as usize,
2165            max_attempts: max_attempts as usize,
2166            started_at: Instant::now(),
2167            duration: delay,
2168        })
2169    }
2170
2171    /// A helper method that's called on every streamed completion event.
2172    /// Returns an optional tool result task, which the main agentic loop will
2173    /// send back to the model when it resolves.
2174    fn handle_completion_event(
2175        &mut self,
2176        event: LanguageModelCompletionEvent,
2177        event_stream: &ThreadEventStream,
2178        cancellation_rx: watch::Receiver<bool>,
2179        cx: &mut Context<Self>,
2180    ) -> Result<Option<Task<LanguageModelToolResult>>> {
2181        log::trace!("Handling streamed completion event: {:?}", event);
2182        use LanguageModelCompletionEvent::*;
2183
2184        match event {
2185            StartMessage { .. } => {
2186                self.flush_pending_message(cx);
2187                self.pending_message = Some(AgentMessage::default());
2188            }
2189            Text(new_text) => self.handle_text_event(new_text, event_stream),
2190            Thinking { text, signature } => {
2191                self.handle_thinking_event(text, signature, event_stream)
2192            }
2193            RedactedThinking { data } => self.handle_redacted_thinking_event(data),
2194            ReasoningDetails(details) => {
2195                let last_message = self.pending_message();
2196                // Store the last non-empty reasoning_details (overwrites earlier ones)
2197                // This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
2198                if let serde_json::Value::Array(ref arr) = details {
2199                    if !arr.is_empty() {
2200                        last_message.reasoning_details = Some(details);
2201                    }
2202                } else {
2203                    last_message.reasoning_details = Some(details);
2204                }
2205            }
2206            ToolUse(tool_use) => {
2207                return Ok(self.handle_tool_use_event(tool_use, event_stream, cancellation_rx, cx));
2208            }
2209            ToolUseJsonParseError {
2210                id,
2211                tool_name,
2212                raw_input,
2213                json_parse_error,
2214            } => {
2215                return Ok(self.handle_tool_use_json_parse_error_event(
2216                    id,
2217                    tool_name,
2218                    raw_input,
2219                    json_parse_error,
2220                    event_stream,
2221                    cancellation_rx,
2222                    cx,
2223                ));
2224            }
2225            UsageUpdate(usage) => {
2226                telemetry::event!(
2227                    "Agent Thread Completion Usage Updated",
2228                    thread_id = self.id.to_string(),
2229                    parent_thread_id = self.parent_thread_id().map(|id| id.to_string()),
2230                    prompt_id = self.prompt_id.to_string(),
2231                    model = self.model.as_ref().map(|m| m.telemetry_id()),
2232                    model_provider = self.model.as_ref().map(|m| m.provider_id().to_string()),
2233                    input_tokens = usage.input_tokens,
2234                    output_tokens = usage.output_tokens,
2235                    cache_creation_input_tokens = usage.cache_creation_input_tokens,
2236                    cache_read_input_tokens = usage.cache_read_input_tokens,
2237                );
2238                self.update_token_usage(usage, cx);
2239            }
2240            Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()),
2241            Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()),
2242            Stop(StopReason::ToolUse | StopReason::EndTurn) => {}
2243            Started | Queued { .. } => {}
2244        }
2245
2246        Ok(None)
2247    }
2248
2249    fn handle_text_event(&mut self, new_text: String, event_stream: &ThreadEventStream) {
2250        event_stream.send_text(&new_text);
2251
2252        let last_message = self.pending_message();
2253        if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
2254            text.push_str(&new_text);
2255        } else {
2256            last_message
2257                .content
2258                .push(AgentMessageContent::Text(new_text));
2259        }
2260    }
2261
2262    fn handle_thinking_event(
2263        &mut self,
2264        new_text: String,
2265        new_signature: Option<String>,
2266        event_stream: &ThreadEventStream,
2267    ) {
2268        event_stream.send_thinking(&new_text);
2269
2270        let last_message = self.pending_message();
2271        if let Some(AgentMessageContent::Thinking { text, signature }) =
2272            last_message.content.last_mut()
2273        {
2274            text.push_str(&new_text);
2275            *signature = new_signature.or(signature.take());
2276        } else {
2277            last_message.content.push(AgentMessageContent::Thinking {
2278                text: new_text,
2279                signature: new_signature,
2280            });
2281        }
2282    }
2283
2284    fn handle_redacted_thinking_event(&mut self, data: String) {
2285        let last_message = self.pending_message();
2286        last_message
2287            .content
2288            .push(AgentMessageContent::RedactedThinking(data));
2289    }
2290
2291    fn handle_tool_use_event(
2292        &mut self,
2293        tool_use: LanguageModelToolUse,
2294        event_stream: &ThreadEventStream,
2295        cancellation_rx: watch::Receiver<bool>,
2296        cx: &mut Context<Self>,
2297    ) -> Option<Task<LanguageModelToolResult>> {
2298        cx.notify();
2299
2300        let tool = self.tool(tool_use.name.as_ref());
2301        let mut title = SharedString::from(&tool_use.name);
2302        let mut kind = acp::ToolKind::Other;
2303        if let Some(tool) = tool.as_ref() {
2304            title = tool.initial_title(tool_use.input.clone(), cx);
2305            kind = tool.kind();
2306        }
2307
2308        self.send_or_update_tool_use(&tool_use, title, kind, event_stream);
2309
2310        let Some(tool) = tool else {
2311            let content = format!("No tool named {} exists", tool_use.name);
2312            return Some(Task::ready(LanguageModelToolResult {
2313                content: LanguageModelToolResultContent::Text(Arc::from(content)),
2314                tool_use_id: tool_use.id,
2315                tool_name: tool_use.name,
2316                is_error: true,
2317                output: None,
2318            }));
2319        };
2320
2321        if !tool_use.is_input_complete {
2322            if tool.supports_input_streaming() {
2323                let running_turn = self.running_turn.as_mut()?;
2324                if let Some(sender) = running_turn.streaming_tool_inputs.get_mut(&tool_use.id) {
2325                    sender.send_partial(tool_use.input);
2326                    return None;
2327                }
2328
2329                let (mut sender, tool_input) = ToolInputSender::channel();
2330                sender.send_partial(tool_use.input);
2331                running_turn
2332                    .streaming_tool_inputs
2333                    .insert(tool_use.id.clone(), sender);
2334
2335                let tool = tool.clone();
2336                log::debug!("Running streaming tool {}", tool_use.name);
2337                return Some(self.run_tool(
2338                    tool,
2339                    tool_input,
2340                    tool_use.id,
2341                    tool_use.name,
2342                    event_stream,
2343                    cancellation_rx,
2344                    cx,
2345                ));
2346            } else {
2347                return None;
2348            }
2349        }
2350
2351        if let Some(mut sender) = self
2352            .running_turn
2353            .as_mut()?
2354            .streaming_tool_inputs
2355            .remove(&tool_use.id)
2356        {
2357            sender.send_full(tool_use.input);
2358            return None;
2359        }
2360
2361        log::debug!("Running tool {}", tool_use.name);
2362        let tool_input = ToolInput::ready(tool_use.input);
2363        Some(self.run_tool(
2364            tool,
2365            tool_input,
2366            tool_use.id,
2367            tool_use.name,
2368            event_stream,
2369            cancellation_rx,
2370            cx,
2371        ))
2372    }
2373
2374    fn run_tool(
2375        &self,
2376        tool: Arc<dyn AnyAgentTool>,
2377        tool_input: ToolInput<serde_json::Value>,
2378        tool_use_id: LanguageModelToolUseId,
2379        tool_name: Arc<str>,
2380        event_stream: &ThreadEventStream,
2381        cancellation_rx: watch::Receiver<bool>,
2382        cx: &mut Context<Self>,
2383    ) -> Task<LanguageModelToolResult> {
2384        let fs = self.project.read(cx).fs().clone();
2385        let tool_event_stream = ToolCallEventStream::new(
2386            tool_use_id.clone(),
2387            event_stream.clone(),
2388            Some(fs),
2389            cancellation_rx,
2390        );
2391        tool_event_stream.update_fields(
2392            acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
2393        );
2394        let supports_images = self.model().is_some_and(|model| model.supports_images());
2395        let tool_result = tool.run(tool_input, tool_event_stream, cx);
2396        cx.foreground_executor().spawn(async move {
2397            let (is_error, output) = match tool_result.await {
2398                Ok(mut output) => {
2399                    if let LanguageModelToolResultContent::Image(_) = &output.llm_output
2400                        && !supports_images
2401                    {
2402                        output = AgentToolOutput::from_error(
2403                            "Attempted to read an image, but this model doesn't support it.",
2404                        );
2405                        (true, output)
2406                    } else {
2407                        (false, output)
2408                    }
2409                }
2410                Err(output) => (true, output),
2411            };
2412
2413            LanguageModelToolResult {
2414                tool_use_id,
2415                tool_name,
2416                is_error,
2417                content: output.llm_output,
2418                output: Some(output.raw_output),
2419            }
2420        })
2421    }
2422
2423    fn handle_tool_use_json_parse_error_event(
2424        &mut self,
2425        tool_use_id: LanguageModelToolUseId,
2426        tool_name: Arc<str>,
2427        raw_input: Arc<str>,
2428        json_parse_error: String,
2429        event_stream: &ThreadEventStream,
2430        cancellation_rx: watch::Receiver<bool>,
2431        cx: &mut Context<Self>,
2432    ) -> Option<Task<LanguageModelToolResult>> {
2433        let tool_use = LanguageModelToolUse {
2434            id: tool_use_id,
2435            name: tool_name,
2436            raw_input: raw_input.to_string(),
2437            input: serde_json::json!({}),
2438            is_input_complete: true,
2439            thought_signature: None,
2440        };
2441        self.send_or_update_tool_use(
2442            &tool_use,
2443            SharedString::from(&tool_use.name),
2444            acp::ToolKind::Other,
2445            event_stream,
2446        );
2447
2448        let tool = self.tool(tool_use.name.as_ref());
2449
2450        let Some(tool) = tool else {
2451            let content = format!("No tool named {} exists", tool_use.name);
2452            return Some(Task::ready(LanguageModelToolResult {
2453                content: LanguageModelToolResultContent::Text(Arc::from(content)),
2454                tool_use_id: tool_use.id,
2455                tool_name: tool_use.name,
2456                is_error: true,
2457                output: None,
2458            }));
2459        };
2460
2461        let error_message = format!("Error parsing input JSON: {json_parse_error}");
2462
2463        if tool.supports_input_streaming()
2464            && let Some(mut sender) = self
2465                .running_turn
2466                .as_mut()?
2467                .streaming_tool_inputs
2468                .remove(&tool_use.id)
2469        {
2470            sender.send_invalid_json(error_message);
2471            return None;
2472        }
2473
2474        log::debug!("Running tool {}. Received invalid JSON", tool_use.name);
2475        let tool_input = ToolInput::invalid_json(error_message);
2476        Some(self.run_tool(
2477            tool,
2478            tool_input,
2479            tool_use.id,
2480            tool_use.name,
2481            event_stream,
2482            cancellation_rx,
2483            cx,
2484        ))
2485    }
2486
2487    fn send_or_update_tool_use(
2488        &mut self,
2489        tool_use: &LanguageModelToolUse,
2490        title: SharedString,
2491        kind: acp::ToolKind,
2492        event_stream: &ThreadEventStream,
2493    ) {
2494        // Ensure the last message ends in the current tool use
2495        let last_message = self.pending_message();
2496
2497        let has_tool_use = last_message.content.iter_mut().rev().any(|content| {
2498            if let AgentMessageContent::ToolUse(last_tool_use) = content {
2499                if last_tool_use.id == tool_use.id {
2500                    *last_tool_use = tool_use.clone();
2501                    return true;
2502                }
2503            }
2504            false
2505        });
2506
2507        if !has_tool_use {
2508            event_stream.send_tool_call(
2509                &tool_use.id,
2510                &tool_use.name,
2511                title,
2512                kind,
2513                tool_use.input.clone(),
2514            );
2515            last_message
2516                .content
2517                .push(AgentMessageContent::ToolUse(tool_use.clone()));
2518        } else {
2519            event_stream.update_tool_call_fields(
2520                &tool_use.id,
2521                acp::ToolCallUpdateFields::new()
2522                    .title(title.as_str())
2523                    .kind(kind)
2524                    .raw_input(tool_use.input.clone()),
2525                None,
2526            );
2527        }
2528    }
2529
2530    pub fn title(&self) -> Option<SharedString> {
2531        self.title.clone()
2532    }
2533
2534    pub fn is_generating_summary(&self) -> bool {
2535        self.pending_summary_generation.is_some()
2536    }
2537
2538    pub fn is_generating_title(&self) -> bool {
2539        self.pending_title_generation.is_some()
2540    }
2541
2542    pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
2543        if let Some(summary) = self.summary.as_ref() {
2544            return Task::ready(Some(summary.clone())).shared();
2545        }
2546        if let Some(task) = self.pending_summary_generation.clone() {
2547            return task;
2548        }
2549        let Some(model) = self.summarization_model.clone() else {
2550            log::error!("No summarization model available");
2551            return Task::ready(None).shared();
2552        };
2553        let mut request = LanguageModelRequest {
2554            intent: Some(CompletionIntent::ThreadContextSummarization),
2555            temperature: AgentSettings::temperature_for_model(&model, cx),
2556            ..Default::default()
2557        };
2558
2559        for message in &self.messages {
2560            request.messages.extend(message.to_request());
2561        }
2562
2563        request.messages.push(LanguageModelRequestMessage {
2564            role: Role::User,
2565            content: vec![SUMMARIZE_THREAD_DETAILED_PROMPT.into()],
2566            cache: false,
2567            reasoning_details: None,
2568        });
2569
2570        let task = cx
2571            .spawn(async move |this, cx| {
2572                let mut summary = String::new();
2573                let mut messages = model.stream_completion(request, cx).await.log_err()?;
2574                while let Some(event) = messages.next().await {
2575                    let event = event.log_err()?;
2576                    let text = match event {
2577                        LanguageModelCompletionEvent::Text(text) => text,
2578                        _ => continue,
2579                    };
2580
2581                    let mut lines = text.lines();
2582                    summary.extend(lines.next());
2583                }
2584
2585                log::debug!("Setting summary: {}", summary);
2586                let summary = SharedString::from(summary);
2587
2588                this.update(cx, |this, cx| {
2589                    this.summary = Some(summary.clone());
2590                    this.pending_summary_generation = None;
2591                    cx.notify()
2592                })
2593                .ok()?;
2594
2595                Some(summary)
2596            })
2597            .shared();
2598        self.pending_summary_generation = Some(task.clone());
2599        task
2600    }
2601
2602    pub fn generate_title(&mut self, cx: &mut Context<Self>) {
2603        let Some(model) = self.summarization_model.clone() else {
2604            return;
2605        };
2606
2607        log::debug!(
2608            "Generating title with model: {:?}",
2609            self.summarization_model.as_ref().map(|model| model.name())
2610        );
2611        let mut request = LanguageModelRequest {
2612            intent: Some(CompletionIntent::ThreadSummarization),
2613            temperature: AgentSettings::temperature_for_model(&model, cx),
2614            ..Default::default()
2615        };
2616
2617        for message in &self.messages {
2618            request.messages.extend(message.to_request());
2619        }
2620
2621        request.messages.push(LanguageModelRequestMessage {
2622            role: Role::User,
2623            content: vec![SUMMARIZE_THREAD_PROMPT.into()],
2624            cache: false,
2625            reasoning_details: None,
2626        });
2627        self.pending_title_generation = Some(cx.spawn(async move |this, cx| {
2628            let mut title = String::new();
2629
2630            let generate = async {
2631                let mut messages = model.stream_completion(request, cx).await?;
2632                while let Some(event) = messages.next().await {
2633                    let event = event?;
2634                    let text = match event {
2635                        LanguageModelCompletionEvent::Text(text) => text,
2636                        _ => continue,
2637                    };
2638
2639                    let mut lines = text.lines();
2640                    title.extend(lines.next());
2641
2642                    // Stop if the LLM generated multiple lines.
2643                    if lines.next().is_some() {
2644                        break;
2645                    }
2646                }
2647                anyhow::Ok(())
2648            };
2649
2650            if generate
2651                .await
2652                .context("failed to generate thread title")
2653                .log_err()
2654                .is_some()
2655            {
2656                _ = this.update(cx, |this, cx| this.set_title(title.into(), cx));
2657            } else {
2658                // Emit TitleUpdated even on failure so that the propagation
2659                // chain (agent::Thread → NativeAgent → AcpThread) fires and
2660                // clears any provisional title that was set before the turn.
2661                _ = this.update(cx, |_, cx| {
2662                    cx.emit(TitleUpdated);
2663                    cx.notify();
2664                });
2665            }
2666            _ = this.update(cx, |this, _| this.pending_title_generation = None);
2667        }));
2668    }
2669
2670    pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
2671        self.pending_title_generation = None;
2672        if Some(&title) != self.title.as_ref() {
2673            self.title = Some(title);
2674            cx.emit(TitleUpdated);
2675            cx.notify();
2676        }
2677    }
2678
2679    fn clear_summary(&mut self) {
2680        self.summary = None;
2681        self.pending_summary_generation = None;
2682    }
2683
2684    fn last_user_message(&self) -> Option<&UserMessage> {
2685        self.messages
2686            .iter()
2687            .rev()
2688            .find_map(|message| match message {
2689                Message::User(user_message) => Some(user_message),
2690                Message::Agent(_) => None,
2691                Message::Resume => None,
2692            })
2693    }
2694
2695    fn pending_message(&mut self) -> &mut AgentMessage {
2696        self.pending_message.get_or_insert_default()
2697    }
2698
2699    fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
2700        let Some(mut message) = self.pending_message.take() else {
2701            return;
2702        };
2703
2704        if message.content.is_empty() {
2705            return;
2706        }
2707
2708        for content in &message.content {
2709            let AgentMessageContent::ToolUse(tool_use) = content else {
2710                continue;
2711            };
2712
2713            if !message.tool_results.contains_key(&tool_use.id) {
2714                message.tool_results.insert(
2715                    tool_use.id.clone(),
2716                    LanguageModelToolResult {
2717                        tool_use_id: tool_use.id.clone(),
2718                        tool_name: tool_use.name.clone(),
2719                        is_error: true,
2720                        content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
2721                        output: None,
2722                    },
2723                );
2724            }
2725        }
2726
2727        self.messages.push(Message::Agent(message));
2728        self.updated_at = Utc::now();
2729        self.clear_summary();
2730        cx.notify()
2731    }
2732
2733    pub(crate) fn build_completion_request(
2734        &self,
2735        completion_intent: CompletionIntent,
2736        cx: &App,
2737    ) -> Result<LanguageModelRequest> {
2738        let completion_intent =
2739            if self.is_subagent() && completion_intent == CompletionIntent::UserPrompt {
2740                CompletionIntent::Subagent
2741            } else {
2742                completion_intent
2743            };
2744
2745        let model = self.model().context("No language model configured")?;
2746        let tools = if let Some(turn) = self.running_turn.as_ref() {
2747            turn.tools
2748                .iter()
2749                .filter_map(|(tool_name, tool)| {
2750                    log::trace!("Including tool: {}", tool_name);
2751                    Some(LanguageModelRequestTool {
2752                        name: tool_name.to_string(),
2753                        description: tool.description().to_string(),
2754                        input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
2755                        use_input_streaming: tool.supports_input_streaming(),
2756                    })
2757                })
2758                .collect::<Vec<_>>()
2759        } else {
2760            Vec::new()
2761        };
2762
2763        log::debug!("Building completion request");
2764        log::debug!("Completion intent: {:?}", completion_intent);
2765
2766        let available_tools: Vec<_> = self
2767            .running_turn
2768            .as_ref()
2769            .map(|turn| turn.tools.keys().cloned().collect())
2770            .unwrap_or_default();
2771
2772        log::debug!("Request includes {} tools", available_tools.len());
2773        let messages = self.build_request_messages(available_tools, cx);
2774        log::debug!("Request will include {} messages", messages.len());
2775
2776        let request = LanguageModelRequest {
2777            thread_id: Some(self.id.to_string()),
2778            prompt_id: Some(self.prompt_id.to_string()),
2779            intent: Some(completion_intent),
2780            messages,
2781            tools,
2782            tool_choice: None,
2783            stop: Vec::new(),
2784            temperature: AgentSettings::temperature_for_model(model, cx),
2785            thinking_allowed: self.thinking_enabled,
2786            thinking_effort: self.thinking_effort.clone(),
2787            speed: self.speed(),
2788        };
2789
2790        log::debug!("Completion request built successfully");
2791        Ok(request)
2792    }
2793
2794    fn enabled_tools(&self, cx: &App) -> BTreeMap<SharedString, Arc<dyn AnyAgentTool>> {
2795        let Some(model) = self.model.as_ref() else {
2796            return BTreeMap::new();
2797        };
2798        let Some(profile) = AgentSettings::get_global(cx).profiles.get(&self.profile_id) else {
2799            return BTreeMap::new();
2800        };
2801        fn truncate(tool_name: &SharedString) -> SharedString {
2802            if tool_name.len() > MAX_TOOL_NAME_LENGTH {
2803                let mut truncated = tool_name.to_string();
2804                truncated.truncate(MAX_TOOL_NAME_LENGTH);
2805                truncated.into()
2806            } else {
2807                tool_name.clone()
2808            }
2809        }
2810
2811        let use_streaming_edit_tool =
2812            cx.has_flag::<StreamingEditFileToolFeatureFlag>() && model.supports_streaming_tools();
2813
2814        let mut tools = self
2815            .tools
2816            .iter()
2817            .filter_map(|(tool_name, tool)| {
2818                // For streaming_edit_file, check profile against "edit_file" since that's what users configure
2819                let profile_tool_name = if tool_name == StreamingEditFileTool::NAME {
2820                    EditFileTool::NAME
2821                } else {
2822                    tool_name.as_ref()
2823                };
2824
2825                if tool.supports_provider(&model.provider_id())
2826                    && profile.is_tool_enabled(profile_tool_name)
2827                {
2828                    match (tool_name.as_ref(), use_streaming_edit_tool) {
2829                        (StreamingEditFileTool::NAME, false) | (EditFileTool::NAME, true) => None,
2830                        (StreamingEditFileTool::NAME, true) => {
2831                            // Expose streaming tool as "edit_file"
2832                            Some((SharedString::from(EditFileTool::NAME), tool.clone()))
2833                        }
2834                        _ => Some((truncate(tool_name), tool.clone())),
2835                    }
2836                } else {
2837                    None
2838                }
2839            })
2840            .collect::<BTreeMap<_, _>>();
2841
2842        let mut context_server_tools = Vec::new();
2843        let mut seen_tools = tools.keys().cloned().collect::<HashSet<_>>();
2844        let mut duplicate_tool_names = HashSet::default();
2845        for (server_id, server_tools) in self.context_server_registry.read(cx).servers() {
2846            for (tool_name, tool) in server_tools {
2847                if profile.is_context_server_tool_enabled(&server_id.0, &tool_name) {
2848                    let tool_name = truncate(tool_name);
2849                    if !seen_tools.insert(tool_name.clone()) {
2850                        duplicate_tool_names.insert(tool_name.clone());
2851                    }
2852                    context_server_tools.push((server_id.clone(), tool_name, tool.clone()));
2853                }
2854            }
2855        }
2856
2857        // When there are duplicate tool names, disambiguate by prefixing them
2858        // with the server ID (converted to snake_case for API compatibility).
2859        // In the rare case there isn't enough space for the disambiguated tool
2860        // name, keep only the last tool with this name.
2861        for (server_id, tool_name, tool) in context_server_tools {
2862            if duplicate_tool_names.contains(&tool_name) {
2863                let available = MAX_TOOL_NAME_LENGTH.saturating_sub(tool_name.len());
2864                if available >= 2 {
2865                    let mut disambiguated = server_id.0.to_snake_case();
2866                    disambiguated.truncate(available - 1);
2867                    disambiguated.push('_');
2868                    disambiguated.push_str(&tool_name);
2869                    tools.insert(disambiguated.into(), tool.clone());
2870                } else {
2871                    tools.insert(tool_name, tool.clone());
2872                }
2873            } else {
2874                tools.insert(tool_name, tool.clone());
2875            }
2876        }
2877
2878        tools
2879    }
2880
2881    fn refresh_turn_tools(&mut self, cx: &App) {
2882        let tools = self.enabled_tools(cx);
2883        if let Some(turn) = self.running_turn.as_mut() {
2884            turn.tools = tools;
2885        }
2886    }
2887
2888    fn tool(&self, name: &str) -> Option<Arc<dyn AnyAgentTool>> {
2889        self.running_turn.as_ref()?.tools.get(name).cloned()
2890    }
2891
2892    pub fn has_tool(&self, name: &str) -> bool {
2893        self.running_turn
2894            .as_ref()
2895            .is_some_and(|turn| turn.tools.contains_key(name))
2896    }
2897
2898    #[cfg(any(test, feature = "test-support"))]
2899    pub fn has_registered_tool(&self, name: &str) -> bool {
2900        self.tools.contains_key(name)
2901    }
2902
2903    pub fn registered_tool_names(&self) -> Vec<SharedString> {
2904        self.tools.keys().cloned().collect()
2905    }
2906
2907    pub(crate) fn register_running_subagent(&mut self, subagent: WeakEntity<Thread>) {
2908        self.running_subagents.push(subagent);
2909    }
2910
2911    pub(crate) fn unregister_running_subagent(
2912        &mut self,
2913        subagent_session_id: &acp::SessionId,
2914        cx: &App,
2915    ) {
2916        self.running_subagents.retain(|s| {
2917            s.upgrade()
2918                .map_or(false, |s| s.read(cx).id() != subagent_session_id)
2919        });
2920    }
2921
2922    #[cfg(any(test, feature = "test-support"))]
2923    pub fn running_subagent_ids(&self, cx: &App) -> Vec<acp::SessionId> {
2924        self.running_subagents
2925            .iter()
2926            .filter_map(|s| s.upgrade().map(|s| s.read(cx).id().clone()))
2927            .collect()
2928    }
2929
2930    pub fn is_subagent(&self) -> bool {
2931        self.subagent_context.is_some()
2932    }
2933
2934    pub fn parent_thread_id(&self) -> Option<acp::SessionId> {
2935        self.subagent_context
2936            .as_ref()
2937            .map(|c| c.parent_thread_id.clone())
2938    }
2939
2940    pub fn depth(&self) -> u8 {
2941        self.subagent_context.as_ref().map(|c| c.depth).unwrap_or(0)
2942    }
2943
2944    #[cfg(any(test, feature = "test-support"))]
2945    pub fn set_subagent_context(&mut self, context: SubagentContext) {
2946        self.subagent_context = Some(context);
2947    }
2948
2949    pub fn is_turn_complete(&self) -> bool {
2950        self.running_turn.is_none()
2951    }
2952
2953    fn build_request_messages(
2954        &self,
2955        available_tools: Vec<SharedString>,
2956        cx: &App,
2957    ) -> Vec<LanguageModelRequestMessage> {
2958        log::trace!(
2959            "Building request messages from {} thread messages",
2960            self.messages.len()
2961        );
2962
2963        let system_prompt = SystemPromptTemplate {
2964            project: self.project_context.read(cx),
2965            available_tools,
2966            model_name: self.model.as_ref().map(|m| m.name().0.to_string()),
2967        }
2968        .render(&self.templates)
2969        .context("failed to build system prompt")
2970        .expect("Invalid template");
2971        let mut messages = vec![LanguageModelRequestMessage {
2972            role: Role::System,
2973            content: vec![system_prompt.into()],
2974            cache: false,
2975            reasoning_details: None,
2976        }];
2977        for message in &self.messages {
2978            messages.extend(message.to_request());
2979        }
2980
2981        if let Some(last_message) = messages.last_mut() {
2982            last_message.cache = true;
2983        }
2984
2985        if let Some(message) = self.pending_message.as_ref() {
2986            messages.extend(message.to_request());
2987        }
2988
2989        messages
2990    }
2991
2992    pub fn to_markdown(&self) -> String {
2993        let mut markdown = String::new();
2994        for (ix, message) in self.messages.iter().enumerate() {
2995            if ix > 0 {
2996                markdown.push('\n');
2997            }
2998            match message {
2999                Message::User(_) => markdown.push_str("## User\n\n"),
3000                Message::Agent(_) => markdown.push_str("## Assistant\n\n"),
3001                Message::Resume => {}
3002            }
3003            markdown.push_str(&message.to_markdown());
3004        }
3005
3006        if let Some(message) = self.pending_message.as_ref() {
3007            markdown.push_str("\n## Assistant\n\n");
3008            markdown.push_str(&message.to_markdown());
3009        }
3010
3011        markdown
3012    }
3013
3014    fn advance_prompt_id(&mut self) {
3015        self.prompt_id = PromptId::new();
3016    }
3017
3018    fn retry_strategy_for(error: &LanguageModelCompletionError) -> Option<RetryStrategy> {
3019        use LanguageModelCompletionError::*;
3020        use http_client::StatusCode;
3021
3022        // General strategy here:
3023        // - If retrying won't help (e.g. invalid API key or payload too large), return None so we don't retry at all.
3024        // - If it's a time-based issue (e.g. server overloaded, rate limit exceeded), retry up to 4 times with exponential backoff.
3025        // - If it's an issue that *might* be fixed by retrying (e.g. internal server error), retry up to 3 times.
3026        match error {
3027            HttpResponseError {
3028                status_code: StatusCode::TOO_MANY_REQUESTS,
3029                ..
3030            } => Some(RetryStrategy::ExponentialBackoff {
3031                initial_delay: BASE_RETRY_DELAY,
3032                max_attempts: MAX_RETRY_ATTEMPTS,
3033            }),
3034            ServerOverloaded { retry_after, .. } | RateLimitExceeded { retry_after, .. } => {
3035                Some(RetryStrategy::Fixed {
3036                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
3037                    max_attempts: MAX_RETRY_ATTEMPTS,
3038                })
3039            }
3040            UpstreamProviderError {
3041                status,
3042                retry_after,
3043                ..
3044            } => match *status {
3045                StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
3046                    Some(RetryStrategy::Fixed {
3047                        delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
3048                        max_attempts: MAX_RETRY_ATTEMPTS,
3049                    })
3050                }
3051                StatusCode::INTERNAL_SERVER_ERROR => Some(RetryStrategy::Fixed {
3052                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
3053                    // Internal Server Error could be anything, retry up to 3 times.
3054                    max_attempts: 3,
3055                }),
3056                status => {
3057                    // There is no StatusCode variant for the unofficial HTTP 529 ("The service is overloaded"),
3058                    // but we frequently get them in practice. See https://http.dev/529
3059                    if status.as_u16() == 529 {
3060                        Some(RetryStrategy::Fixed {
3061                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
3062                            max_attempts: MAX_RETRY_ATTEMPTS,
3063                        })
3064                    } else {
3065                        Some(RetryStrategy::Fixed {
3066                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
3067                            max_attempts: 2,
3068                        })
3069                    }
3070                }
3071            },
3072            ApiInternalServerError { .. } => Some(RetryStrategy::Fixed {
3073                delay: BASE_RETRY_DELAY,
3074                max_attempts: 3,
3075            }),
3076            ApiReadResponseError { .. }
3077            | HttpSend { .. }
3078            | DeserializeResponse { .. }
3079            | BadRequestFormat { .. } => Some(RetryStrategy::Fixed {
3080                delay: BASE_RETRY_DELAY,
3081                max_attempts: 3,
3082            }),
3083            // Retrying these errors definitely shouldn't help.
3084            HttpResponseError {
3085                status_code:
3086                    StatusCode::PAYLOAD_TOO_LARGE | StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED,
3087                ..
3088            }
3089            | AuthenticationError { .. }
3090            | PermissionError { .. }
3091            | NoApiKey { .. }
3092            | ApiEndpointNotFound { .. }
3093            | PromptTooLarge { .. } => None,
3094            // These errors might be transient, so retry them
3095            SerializeRequest { .. } | BuildRequestBody { .. } | StreamEndedUnexpectedly { .. } => {
3096                Some(RetryStrategy::Fixed {
3097                    delay: BASE_RETRY_DELAY,
3098                    max_attempts: 1,
3099                })
3100            }
3101            // Retry all other 4xx and 5xx errors once.
3102            HttpResponseError { status_code, .. }
3103                if status_code.is_client_error() || status_code.is_server_error() =>
3104            {
3105                Some(RetryStrategy::Fixed {
3106                    delay: BASE_RETRY_DELAY,
3107                    max_attempts: 3,
3108                })
3109            }
3110            Other(err) if err.is::<language_model::PaymentRequiredError>() => {
3111                // Retrying won't help for Payment Required errors.
3112                None
3113            }
3114            // Conservatively assume that any other errors are non-retryable
3115            HttpResponseError { .. } | Other(..) => Some(RetryStrategy::Fixed {
3116                delay: BASE_RETRY_DELAY,
3117                max_attempts: 2,
3118            }),
3119        }
3120    }
3121}
3122
3123struct RunningTurn {
3124    /// Holds the task that handles agent interaction until the end of the turn.
3125    /// Survives across multiple requests as the model performs tool calls and
3126    /// we run tools, report their results.
3127    _task: Task<()>,
3128    /// The current event stream for the running turn. Used to report a final
3129    /// cancellation event if we cancel the turn.
3130    event_stream: ThreadEventStream,
3131    /// The tools that are enabled for the current iteration of the turn.
3132    /// Refreshed at the start of each iteration via `refresh_turn_tools`.
3133    tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
3134    /// Sender to signal tool cancellation. When cancel is called, this is
3135    /// set to true so all tools can detect user-initiated cancellation.
3136    cancellation_tx: watch::Sender<bool>,
3137    /// Senders for tools that support input streaming and have already been
3138    /// started but are still receiving input from the LLM.
3139    streaming_tool_inputs: HashMap<LanguageModelToolUseId, ToolInputSender>,
3140}
3141
3142impl RunningTurn {
3143    fn cancel(mut self) -> Task<()> {
3144        log::debug!("Cancelling in progress turn");
3145        self.cancellation_tx.send(true).ok();
3146        self.event_stream.send_canceled();
3147        self._task
3148    }
3149}
3150
3151pub struct TokenUsageUpdated(pub Option<acp_thread::TokenUsage>);
3152
3153impl EventEmitter<TokenUsageUpdated> for Thread {}
3154
3155pub struct TitleUpdated;
3156
3157impl EventEmitter<TitleUpdated> for Thread {}
3158
3159/// A channel-based wrapper that delivers tool input to a running tool.
3160///
3161/// For non-streaming tools, created via `ToolInput::ready()` so `.recv()` resolves immediately.
3162/// For streaming tools, partial JSON snapshots arrive via `.recv_partial()` as the LLM streams
3163/// them, followed by the final complete input available through `.recv()`.
3164pub struct ToolInput<T> {
3165    rx: mpsc::UnboundedReceiver<ToolInputPayload<serde_json::Value>>,
3166    _phantom: PhantomData<T>,
3167}
3168
3169impl<T: DeserializeOwned> ToolInput<T> {
3170    #[cfg(any(test, feature = "test-support"))]
3171    pub fn resolved(input: impl Serialize) -> Self {
3172        let value = serde_json::to_value(input).expect("failed to serialize tool input");
3173        Self::ready(value)
3174    }
3175
3176    pub fn ready(value: serde_json::Value) -> Self {
3177        let (tx, rx) = mpsc::unbounded();
3178        tx.unbounded_send(ToolInputPayload::Full(value)).ok();
3179        Self {
3180            rx,
3181            _phantom: PhantomData,
3182        }
3183    }
3184
3185    pub fn invalid_json(error_message: String) -> Self {
3186        let (tx, rx) = mpsc::unbounded();
3187        tx.unbounded_send(ToolInputPayload::InvalidJson { error_message })
3188            .ok();
3189        Self {
3190            rx,
3191            _phantom: PhantomData,
3192        }
3193    }
3194
3195    #[cfg(any(test, feature = "test-support"))]
3196    pub fn test() -> (ToolInputSender, Self) {
3197        let (sender, input) = ToolInputSender::channel();
3198        (sender, input.cast())
3199    }
3200
3201    /// Wait for the final deserialized input, ignoring all partial updates.
3202    /// Non-streaming tools can use this to wait until the whole input is available.
3203    pub async fn recv(mut self) -> Result<T> {
3204        while let Ok(value) = self.next().await {
3205            match value {
3206                ToolInputPayload::Full(value) => return Ok(value),
3207                ToolInputPayload::Partial(_) => {}
3208                ToolInputPayload::InvalidJson { error_message } => {
3209                    return Err(anyhow!(error_message));
3210                }
3211            }
3212        }
3213        Err(anyhow!("tool input was not fully received"))
3214    }
3215
3216    pub async fn next(&mut self) -> Result<ToolInputPayload<T>> {
3217        let value = self
3218            .rx
3219            .next()
3220            .await
3221            .ok_or_else(|| anyhow!("tool input was not fully received"))?;
3222
3223        Ok(match value {
3224            ToolInputPayload::Partial(payload) => ToolInputPayload::Partial(payload),
3225            ToolInputPayload::Full(payload) => {
3226                ToolInputPayload::Full(serde_json::from_value(payload)?)
3227            }
3228            ToolInputPayload::InvalidJson { error_message } => {
3229                ToolInputPayload::InvalidJson { error_message }
3230            }
3231        })
3232    }
3233
3234    fn cast<U: DeserializeOwned>(self) -> ToolInput<U> {
3235        ToolInput {
3236            rx: self.rx,
3237            _phantom: PhantomData,
3238        }
3239    }
3240}
3241
3242pub enum ToolInputPayload<T> {
3243    Partial(serde_json::Value),
3244    Full(T),
3245    InvalidJson { error_message: String },
3246}
3247
3248pub struct ToolInputSender {
3249    has_received_final: bool,
3250    tx: mpsc::UnboundedSender<ToolInputPayload<serde_json::Value>>,
3251}
3252
3253impl ToolInputSender {
3254    pub(crate) fn channel() -> (Self, ToolInput<serde_json::Value>) {
3255        let (tx, rx) = mpsc::unbounded();
3256        let sender = Self {
3257            tx,
3258            has_received_final: false,
3259        };
3260        let input = ToolInput {
3261            rx,
3262            _phantom: PhantomData,
3263        };
3264        (sender, input)
3265    }
3266
3267    pub(crate) fn has_received_final(&self) -> bool {
3268        self.has_received_final
3269    }
3270
3271    pub fn send_partial(&mut self, payload: serde_json::Value) {
3272        self.tx
3273            .unbounded_send(ToolInputPayload::Partial(payload))
3274            .ok();
3275    }
3276
3277    pub fn send_full(&mut self, payload: serde_json::Value) {
3278        self.has_received_final = true;
3279        self.tx.unbounded_send(ToolInputPayload::Full(payload)).ok();
3280    }
3281
3282    pub fn send_invalid_json(&mut self, error_message: String) {
3283        self.has_received_final = true;
3284        self.tx
3285            .unbounded_send(ToolInputPayload::InvalidJson { error_message })
3286            .ok();
3287    }
3288}
3289
3290pub trait AgentTool
3291where
3292    Self: 'static + Sized,
3293{
3294    type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
3295    type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
3296
3297    const NAME: &'static str;
3298
3299    fn description() -> SharedString {
3300        let schema = schemars::schema_for!(Self::Input);
3301        SharedString::new(
3302            schema
3303                .get("description")
3304                .and_then(|description| description.as_str())
3305                .unwrap_or_default(),
3306        )
3307    }
3308
3309    fn kind() -> acp::ToolKind;
3310
3311    /// The initial tool title to display. Can be updated during the tool run.
3312    fn initial_title(
3313        &self,
3314        input: Result<Self::Input, serde_json::Value>,
3315        cx: &mut App,
3316    ) -> SharedString;
3317
3318    /// Returns the JSON schema that describes the tool's input.
3319    fn input_schema(format: LanguageModelToolSchemaFormat) -> Schema {
3320        language_model::tool_schema::root_schema_for::<Self::Input>(format)
3321    }
3322
3323    /// Returns whether the tool supports streaming of tool use parameters.
3324    fn supports_input_streaming() -> bool {
3325        false
3326    }
3327
3328    /// Some tools rely on a provider for the underlying billing or other reasons.
3329    /// Allow the tool to check if they are compatible, or should be filtered out.
3330    fn supports_provider(_provider: &LanguageModelProviderId) -> bool {
3331        true
3332    }
3333
3334    /// Runs the tool with the provided input.
3335    ///
3336    /// Returns `Result<Self::Output, Self::Output>` rather than `Result<Self::Output, anyhow::Error>`
3337    /// because tool errors are sent back to the model as tool results. This means error output must
3338    /// be structured and readable by the agent — not an arbitrary `anyhow::Error`. Returning the
3339    /// same `Output` type for both success and failure lets tools provide structured data while
3340    /// still signaling whether the invocation succeeded or failed.
3341    fn run(
3342        self: Arc<Self>,
3343        input: ToolInput<Self::Input>,
3344        event_stream: ToolCallEventStream,
3345        cx: &mut App,
3346    ) -> Task<Result<Self::Output, Self::Output>>;
3347
3348    /// Emits events for a previous execution of the tool.
3349    fn replay(
3350        &self,
3351        _input: Self::Input,
3352        _output: Self::Output,
3353        _event_stream: ToolCallEventStream,
3354        _cx: &mut App,
3355    ) -> Result<()> {
3356        Ok(())
3357    }
3358
3359    fn erase(self) -> Arc<dyn AnyAgentTool> {
3360        Arc::new(Erased(Arc::new(self)))
3361    }
3362}
3363
3364pub struct Erased<T>(T);
3365
3366pub struct AgentToolOutput {
3367    pub llm_output: LanguageModelToolResultContent,
3368    pub raw_output: serde_json::Value,
3369}
3370
3371impl AgentToolOutput {
3372    pub fn from_error(message: impl Into<String>) -> Self {
3373        let message = message.into();
3374        let llm_output = LanguageModelToolResultContent::Text(Arc::from(message.as_str()));
3375        Self {
3376            raw_output: serde_json::Value::String(message),
3377            llm_output,
3378        }
3379    }
3380}
3381
3382pub trait AnyAgentTool {
3383    fn name(&self) -> SharedString;
3384    fn description(&self) -> SharedString;
3385    fn kind(&self) -> acp::ToolKind;
3386    fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString;
3387    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
3388    fn supports_input_streaming(&self) -> bool {
3389        false
3390    }
3391    fn supports_provider(&self, _provider: &LanguageModelProviderId) -> bool {
3392        true
3393    }
3394    /// See [`AgentTool::run`] for why this returns `Result<AgentToolOutput, AgentToolOutput>`.
3395    fn run(
3396        self: Arc<Self>,
3397        input: ToolInput<serde_json::Value>,
3398        event_stream: ToolCallEventStream,
3399        cx: &mut App,
3400    ) -> Task<Result<AgentToolOutput, AgentToolOutput>>;
3401    fn replay(
3402        &self,
3403        input: serde_json::Value,
3404        output: serde_json::Value,
3405        event_stream: ToolCallEventStream,
3406        cx: &mut App,
3407    ) -> Result<()>;
3408}
3409
3410impl<T> AnyAgentTool for Erased<Arc<T>>
3411where
3412    T: AgentTool,
3413{
3414    fn name(&self) -> SharedString {
3415        T::NAME.into()
3416    }
3417
3418    fn description(&self) -> SharedString {
3419        T::description()
3420    }
3421
3422    fn kind(&self) -> agent_client_protocol::ToolKind {
3423        T::kind()
3424    }
3425
3426    fn supports_input_streaming(&self) -> bool {
3427        T::supports_input_streaming()
3428    }
3429
3430    fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString {
3431        let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
3432        self.0.initial_title(parsed_input, _cx)
3433    }
3434
3435    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
3436        let mut json = serde_json::to_value(T::input_schema(format))?;
3437        language_model::tool_schema::adapt_schema_to_format(&mut json, format)?;
3438        Ok(json)
3439    }
3440
3441    fn supports_provider(&self, provider: &LanguageModelProviderId) -> bool {
3442        T::supports_provider(provider)
3443    }
3444
3445    fn run(
3446        self: Arc<Self>,
3447        input: ToolInput<serde_json::Value>,
3448        event_stream: ToolCallEventStream,
3449        cx: &mut App,
3450    ) -> Task<Result<AgentToolOutput, AgentToolOutput>> {
3451        let tool_input: ToolInput<T::Input> = input.cast();
3452        let task = self.0.clone().run(tool_input, event_stream, cx);
3453        cx.spawn(async move |_cx| match task.await {
3454            Ok(output) => {
3455                let raw_output = serde_json::to_value(&output).map_err(|e| {
3456                    AgentToolOutput::from_error(format!("Failed to serialize tool output: {e}"))
3457                })?;
3458                Ok(AgentToolOutput {
3459                    llm_output: output.into(),
3460                    raw_output,
3461                })
3462            }
3463            Err(error_output) => {
3464                let raw_output = serde_json::to_value(&error_output).unwrap_or_else(|e| {
3465                    log::error!("Failed to serialize tool error output: {e}");
3466                    serde_json::Value::Null
3467                });
3468                Err(AgentToolOutput {
3469                    llm_output: error_output.into(),
3470                    raw_output,
3471                })
3472            }
3473        })
3474    }
3475
3476    fn replay(
3477        &self,
3478        input: serde_json::Value,
3479        output: serde_json::Value,
3480        event_stream: ToolCallEventStream,
3481        cx: &mut App,
3482    ) -> Result<()> {
3483        let input = serde_json::from_value(input)?;
3484        let output = serde_json::from_value(output)?;
3485        self.0.replay(input, output, event_stream, cx)
3486    }
3487}
3488
3489#[derive(Clone)]
3490struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
3491
3492impl ThreadEventStream {
3493    fn send_user_message(&self, message: &UserMessage) {
3494        self.0
3495            .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
3496            .ok();
3497    }
3498
3499    fn send_text(&self, text: &str) {
3500        self.0
3501            .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
3502            .ok();
3503    }
3504
3505    fn send_thinking(&self, text: &str) {
3506        self.0
3507            .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
3508            .ok();
3509    }
3510
3511    fn send_tool_call(
3512        &self,
3513        id: &LanguageModelToolUseId,
3514        tool_name: &str,
3515        title: SharedString,
3516        kind: acp::ToolKind,
3517        input: serde_json::Value,
3518    ) {
3519        self.0
3520            .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
3521                id,
3522                tool_name,
3523                title.to_string(),
3524                kind,
3525                input,
3526            ))))
3527            .ok();
3528    }
3529
3530    fn initial_tool_call(
3531        id: &LanguageModelToolUseId,
3532        tool_name: &str,
3533        title: String,
3534        kind: acp::ToolKind,
3535        input: serde_json::Value,
3536    ) -> acp::ToolCall {
3537        acp::ToolCall::new(id.to_string(), title)
3538            .kind(kind)
3539            .raw_input(input)
3540            .meta(acp_thread::meta_with_tool_name(tool_name))
3541    }
3542
3543    fn update_tool_call_fields(
3544        &self,
3545        tool_use_id: &LanguageModelToolUseId,
3546        fields: acp::ToolCallUpdateFields,
3547        meta: Option<acp::Meta>,
3548    ) {
3549        self.0
3550            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3551                acp::ToolCallUpdate::new(tool_use_id.to_string(), fields)
3552                    .meta(meta)
3553                    .into(),
3554            )))
3555            .ok();
3556    }
3557
3558    fn send_plan(&self, plan: acp::Plan) {
3559        self.0.unbounded_send(Ok(ThreadEvent::Plan(plan))).ok();
3560    }
3561
3562    fn send_retry(&self, status: acp_thread::RetryStatus) {
3563        self.0.unbounded_send(Ok(ThreadEvent::Retry(status))).ok();
3564    }
3565
3566    fn send_stop(&self, reason: acp::StopReason) {
3567        self.0.unbounded_send(Ok(ThreadEvent::Stop(reason))).ok();
3568    }
3569
3570    fn send_canceled(&self) {
3571        self.0
3572            .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))
3573            .ok();
3574    }
3575
3576    fn send_error(&self, error: impl Into<anyhow::Error>) {
3577        self.0.unbounded_send(Err(error.into())).ok();
3578    }
3579}
3580
3581#[derive(Clone)]
3582pub struct ToolCallEventStream {
3583    tool_use_id: LanguageModelToolUseId,
3584    stream: ThreadEventStream,
3585    fs: Option<Arc<dyn Fs>>,
3586    cancellation_rx: watch::Receiver<bool>,
3587}
3588
3589impl ToolCallEventStream {
3590    #[cfg(any(test, feature = "test-support"))]
3591    pub fn test() -> (Self, ToolCallEventStreamReceiver) {
3592        let (stream, receiver, _cancellation_tx) = Self::test_with_cancellation();
3593        (stream, receiver)
3594    }
3595
3596    #[cfg(any(test, feature = "test-support"))]
3597    pub fn test_with_cancellation() -> (Self, ToolCallEventStreamReceiver, watch::Sender<bool>) {
3598        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
3599        let (cancellation_tx, cancellation_rx) = watch::channel(false);
3600
3601        let stream = ToolCallEventStream::new(
3602            "test_id".into(),
3603            ThreadEventStream(events_tx),
3604            None,
3605            cancellation_rx,
3606        );
3607
3608        (
3609            stream,
3610            ToolCallEventStreamReceiver(events_rx),
3611            cancellation_tx,
3612        )
3613    }
3614
3615    /// Signal cancellation for this event stream. Only available in tests.
3616    #[cfg(any(test, feature = "test-support"))]
3617    pub fn signal_cancellation_with_sender(cancellation_tx: &mut watch::Sender<bool>) {
3618        cancellation_tx.send(true).ok();
3619    }
3620
3621    fn new(
3622        tool_use_id: LanguageModelToolUseId,
3623        stream: ThreadEventStream,
3624        fs: Option<Arc<dyn Fs>>,
3625        cancellation_rx: watch::Receiver<bool>,
3626    ) -> Self {
3627        Self {
3628            tool_use_id,
3629            stream,
3630            fs,
3631            cancellation_rx,
3632        }
3633    }
3634
3635    /// Returns a future that resolves when the user cancels the tool call.
3636    /// Tools should select on this alongside their main work to detect user cancellation.
3637    pub fn cancelled_by_user(&self) -> impl std::future::Future<Output = ()> + '_ {
3638        let mut rx = self.cancellation_rx.clone();
3639        async move {
3640            loop {
3641                if *rx.borrow() {
3642                    return;
3643                }
3644                if rx.changed().await.is_err() {
3645                    // Sender dropped, will never be cancelled
3646                    std::future::pending::<()>().await;
3647                }
3648            }
3649        }
3650    }
3651
3652    /// Returns true if the user has cancelled this tool call.
3653    /// This is useful for checking cancellation state after an operation completes,
3654    /// to determine if the completion was due to user cancellation.
3655    pub fn was_cancelled_by_user(&self) -> bool {
3656        *self.cancellation_rx.clone().borrow()
3657    }
3658
3659    pub fn tool_use_id(&self) -> &LanguageModelToolUseId {
3660        &self.tool_use_id
3661    }
3662
3663    pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
3664        self.stream
3665            .update_tool_call_fields(&self.tool_use_id, fields, None);
3666    }
3667
3668    pub fn update_fields_with_meta(
3669        &self,
3670        fields: acp::ToolCallUpdateFields,
3671        meta: Option<acp::Meta>,
3672    ) {
3673        self.stream
3674            .update_tool_call_fields(&self.tool_use_id, fields, meta);
3675    }
3676
3677    pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
3678        self.stream
3679            .0
3680            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3681                acp_thread::ToolCallUpdateDiff {
3682                    id: acp::ToolCallId::new(self.tool_use_id.to_string()),
3683                    diff,
3684                }
3685                .into(),
3686            )))
3687            .ok();
3688    }
3689
3690    pub fn subagent_spawned(&self, id: acp::SessionId) {
3691        self.stream
3692            .0
3693            .unbounded_send(Ok(ThreadEvent::SubagentSpawned(id)))
3694            .ok();
3695    }
3696
3697    pub fn update_plan(&self, plan: acp::Plan) {
3698        self.stream.send_plan(plan);
3699    }
3700
3701    /// Authorize a third-party tool (e.g., MCP tool from a context server).
3702    ///
3703    /// Unlike built-in tools, third-party tools don't support pattern-based permissions.
3704    /// They only support `default` (allow/deny/confirm) per tool.
3705    ///
3706    /// Uses the dropdown authorization flow with two granularities:
3707    /// - "Always for <display_name> MCP tool" → sets `tools.<tool_id>.default = "allow"` or "deny"
3708    /// - "Only this time" → allow/deny once
3709    pub fn authorize_third_party_tool(
3710        &self,
3711        title: impl Into<String>,
3712        tool_id: String,
3713        display_name: String,
3714        cx: &mut App,
3715    ) -> Task<Result<()>> {
3716        let settings = agent_settings::AgentSettings::get_global(cx);
3717
3718        let decision = decide_permission_from_settings(&tool_id, &[String::new()], &settings);
3719
3720        match decision {
3721            ToolPermissionDecision::Allow => return Task::ready(Ok(())),
3722            ToolPermissionDecision::Deny(reason) => return Task::ready(Err(anyhow!(reason))),
3723            ToolPermissionDecision::Confirm => {}
3724        }
3725
3726        let (response_tx, response_rx) = oneshot::channel();
3727        if let Err(error) = self
3728            .stream
3729            .0
3730            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3731                ToolCallAuthorization {
3732                    tool_call: acp::ToolCallUpdate::new(
3733                        self.tool_use_id.to_string(),
3734                        acp::ToolCallUpdateFields::new().title(title.into()),
3735                    ),
3736                    options: acp_thread::PermissionOptions::Dropdown(vec![
3737                        acp_thread::PermissionOptionChoice {
3738                            allow: acp::PermissionOption::new(
3739                                acp::PermissionOptionId::new(format!(
3740                                    "always_allow_mcp:{}",
3741                                    tool_id
3742                                )),
3743                                format!("Always for {} MCP tool", display_name),
3744                                acp::PermissionOptionKind::AllowAlways,
3745                            ),
3746                            deny: acp::PermissionOption::new(
3747                                acp::PermissionOptionId::new(format!(
3748                                    "always_deny_mcp:{}",
3749                                    tool_id
3750                                )),
3751                                format!("Always for {} MCP tool", display_name),
3752                                acp::PermissionOptionKind::RejectAlways,
3753                            ),
3754                            sub_patterns: vec![],
3755                        },
3756                        acp_thread::PermissionOptionChoice {
3757                            allow: acp::PermissionOption::new(
3758                                acp::PermissionOptionId::new("allow"),
3759                                "Only this time",
3760                                acp::PermissionOptionKind::AllowOnce,
3761                            ),
3762                            deny: acp::PermissionOption::new(
3763                                acp::PermissionOptionId::new("deny"),
3764                                "Only this time",
3765                                acp::PermissionOptionKind::RejectOnce,
3766                            ),
3767                            sub_patterns: vec![],
3768                        },
3769                    ]),
3770                    response: response_tx,
3771                    context: None,
3772                },
3773            )))
3774        {
3775            log::error!("Failed to send tool call authorization: {error}");
3776            return Task::ready(Err(anyhow!(
3777                "Failed to send tool call authorization: {error}"
3778            )));
3779        }
3780
3781        let fs = self.fs.clone();
3782        cx.spawn(async move |cx| {
3783            let outcome = response_rx.await?;
3784            let is_allow = Self::persist_permission_outcome(&outcome, fs, &cx);
3785            if is_allow {
3786                Ok(())
3787            } else {
3788                Err(anyhow!("Permission to run tool denied by user"))
3789            }
3790        })
3791    }
3792
3793    pub fn authorize(
3794        &self,
3795        title: impl Into<String>,
3796        context: ToolPermissionContext,
3797        cx: &mut App,
3798    ) -> Task<Result<()>> {
3799        let options = context.build_permission_options();
3800
3801        let (response_tx, response_rx) = oneshot::channel();
3802        if let Err(error) = self
3803            .stream
3804            .0
3805            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3806                ToolCallAuthorization {
3807                    tool_call: acp::ToolCallUpdate::new(
3808                        self.tool_use_id.to_string(),
3809                        acp::ToolCallUpdateFields::new().title(title.into()),
3810                    ),
3811                    options,
3812                    response: response_tx,
3813                    context: Some(context),
3814                },
3815            )))
3816        {
3817            log::error!("Failed to send tool call authorization: {error}");
3818            return Task::ready(Err(anyhow!(
3819                "Failed to send tool call authorization: {error}"
3820            )));
3821        }
3822
3823        let fs = self.fs.clone();
3824        cx.spawn(async move |cx| {
3825            let outcome = response_rx.await?;
3826            let is_allow = Self::persist_permission_outcome(&outcome, fs, &cx);
3827            if is_allow {
3828                Ok(())
3829            } else {
3830                Err(anyhow!("Permission to run tool denied by user"))
3831            }
3832        })
3833    }
3834
3835    /// Interprets a `SelectedPermissionOutcome` and persists any settings changes.
3836    /// Returns `true` if the tool call should be allowed, `false` if denied.
3837    fn persist_permission_outcome(
3838        outcome: &acp_thread::SelectedPermissionOutcome,
3839        fs: Option<Arc<dyn Fs>>,
3840        cx: &AsyncApp,
3841    ) -> bool {
3842        let option_id = outcome.option_id.0.as_ref();
3843
3844        let always_permission = option_id
3845            .strip_prefix("always_allow:")
3846            .map(|tool| (tool, ToolPermissionMode::Allow))
3847            .or_else(|| {
3848                option_id
3849                    .strip_prefix("always_deny:")
3850                    .map(|tool| (tool, ToolPermissionMode::Deny))
3851            })
3852            .or_else(|| {
3853                option_id
3854                    .strip_prefix("always_allow_mcp:")
3855                    .map(|tool| (tool, ToolPermissionMode::Allow))
3856            })
3857            .or_else(|| {
3858                option_id
3859                    .strip_prefix("always_deny_mcp:")
3860                    .map(|tool| (tool, ToolPermissionMode::Deny))
3861            });
3862
3863        if let Some((tool, mode)) = always_permission {
3864            let params = outcome.params.as_ref();
3865            Self::persist_always_permission(tool, mode, params, fs, cx);
3866            return mode == ToolPermissionMode::Allow;
3867        }
3868
3869        // Handle simple "allow" / "deny" (once, no persistence)
3870        if option_id == "allow" || option_id == "deny" {
3871            debug_assert!(
3872                outcome.params.is_none(),
3873                "unexpected params for once-only permission"
3874            );
3875            return option_id == "allow";
3876        }
3877
3878        debug_assert!(false, "unexpected permission option_id: {option_id}");
3879        false
3880    }
3881
3882    /// Persists an "always allow" or "always deny" permission, using sub_patterns
3883    /// from params when present.
3884    fn persist_always_permission(
3885        tool: &str,
3886        mode: ToolPermissionMode,
3887        params: Option<&acp_thread::SelectedPermissionParams>,
3888        fs: Option<Arc<dyn Fs>>,
3889        cx: &AsyncApp,
3890    ) {
3891        let Some(fs) = fs else {
3892            return;
3893        };
3894
3895        match params {
3896            Some(acp_thread::SelectedPermissionParams::Terminal {
3897                patterns: sub_patterns,
3898            }) => {
3899                debug_assert!(
3900                    !sub_patterns.is_empty(),
3901                    "empty sub_patterns for tool {tool} — callers should pass None instead"
3902                );
3903                let tool = tool.to_string();
3904                let sub_patterns = sub_patterns.clone();
3905                cx.update(|cx| {
3906                    update_settings_file(fs, cx, move |settings, _| {
3907                        let agent = settings.agent.get_or_insert_default();
3908                        for pattern in sub_patterns {
3909                            match mode {
3910                                ToolPermissionMode::Allow => {
3911                                    agent.add_tool_allow_pattern(&tool, pattern);
3912                                }
3913                                ToolPermissionMode::Deny => {
3914                                    agent.add_tool_deny_pattern(&tool, pattern);
3915                                }
3916                                // If there's no matching pattern this will
3917                                // default to confirm, so falling through is
3918                                // fine here.
3919                                ToolPermissionMode::Confirm => (),
3920                            }
3921                        }
3922                    });
3923                });
3924            }
3925            None => {
3926                let tool = tool.to_string();
3927                cx.update(|cx| {
3928                    update_settings_file(fs, cx, move |settings, _| {
3929                        settings
3930                            .agent
3931                            .get_or_insert_default()
3932                            .set_tool_default_permission(&tool, mode);
3933                    });
3934                });
3935            }
3936        }
3937    }
3938}
3939
3940#[cfg(any(test, feature = "test-support"))]
3941pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
3942
3943#[cfg(any(test, feature = "test-support"))]
3944impl ToolCallEventStreamReceiver {
3945    pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
3946        let event = self.0.next().await;
3947        if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
3948            auth
3949        } else {
3950            panic!("Expected ToolCallAuthorization but got: {:?}", event);
3951        }
3952    }
3953
3954    pub async fn expect_update_fields(&mut self) -> acp::ToolCallUpdateFields {
3955        let event = self.0.next().await;
3956        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
3957            update,
3958        )))) = event
3959        {
3960            update.fields
3961        } else {
3962            panic!("Expected update fields but got: {:?}", event);
3963        }
3964    }
3965
3966    pub async fn expect_diff(&mut self) -> Entity<acp_thread::Diff> {
3967        let event = self.0.next().await;
3968        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateDiff(
3969            update,
3970        )))) = event
3971        {
3972            update.diff
3973        } else {
3974            panic!("Expected diff but got: {:?}", event);
3975        }
3976    }
3977
3978    pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
3979        let event = self.0.next().await;
3980        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
3981            update,
3982        )))) = event
3983        {
3984            update.terminal
3985        } else {
3986            panic!("Expected terminal but got: {:?}", event);
3987        }
3988    }
3989
3990    pub async fn expect_plan(&mut self) -> acp::Plan {
3991        let event = self.0.next().await;
3992        if let Some(Ok(ThreadEvent::Plan(plan))) = event {
3993            plan
3994        } else {
3995            panic!("Expected plan but got: {:?}", event);
3996        }
3997    }
3998}
3999
4000#[cfg(any(test, feature = "test-support"))]
4001impl std::ops::Deref for ToolCallEventStreamReceiver {
4002    type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
4003
4004    fn deref(&self) -> &Self::Target {
4005        &self.0
4006    }
4007}
4008
4009#[cfg(any(test, feature = "test-support"))]
4010impl std::ops::DerefMut for ToolCallEventStreamReceiver {
4011    fn deref_mut(&mut self) -> &mut Self::Target {
4012        &mut self.0
4013    }
4014}
4015
4016impl From<&str> for UserMessageContent {
4017    fn from(text: &str) -> Self {
4018        Self::Text(text.into())
4019    }
4020}
4021
4022impl From<String> for UserMessageContent {
4023    fn from(text: String) -> Self {
4024        Self::Text(text)
4025    }
4026}
4027
4028impl UserMessageContent {
4029    pub fn from_content_block(value: acp::ContentBlock, path_style: PathStyle) -> Self {
4030        match value {
4031            acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
4032            acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
4033            acp::ContentBlock::Audio(_) => {
4034                // TODO
4035                Self::Text("[audio]".to_string())
4036            }
4037            acp::ContentBlock::ResourceLink(resource_link) => {
4038                match MentionUri::parse(&resource_link.uri, path_style) {
4039                    Ok(uri) => Self::Mention {
4040                        uri,
4041                        content: String::new(),
4042                    },
4043                    Err(err) => {
4044                        log::error!("Failed to parse mention link: {}", err);
4045                        Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
4046                    }
4047                }
4048            }
4049            acp::ContentBlock::Resource(resource) => match resource.resource {
4050                acp::EmbeddedResourceResource::TextResourceContents(resource) => {
4051                    match MentionUri::parse(&resource.uri, path_style) {
4052                        Ok(uri) => Self::Mention {
4053                            uri,
4054                            content: resource.text,
4055                        },
4056                        Err(err) => {
4057                            log::error!("Failed to parse mention link: {}", err);
4058                            Self::Text(
4059                                MarkdownCodeBlock {
4060                                    tag: &resource.uri,
4061                                    text: &resource.text,
4062                                }
4063                                .to_string(),
4064                            )
4065                        }
4066                    }
4067                }
4068                acp::EmbeddedResourceResource::BlobResourceContents(_) => {
4069                    // TODO
4070                    Self::Text("[blob]".to_string())
4071                }
4072                other => {
4073                    log::warn!("Unexpected content type: {:?}", other);
4074                    Self::Text("[unknown]".to_string())
4075                }
4076            },
4077            other => {
4078                log::warn!("Unexpected content type: {:?}", other);
4079                Self::Text("[unknown]".to_string())
4080            }
4081        }
4082    }
4083}
4084
4085impl From<UserMessageContent> for acp::ContentBlock {
4086    fn from(content: UserMessageContent) -> Self {
4087        match content {
4088            UserMessageContent::Text(text) => text.into(),
4089            UserMessageContent::Image(image) => {
4090                acp::ContentBlock::Image(acp::ImageContent::new(image.source, "image/png"))
4091            }
4092            UserMessageContent::Mention { uri, content } => acp::ContentBlock::Resource(
4093                acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(
4094                    acp::TextResourceContents::new(content, uri.to_uri().to_string()),
4095                )),
4096            ),
4097        }
4098    }
4099}
4100
4101fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
4102    LanguageModelImage {
4103        source: image_content.data.into(),
4104        size: None,
4105    }
4106}
4107
4108#[cfg(test)]
4109mod tests {
4110    use super::*;
4111    use gpui::TestAppContext;
4112    use language_model::LanguageModelToolUseId;
4113    use language_model::fake_provider::FakeLanguageModel;
4114    use serde_json::json;
4115    use std::sync::Arc;
4116
4117    async fn setup_thread_for_test(cx: &mut TestAppContext) -> (Entity<Thread>, ThreadEventStream) {
4118        cx.update(|cx| {
4119            let settings_store = settings::SettingsStore::test(cx);
4120            cx.set_global(settings_store);
4121        });
4122
4123        let fs = fs::FakeFs::new(cx.background_executor.clone());
4124        let templates = Templates::new();
4125        let project = Project::test(fs.clone(), [], cx).await;
4126
4127        cx.update(|cx| {
4128            let project_context = cx.new(|_cx| prompt_store::ProjectContext::default());
4129            let context_server_store = project.read(cx).context_server_store();
4130            let context_server_registry =
4131                cx.new(|cx| ContextServerRegistry::new(context_server_store, cx));
4132
4133            let thread = cx.new(|cx| {
4134                Thread::new(
4135                    project,
4136                    project_context,
4137                    context_server_registry,
4138                    templates,
4139                    None,
4140                    cx,
4141                )
4142            });
4143
4144            let (event_tx, _event_rx) = mpsc::unbounded();
4145            let event_stream = ThreadEventStream(event_tx);
4146
4147            (thread, event_stream)
4148        })
4149    }
4150
4151    fn setup_parent_with_subagents(
4152        cx: &mut TestAppContext,
4153        parent: &Entity<Thread>,
4154        count: usize,
4155    ) -> Vec<Entity<Thread>> {
4156        cx.update(|cx| {
4157            let mut subagents = Vec::new();
4158            for _ in 0..count {
4159                let subagent = cx.new(|cx| Thread::new_subagent(parent, cx));
4160                parent.update(cx, |thread, _cx| {
4161                    thread.register_running_subagent(subagent.downgrade());
4162                });
4163                subagents.push(subagent);
4164            }
4165            subagents
4166        })
4167    }
4168
4169    #[gpui::test]
4170    async fn test_set_model_propagates_to_subagents(cx: &mut TestAppContext) {
4171        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4172        let subagents = setup_parent_with_subagents(cx, &parent, 2);
4173
4174        let new_model: Arc<dyn LanguageModel> = Arc::new(FakeLanguageModel::with_id_and_thinking(
4175            "test-provider",
4176            "new-model",
4177            "New Model",
4178            false,
4179        ));
4180
4181        cx.update(|cx| {
4182            parent.update(cx, |thread, cx| {
4183                thread.set_model(new_model, cx);
4184            });
4185
4186            for subagent in &subagents {
4187                let subagent_model_id = subagent.read(cx).model().unwrap().id();
4188                assert_eq!(
4189                    subagent_model_id.0.as_ref(),
4190                    "new-model",
4191                    "Subagent model should match parent model after set_model"
4192                );
4193            }
4194        });
4195    }
4196
4197    #[gpui::test]
4198    async fn test_set_summarization_model_propagates_to_subagents(cx: &mut TestAppContext) {
4199        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4200        let subagents = setup_parent_with_subagents(cx, &parent, 2);
4201
4202        let summary_model: Arc<dyn LanguageModel> =
4203            Arc::new(FakeLanguageModel::with_id_and_thinking(
4204                "test-provider",
4205                "summary-model",
4206                "Summary Model",
4207                false,
4208            ));
4209
4210        cx.update(|cx| {
4211            parent.update(cx, |thread, cx| {
4212                thread.set_summarization_model(Some(summary_model), cx);
4213            });
4214
4215            for subagent in &subagents {
4216                let subagent_summary_id = subagent.read(cx).summarization_model().unwrap().id();
4217                assert_eq!(
4218                    subagent_summary_id.0.as_ref(),
4219                    "summary-model",
4220                    "Subagent summarization model should match parent after set_summarization_model"
4221                );
4222            }
4223        });
4224    }
4225
4226    #[gpui::test]
4227    async fn test_set_thinking_enabled_propagates_to_subagents(cx: &mut TestAppContext) {
4228        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4229        let subagents = setup_parent_with_subagents(cx, &parent, 2);
4230
4231        cx.update(|cx| {
4232            parent.update(cx, |thread, cx| {
4233                thread.set_thinking_enabled(true, cx);
4234            });
4235
4236            for subagent in &subagents {
4237                assert!(
4238                    subagent.read(cx).thinking_enabled(),
4239                    "Subagent thinking should be enabled after parent enables it"
4240                );
4241            }
4242
4243            parent.update(cx, |thread, cx| {
4244                thread.set_thinking_enabled(false, cx);
4245            });
4246
4247            for subagent in &subagents {
4248                assert!(
4249                    !subagent.read(cx).thinking_enabled(),
4250                    "Subagent thinking should be disabled after parent disables it"
4251                );
4252            }
4253        });
4254    }
4255
4256    #[gpui::test]
4257    async fn test_set_thinking_effort_propagates_to_subagents(cx: &mut TestAppContext) {
4258        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4259        let subagents = setup_parent_with_subagents(cx, &parent, 2);
4260
4261        cx.update(|cx| {
4262            parent.update(cx, |thread, cx| {
4263                thread.set_thinking_effort(Some("high".to_string()), cx);
4264            });
4265
4266            for subagent in &subagents {
4267                assert_eq!(
4268                    subagent.read(cx).thinking_effort().map(|s| s.as_str()),
4269                    Some("high"),
4270                    "Subagent thinking effort should match parent"
4271                );
4272            }
4273
4274            parent.update(cx, |thread, cx| {
4275                thread.set_thinking_effort(None, cx);
4276            });
4277
4278            for subagent in &subagents {
4279                assert_eq!(
4280                    subagent.read(cx).thinking_effort(),
4281                    None,
4282                    "Subagent thinking effort should be None after parent clears it"
4283                );
4284            }
4285        });
4286    }
4287
4288    #[gpui::test]
4289    async fn test_subagent_inherits_settings_at_creation(cx: &mut TestAppContext) {
4290        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4291
4292        cx.update(|cx| {
4293            parent.update(cx, |thread, cx| {
4294                thread.set_speed(Speed::Fast, cx);
4295                thread.set_thinking_enabled(true, cx);
4296                thread.set_thinking_effort(Some("high".to_string()), cx);
4297                thread.set_profile(AgentProfileId("custom-profile".into()), cx);
4298            });
4299        });
4300
4301        let subagents = setup_parent_with_subagents(cx, &parent, 1);
4302
4303        cx.update(|cx| {
4304            let sub = subagents[0].read(cx);
4305            assert_eq!(sub.speed(), Some(Speed::Fast));
4306            assert!(sub.thinking_enabled());
4307            assert_eq!(sub.thinking_effort().map(|s| s.as_str()), Some("high"));
4308            assert_eq!(sub.profile(), &AgentProfileId("custom-profile".into()));
4309        });
4310    }
4311
4312    #[gpui::test]
4313    async fn test_set_speed_propagates_to_subagents(cx: &mut TestAppContext) {
4314        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4315        let subagents = setup_parent_with_subagents(cx, &parent, 2);
4316
4317        cx.update(|cx| {
4318            parent.update(cx, |thread, cx| {
4319                thread.set_speed(Speed::Fast, cx);
4320            });
4321
4322            for subagent in &subagents {
4323                assert_eq!(
4324                    subagent.read(cx).speed(),
4325                    Some(Speed::Fast),
4326                    "Subagent speed should match parent after set_speed"
4327                );
4328            }
4329        });
4330    }
4331
4332    #[gpui::test]
4333    async fn test_dropped_subagent_does_not_panic(cx: &mut TestAppContext) {
4334        let (parent, _event_stream) = setup_thread_for_test(cx).await;
4335        let subagents = setup_parent_with_subagents(cx, &parent, 1);
4336
4337        // Drop the subagent so the WeakEntity can no longer be upgraded
4338        drop(subagents);
4339
4340        // Should not panic even though the subagent was dropped
4341        cx.update(|cx| {
4342            parent.update(cx, |thread, cx| {
4343                thread.set_thinking_enabled(true, cx);
4344                thread.set_speed(Speed::Fast, cx);
4345                thread.set_thinking_effort(Some("high".to_string()), cx);
4346            });
4347        });
4348    }
4349
4350    #[gpui::test]
4351    async fn test_handle_tool_use_json_parse_error_adds_tool_use_to_content(
4352        cx: &mut TestAppContext,
4353    ) {
4354        let (thread, event_stream) = setup_thread_for_test(cx).await;
4355
4356        let tool_use_id = LanguageModelToolUseId::from("test_tool_id");
4357        let tool_name: Arc<str> = Arc::from("test_tool");
4358        let raw_input: Arc<str> = Arc::from("{invalid json");
4359        let json_parse_error = "expected value at line 1 column 1".to_string();
4360
4361        let (_cancellation_tx, cancellation_rx) = watch::channel(false);
4362
4363        let result = cx
4364            .update(|cx| {
4365                thread.update(cx, |thread, cx| {
4366                    // Call the function under test
4367                    thread
4368                        .handle_tool_use_json_parse_error_event(
4369                            tool_use_id.clone(),
4370                            tool_name.clone(),
4371                            raw_input.clone(),
4372                            json_parse_error,
4373                            &event_stream,
4374                            cancellation_rx,
4375                            cx,
4376                        )
4377                        .unwrap()
4378                })
4379            })
4380            .await;
4381
4382        // Verify the result is an error
4383        assert!(result.is_error);
4384        assert_eq!(result.tool_use_id, tool_use_id);
4385        assert_eq!(result.tool_name, tool_name);
4386        assert!(matches!(
4387            result.content,
4388            LanguageModelToolResultContent::Text(_)
4389        ));
4390
4391        thread.update(cx, |thread, _cx| {
4392            // Verify the tool use was added to the message content
4393            {
4394                let last_message = thread.pending_message();
4395                assert_eq!(
4396                    last_message.content.len(),
4397                    1,
4398                    "Should have one tool_use in content"
4399                );
4400
4401                match &last_message.content[0] {
4402                    AgentMessageContent::ToolUse(tool_use) => {
4403                        assert_eq!(tool_use.id, tool_use_id);
4404                        assert_eq!(tool_use.name, tool_name);
4405                        assert_eq!(tool_use.raw_input, raw_input.to_string());
4406                        assert!(tool_use.is_input_complete);
4407                        // Should fall back to empty object for invalid JSON
4408                        assert_eq!(tool_use.input, json!({}));
4409                    }
4410                    _ => panic!("Expected ToolUse content"),
4411                }
4412            }
4413
4414            // Insert the tool result (simulating what the caller does)
4415            thread
4416                .pending_message()
4417                .tool_results
4418                .insert(result.tool_use_id.clone(), result);
4419
4420            // Verify the tool result was added
4421            let last_message = thread.pending_message();
4422            assert_eq!(
4423                last_message.tool_results.len(),
4424                1,
4425                "Should have one tool_result"
4426            );
4427            assert!(last_message.tool_results.contains_key(&tool_use_id));
4428        })
4429    }
4430}