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