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    SystemPromptTemplate, Template, Templates, TerminalTool, ThinkingTool, WebSearchTool,
   6};
   7use acp_thread::{MentionUri, UserMessageId};
   8use action_log::ActionLog;
   9
  10use agent_client_protocol as acp;
  11use agent_settings::{
  12    AgentProfileId, AgentProfileSettings, AgentSettings, CompletionMode,
  13    SUMMARIZE_THREAD_DETAILED_PROMPT, SUMMARIZE_THREAD_PROMPT,
  14};
  15use anyhow::{Context as _, Result, anyhow};
  16use chrono::{DateTime, Utc};
  17use client::{ModelRequestUsage, RequestUsage, UserStore};
  18use cloud_llm_client::{CompletionIntent, CompletionRequestStatus, Plan, UsageLimit};
  19use collections::{HashMap, HashSet, IndexMap};
  20use fs::Fs;
  21use futures::stream;
  22use futures::{
  23    FutureExt,
  24    channel::{mpsc, oneshot},
  25    future::Shared,
  26    stream::FuturesUnordered,
  27};
  28use gpui::{
  29    App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task, WeakEntity,
  30};
  31use language_model::{
  32    LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelExt,
  33    LanguageModelId, LanguageModelImage, LanguageModelProviderId, LanguageModelRegistry,
  34    LanguageModelRequest, LanguageModelRequestMessage, LanguageModelRequestTool,
  35    LanguageModelToolResult, LanguageModelToolResultContent, LanguageModelToolSchemaFormat,
  36    LanguageModelToolUse, LanguageModelToolUseId, Role, SelectedModel, StopReason, TokenUsage,
  37    ZED_CLOUD_PROVIDER_ID,
  38};
  39use project::Project;
  40use prompt_store::ProjectContext;
  41use schemars::{JsonSchema, Schema};
  42use serde::{Deserialize, Serialize};
  43use settings::{LanguageModelSelection, Settings, update_settings_file};
  44use smol::stream::StreamExt;
  45use std::{
  46    collections::BTreeMap,
  47    ops::RangeInclusive,
  48    path::Path,
  49    rc::Rc,
  50    sync::Arc,
  51    time::{Duration, Instant},
  52};
  53use std::{fmt::Write, path::PathBuf};
  54use util::{ResultExt, debug_panic, markdown::MarkdownCodeBlock, paths::PathStyle};
  55use uuid::Uuid;
  56
  57const TOOL_CANCELED_MESSAGE: &str = "Tool canceled by user";
  58pub const MAX_TOOL_NAME_LENGTH: usize = 64;
  59
  60/// The ID of the user prompt that initiated a request.
  61///
  62/// This equates to the user physically submitting a message to the model (e.g., by pressing the Enter key).
  63#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
  64pub struct PromptId(Arc<str>);
  65
  66impl PromptId {
  67    pub fn new() -> Self {
  68        Self(Uuid::new_v4().to_string().into())
  69    }
  70}
  71
  72impl std::fmt::Display for PromptId {
  73    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  74        write!(f, "{}", self.0)
  75    }
  76}
  77
  78pub(crate) const MAX_RETRY_ATTEMPTS: u8 = 4;
  79pub(crate) const BASE_RETRY_DELAY: Duration = Duration::from_secs(5);
  80
  81#[derive(Debug, Clone)]
  82enum RetryStrategy {
  83    ExponentialBackoff {
  84        initial_delay: Duration,
  85        max_attempts: u8,
  86    },
  87    Fixed {
  88        delay: Duration,
  89        max_attempts: u8,
  90    },
  91}
  92
  93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  94pub enum Message {
  95    User(UserMessage),
  96    Agent(AgentMessage),
  97    Resume,
  98}
  99
 100impl Message {
 101    pub fn as_agent_message(&self) -> Option<&AgentMessage> {
 102        match self {
 103            Message::Agent(agent_message) => Some(agent_message),
 104            _ => None,
 105        }
 106    }
 107
 108    pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
 109        match self {
 110            Message::User(message) => vec![message.to_request()],
 111            Message::Agent(message) => message.to_request(),
 112            Message::Resume => vec![LanguageModelRequestMessage {
 113                role: Role::User,
 114                content: vec!["Continue where you left off".into()],
 115                cache: false,
 116                reasoning_details: None,
 117            }],
 118        }
 119    }
 120
 121    pub fn to_markdown(&self) -> String {
 122        match self {
 123            Message::User(message) => message.to_markdown(),
 124            Message::Agent(message) => message.to_markdown(),
 125            Message::Resume => "[resume]\n".into(),
 126        }
 127    }
 128
 129    pub fn role(&self) -> Role {
 130        match self {
 131            Message::User(_) | Message::Resume => Role::User,
 132            Message::Agent(_) => Role::Assistant,
 133        }
 134    }
 135}
 136
 137#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 138pub struct UserMessage {
 139    pub id: UserMessageId,
 140    pub content: Vec<UserMessageContent>,
 141}
 142
 143#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 144pub enum UserMessageContent {
 145    Text(String),
 146    Mention { uri: MentionUri, content: String },
 147    Image(LanguageModelImage),
 148}
 149
 150impl UserMessage {
 151    pub fn to_markdown(&self) -> String {
 152        let mut markdown = String::from("## User\n\n");
 153
 154        for content in &self.content {
 155            match content {
 156                UserMessageContent::Text(text) => {
 157                    markdown.push_str(text);
 158                    markdown.push('\n');
 159                }
 160                UserMessageContent::Image(_) => {
 161                    markdown.push_str("<image />\n");
 162                }
 163                UserMessageContent::Mention { uri, content } => {
 164                    if !content.is_empty() {
 165                        let _ = writeln!(&mut markdown, "{}\n\n{}", uri.as_link(), content);
 166                    } else {
 167                        let _ = writeln!(&mut markdown, "{}", uri.as_link());
 168                    }
 169                }
 170            }
 171        }
 172
 173        markdown
 174    }
 175
 176    fn to_request(&self) -> LanguageModelRequestMessage {
 177        let mut message = LanguageModelRequestMessage {
 178            role: Role::User,
 179            content: Vec::with_capacity(self.content.len()),
 180            cache: false,
 181            reasoning_details: None,
 182        };
 183
 184        const OPEN_CONTEXT: &str = "<context>\n\
 185            The following items were attached by the user. \
 186            They are up-to-date and don't need to be re-read.\n\n";
 187
 188        const OPEN_FILES_TAG: &str = "<files>";
 189        const OPEN_DIRECTORIES_TAG: &str = "<directories>";
 190        const OPEN_SYMBOLS_TAG: &str = "<symbols>";
 191        const OPEN_SELECTIONS_TAG: &str = "<selections>";
 192        const OPEN_THREADS_TAG: &str = "<threads>";
 193        const OPEN_FETCH_TAG: &str = "<fetched_urls>";
 194        const OPEN_RULES_TAG: &str =
 195            "<rules>\nThe user has specified the following rules that should be applied:\n";
 196
 197        let mut file_context = OPEN_FILES_TAG.to_string();
 198        let mut directory_context = OPEN_DIRECTORIES_TAG.to_string();
 199        let mut symbol_context = OPEN_SYMBOLS_TAG.to_string();
 200        let mut selection_context = OPEN_SELECTIONS_TAG.to_string();
 201        let mut thread_context = OPEN_THREADS_TAG.to_string();
 202        let mut fetch_context = OPEN_FETCH_TAG.to_string();
 203        let mut rules_context = OPEN_RULES_TAG.to_string();
 204
 205        for chunk in &self.content {
 206            let chunk = match chunk {
 207                UserMessageContent::Text(text) => {
 208                    language_model::MessageContent::Text(text.clone())
 209                }
 210                UserMessageContent::Image(value) => {
 211                    language_model::MessageContent::Image(value.clone())
 212                }
 213                UserMessageContent::Mention { uri, content } => {
 214                    match uri {
 215                        MentionUri::File { abs_path } => {
 216                            write!(
 217                                &mut file_context,
 218                                "\n{}",
 219                                MarkdownCodeBlock {
 220                                    tag: &codeblock_tag(abs_path, None),
 221                                    text: &content.to_string(),
 222                                }
 223                            )
 224                            .ok();
 225                        }
 226                        MentionUri::PastedImage => {
 227                            debug_panic!("pasted image URI should not be used in mention content")
 228                        }
 229                        MentionUri::Directory { .. } => {
 230                            write!(&mut directory_context, "\n{}\n", content).ok();
 231                        }
 232                        MentionUri::Symbol {
 233                            abs_path: path,
 234                            line_range,
 235                            ..
 236                        } => {
 237                            write!(
 238                                &mut symbol_context,
 239                                "\n{}",
 240                                MarkdownCodeBlock {
 241                                    tag: &codeblock_tag(path, Some(line_range)),
 242                                    text: content
 243                                }
 244                            )
 245                            .ok();
 246                        }
 247                        MentionUri::Selection {
 248                            abs_path: path,
 249                            line_range,
 250                            ..
 251                        } => {
 252                            write!(
 253                                &mut selection_context,
 254                                "\n{}",
 255                                MarkdownCodeBlock {
 256                                    tag: &codeblock_tag(
 257                                        path.as_deref().unwrap_or("Untitled".as_ref()),
 258                                        Some(line_range)
 259                                    ),
 260                                    text: content
 261                                }
 262                            )
 263                            .ok();
 264                        }
 265                        MentionUri::Thread { .. } => {
 266                            write!(&mut thread_context, "\n{}\n", content).ok();
 267                        }
 268                        MentionUri::TextThread { .. } => {
 269                            write!(&mut thread_context, "\n{}\n", content).ok();
 270                        }
 271                        MentionUri::Rule { .. } => {
 272                            write!(
 273                                &mut rules_context,
 274                                "\n{}",
 275                                MarkdownCodeBlock {
 276                                    tag: "",
 277                                    text: content
 278                                }
 279                            )
 280                            .ok();
 281                        }
 282                        MentionUri::Fetch { url } => {
 283                            write!(&mut fetch_context, "\nFetch: {}\n\n{}", url, content).ok();
 284                        }
 285                    }
 286
 287                    language_model::MessageContent::Text(uri.as_link().to_string())
 288                }
 289            };
 290
 291            message.content.push(chunk);
 292        }
 293
 294        let len_before_context = message.content.len();
 295
 296        if file_context.len() > OPEN_FILES_TAG.len() {
 297            file_context.push_str("</files>\n");
 298            message
 299                .content
 300                .push(language_model::MessageContent::Text(file_context));
 301        }
 302
 303        if directory_context.len() > OPEN_DIRECTORIES_TAG.len() {
 304            directory_context.push_str("</directories>\n");
 305            message
 306                .content
 307                .push(language_model::MessageContent::Text(directory_context));
 308        }
 309
 310        if symbol_context.len() > OPEN_SYMBOLS_TAG.len() {
 311            symbol_context.push_str("</symbols>\n");
 312            message
 313                .content
 314                .push(language_model::MessageContent::Text(symbol_context));
 315        }
 316
 317        if selection_context.len() > OPEN_SELECTIONS_TAG.len() {
 318            selection_context.push_str("</selections>\n");
 319            message
 320                .content
 321                .push(language_model::MessageContent::Text(selection_context));
 322        }
 323
 324        if thread_context.len() > OPEN_THREADS_TAG.len() {
 325            thread_context.push_str("</threads>\n");
 326            message
 327                .content
 328                .push(language_model::MessageContent::Text(thread_context));
 329        }
 330
 331        if fetch_context.len() > OPEN_FETCH_TAG.len() {
 332            fetch_context.push_str("</fetched_urls>\n");
 333            message
 334                .content
 335                .push(language_model::MessageContent::Text(fetch_context));
 336        }
 337
 338        if rules_context.len() > OPEN_RULES_TAG.len() {
 339            rules_context.push_str("</user_rules>\n");
 340            message
 341                .content
 342                .push(language_model::MessageContent::Text(rules_context));
 343        }
 344
 345        if message.content.len() > len_before_context {
 346            message.content.insert(
 347                len_before_context,
 348                language_model::MessageContent::Text(OPEN_CONTEXT.into()),
 349            );
 350            message
 351                .content
 352                .push(language_model::MessageContent::Text("</context>".into()));
 353        }
 354
 355        message
 356    }
 357}
 358
 359fn codeblock_tag(full_path: &Path, line_range: Option<&RangeInclusive<u32>>) -> String {
 360    let mut result = String::new();
 361
 362    if let Some(extension) = full_path.extension().and_then(|ext| ext.to_str()) {
 363        let _ = write!(result, "{} ", extension);
 364    }
 365
 366    let _ = write!(result, "{}", full_path.display());
 367
 368    if let Some(range) = line_range {
 369        if range.start() == range.end() {
 370            let _ = write!(result, ":{}", range.start() + 1);
 371        } else {
 372            let _ = write!(result, ":{}-{}", range.start() + 1, range.end() + 1);
 373        }
 374    }
 375
 376    result
 377}
 378
 379impl AgentMessage {
 380    pub fn to_markdown(&self) -> String {
 381        let mut markdown = String::from("## Assistant\n\n");
 382
 383        for content in &self.content {
 384            match content {
 385                AgentMessageContent::Text(text) => {
 386                    markdown.push_str(text);
 387                    markdown.push('\n');
 388                }
 389                AgentMessageContent::Thinking { text, .. } => {
 390                    markdown.push_str("<think>");
 391                    markdown.push_str(text);
 392                    markdown.push_str("</think>\n");
 393                }
 394                AgentMessageContent::RedactedThinking(_) => {
 395                    markdown.push_str("<redacted_thinking />\n")
 396                }
 397                AgentMessageContent::ToolUse(tool_use) => {
 398                    markdown.push_str(&format!(
 399                        "**Tool Use**: {} (ID: {})\n",
 400                        tool_use.name, tool_use.id
 401                    ));
 402                    markdown.push_str(&format!(
 403                        "{}\n",
 404                        MarkdownCodeBlock {
 405                            tag: "json",
 406                            text: &format!("{:#}", tool_use.input)
 407                        }
 408                    ));
 409                }
 410            }
 411        }
 412
 413        for tool_result in self.tool_results.values() {
 414            markdown.push_str(&format!(
 415                "**Tool Result**: {} (ID: {})\n\n",
 416                tool_result.tool_name, tool_result.tool_use_id
 417            ));
 418            if tool_result.is_error {
 419                markdown.push_str("**ERROR:**\n");
 420            }
 421
 422            match &tool_result.content {
 423                LanguageModelToolResultContent::Text(text) => {
 424                    writeln!(markdown, "{text}\n").ok();
 425                }
 426                LanguageModelToolResultContent::Image(_) => {
 427                    writeln!(markdown, "<image />\n").ok();
 428                }
 429            }
 430
 431            if let Some(output) = tool_result.output.as_ref() {
 432                writeln!(
 433                    markdown,
 434                    "**Debug Output**:\n\n```json\n{}\n```\n",
 435                    serde_json::to_string_pretty(output).unwrap()
 436                )
 437                .unwrap();
 438            }
 439        }
 440
 441        markdown
 442    }
 443
 444    pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
 445        let mut assistant_message = LanguageModelRequestMessage {
 446            role: Role::Assistant,
 447            content: Vec::with_capacity(self.content.len()),
 448            cache: false,
 449            reasoning_details: self.reasoning_details.clone(),
 450        };
 451        for chunk in &self.content {
 452            match chunk {
 453                AgentMessageContent::Text(text) => {
 454                    assistant_message
 455                        .content
 456                        .push(language_model::MessageContent::Text(text.clone()));
 457                }
 458                AgentMessageContent::Thinking { text, signature } => {
 459                    assistant_message
 460                        .content
 461                        .push(language_model::MessageContent::Thinking {
 462                            text: text.clone(),
 463                            signature: signature.clone(),
 464                        });
 465                }
 466                AgentMessageContent::RedactedThinking(value) => {
 467                    assistant_message.content.push(
 468                        language_model::MessageContent::RedactedThinking(value.clone()),
 469                    );
 470                }
 471                AgentMessageContent::ToolUse(tool_use) => {
 472                    if self.tool_results.contains_key(&tool_use.id) {
 473                        assistant_message
 474                            .content
 475                            .push(language_model::MessageContent::ToolUse(tool_use.clone()));
 476                    }
 477                }
 478            };
 479        }
 480
 481        let mut user_message = LanguageModelRequestMessage {
 482            role: Role::User,
 483            content: Vec::new(),
 484            cache: false,
 485            reasoning_details: None,
 486        };
 487
 488        for tool_result in self.tool_results.values() {
 489            let mut tool_result = tool_result.clone();
 490            // Surprisingly, the API fails if we return an empty string here.
 491            // It thinks we are sending a tool use without a tool result.
 492            if tool_result.content.is_empty() {
 493                tool_result.content = "<Tool returned an empty string>".into();
 494            }
 495            user_message
 496                .content
 497                .push(language_model::MessageContent::ToolResult(tool_result));
 498        }
 499
 500        let mut messages = Vec::new();
 501        if !assistant_message.content.is_empty() {
 502            messages.push(assistant_message);
 503        }
 504        if !user_message.content.is_empty() {
 505            messages.push(user_message);
 506        }
 507        messages
 508    }
 509}
 510
 511#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 512pub struct AgentMessage {
 513    pub content: Vec<AgentMessageContent>,
 514    pub tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
 515    pub reasoning_details: Option<serde_json::Value>,
 516}
 517
 518#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 519pub enum AgentMessageContent {
 520    Text(String),
 521    Thinking {
 522        text: String,
 523        signature: Option<String>,
 524    },
 525    RedactedThinking(String),
 526    ToolUse(LanguageModelToolUse),
 527}
 528
 529pub trait TerminalHandle {
 530    fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId>;
 531    fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse>;
 532    fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>>;
 533}
 534
 535pub trait ThreadEnvironment {
 536    fn create_terminal(
 537        &self,
 538        command: String,
 539        cwd: Option<PathBuf>,
 540        output_byte_limit: Option<u64>,
 541        cx: &mut AsyncApp,
 542    ) -> Task<Result<Rc<dyn TerminalHandle>>>;
 543}
 544
 545#[derive(Debug)]
 546pub enum ThreadEvent {
 547    UserMessage(UserMessage),
 548    AgentText(String),
 549    AgentThinking(String),
 550    ToolCall(acp::ToolCall),
 551    ToolCallUpdate(acp_thread::ToolCallUpdate),
 552    ToolCallAuthorization(ToolCallAuthorization),
 553    Retry(acp_thread::RetryStatus),
 554    Stop(acp::StopReason),
 555}
 556
 557#[derive(Debug)]
 558pub struct NewTerminal {
 559    pub command: String,
 560    pub output_byte_limit: Option<u64>,
 561    pub cwd: Option<PathBuf>,
 562    pub response: oneshot::Sender<Result<Entity<acp_thread::Terminal>>>,
 563}
 564
 565#[derive(Debug)]
 566pub struct ToolCallAuthorization {
 567    pub tool_call: acp::ToolCallUpdate,
 568    pub options: Vec<acp::PermissionOption>,
 569    pub response: oneshot::Sender<acp::PermissionOptionId>,
 570}
 571
 572#[derive(Debug, thiserror::Error)]
 573enum CompletionError {
 574    #[error("max tokens")]
 575    MaxTokens,
 576    #[error("refusal")]
 577    Refusal,
 578    #[error(transparent)]
 579    Other(#[from] anyhow::Error),
 580}
 581
 582pub struct Thread {
 583    id: acp::SessionId,
 584    prompt_id: PromptId,
 585    updated_at: DateTime<Utc>,
 586    title: Option<SharedString>,
 587    pending_title_generation: Option<Task<()>>,
 588    pending_summary_generation: Option<Shared<Task<Option<SharedString>>>>,
 589    summary: Option<SharedString>,
 590    messages: Vec<Message>,
 591    user_store: Entity<UserStore>,
 592    completion_mode: CompletionMode,
 593    /// Holds the task that handles agent interaction until the end of the turn.
 594    /// Survives across multiple requests as the model performs tool calls and
 595    /// we run tools, report their results.
 596    running_turn: Option<RunningTurn>,
 597    pending_message: Option<AgentMessage>,
 598    tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
 599    tool_use_limit_reached: bool,
 600    request_token_usage: HashMap<UserMessageId, language_model::TokenUsage>,
 601    #[allow(unused)]
 602    cumulative_token_usage: TokenUsage,
 603    #[allow(unused)]
 604    initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
 605    context_server_registry: Entity<ContextServerRegistry>,
 606    profile_id: AgentProfileId,
 607    project_context: Entity<ProjectContext>,
 608    templates: Arc<Templates>,
 609    model: Option<Arc<dyn LanguageModel>>,
 610    summarization_model: Option<Arc<dyn LanguageModel>>,
 611    prompt_capabilities_tx: watch::Sender<acp::PromptCapabilities>,
 612    pub(crate) prompt_capabilities_rx: watch::Receiver<acp::PromptCapabilities>,
 613    pub(crate) project: Entity<Project>,
 614    pub(crate) action_log: Entity<ActionLog>,
 615}
 616
 617impl Thread {
 618    fn prompt_capabilities(model: Option<&dyn LanguageModel>) -> acp::PromptCapabilities {
 619        let image = model.map_or(true, |model| model.supports_images());
 620        acp::PromptCapabilities {
 621            meta: None,
 622            image,
 623            audio: false,
 624            embedded_context: true,
 625        }
 626    }
 627
 628    pub fn new(
 629        project: Entity<Project>,
 630        project_context: Entity<ProjectContext>,
 631        context_server_registry: Entity<ContextServerRegistry>,
 632        templates: Arc<Templates>,
 633        model: Option<Arc<dyn LanguageModel>>,
 634        cx: &mut Context<Self>,
 635    ) -> Self {
 636        let profile_id = AgentSettings::get_global(cx).default_profile.clone();
 637        let action_log = cx.new(|_cx| ActionLog::new(project.clone()));
 638        let (prompt_capabilities_tx, prompt_capabilities_rx) =
 639            watch::channel(Self::prompt_capabilities(model.as_deref()));
 640        Self {
 641            id: acp::SessionId(uuid::Uuid::new_v4().to_string().into()),
 642            prompt_id: PromptId::new(),
 643            updated_at: Utc::now(),
 644            title: None,
 645            pending_title_generation: None,
 646            pending_summary_generation: None,
 647            summary: None,
 648            messages: Vec::new(),
 649            user_store: project.read(cx).user_store(),
 650            completion_mode: AgentSettings::get_global(cx).preferred_completion_mode,
 651            running_turn: None,
 652            pending_message: None,
 653            tools: BTreeMap::default(),
 654            tool_use_limit_reached: false,
 655            request_token_usage: HashMap::default(),
 656            cumulative_token_usage: TokenUsage::default(),
 657            initial_project_snapshot: {
 658                let project_snapshot = Self::project_snapshot(project.clone(), cx);
 659                cx.foreground_executor()
 660                    .spawn(async move { Some(project_snapshot.await) })
 661                    .shared()
 662            },
 663            context_server_registry,
 664            profile_id,
 665            project_context,
 666            templates,
 667            model,
 668            summarization_model: None,
 669            prompt_capabilities_tx,
 670            prompt_capabilities_rx,
 671            project,
 672            action_log,
 673        }
 674    }
 675
 676    pub fn id(&self) -> &acp::SessionId {
 677        &self.id
 678    }
 679
 680    pub fn replay(
 681        &mut self,
 682        cx: &mut Context<Self>,
 683    ) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {
 684        let (tx, rx) = mpsc::unbounded();
 685        let stream = ThreadEventStream(tx);
 686        for message in &self.messages {
 687            match message {
 688                Message::User(user_message) => stream.send_user_message(user_message),
 689                Message::Agent(assistant_message) => {
 690                    for content in &assistant_message.content {
 691                        match content {
 692                            AgentMessageContent::Text(text) => stream.send_text(text),
 693                            AgentMessageContent::Thinking { text, .. } => {
 694                                stream.send_thinking(text)
 695                            }
 696                            AgentMessageContent::RedactedThinking(_) => {}
 697                            AgentMessageContent::ToolUse(tool_use) => {
 698                                self.replay_tool_call(
 699                                    tool_use,
 700                                    assistant_message.tool_results.get(&tool_use.id),
 701                                    &stream,
 702                                    cx,
 703                                );
 704                            }
 705                        }
 706                    }
 707                }
 708                Message::Resume => {}
 709            }
 710        }
 711        rx
 712    }
 713
 714    fn replay_tool_call(
 715        &self,
 716        tool_use: &LanguageModelToolUse,
 717        tool_result: Option<&LanguageModelToolResult>,
 718        stream: &ThreadEventStream,
 719        cx: &mut Context<Self>,
 720    ) {
 721        let tool = self.tools.get(tool_use.name.as_ref()).cloned().or_else(|| {
 722            self.context_server_registry
 723                .read(cx)
 724                .servers()
 725                .find_map(|(_, tools)| {
 726                    if let Some(tool) = tools.get(tool_use.name.as_ref()) {
 727                        Some(tool.clone())
 728                    } else {
 729                        None
 730                    }
 731                })
 732        });
 733
 734        let Some(tool) = tool else {
 735            stream
 736                .0
 737                .unbounded_send(Ok(ThreadEvent::ToolCall(acp::ToolCall {
 738                    meta: None,
 739                    id: acp::ToolCallId(tool_use.id.to_string().into()),
 740                    title: tool_use.name.to_string(),
 741                    kind: acp::ToolKind::Other,
 742                    status: acp::ToolCallStatus::Failed,
 743                    content: Vec::new(),
 744                    locations: Vec::new(),
 745                    raw_input: Some(tool_use.input.clone()),
 746                    raw_output: None,
 747                })))
 748                .ok();
 749            return;
 750        };
 751
 752        let title = tool.initial_title(tool_use.input.clone(), cx);
 753        let kind = tool.kind();
 754        stream.send_tool_call(
 755            &tool_use.id,
 756            &tool_use.name,
 757            title,
 758            kind,
 759            tool_use.input.clone(),
 760        );
 761
 762        let output = tool_result
 763            .as_ref()
 764            .and_then(|result| result.output.clone());
 765        if let Some(output) = output.clone() {
 766            let tool_event_stream = ToolCallEventStream::new(
 767                tool_use.id.clone(),
 768                stream.clone(),
 769                Some(self.project.read(cx).fs().clone()),
 770            );
 771            tool.replay(tool_use.input.clone(), output, tool_event_stream, cx)
 772                .log_err();
 773        }
 774
 775        stream.update_tool_call_fields(
 776            &tool_use.id,
 777            acp::ToolCallUpdateFields {
 778                status: Some(
 779                    tool_result
 780                        .as_ref()
 781                        .map_or(acp::ToolCallStatus::Failed, |result| {
 782                            if result.is_error {
 783                                acp::ToolCallStatus::Failed
 784                            } else {
 785                                acp::ToolCallStatus::Completed
 786                            }
 787                        }),
 788                ),
 789                raw_output: output,
 790                ..Default::default()
 791            },
 792        );
 793    }
 794
 795    pub fn from_db(
 796        id: acp::SessionId,
 797        db_thread: DbThread,
 798        project: Entity<Project>,
 799        project_context: Entity<ProjectContext>,
 800        context_server_registry: Entity<ContextServerRegistry>,
 801        templates: Arc<Templates>,
 802        cx: &mut Context<Self>,
 803    ) -> Self {
 804        let profile_id = db_thread
 805            .profile
 806            .unwrap_or_else(|| AgentSettings::get_global(cx).default_profile.clone());
 807
 808        let mut model = LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
 809            db_thread
 810                .model
 811                .and_then(|model| {
 812                    let model = SelectedModel {
 813                        provider: model.provider.clone().into(),
 814                        model: model.model.into(),
 815                    };
 816                    registry.select_model(&model, cx)
 817                })
 818                .or_else(|| registry.default_model())
 819                .map(|model| model.model)
 820        });
 821
 822        if model.is_none() {
 823            model = Self::resolve_profile_model(&profile_id, cx);
 824        }
 825        if model.is_none() {
 826            model = LanguageModelRegistry::global(cx).update(cx, |registry, _cx| {
 827                registry.default_model().map(|model| model.model)
 828            });
 829        }
 830
 831        let (prompt_capabilities_tx, prompt_capabilities_rx) =
 832            watch::channel(Self::prompt_capabilities(model.as_deref()));
 833
 834        let action_log = cx.new(|_| ActionLog::new(project.clone()));
 835
 836        Self {
 837            id,
 838            prompt_id: PromptId::new(),
 839            title: if db_thread.title.is_empty() {
 840                None
 841            } else {
 842                Some(db_thread.title.clone())
 843            },
 844            pending_title_generation: None,
 845            pending_summary_generation: None,
 846            summary: db_thread.detailed_summary,
 847            messages: db_thread.messages,
 848            user_store: project.read(cx).user_store(),
 849            completion_mode: db_thread.completion_mode.unwrap_or_default(),
 850            running_turn: None,
 851            pending_message: None,
 852            tools: BTreeMap::default(),
 853            tool_use_limit_reached: false,
 854            request_token_usage: db_thread.request_token_usage.clone(),
 855            cumulative_token_usage: db_thread.cumulative_token_usage,
 856            initial_project_snapshot: Task::ready(db_thread.initial_project_snapshot).shared(),
 857            context_server_registry,
 858            profile_id,
 859            project_context,
 860            templates,
 861            model,
 862            summarization_model: None,
 863            project,
 864            action_log,
 865            updated_at: db_thread.updated_at,
 866            prompt_capabilities_tx,
 867            prompt_capabilities_rx,
 868        }
 869    }
 870
 871    pub fn to_db(&self, cx: &App) -> Task<DbThread> {
 872        let initial_project_snapshot = self.initial_project_snapshot.clone();
 873        let mut thread = DbThread {
 874            title: self.title(),
 875            messages: self.messages.clone(),
 876            updated_at: self.updated_at,
 877            detailed_summary: self.summary.clone(),
 878            initial_project_snapshot: None,
 879            cumulative_token_usage: self.cumulative_token_usage,
 880            request_token_usage: self.request_token_usage.clone(),
 881            model: self.model.as_ref().map(|model| DbLanguageModel {
 882                provider: model.provider_id().to_string(),
 883                model: model.name().0.to_string(),
 884            }),
 885            completion_mode: Some(self.completion_mode),
 886            profile: Some(self.profile_id.clone()),
 887        };
 888
 889        cx.background_spawn(async move {
 890            let initial_project_snapshot = initial_project_snapshot.await;
 891            thread.initial_project_snapshot = initial_project_snapshot;
 892            thread
 893        })
 894    }
 895
 896    /// Create a snapshot of the current project state including git information and unsaved buffers.
 897    fn project_snapshot(
 898        project: Entity<Project>,
 899        cx: &mut Context<Self>,
 900    ) -> Task<Arc<ProjectSnapshot>> {
 901        let task = project::telemetry_snapshot::TelemetrySnapshot::new(&project, cx);
 902        cx.spawn(async move |_, _| {
 903            let snapshot = task.await;
 904
 905            Arc::new(ProjectSnapshot {
 906                worktree_snapshots: snapshot.worktree_snapshots,
 907                timestamp: Utc::now(),
 908            })
 909        })
 910    }
 911
 912    pub fn project_context(&self) -> &Entity<ProjectContext> {
 913        &self.project_context
 914    }
 915
 916    pub fn project(&self) -> &Entity<Project> {
 917        &self.project
 918    }
 919
 920    pub fn action_log(&self) -> &Entity<ActionLog> {
 921        &self.action_log
 922    }
 923
 924    pub fn is_empty(&self) -> bool {
 925        self.messages.is_empty() && self.title.is_none()
 926    }
 927
 928    pub fn model(&self) -> Option<&Arc<dyn LanguageModel>> {
 929        self.model.as_ref()
 930    }
 931
 932    pub fn set_model(&mut self, model: Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
 933        let old_usage = self.latest_token_usage();
 934        self.model = Some(model);
 935        let new_caps = Self::prompt_capabilities(self.model.as_deref());
 936        let new_usage = self.latest_token_usage();
 937        if old_usage != new_usage {
 938            cx.emit(TokenUsageUpdated(new_usage));
 939        }
 940        self.prompt_capabilities_tx.send(new_caps).log_err();
 941        cx.notify()
 942    }
 943
 944    pub fn summarization_model(&self) -> Option<&Arc<dyn LanguageModel>> {
 945        self.summarization_model.as_ref()
 946    }
 947
 948    pub fn set_summarization_model(
 949        &mut self,
 950        model: Option<Arc<dyn LanguageModel>>,
 951        cx: &mut Context<Self>,
 952    ) {
 953        self.summarization_model = model;
 954        cx.notify()
 955    }
 956
 957    pub fn completion_mode(&self) -> CompletionMode {
 958        self.completion_mode
 959    }
 960
 961    pub fn set_completion_mode(&mut self, mode: CompletionMode, cx: &mut Context<Self>) {
 962        let old_usage = self.latest_token_usage();
 963        self.completion_mode = mode;
 964        let new_usage = self.latest_token_usage();
 965        if old_usage != new_usage {
 966            cx.emit(TokenUsageUpdated(new_usage));
 967        }
 968        cx.notify()
 969    }
 970
 971    #[cfg(any(test, feature = "test-support"))]
 972    pub fn last_message(&self) -> Option<Message> {
 973        if let Some(message) = self.pending_message.clone() {
 974            Some(Message::Agent(message))
 975        } else {
 976            self.messages.last().cloned()
 977        }
 978    }
 979
 980    pub fn add_default_tools(
 981        &mut self,
 982        environment: Rc<dyn ThreadEnvironment>,
 983        cx: &mut Context<Self>,
 984    ) {
 985        let language_registry = self.project.read(cx).languages().clone();
 986        self.add_tool(CopyPathTool::new(self.project.clone()));
 987        self.add_tool(CreateDirectoryTool::new(self.project.clone()));
 988        self.add_tool(DeletePathTool::new(
 989            self.project.clone(),
 990            self.action_log.clone(),
 991        ));
 992        self.add_tool(DiagnosticsTool::new(self.project.clone()));
 993        self.add_tool(EditFileTool::new(
 994            self.project.clone(),
 995            cx.weak_entity(),
 996            language_registry,
 997            Templates::new(),
 998        ));
 999        self.add_tool(FetchTool::new(self.project.read(cx).client().http_client()));
1000        self.add_tool(FindPathTool::new(self.project.clone()));
1001        self.add_tool(GrepTool::new(self.project.clone()));
1002        self.add_tool(ListDirectoryTool::new(self.project.clone()));
1003        self.add_tool(MovePathTool::new(self.project.clone()));
1004        self.add_tool(NowTool);
1005        self.add_tool(OpenTool::new(self.project.clone()));
1006        self.add_tool(ReadFileTool::new(
1007            self.project.clone(),
1008            self.action_log.clone(),
1009        ));
1010        self.add_tool(TerminalTool::new(self.project.clone(), environment));
1011        self.add_tool(ThinkingTool);
1012        self.add_tool(WebSearchTool);
1013    }
1014
1015    pub fn add_tool<T: AgentTool>(&mut self, tool: T) {
1016        self.tools.insert(T::name().into(), tool.erase());
1017    }
1018
1019    pub fn remove_tool(&mut self, name: &str) -> bool {
1020        self.tools.remove(name).is_some()
1021    }
1022
1023    pub fn profile(&self) -> &AgentProfileId {
1024        &self.profile_id
1025    }
1026
1027    pub fn set_profile(&mut self, profile_id: AgentProfileId, cx: &mut Context<Self>) {
1028        if self.profile_id == profile_id {
1029            return;
1030        }
1031
1032        self.profile_id = profile_id;
1033
1034        // Swap to the profile's preferred model when available.
1035        if let Some(model) = Self::resolve_profile_model(&self.profile_id, cx) {
1036            self.set_model(model, cx);
1037        }
1038    }
1039
1040    pub fn cancel(&mut self, cx: &mut Context<Self>) {
1041        if let Some(running_turn) = self.running_turn.take() {
1042            running_turn.cancel();
1043        }
1044        self.flush_pending_message(cx);
1045    }
1046
1047    fn update_token_usage(&mut self, update: language_model::TokenUsage, cx: &mut Context<Self>) {
1048        let Some(last_user_message) = self.last_user_message() else {
1049            return;
1050        };
1051
1052        self.request_token_usage
1053            .insert(last_user_message.id.clone(), update);
1054        cx.emit(TokenUsageUpdated(self.latest_token_usage()));
1055        cx.notify();
1056    }
1057
1058    pub fn truncate(&mut self, message_id: UserMessageId, cx: &mut Context<Self>) -> Result<()> {
1059        self.cancel(cx);
1060        let Some(position) = self.messages.iter().position(
1061            |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
1062        ) else {
1063            return Err(anyhow!("Message not found"));
1064        };
1065
1066        for message in self.messages.drain(position..) {
1067            match message {
1068                Message::User(message) => {
1069                    self.request_token_usage.remove(&message.id);
1070                }
1071                Message::Agent(_) | Message::Resume => {}
1072            }
1073        }
1074        self.clear_summary();
1075        cx.notify();
1076        Ok(())
1077    }
1078
1079    pub fn latest_request_token_usage(&self) -> Option<language_model::TokenUsage> {
1080        let last_user_message = self.last_user_message()?;
1081        let tokens = self.request_token_usage.get(&last_user_message.id)?;
1082        Some(*tokens)
1083    }
1084
1085    pub fn latest_token_usage(&self) -> Option<acp_thread::TokenUsage> {
1086        let usage = self.latest_request_token_usage()?;
1087        let model = self.model.clone()?;
1088        Some(acp_thread::TokenUsage {
1089            max_tokens: model.max_token_count_for_mode(self.completion_mode.into()),
1090            used_tokens: usage.total_tokens(),
1091        })
1092    }
1093
1094    /// Look up the active profile and resolve its preferred model if one is configured.
1095    fn resolve_profile_model(
1096        profile_id: &AgentProfileId,
1097        cx: &mut Context<Self>,
1098    ) -> Option<Arc<dyn LanguageModel>> {
1099        let selection = AgentSettings::get_global(cx)
1100            .profiles
1101            .get(profile_id)?
1102            .default_model
1103            .clone()?;
1104        Self::resolve_model_from_selection(&selection, cx)
1105    }
1106
1107    /// Translate a stored model selection into the configured model from the registry.
1108    fn resolve_model_from_selection(
1109        selection: &LanguageModelSelection,
1110        cx: &mut Context<Self>,
1111    ) -> Option<Arc<dyn LanguageModel>> {
1112        let selected = SelectedModel {
1113            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
1114            model: LanguageModelId::from(selection.model.clone()),
1115        };
1116        LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1117            registry
1118                .select_model(&selected, cx)
1119                .map(|configured| configured.model)
1120        })
1121    }
1122
1123    pub fn resume(
1124        &mut self,
1125        cx: &mut Context<Self>,
1126    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1127        self.messages.push(Message::Resume);
1128        cx.notify();
1129
1130        log::debug!("Total messages in thread: {}", self.messages.len());
1131        self.run_turn(cx)
1132    }
1133
1134    /// Sending a message results in the model streaming a response, which could include tool calls.
1135    /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
1136    /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
1137    pub fn send<T>(
1138        &mut self,
1139        id: UserMessageId,
1140        content: impl IntoIterator<Item = T>,
1141        cx: &mut Context<Self>,
1142    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
1143    where
1144        T: Into<UserMessageContent>,
1145    {
1146        let model = self.model().context("No language model configured")?;
1147
1148        log::info!("Thread::send called with model: {}", model.name().0);
1149        self.advance_prompt_id();
1150
1151        let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
1152        log::debug!("Thread::send content: {:?}", content);
1153
1154        self.messages
1155            .push(Message::User(UserMessage { id, content }));
1156        cx.notify();
1157
1158        log::debug!("Total messages in thread: {}", self.messages.len());
1159        self.run_turn(cx)
1160    }
1161
1162    #[cfg(feature = "eval")]
1163    pub fn proceed(
1164        &mut self,
1165        cx: &mut Context<Self>,
1166    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1167        self.run_turn(cx)
1168    }
1169
1170    fn run_turn(
1171        &mut self,
1172        cx: &mut Context<Self>,
1173    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1174        self.cancel(cx);
1175
1176        let model = self.model.clone().context("No language model configured")?;
1177        let profile = AgentSettings::get_global(cx)
1178            .profiles
1179            .get(&self.profile_id)
1180            .context("Profile not found")?;
1181        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1182        let event_stream = ThreadEventStream(events_tx);
1183        let message_ix = self.messages.len().saturating_sub(1);
1184        self.tool_use_limit_reached = false;
1185        self.clear_summary();
1186        self.running_turn = Some(RunningTurn {
1187            event_stream: event_stream.clone(),
1188            tools: self.enabled_tools(profile, &model, cx),
1189            _task: cx.spawn(async move |this, cx| {
1190                log::debug!("Starting agent turn execution");
1191
1192                let turn_result = Self::run_turn_internal(&this, model, &event_stream, cx).await;
1193                _ = this.update(cx, |this, cx| this.flush_pending_message(cx));
1194
1195                match turn_result {
1196                    Ok(()) => {
1197                        log::debug!("Turn execution completed");
1198                        event_stream.send_stop(acp::StopReason::EndTurn);
1199                    }
1200                    Err(error) => {
1201                        log::error!("Turn execution failed: {:?}", error);
1202                        match error.downcast::<CompletionError>() {
1203                            Ok(CompletionError::Refusal) => {
1204                                event_stream.send_stop(acp::StopReason::Refusal);
1205                                _ = this.update(cx, |this, _| this.messages.truncate(message_ix));
1206                            }
1207                            Ok(CompletionError::MaxTokens) => {
1208                                event_stream.send_stop(acp::StopReason::MaxTokens);
1209                            }
1210                            Ok(CompletionError::Other(error)) | Err(error) => {
1211                                event_stream.send_error(error);
1212                            }
1213                        }
1214                    }
1215                }
1216
1217                _ = this.update(cx, |this, _| this.running_turn.take());
1218            }),
1219        });
1220        Ok(events_rx)
1221    }
1222
1223    async fn run_turn_internal(
1224        this: &WeakEntity<Self>,
1225        model: Arc<dyn LanguageModel>,
1226        event_stream: &ThreadEventStream,
1227        cx: &mut AsyncApp,
1228    ) -> Result<()> {
1229        let mut attempt = 0;
1230        let mut intent = CompletionIntent::UserPrompt;
1231        loop {
1232            let request =
1233                this.update(cx, |this, cx| this.build_completion_request(intent, cx))??;
1234
1235            telemetry::event!(
1236                "Agent Thread Completion",
1237                thread_id = this.read_with(cx, |this, _| this.id.to_string())?,
1238                prompt_id = this.read_with(cx, |this, _| this.prompt_id.to_string())?,
1239                model = model.telemetry_id(),
1240                model_provider = model.provider_id().to_string(),
1241                attempt
1242            );
1243
1244            log::debug!("Calling model.stream_completion, attempt {}", attempt);
1245
1246            let (mut events, mut error) = match model.stream_completion(request, cx).await {
1247                Ok(events) => (events, None),
1248                Err(err) => (stream::empty().boxed(), Some(err)),
1249            };
1250            let mut tool_results = FuturesUnordered::new();
1251            while let Some(event) = events.next().await {
1252                log::trace!("Received completion event: {:?}", event);
1253                match event {
1254                    Ok(event) => {
1255                        tool_results.extend(this.update(cx, |this, cx| {
1256                            this.handle_completion_event(event, event_stream, cx)
1257                        })??);
1258                    }
1259                    Err(err) => {
1260                        error = Some(err);
1261                        break;
1262                    }
1263                }
1264            }
1265
1266            let end_turn = tool_results.is_empty();
1267            while let Some(tool_result) = tool_results.next().await {
1268                log::debug!("Tool finished {:?}", tool_result);
1269
1270                event_stream.update_tool_call_fields(
1271                    &tool_result.tool_use_id,
1272                    acp::ToolCallUpdateFields {
1273                        status: Some(if tool_result.is_error {
1274                            acp::ToolCallStatus::Failed
1275                        } else {
1276                            acp::ToolCallStatus::Completed
1277                        }),
1278                        raw_output: tool_result.output.clone(),
1279                        ..Default::default()
1280                    },
1281                );
1282                this.update(cx, |this, _cx| {
1283                    this.pending_message()
1284                        .tool_results
1285                        .insert(tool_result.tool_use_id.clone(), tool_result);
1286                })?;
1287            }
1288
1289            this.update(cx, |this, cx| {
1290                this.flush_pending_message(cx);
1291                if this.title.is_none() && this.pending_title_generation.is_none() {
1292                    this.generate_title(cx);
1293                }
1294            })?;
1295
1296            if let Some(error) = error {
1297                attempt += 1;
1298                let retry = this.update(cx, |this, cx| {
1299                    let user_store = this.user_store.read(cx);
1300                    this.handle_completion_error(error, attempt, user_store.plan())
1301                })??;
1302                let timer = cx.background_executor().timer(retry.duration);
1303                event_stream.send_retry(retry);
1304                timer.await;
1305                this.update(cx, |this, _cx| {
1306                    if let Some(Message::Agent(message)) = this.messages.last() {
1307                        if message.tool_results.is_empty() {
1308                            intent = CompletionIntent::UserPrompt;
1309                            this.messages.push(Message::Resume);
1310                        }
1311                    }
1312                })?;
1313            } else if this.read_with(cx, |this, _| this.tool_use_limit_reached)? {
1314                return Err(language_model::ToolUseLimitReachedError.into());
1315            } else if end_turn {
1316                return Ok(());
1317            } else {
1318                intent = CompletionIntent::ToolResults;
1319                attempt = 0;
1320            }
1321        }
1322    }
1323
1324    fn handle_completion_error(
1325        &mut self,
1326        error: LanguageModelCompletionError,
1327        attempt: u8,
1328        plan: Option<Plan>,
1329    ) -> Result<acp_thread::RetryStatus> {
1330        let Some(model) = self.model.as_ref() else {
1331            return Err(anyhow!(error));
1332        };
1333
1334        let auto_retry = if model.provider_id() == ZED_CLOUD_PROVIDER_ID {
1335            match plan {
1336                Some(Plan::V2(_)) => true,
1337                Some(Plan::V1(_)) => self.completion_mode == CompletionMode::Burn,
1338                None => false,
1339            }
1340        } else {
1341            true
1342        };
1343
1344        if !auto_retry {
1345            return Err(anyhow!(error));
1346        }
1347
1348        let Some(strategy) = Self::retry_strategy_for(&error) else {
1349            return Err(anyhow!(error));
1350        };
1351
1352        let max_attempts = match &strategy {
1353            RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
1354            RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
1355        };
1356
1357        if attempt > max_attempts {
1358            return Err(anyhow!(error));
1359        }
1360
1361        let delay = match &strategy {
1362            RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
1363                let delay_secs = initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
1364                Duration::from_secs(delay_secs)
1365            }
1366            RetryStrategy::Fixed { delay, .. } => *delay,
1367        };
1368        log::debug!("Retry attempt {attempt} with delay {delay:?}");
1369
1370        Ok(acp_thread::RetryStatus {
1371            last_error: error.to_string().into(),
1372            attempt: attempt as usize,
1373            max_attempts: max_attempts as usize,
1374            started_at: Instant::now(),
1375            duration: delay,
1376        })
1377    }
1378
1379    /// A helper method that's called on every streamed completion event.
1380    /// Returns an optional tool result task, which the main agentic loop will
1381    /// send back to the model when it resolves.
1382    fn handle_completion_event(
1383        &mut self,
1384        event: LanguageModelCompletionEvent,
1385        event_stream: &ThreadEventStream,
1386        cx: &mut Context<Self>,
1387    ) -> Result<Option<Task<LanguageModelToolResult>>> {
1388        log::trace!("Handling streamed completion event: {:?}", event);
1389        use LanguageModelCompletionEvent::*;
1390
1391        match event {
1392            StartMessage { .. } => {
1393                self.flush_pending_message(cx);
1394                self.pending_message = Some(AgentMessage::default());
1395            }
1396            Text(new_text) => self.handle_text_event(new_text, event_stream, cx),
1397            Thinking { text, signature } => {
1398                self.handle_thinking_event(text, signature, event_stream, cx)
1399            }
1400            RedactedThinking { data } => self.handle_redacted_thinking_event(data, cx),
1401            ReasoningDetails(details) => {
1402                let last_message = self.pending_message();
1403                // Store the last non-empty reasoning_details (overwrites earlier ones)
1404                // This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
1405                if let serde_json::Value::Array(ref arr) = details {
1406                    if !arr.is_empty() {
1407                        last_message.reasoning_details = Some(details);
1408                    }
1409                } else {
1410                    last_message.reasoning_details = Some(details);
1411                }
1412            }
1413            ToolUse(tool_use) => {
1414                return Ok(self.handle_tool_use_event(tool_use, event_stream, cx));
1415            }
1416            ToolUseJsonParseError {
1417                id,
1418                tool_name,
1419                raw_input,
1420                json_parse_error,
1421            } => {
1422                return Ok(Some(Task::ready(
1423                    self.handle_tool_use_json_parse_error_event(
1424                        id,
1425                        tool_name,
1426                        raw_input,
1427                        json_parse_error,
1428                    ),
1429                )));
1430            }
1431            UsageUpdate(usage) => {
1432                telemetry::event!(
1433                    "Agent Thread Completion Usage Updated",
1434                    thread_id = self.id.to_string(),
1435                    prompt_id = self.prompt_id.to_string(),
1436                    model = self.model.as_ref().map(|m| m.telemetry_id()),
1437                    model_provider = self.model.as_ref().map(|m| m.provider_id().to_string()),
1438                    input_tokens = usage.input_tokens,
1439                    output_tokens = usage.output_tokens,
1440                    cache_creation_input_tokens = usage.cache_creation_input_tokens,
1441                    cache_read_input_tokens = usage.cache_read_input_tokens,
1442                );
1443                self.update_token_usage(usage, cx);
1444            }
1445            StatusUpdate(CompletionRequestStatus::UsageUpdated { amount, limit }) => {
1446                self.update_model_request_usage(amount, limit, cx);
1447            }
1448            StatusUpdate(
1449                CompletionRequestStatus::Started
1450                | CompletionRequestStatus::Queued { .. }
1451                | CompletionRequestStatus::Failed { .. },
1452            ) => {}
1453            StatusUpdate(CompletionRequestStatus::ToolUseLimitReached) => {
1454                self.tool_use_limit_reached = true;
1455            }
1456            Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()),
1457            Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()),
1458            Stop(StopReason::ToolUse | StopReason::EndTurn) => {}
1459        }
1460
1461        Ok(None)
1462    }
1463
1464    fn handle_text_event(
1465        &mut self,
1466        new_text: String,
1467        event_stream: &ThreadEventStream,
1468        cx: &mut Context<Self>,
1469    ) {
1470        event_stream.send_text(&new_text);
1471
1472        let last_message = self.pending_message();
1473        if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
1474            text.push_str(&new_text);
1475        } else {
1476            last_message
1477                .content
1478                .push(AgentMessageContent::Text(new_text));
1479        }
1480
1481        cx.notify();
1482    }
1483
1484    fn handle_thinking_event(
1485        &mut self,
1486        new_text: String,
1487        new_signature: Option<String>,
1488        event_stream: &ThreadEventStream,
1489        cx: &mut Context<Self>,
1490    ) {
1491        event_stream.send_thinking(&new_text);
1492
1493        let last_message = self.pending_message();
1494        if let Some(AgentMessageContent::Thinking { text, signature }) =
1495            last_message.content.last_mut()
1496        {
1497            text.push_str(&new_text);
1498            *signature = new_signature.or(signature.take());
1499        } else {
1500            last_message.content.push(AgentMessageContent::Thinking {
1501                text: new_text,
1502                signature: new_signature,
1503            });
1504        }
1505
1506        cx.notify();
1507    }
1508
1509    fn handle_redacted_thinking_event(&mut self, data: String, cx: &mut Context<Self>) {
1510        let last_message = self.pending_message();
1511        last_message
1512            .content
1513            .push(AgentMessageContent::RedactedThinking(data));
1514        cx.notify();
1515    }
1516
1517    fn handle_tool_use_event(
1518        &mut self,
1519        tool_use: LanguageModelToolUse,
1520        event_stream: &ThreadEventStream,
1521        cx: &mut Context<Self>,
1522    ) -> Option<Task<LanguageModelToolResult>> {
1523        cx.notify();
1524
1525        let tool = self.tool(tool_use.name.as_ref());
1526        let mut title = SharedString::from(&tool_use.name);
1527        let mut kind = acp::ToolKind::Other;
1528        if let Some(tool) = tool.as_ref() {
1529            title = tool.initial_title(tool_use.input.clone(), cx);
1530            kind = tool.kind();
1531        }
1532
1533        // Ensure the last message ends in the current tool use
1534        let last_message = self.pending_message();
1535        let push_new_tool_use = last_message.content.last_mut().is_none_or(|content| {
1536            if let AgentMessageContent::ToolUse(last_tool_use) = content {
1537                if last_tool_use.id == tool_use.id {
1538                    *last_tool_use = tool_use.clone();
1539                    false
1540                } else {
1541                    true
1542                }
1543            } else {
1544                true
1545            }
1546        });
1547
1548        if push_new_tool_use {
1549            event_stream.send_tool_call(
1550                &tool_use.id,
1551                &tool_use.name,
1552                title,
1553                kind,
1554                tool_use.input.clone(),
1555            );
1556            last_message
1557                .content
1558                .push(AgentMessageContent::ToolUse(tool_use.clone()));
1559        } else {
1560            event_stream.update_tool_call_fields(
1561                &tool_use.id,
1562                acp::ToolCallUpdateFields {
1563                    title: Some(title.into()),
1564                    kind: Some(kind),
1565                    raw_input: Some(tool_use.input.clone()),
1566                    ..Default::default()
1567                },
1568            );
1569        }
1570
1571        if !tool_use.is_input_complete {
1572            return None;
1573        }
1574
1575        let Some(tool) = tool else {
1576            let content = format!("No tool named {} exists", tool_use.name);
1577            return Some(Task::ready(LanguageModelToolResult {
1578                content: LanguageModelToolResultContent::Text(Arc::from(content)),
1579                tool_use_id: tool_use.id,
1580                tool_name: tool_use.name,
1581                is_error: true,
1582                output: None,
1583            }));
1584        };
1585
1586        let fs = self.project.read(cx).fs().clone();
1587        let tool_event_stream =
1588            ToolCallEventStream::new(tool_use.id.clone(), event_stream.clone(), Some(fs));
1589        tool_event_stream.update_fields(acp::ToolCallUpdateFields {
1590            status: Some(acp::ToolCallStatus::InProgress),
1591            ..Default::default()
1592        });
1593        let supports_images = self.model().is_some_and(|model| model.supports_images());
1594        let tool_result = tool.run(tool_use.input, tool_event_stream, cx);
1595        log::debug!("Running tool {}", tool_use.name);
1596        Some(cx.foreground_executor().spawn(async move {
1597            let tool_result = tool_result.await.and_then(|output| {
1598                if let LanguageModelToolResultContent::Image(_) = &output.llm_output
1599                    && !supports_images
1600                {
1601                    return Err(anyhow!(
1602                        "Attempted to read an image, but this model doesn't support it.",
1603                    ));
1604                }
1605                Ok(output)
1606            });
1607
1608            match tool_result {
1609                Ok(output) => LanguageModelToolResult {
1610                    tool_use_id: tool_use.id,
1611                    tool_name: tool_use.name,
1612                    is_error: false,
1613                    content: output.llm_output,
1614                    output: Some(output.raw_output),
1615                },
1616                Err(error) => LanguageModelToolResult {
1617                    tool_use_id: tool_use.id,
1618                    tool_name: tool_use.name,
1619                    is_error: true,
1620                    content: LanguageModelToolResultContent::Text(Arc::from(error.to_string())),
1621                    output: Some(error.to_string().into()),
1622                },
1623            }
1624        }))
1625    }
1626
1627    fn handle_tool_use_json_parse_error_event(
1628        &mut self,
1629        tool_use_id: LanguageModelToolUseId,
1630        tool_name: Arc<str>,
1631        raw_input: Arc<str>,
1632        json_parse_error: String,
1633    ) -> LanguageModelToolResult {
1634        let tool_output = format!("Error parsing input JSON: {json_parse_error}");
1635        LanguageModelToolResult {
1636            tool_use_id,
1637            tool_name,
1638            is_error: true,
1639            content: LanguageModelToolResultContent::Text(tool_output.into()),
1640            output: Some(serde_json::Value::String(raw_input.to_string())),
1641        }
1642    }
1643
1644    fn update_model_request_usage(&self, amount: usize, limit: UsageLimit, cx: &mut Context<Self>) {
1645        self.project
1646            .read(cx)
1647            .user_store()
1648            .update(cx, |user_store, cx| {
1649                user_store.update_model_request_usage(
1650                    ModelRequestUsage(RequestUsage {
1651                        amount: amount as i32,
1652                        limit,
1653                    }),
1654                    cx,
1655                )
1656            });
1657    }
1658
1659    pub fn title(&self) -> SharedString {
1660        self.title.clone().unwrap_or("New Thread".into())
1661    }
1662
1663    pub fn is_generating_summary(&self) -> bool {
1664        self.pending_summary_generation.is_some()
1665    }
1666
1667    pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
1668        if let Some(summary) = self.summary.as_ref() {
1669            return Task::ready(Some(summary.clone())).shared();
1670        }
1671        if let Some(task) = self.pending_summary_generation.clone() {
1672            return task;
1673        }
1674        let Some(model) = self.summarization_model.clone() else {
1675            log::error!("No summarization model available");
1676            return Task::ready(None).shared();
1677        };
1678        let mut request = LanguageModelRequest {
1679            intent: Some(CompletionIntent::ThreadContextSummarization),
1680            temperature: AgentSettings::temperature_for_model(&model, cx),
1681            ..Default::default()
1682        };
1683
1684        for message in &self.messages {
1685            request.messages.extend(message.to_request());
1686        }
1687
1688        request.messages.push(LanguageModelRequestMessage {
1689            role: Role::User,
1690            content: vec![SUMMARIZE_THREAD_DETAILED_PROMPT.into()],
1691            cache: false,
1692            reasoning_details: None,
1693        });
1694
1695        let task = cx
1696            .spawn(async move |this, cx| {
1697                let mut summary = String::new();
1698                let mut messages = model.stream_completion(request, cx).await.log_err()?;
1699                while let Some(event) = messages.next().await {
1700                    let event = event.log_err()?;
1701                    let text = match event {
1702                        LanguageModelCompletionEvent::Text(text) => text,
1703                        LanguageModelCompletionEvent::StatusUpdate(
1704                            CompletionRequestStatus::UsageUpdated { amount, limit },
1705                        ) => {
1706                            this.update(cx, |thread, cx| {
1707                                thread.update_model_request_usage(amount, limit, cx);
1708                            })
1709                            .ok()?;
1710                            continue;
1711                        }
1712                        _ => continue,
1713                    };
1714
1715                    let mut lines = text.lines();
1716                    summary.extend(lines.next());
1717                }
1718
1719                log::debug!("Setting summary: {}", summary);
1720                let summary = SharedString::from(summary);
1721
1722                this.update(cx, |this, cx| {
1723                    this.summary = Some(summary.clone());
1724                    this.pending_summary_generation = None;
1725                    cx.notify()
1726                })
1727                .ok()?;
1728
1729                Some(summary)
1730            })
1731            .shared();
1732        self.pending_summary_generation = Some(task.clone());
1733        task
1734    }
1735
1736    fn generate_title(&mut self, cx: &mut Context<Self>) {
1737        let Some(model) = self.summarization_model.clone() else {
1738            return;
1739        };
1740
1741        log::debug!(
1742            "Generating title with model: {:?}",
1743            self.summarization_model.as_ref().map(|model| model.name())
1744        );
1745        let mut request = LanguageModelRequest {
1746            intent: Some(CompletionIntent::ThreadSummarization),
1747            temperature: AgentSettings::temperature_for_model(&model, cx),
1748            ..Default::default()
1749        };
1750
1751        for message in &self.messages {
1752            request.messages.extend(message.to_request());
1753        }
1754
1755        request.messages.push(LanguageModelRequestMessage {
1756            role: Role::User,
1757            content: vec![SUMMARIZE_THREAD_PROMPT.into()],
1758            cache: false,
1759            reasoning_details: None,
1760        });
1761        self.pending_title_generation = Some(cx.spawn(async move |this, cx| {
1762            let mut title = String::new();
1763
1764            let generate = async {
1765                let mut messages = model.stream_completion(request, cx).await?;
1766                while let Some(event) = messages.next().await {
1767                    let event = event?;
1768                    let text = match event {
1769                        LanguageModelCompletionEvent::Text(text) => text,
1770                        LanguageModelCompletionEvent::StatusUpdate(
1771                            CompletionRequestStatus::UsageUpdated { amount, limit },
1772                        ) => {
1773                            this.update(cx, |thread, cx| {
1774                                thread.update_model_request_usage(amount, limit, cx);
1775                            })?;
1776                            continue;
1777                        }
1778                        _ => continue,
1779                    };
1780
1781                    let mut lines = text.lines();
1782                    title.extend(lines.next());
1783
1784                    // Stop if the LLM generated multiple lines.
1785                    if lines.next().is_some() {
1786                        break;
1787                    }
1788                }
1789                anyhow::Ok(())
1790            };
1791
1792            if generate.await.context("failed to generate title").is_ok() {
1793                _ = this.update(cx, |this, cx| this.set_title(title.into(), cx));
1794            }
1795            _ = this.update(cx, |this, _| this.pending_title_generation = None);
1796        }));
1797    }
1798
1799    pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
1800        self.pending_title_generation = None;
1801        if Some(&title) != self.title.as_ref() {
1802            self.title = Some(title);
1803            cx.emit(TitleUpdated);
1804            cx.notify();
1805        }
1806    }
1807
1808    fn clear_summary(&mut self) {
1809        self.summary = None;
1810        self.pending_summary_generation = None;
1811    }
1812
1813    fn last_user_message(&self) -> Option<&UserMessage> {
1814        self.messages
1815            .iter()
1816            .rev()
1817            .find_map(|message| match message {
1818                Message::User(user_message) => Some(user_message),
1819                Message::Agent(_) => None,
1820                Message::Resume => None,
1821            })
1822    }
1823
1824    fn pending_message(&mut self) -> &mut AgentMessage {
1825        self.pending_message.get_or_insert_default()
1826    }
1827
1828    fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
1829        let Some(mut message) = self.pending_message.take() else {
1830            return;
1831        };
1832
1833        if message.content.is_empty() {
1834            return;
1835        }
1836
1837        for content in &message.content {
1838            let AgentMessageContent::ToolUse(tool_use) = content else {
1839                continue;
1840            };
1841
1842            if !message.tool_results.contains_key(&tool_use.id) {
1843                message.tool_results.insert(
1844                    tool_use.id.clone(),
1845                    LanguageModelToolResult {
1846                        tool_use_id: tool_use.id.clone(),
1847                        tool_name: tool_use.name.clone(),
1848                        is_error: true,
1849                        content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
1850                        output: None,
1851                    },
1852                );
1853            }
1854        }
1855
1856        self.messages.push(Message::Agent(message));
1857        self.updated_at = Utc::now();
1858        self.clear_summary();
1859        cx.notify()
1860    }
1861
1862    pub(crate) fn build_completion_request(
1863        &self,
1864        completion_intent: CompletionIntent,
1865        cx: &App,
1866    ) -> Result<LanguageModelRequest> {
1867        let model = self.model().context("No language model configured")?;
1868        let tools = if let Some(turn) = self.running_turn.as_ref() {
1869            turn.tools
1870                .iter()
1871                .filter_map(|(tool_name, tool)| {
1872                    log::trace!("Including tool: {}", tool_name);
1873                    Some(LanguageModelRequestTool {
1874                        name: tool_name.to_string(),
1875                        description: tool.description().to_string(),
1876                        input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
1877                    })
1878                })
1879                .collect::<Vec<_>>()
1880        } else {
1881            Vec::new()
1882        };
1883
1884        log::debug!("Building completion request");
1885        log::debug!("Completion intent: {:?}", completion_intent);
1886        log::debug!("Completion mode: {:?}", self.completion_mode);
1887
1888        let available_tools: Vec<_> = self
1889            .running_turn
1890            .as_ref()
1891            .map(|turn| turn.tools.keys().cloned().collect())
1892            .unwrap_or_default();
1893
1894        log::debug!("Request includes {} tools", available_tools.len());
1895        let messages = self.build_request_messages(available_tools, cx);
1896        log::debug!("Request will include {} messages", messages.len());
1897
1898        let request = LanguageModelRequest {
1899            thread_id: Some(self.id.to_string()),
1900            prompt_id: Some(self.prompt_id.to_string()),
1901            intent: Some(completion_intent),
1902            mode: Some(self.completion_mode.into()),
1903            messages,
1904            tools,
1905            tool_choice: None,
1906            stop: Vec::new(),
1907            temperature: AgentSettings::temperature_for_model(model, cx),
1908            thinking_allowed: true,
1909        };
1910
1911        log::debug!("Completion request built successfully");
1912        Ok(request)
1913    }
1914
1915    fn enabled_tools(
1916        &self,
1917        profile: &AgentProfileSettings,
1918        model: &Arc<dyn LanguageModel>,
1919        cx: &App,
1920    ) -> BTreeMap<SharedString, Arc<dyn AnyAgentTool>> {
1921        fn truncate(tool_name: &SharedString) -> SharedString {
1922            if tool_name.len() > MAX_TOOL_NAME_LENGTH {
1923                let mut truncated = tool_name.to_string();
1924                truncated.truncate(MAX_TOOL_NAME_LENGTH);
1925                truncated.into()
1926            } else {
1927                tool_name.clone()
1928            }
1929        }
1930
1931        let mut tools = self
1932            .tools
1933            .iter()
1934            .filter_map(|(tool_name, tool)| {
1935                if tool.supports_provider(&model.provider_id())
1936                    && profile.is_tool_enabled(tool_name)
1937                {
1938                    Some((truncate(tool_name), tool.clone()))
1939                } else {
1940                    None
1941                }
1942            })
1943            .collect::<BTreeMap<_, _>>();
1944
1945        let mut context_server_tools = Vec::new();
1946        let mut seen_tools = tools.keys().cloned().collect::<HashSet<_>>();
1947        let mut duplicate_tool_names = HashSet::default();
1948        for (server_id, server_tools) in self.context_server_registry.read(cx).servers() {
1949            for (tool_name, tool) in server_tools {
1950                if profile.is_context_server_tool_enabled(&server_id.0, &tool_name) {
1951                    let tool_name = truncate(tool_name);
1952                    if !seen_tools.insert(tool_name.clone()) {
1953                        duplicate_tool_names.insert(tool_name.clone());
1954                    }
1955                    context_server_tools.push((server_id.clone(), tool_name, tool.clone()));
1956                }
1957            }
1958        }
1959
1960        // When there are duplicate tool names, disambiguate by prefixing them
1961        // with the server ID. In the rare case there isn't enough space for the
1962        // disambiguated tool name, keep only the last tool with this name.
1963        for (server_id, tool_name, tool) in context_server_tools {
1964            if duplicate_tool_names.contains(&tool_name) {
1965                let available = MAX_TOOL_NAME_LENGTH.saturating_sub(tool_name.len());
1966                if available >= 2 {
1967                    let mut disambiguated = server_id.0.to_string();
1968                    disambiguated.truncate(available - 1);
1969                    disambiguated.push('_');
1970                    disambiguated.push_str(&tool_name);
1971                    tools.insert(disambiguated.into(), tool.clone());
1972                } else {
1973                    tools.insert(tool_name, tool.clone());
1974                }
1975            } else {
1976                tools.insert(tool_name, tool.clone());
1977            }
1978        }
1979
1980        tools
1981    }
1982
1983    fn tool(&self, name: &str) -> Option<Arc<dyn AnyAgentTool>> {
1984        self.running_turn.as_ref()?.tools.get(name).cloned()
1985    }
1986
1987    fn build_request_messages(
1988        &self,
1989        available_tools: Vec<SharedString>,
1990        cx: &App,
1991    ) -> Vec<LanguageModelRequestMessage> {
1992        log::trace!(
1993            "Building request messages from {} thread messages",
1994            self.messages.len()
1995        );
1996
1997        let system_prompt = SystemPromptTemplate {
1998            project: self.project_context.read(cx),
1999            available_tools,
2000            model_name: self.model.as_ref().map(|m| m.name().0.to_string()),
2001        }
2002        .render(&self.templates)
2003        .context("failed to build system prompt")
2004        .expect("Invalid template");
2005        let mut messages = vec![LanguageModelRequestMessage {
2006            role: Role::System,
2007            content: vec![system_prompt.into()],
2008            cache: false,
2009            reasoning_details: None,
2010        }];
2011        for message in &self.messages {
2012            messages.extend(message.to_request());
2013        }
2014
2015        if let Some(last_message) = messages.last_mut() {
2016            last_message.cache = true;
2017        }
2018
2019        if let Some(message) = self.pending_message.as_ref() {
2020            messages.extend(message.to_request());
2021        }
2022
2023        messages
2024    }
2025
2026    pub fn to_markdown(&self) -> String {
2027        let mut markdown = String::new();
2028        for (ix, message) in self.messages.iter().enumerate() {
2029            if ix > 0 {
2030                markdown.push('\n');
2031            }
2032            markdown.push_str(&message.to_markdown());
2033        }
2034
2035        if let Some(message) = self.pending_message.as_ref() {
2036            markdown.push('\n');
2037            markdown.push_str(&message.to_markdown());
2038        }
2039
2040        markdown
2041    }
2042
2043    fn advance_prompt_id(&mut self) {
2044        self.prompt_id = PromptId::new();
2045    }
2046
2047    fn retry_strategy_for(error: &LanguageModelCompletionError) -> Option<RetryStrategy> {
2048        use LanguageModelCompletionError::*;
2049        use http_client::StatusCode;
2050
2051        // General strategy here:
2052        // - If retrying won't help (e.g. invalid API key or payload too large), return None so we don't retry at all.
2053        // - If it's a time-based issue (e.g. server overloaded, rate limit exceeded), retry up to 4 times with exponential backoff.
2054        // - If it's an issue that *might* be fixed by retrying (e.g. internal server error), retry up to 3 times.
2055        match error {
2056            HttpResponseError {
2057                status_code: StatusCode::TOO_MANY_REQUESTS,
2058                ..
2059            } => Some(RetryStrategy::ExponentialBackoff {
2060                initial_delay: BASE_RETRY_DELAY,
2061                max_attempts: MAX_RETRY_ATTEMPTS,
2062            }),
2063            ServerOverloaded { retry_after, .. } | RateLimitExceeded { retry_after, .. } => {
2064                Some(RetryStrategy::Fixed {
2065                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2066                    max_attempts: MAX_RETRY_ATTEMPTS,
2067                })
2068            }
2069            UpstreamProviderError {
2070                status,
2071                retry_after,
2072                ..
2073            } => match *status {
2074                StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
2075                    Some(RetryStrategy::Fixed {
2076                        delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2077                        max_attempts: MAX_RETRY_ATTEMPTS,
2078                    })
2079                }
2080                StatusCode::INTERNAL_SERVER_ERROR => Some(RetryStrategy::Fixed {
2081                    delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2082                    // Internal Server Error could be anything, retry up to 3 times.
2083                    max_attempts: 3,
2084                }),
2085                status => {
2086                    // There is no StatusCode variant for the unofficial HTTP 529 ("The service is overloaded"),
2087                    // but we frequently get them in practice. See https://http.dev/529
2088                    if status.as_u16() == 529 {
2089                        Some(RetryStrategy::Fixed {
2090                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2091                            max_attempts: MAX_RETRY_ATTEMPTS,
2092                        })
2093                    } else {
2094                        Some(RetryStrategy::Fixed {
2095                            delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2096                            max_attempts: 2,
2097                        })
2098                    }
2099                }
2100            },
2101            ApiInternalServerError { .. } => Some(RetryStrategy::Fixed {
2102                delay: BASE_RETRY_DELAY,
2103                max_attempts: 3,
2104            }),
2105            ApiReadResponseError { .. }
2106            | HttpSend { .. }
2107            | DeserializeResponse { .. }
2108            | BadRequestFormat { .. } => Some(RetryStrategy::Fixed {
2109                delay: BASE_RETRY_DELAY,
2110                max_attempts: 3,
2111            }),
2112            // Retrying these errors definitely shouldn't help.
2113            HttpResponseError {
2114                status_code:
2115                    StatusCode::PAYLOAD_TOO_LARGE | StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED,
2116                ..
2117            }
2118            | AuthenticationError { .. }
2119            | PermissionError { .. }
2120            | NoApiKey { .. }
2121            | ApiEndpointNotFound { .. }
2122            | PromptTooLarge { .. } => None,
2123            // These errors might be transient, so retry them
2124            SerializeRequest { .. } | BuildRequestBody { .. } => Some(RetryStrategy::Fixed {
2125                delay: BASE_RETRY_DELAY,
2126                max_attempts: 1,
2127            }),
2128            // Retry all other 4xx and 5xx errors once.
2129            HttpResponseError { status_code, .. }
2130                if status_code.is_client_error() || status_code.is_server_error() =>
2131            {
2132                Some(RetryStrategy::Fixed {
2133                    delay: BASE_RETRY_DELAY,
2134                    max_attempts: 3,
2135                })
2136            }
2137            Other(err)
2138                if err.is::<language_model::PaymentRequiredError>()
2139                    || err.is::<language_model::ModelRequestLimitReachedError>() =>
2140            {
2141                // Retrying won't help for Payment Required or Model Request Limit errors (where
2142                // the user must upgrade to usage-based billing to get more requests, or else wait
2143                // for a significant amount of time for the request limit to reset).
2144                None
2145            }
2146            // Conservatively assume that any other errors are non-retryable
2147            HttpResponseError { .. } | Other(..) => Some(RetryStrategy::Fixed {
2148                delay: BASE_RETRY_DELAY,
2149                max_attempts: 2,
2150            }),
2151        }
2152    }
2153}
2154
2155struct RunningTurn {
2156    /// Holds the task that handles agent interaction until the end of the turn.
2157    /// Survives across multiple requests as the model performs tool calls and
2158    /// we run tools, report their results.
2159    _task: Task<()>,
2160    /// The current event stream for the running turn. Used to report a final
2161    /// cancellation event if we cancel the turn.
2162    event_stream: ThreadEventStream,
2163    /// The tools that were enabled for this turn.
2164    tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
2165}
2166
2167impl RunningTurn {
2168    fn cancel(self) {
2169        log::debug!("Cancelling in progress turn");
2170        self.event_stream.send_canceled();
2171    }
2172}
2173
2174pub struct TokenUsageUpdated(pub Option<acp_thread::TokenUsage>);
2175
2176impl EventEmitter<TokenUsageUpdated> for Thread {}
2177
2178pub struct TitleUpdated;
2179
2180impl EventEmitter<TitleUpdated> for Thread {}
2181
2182pub trait AgentTool
2183where
2184    Self: 'static + Sized,
2185{
2186    type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
2187    type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
2188
2189    fn name() -> &'static str;
2190
2191    fn description() -> SharedString {
2192        let schema = schemars::schema_for!(Self::Input);
2193        SharedString::new(
2194            schema
2195                .get("description")
2196                .and_then(|description| description.as_str())
2197                .unwrap_or_default(),
2198        )
2199    }
2200
2201    fn kind() -> acp::ToolKind;
2202
2203    /// The initial tool title to display. Can be updated during the tool run.
2204    fn initial_title(
2205        &self,
2206        input: Result<Self::Input, serde_json::Value>,
2207        cx: &mut App,
2208    ) -> SharedString;
2209
2210    /// Returns the JSON schema that describes the tool's input.
2211    fn input_schema(format: LanguageModelToolSchemaFormat) -> Schema {
2212        language_model::tool_schema::root_schema_for::<Self::Input>(format)
2213    }
2214
2215    /// Some tools rely on a provider for the underlying billing or other reasons.
2216    /// Allow the tool to check if they are compatible, or should be filtered out.
2217    fn supports_provider(_provider: &LanguageModelProviderId) -> bool {
2218        true
2219    }
2220
2221    /// Runs the tool with the provided input.
2222    fn run(
2223        self: Arc<Self>,
2224        input: Self::Input,
2225        event_stream: ToolCallEventStream,
2226        cx: &mut App,
2227    ) -> Task<Result<Self::Output>>;
2228
2229    /// Emits events for a previous execution of the tool.
2230    fn replay(
2231        &self,
2232        _input: Self::Input,
2233        _output: Self::Output,
2234        _event_stream: ToolCallEventStream,
2235        _cx: &mut App,
2236    ) -> Result<()> {
2237        Ok(())
2238    }
2239
2240    fn erase(self) -> Arc<dyn AnyAgentTool> {
2241        Arc::new(Erased(Arc::new(self)))
2242    }
2243}
2244
2245pub struct Erased<T>(T);
2246
2247pub struct AgentToolOutput {
2248    pub llm_output: LanguageModelToolResultContent,
2249    pub raw_output: serde_json::Value,
2250}
2251
2252pub trait AnyAgentTool {
2253    fn name(&self) -> SharedString;
2254    fn description(&self) -> SharedString;
2255    fn kind(&self) -> acp::ToolKind;
2256    fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString;
2257    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
2258    fn supports_provider(&self, _provider: &LanguageModelProviderId) -> bool {
2259        true
2260    }
2261    fn run(
2262        self: Arc<Self>,
2263        input: serde_json::Value,
2264        event_stream: ToolCallEventStream,
2265        cx: &mut App,
2266    ) -> Task<Result<AgentToolOutput>>;
2267    fn replay(
2268        &self,
2269        input: serde_json::Value,
2270        output: serde_json::Value,
2271        event_stream: ToolCallEventStream,
2272        cx: &mut App,
2273    ) -> Result<()>;
2274}
2275
2276impl<T> AnyAgentTool for Erased<Arc<T>>
2277where
2278    T: AgentTool,
2279{
2280    fn name(&self) -> SharedString {
2281        T::name().into()
2282    }
2283
2284    fn description(&self) -> SharedString {
2285        T::description()
2286    }
2287
2288    fn kind(&self) -> agent_client_protocol::ToolKind {
2289        T::kind()
2290    }
2291
2292    fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString {
2293        let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
2294        self.0.initial_title(parsed_input, _cx)
2295    }
2296
2297    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
2298        let mut json = serde_json::to_value(T::input_schema(format))?;
2299        language_model::tool_schema::adapt_schema_to_format(&mut json, format)?;
2300        Ok(json)
2301    }
2302
2303    fn supports_provider(&self, provider: &LanguageModelProviderId) -> bool {
2304        T::supports_provider(provider)
2305    }
2306
2307    fn run(
2308        self: Arc<Self>,
2309        input: serde_json::Value,
2310        event_stream: ToolCallEventStream,
2311        cx: &mut App,
2312    ) -> Task<Result<AgentToolOutput>> {
2313        cx.spawn(async move |cx| {
2314            let input = serde_json::from_value(input)?;
2315            let output = cx
2316                .update(|cx| self.0.clone().run(input, event_stream, cx))?
2317                .await?;
2318            let raw_output = serde_json::to_value(&output)?;
2319            Ok(AgentToolOutput {
2320                llm_output: output.into(),
2321                raw_output,
2322            })
2323        })
2324    }
2325
2326    fn replay(
2327        &self,
2328        input: serde_json::Value,
2329        output: serde_json::Value,
2330        event_stream: ToolCallEventStream,
2331        cx: &mut App,
2332    ) -> Result<()> {
2333        let input = serde_json::from_value(input)?;
2334        let output = serde_json::from_value(output)?;
2335        self.0.replay(input, output, event_stream, cx)
2336    }
2337}
2338
2339#[derive(Clone)]
2340struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
2341
2342impl ThreadEventStream {
2343    fn send_user_message(&self, message: &UserMessage) {
2344        self.0
2345            .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
2346            .ok();
2347    }
2348
2349    fn send_text(&self, text: &str) {
2350        self.0
2351            .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
2352            .ok();
2353    }
2354
2355    fn send_thinking(&self, text: &str) {
2356        self.0
2357            .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
2358            .ok();
2359    }
2360
2361    fn send_tool_call(
2362        &self,
2363        id: &LanguageModelToolUseId,
2364        tool_name: &str,
2365        title: SharedString,
2366        kind: acp::ToolKind,
2367        input: serde_json::Value,
2368    ) {
2369        self.0
2370            .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
2371                id,
2372                tool_name,
2373                title.to_string(),
2374                kind,
2375                input,
2376            ))))
2377            .ok();
2378    }
2379
2380    fn initial_tool_call(
2381        id: &LanguageModelToolUseId,
2382        tool_name: &str,
2383        title: String,
2384        kind: acp::ToolKind,
2385        input: serde_json::Value,
2386    ) -> acp::ToolCall {
2387        acp::ToolCall {
2388            meta: Some(serde_json::json!({
2389                "tool_name": tool_name
2390            })),
2391            id: acp::ToolCallId(id.to_string().into()),
2392            title,
2393            kind,
2394            status: acp::ToolCallStatus::Pending,
2395            content: vec![],
2396            locations: vec![],
2397            raw_input: Some(input),
2398            raw_output: None,
2399        }
2400    }
2401
2402    fn update_tool_call_fields(
2403        &self,
2404        tool_use_id: &LanguageModelToolUseId,
2405        fields: acp::ToolCallUpdateFields,
2406    ) {
2407        self.0
2408            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
2409                acp::ToolCallUpdate {
2410                    meta: None,
2411                    id: acp::ToolCallId(tool_use_id.to_string().into()),
2412                    fields,
2413                }
2414                .into(),
2415            )))
2416            .ok();
2417    }
2418
2419    fn send_retry(&self, status: acp_thread::RetryStatus) {
2420        self.0.unbounded_send(Ok(ThreadEvent::Retry(status))).ok();
2421    }
2422
2423    fn send_stop(&self, reason: acp::StopReason) {
2424        self.0.unbounded_send(Ok(ThreadEvent::Stop(reason))).ok();
2425    }
2426
2427    fn send_canceled(&self) {
2428        self.0
2429            .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))
2430            .ok();
2431    }
2432
2433    fn send_error(&self, error: impl Into<anyhow::Error>) {
2434        self.0.unbounded_send(Err(error.into())).ok();
2435    }
2436}
2437
2438#[derive(Clone)]
2439pub struct ToolCallEventStream {
2440    tool_use_id: LanguageModelToolUseId,
2441    stream: ThreadEventStream,
2442    fs: Option<Arc<dyn Fs>>,
2443}
2444
2445impl ToolCallEventStream {
2446    #[cfg(any(test, feature = "test-support"))]
2447    pub fn test() -> (Self, ToolCallEventStreamReceiver) {
2448        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
2449
2450        let stream = ToolCallEventStream::new("test_id".into(), ThreadEventStream(events_tx), None);
2451
2452        (stream, ToolCallEventStreamReceiver(events_rx))
2453    }
2454
2455    fn new(
2456        tool_use_id: LanguageModelToolUseId,
2457        stream: ThreadEventStream,
2458        fs: Option<Arc<dyn Fs>>,
2459    ) -> Self {
2460        Self {
2461            tool_use_id,
2462            stream,
2463            fs,
2464        }
2465    }
2466
2467    pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
2468        self.stream
2469            .update_tool_call_fields(&self.tool_use_id, fields);
2470    }
2471
2472    pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
2473        self.stream
2474            .0
2475            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
2476                acp_thread::ToolCallUpdateDiff {
2477                    id: acp::ToolCallId(self.tool_use_id.to_string().into()),
2478                    diff,
2479                }
2480                .into(),
2481            )))
2482            .ok();
2483    }
2484
2485    pub fn authorize(&self, title: impl Into<String>, cx: &mut App) -> Task<Result<()>> {
2486        if agent_settings::AgentSettings::get_global(cx).always_allow_tool_actions {
2487            return Task::ready(Ok(()));
2488        }
2489
2490        let (response_tx, response_rx) = oneshot::channel();
2491        self.stream
2492            .0
2493            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
2494                ToolCallAuthorization {
2495                    tool_call: acp::ToolCallUpdate {
2496                        meta: None,
2497                        id: acp::ToolCallId(self.tool_use_id.to_string().into()),
2498                        fields: acp::ToolCallUpdateFields {
2499                            title: Some(title.into()),
2500                            ..Default::default()
2501                        },
2502                    },
2503                    options: vec![
2504                        acp::PermissionOption {
2505                            id: acp::PermissionOptionId("always_allow".into()),
2506                            name: "Always Allow".into(),
2507                            kind: acp::PermissionOptionKind::AllowAlways,
2508                            meta: None,
2509                        },
2510                        acp::PermissionOption {
2511                            id: acp::PermissionOptionId("allow".into()),
2512                            name: "Allow".into(),
2513                            kind: acp::PermissionOptionKind::AllowOnce,
2514                            meta: None,
2515                        },
2516                        acp::PermissionOption {
2517                            id: acp::PermissionOptionId("deny".into()),
2518                            name: "Deny".into(),
2519                            kind: acp::PermissionOptionKind::RejectOnce,
2520                            meta: None,
2521                        },
2522                    ],
2523                    response: response_tx,
2524                },
2525            )))
2526            .ok();
2527        let fs = self.fs.clone();
2528        cx.spawn(async move |cx| match response_rx.await?.0.as_ref() {
2529            "always_allow" => {
2530                if let Some(fs) = fs.clone() {
2531                    cx.update(|cx| {
2532                        update_settings_file(fs, cx, |settings, _| {
2533                            settings
2534                                .agent
2535                                .get_or_insert_default()
2536                                .set_always_allow_tool_actions(true);
2537                        });
2538                    })?;
2539                }
2540
2541                Ok(())
2542            }
2543            "allow" => Ok(()),
2544            _ => Err(anyhow!("Permission to run tool denied by user")),
2545        })
2546    }
2547}
2548
2549#[cfg(any(test, feature = "test-support"))]
2550pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
2551
2552#[cfg(any(test, feature = "test-support"))]
2553impl ToolCallEventStreamReceiver {
2554    pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
2555        let event = self.0.next().await;
2556        if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
2557            auth
2558        } else {
2559            panic!("Expected ToolCallAuthorization but got: {:?}", event);
2560        }
2561    }
2562
2563    pub async fn expect_update_fields(&mut self) -> acp::ToolCallUpdateFields {
2564        let event = self.0.next().await;
2565        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
2566            update,
2567        )))) = event
2568        {
2569            update.fields
2570        } else {
2571            panic!("Expected update fields but got: {:?}", event);
2572        }
2573    }
2574
2575    pub async fn expect_diff(&mut self) -> Entity<acp_thread::Diff> {
2576        let event = self.0.next().await;
2577        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateDiff(
2578            update,
2579        )))) = event
2580        {
2581            update.diff
2582        } else {
2583            panic!("Expected diff but got: {:?}", event);
2584        }
2585    }
2586
2587    pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
2588        let event = self.0.next().await;
2589        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
2590            update,
2591        )))) = event
2592        {
2593            update.terminal
2594        } else {
2595            panic!("Expected terminal but got: {:?}", event);
2596        }
2597    }
2598}
2599
2600#[cfg(any(test, feature = "test-support"))]
2601impl std::ops::Deref for ToolCallEventStreamReceiver {
2602    type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
2603
2604    fn deref(&self) -> &Self::Target {
2605        &self.0
2606    }
2607}
2608
2609#[cfg(any(test, feature = "test-support"))]
2610impl std::ops::DerefMut for ToolCallEventStreamReceiver {
2611    fn deref_mut(&mut self) -> &mut Self::Target {
2612        &mut self.0
2613    }
2614}
2615
2616impl From<&str> for UserMessageContent {
2617    fn from(text: &str) -> Self {
2618        Self::Text(text.into())
2619    }
2620}
2621
2622impl UserMessageContent {
2623    pub fn from_content_block(value: acp::ContentBlock, path_style: PathStyle) -> Self {
2624        match value {
2625            acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
2626            acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
2627            acp::ContentBlock::Audio(_) => {
2628                // TODO
2629                Self::Text("[audio]".to_string())
2630            }
2631            acp::ContentBlock::ResourceLink(resource_link) => {
2632                match MentionUri::parse(&resource_link.uri, path_style) {
2633                    Ok(uri) => Self::Mention {
2634                        uri,
2635                        content: String::new(),
2636                    },
2637                    Err(err) => {
2638                        log::error!("Failed to parse mention link: {}", err);
2639                        Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
2640                    }
2641                }
2642            }
2643            acp::ContentBlock::Resource(resource) => match resource.resource {
2644                acp::EmbeddedResourceResource::TextResourceContents(resource) => {
2645                    match MentionUri::parse(&resource.uri, path_style) {
2646                        Ok(uri) => Self::Mention {
2647                            uri,
2648                            content: resource.text,
2649                        },
2650                        Err(err) => {
2651                            log::error!("Failed to parse mention link: {}", err);
2652                            Self::Text(
2653                                MarkdownCodeBlock {
2654                                    tag: &resource.uri,
2655                                    text: &resource.text,
2656                                }
2657                                .to_string(),
2658                            )
2659                        }
2660                    }
2661                }
2662                acp::EmbeddedResourceResource::BlobResourceContents(_) => {
2663                    // TODO
2664                    Self::Text("[blob]".to_string())
2665                }
2666            },
2667        }
2668    }
2669}
2670
2671impl From<UserMessageContent> for acp::ContentBlock {
2672    fn from(content: UserMessageContent) -> Self {
2673        match content {
2674            UserMessageContent::Text(text) => acp::ContentBlock::Text(acp::TextContent {
2675                text,
2676                annotations: None,
2677                meta: None,
2678            }),
2679            UserMessageContent::Image(image) => acp::ContentBlock::Image(acp::ImageContent {
2680                data: image.source.to_string(),
2681                mime_type: "image/png".to_string(),
2682                meta: None,
2683                annotations: None,
2684                uri: None,
2685            }),
2686            UserMessageContent::Mention { uri, content } => {
2687                acp::ContentBlock::Resource(acp::EmbeddedResource {
2688                    meta: None,
2689                    resource: acp::EmbeddedResourceResource::TextResourceContents(
2690                        acp::TextResourceContents {
2691                            meta: None,
2692                            mime_type: None,
2693                            text: content,
2694                            uri: uri.to_uri().to_string(),
2695                        },
2696                    ),
2697                    annotations: None,
2698                })
2699            }
2700        }
2701    }
2702}
2703
2704fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
2705    LanguageModelImage {
2706        source: image_content.data.into(),
2707        // TODO: make this optional?
2708        size: gpui::Size::new(0.into(), 0.into()),
2709    }
2710}