thread.rs

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