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