thread.rs

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