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