thread.rs

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