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