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