thread.rs

   1use crate::{ContextServerRegistry, SystemPromptTemplate, Template, Templates};
   2use acp_thread::{MentionUri, UserMessageId};
   3use action_log::ActionLog;
   4use agent_client_protocol as acp;
   5use agent_settings::{AgentProfileId, AgentSettings, CompletionMode};
   6use anyhow::{Context as _, Result, anyhow};
   7use assistant_tool::adapt_schema_to_format;
   8use cloud_llm_client::{CompletionIntent, CompletionRequestStatus};
   9use collections::IndexMap;
  10use fs::Fs;
  11use futures::{
  12    channel::{mpsc, oneshot},
  13    stream::FuturesUnordered,
  14};
  15use gpui::{App, Context, Entity, SharedString, Task};
  16use language_model::{
  17    LanguageModel, LanguageModelCompletionEvent, LanguageModelImage, LanguageModelProviderId,
  18    LanguageModelRequest, LanguageModelRequestMessage, LanguageModelRequestTool,
  19    LanguageModelToolResult, LanguageModelToolResultContent, LanguageModelToolSchemaFormat,
  20    LanguageModelToolUse, LanguageModelToolUseId, Role, StopReason,
  21};
  22use project::Project;
  23use prompt_store::ProjectContext;
  24use schemars::{JsonSchema, Schema};
  25use serde::{Deserialize, Serialize};
  26use settings::{Settings, update_settings_file};
  27use smol::stream::StreamExt;
  28use std::{cell::RefCell, collections::BTreeMap, path::Path, rc::Rc, sync::Arc};
  29use std::{fmt::Write, ops::Range};
  30use util::{ResultExt, markdown::MarkdownCodeBlock};
  31use uuid::Uuid;
  32
  33#[derive(
  34    Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize, JsonSchema,
  35)]
  36pub struct ThreadId(Arc<str>);
  37
  38impl ThreadId {
  39    pub fn new() -> Self {
  40        Self(Uuid::new_v4().to_string().into())
  41    }
  42}
  43
  44impl std::fmt::Display for ThreadId {
  45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  46        write!(f, "{}", self.0)
  47    }
  48}
  49
  50impl From<&str> for ThreadId {
  51    fn from(value: &str) -> Self {
  52        Self(value.into())
  53    }
  54}
  55
  56/// The ID of the user prompt that initiated a request.
  57///
  58/// This equates to the user physically submitting a message to the model (e.g., by pressing the Enter key).
  59#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
  60pub struct PromptId(Arc<str>);
  61
  62impl PromptId {
  63    pub fn new() -> Self {
  64        Self(Uuid::new_v4().to_string().into())
  65    }
  66}
  67
  68impl std::fmt::Display for PromptId {
  69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  70        write!(f, "{}", self.0)
  71    }
  72}
  73
  74#[derive(Debug, Clone, PartialEq, Eq)]
  75pub enum Message {
  76    User(UserMessage),
  77    Agent(AgentMessage),
  78    Resume,
  79}
  80
  81impl Message {
  82    pub fn as_agent_message(&self) -> Option<&AgentMessage> {
  83        match self {
  84            Message::Agent(agent_message) => Some(agent_message),
  85            _ => None,
  86        }
  87    }
  88
  89    pub fn to_markdown(&self) -> String {
  90        match self {
  91            Message::User(message) => message.to_markdown(),
  92            Message::Agent(message) => message.to_markdown(),
  93            Message::Resume => "[resumed after tool use limit was reached]".into(),
  94        }
  95    }
  96}
  97
  98#[derive(Debug, Clone, PartialEq, Eq)]
  99pub struct UserMessage {
 100    pub id: UserMessageId,
 101    pub content: Vec<UserMessageContent>,
 102}
 103
 104#[derive(Debug, Clone, PartialEq, Eq)]
 105pub enum UserMessageContent {
 106    Text(String),
 107    Mention { uri: MentionUri, content: String },
 108    Image(LanguageModelImage),
 109}
 110
 111impl UserMessage {
 112    pub fn to_markdown(&self) -> String {
 113        let mut markdown = String::from("## User\n\n");
 114
 115        for content in &self.content {
 116            match content {
 117                UserMessageContent::Text(text) => {
 118                    markdown.push_str(text);
 119                    markdown.push('\n');
 120                }
 121                UserMessageContent::Image(_) => {
 122                    markdown.push_str("<image />\n");
 123                }
 124                UserMessageContent::Mention { uri, content } => {
 125                    if !content.is_empty() {
 126                        let _ = write!(&mut markdown, "{}\n\n{}\n", uri.as_link(), content);
 127                    } else {
 128                        let _ = write!(&mut markdown, "{}\n", uri.as_link());
 129                    }
 130                }
 131            }
 132        }
 133
 134        markdown
 135    }
 136
 137    fn to_request(&self) -> LanguageModelRequestMessage {
 138        let mut message = LanguageModelRequestMessage {
 139            role: Role::User,
 140            content: Vec::with_capacity(self.content.len()),
 141            cache: false,
 142        };
 143
 144        const OPEN_CONTEXT: &str = "<context>\n\
 145            The following items were attached by the user. \
 146            They are up-to-date and don't need to be re-read.\n\n";
 147
 148        const OPEN_FILES_TAG: &str = "<files>";
 149        const OPEN_SYMBOLS_TAG: &str = "<symbols>";
 150        const OPEN_THREADS_TAG: &str = "<threads>";
 151        const OPEN_FETCH_TAG: &str = "<fetched_urls>";
 152        const OPEN_RULES_TAG: &str =
 153            "<rules>\nThe user has specified the following rules that should be applied:\n";
 154
 155        let mut file_context = OPEN_FILES_TAG.to_string();
 156        let mut symbol_context = OPEN_SYMBOLS_TAG.to_string();
 157        let mut thread_context = OPEN_THREADS_TAG.to_string();
 158        let mut fetch_context = OPEN_FETCH_TAG.to_string();
 159        let mut rules_context = OPEN_RULES_TAG.to_string();
 160
 161        for chunk in &self.content {
 162            let chunk = match chunk {
 163                UserMessageContent::Text(text) => {
 164                    language_model::MessageContent::Text(text.clone())
 165                }
 166                UserMessageContent::Image(value) => {
 167                    language_model::MessageContent::Image(value.clone())
 168                }
 169                UserMessageContent::Mention { uri, content } => {
 170                    match uri {
 171                        MentionUri::File { abs_path, .. } => {
 172                            write!(
 173                                &mut symbol_context,
 174                                "\n{}",
 175                                MarkdownCodeBlock {
 176                                    tag: &codeblock_tag(&abs_path, None),
 177                                    text: &content.to_string(),
 178                                }
 179                            )
 180                            .ok();
 181                        }
 182                        MentionUri::Symbol {
 183                            path, line_range, ..
 184                        }
 185                        | MentionUri::Selection {
 186                            path, line_range, ..
 187                        } => {
 188                            write!(
 189                                &mut rules_context,
 190                                "\n{}",
 191                                MarkdownCodeBlock {
 192                                    tag: &codeblock_tag(&path, Some(line_range)),
 193                                    text: &content
 194                                }
 195                            )
 196                            .ok();
 197                        }
 198                        MentionUri::Thread { .. } => {
 199                            write!(&mut thread_context, "\n{}\n", content).ok();
 200                        }
 201                        MentionUri::TextThread { .. } => {
 202                            write!(&mut thread_context, "\n{}\n", content).ok();
 203                        }
 204                        MentionUri::Rule { .. } => {
 205                            write!(
 206                                &mut rules_context,
 207                                "\n{}",
 208                                MarkdownCodeBlock {
 209                                    tag: "",
 210                                    text: &content
 211                                }
 212                            )
 213                            .ok();
 214                        }
 215                        MentionUri::Fetch { url } => {
 216                            write!(&mut fetch_context, "\nFetch: {}\n\n{}", url, content).ok();
 217                        }
 218                    }
 219
 220                    language_model::MessageContent::Text(uri.as_link().to_string())
 221                }
 222            };
 223
 224            message.content.push(chunk);
 225        }
 226
 227        let len_before_context = message.content.len();
 228
 229        if file_context.len() > OPEN_FILES_TAG.len() {
 230            file_context.push_str("</files>\n");
 231            message
 232                .content
 233                .push(language_model::MessageContent::Text(file_context));
 234        }
 235
 236        if symbol_context.len() > OPEN_SYMBOLS_TAG.len() {
 237            symbol_context.push_str("</symbols>\n");
 238            message
 239                .content
 240                .push(language_model::MessageContent::Text(symbol_context));
 241        }
 242
 243        if thread_context.len() > OPEN_THREADS_TAG.len() {
 244            thread_context.push_str("</threads>\n");
 245            message
 246                .content
 247                .push(language_model::MessageContent::Text(thread_context));
 248        }
 249
 250        if fetch_context.len() > OPEN_FETCH_TAG.len() {
 251            fetch_context.push_str("</fetched_urls>\n");
 252            message
 253                .content
 254                .push(language_model::MessageContent::Text(fetch_context));
 255        }
 256
 257        if rules_context.len() > OPEN_RULES_TAG.len() {
 258            rules_context.push_str("</user_rules>\n");
 259            message
 260                .content
 261                .push(language_model::MessageContent::Text(rules_context));
 262        }
 263
 264        if message.content.len() > len_before_context {
 265            message.content.insert(
 266                len_before_context,
 267                language_model::MessageContent::Text(OPEN_CONTEXT.into()),
 268            );
 269            message
 270                .content
 271                .push(language_model::MessageContent::Text("</context>".into()));
 272        }
 273
 274        message
 275    }
 276}
 277
 278fn codeblock_tag(full_path: &Path, line_range: Option<&Range<u32>>) -> String {
 279    let mut result = String::new();
 280
 281    if let Some(extension) = full_path.extension().and_then(|ext| ext.to_str()) {
 282        let _ = write!(result, "{} ", extension);
 283    }
 284
 285    let _ = write!(result, "{}", full_path.display());
 286
 287    if let Some(range) = line_range {
 288        if range.start == range.end {
 289            let _ = write!(result, ":{}", range.start + 1);
 290        } else {
 291            let _ = write!(result, ":{}-{}", range.start + 1, range.end + 1);
 292        }
 293    }
 294
 295    result
 296}
 297
 298impl AgentMessage {
 299    pub fn to_markdown(&self) -> String {
 300        let mut markdown = String::from("## Assistant\n\n");
 301
 302        for content in &self.content {
 303            match content {
 304                AgentMessageContent::Text(text) => {
 305                    markdown.push_str(text);
 306                    markdown.push('\n');
 307                }
 308                AgentMessageContent::Thinking { text, .. } => {
 309                    markdown.push_str("<think>");
 310                    markdown.push_str(text);
 311                    markdown.push_str("</think>\n");
 312                }
 313                AgentMessageContent::RedactedThinking(_) => {
 314                    markdown.push_str("<redacted_thinking />\n")
 315                }
 316                AgentMessageContent::Image(_) => {
 317                    markdown.push_str("<image />\n");
 318                }
 319                AgentMessageContent::ToolUse(tool_use) => {
 320                    markdown.push_str(&format!(
 321                        "**Tool Use**: {} (ID: {})\n",
 322                        tool_use.name, tool_use.id
 323                    ));
 324                    markdown.push_str(&format!(
 325                        "{}\n",
 326                        MarkdownCodeBlock {
 327                            tag: "json",
 328                            text: &format!("{:#}", tool_use.input)
 329                        }
 330                    ));
 331                }
 332            }
 333        }
 334
 335        for tool_result in self.tool_results.values() {
 336            markdown.push_str(&format!(
 337                "**Tool Result**: {} (ID: {})\n\n",
 338                tool_result.tool_name, tool_result.tool_use_id
 339            ));
 340            if tool_result.is_error {
 341                markdown.push_str("**ERROR:**\n");
 342            }
 343
 344            match &tool_result.content {
 345                LanguageModelToolResultContent::Text(text) => {
 346                    writeln!(markdown, "{text}\n").ok();
 347                }
 348                LanguageModelToolResultContent::Image(_) => {
 349                    writeln!(markdown, "<image />\n").ok();
 350                }
 351            }
 352
 353            if let Some(output) = tool_result.output.as_ref() {
 354                writeln!(
 355                    markdown,
 356                    "**Debug Output**:\n\n```json\n{}\n```\n",
 357                    serde_json::to_string_pretty(output).unwrap()
 358                )
 359                .unwrap();
 360            }
 361        }
 362
 363        markdown
 364    }
 365
 366    pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
 367        let mut assistant_message = LanguageModelRequestMessage {
 368            role: Role::Assistant,
 369            content: Vec::with_capacity(self.content.len()),
 370            cache: false,
 371        };
 372        for chunk in &self.content {
 373            let chunk = match chunk {
 374                AgentMessageContent::Text(text) => {
 375                    language_model::MessageContent::Text(text.clone())
 376                }
 377                AgentMessageContent::Thinking { text, signature } => {
 378                    language_model::MessageContent::Thinking {
 379                        text: text.clone(),
 380                        signature: signature.clone(),
 381                    }
 382                }
 383                AgentMessageContent::RedactedThinking(value) => {
 384                    language_model::MessageContent::RedactedThinking(value.clone())
 385                }
 386                AgentMessageContent::ToolUse(value) => {
 387                    language_model::MessageContent::ToolUse(value.clone())
 388                }
 389                AgentMessageContent::Image(value) => {
 390                    language_model::MessageContent::Image(value.clone())
 391                }
 392            };
 393            assistant_message.content.push(chunk);
 394        }
 395
 396        let mut user_message = LanguageModelRequestMessage {
 397            role: Role::User,
 398            content: Vec::new(),
 399            cache: false,
 400        };
 401
 402        for tool_result in self.tool_results.values() {
 403            user_message
 404                .content
 405                .push(language_model::MessageContent::ToolResult(
 406                    tool_result.clone(),
 407                ));
 408        }
 409
 410        let mut messages = Vec::new();
 411        if !assistant_message.content.is_empty() {
 412            messages.push(assistant_message);
 413        }
 414        if !user_message.content.is_empty() {
 415            messages.push(user_message);
 416        }
 417        messages
 418    }
 419}
 420
 421#[derive(Default, Debug, Clone, PartialEq, Eq)]
 422pub struct AgentMessage {
 423    pub content: Vec<AgentMessageContent>,
 424    pub tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
 425}
 426
 427#[derive(Debug, Clone, PartialEq, Eq)]
 428pub enum AgentMessageContent {
 429    Text(String),
 430    Thinking {
 431        text: String,
 432        signature: Option<String>,
 433    },
 434    RedactedThinking(String),
 435    Image(LanguageModelImage),
 436    ToolUse(LanguageModelToolUse),
 437}
 438
 439#[derive(Debug)]
 440pub enum AgentResponseEvent {
 441    Text(String),
 442    Thinking(String),
 443    ToolCall(acp::ToolCall),
 444    ToolCallUpdate(acp_thread::ToolCallUpdate),
 445    ToolCallAuthorization(ToolCallAuthorization),
 446    Stop(acp::StopReason),
 447}
 448
 449#[derive(Debug)]
 450pub struct ToolCallAuthorization {
 451    pub tool_call: acp::ToolCallUpdate,
 452    pub options: Vec<acp::PermissionOption>,
 453    pub response: oneshot::Sender<acp::PermissionOptionId>,
 454}
 455
 456pub struct Thread {
 457    id: ThreadId,
 458    prompt_id: PromptId,
 459    messages: Vec<Message>,
 460    completion_mode: CompletionMode,
 461    /// Holds the task that handles agent interaction until the end of the turn.
 462    /// Survives across multiple requests as the model performs tool calls and
 463    /// we run tools, report their results.
 464    running_turn: Option<RunningTurn>,
 465    pending_message: Option<AgentMessage>,
 466    tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
 467    tool_use_limit_reached: bool,
 468    context_server_registry: Entity<ContextServerRegistry>,
 469    profile_id: AgentProfileId,
 470    project_context: Rc<RefCell<ProjectContext>>,
 471    templates: Arc<Templates>,
 472    model: Option<Arc<dyn LanguageModel>>,
 473    project: Entity<Project>,
 474    action_log: Entity<ActionLog>,
 475}
 476
 477impl Thread {
 478    pub fn new(
 479        project: Entity<Project>,
 480        project_context: Rc<RefCell<ProjectContext>>,
 481        context_server_registry: Entity<ContextServerRegistry>,
 482        action_log: Entity<ActionLog>,
 483        templates: Arc<Templates>,
 484        model: Option<Arc<dyn LanguageModel>>,
 485        cx: &mut Context<Self>,
 486    ) -> Self {
 487        let profile_id = AgentSettings::get_global(cx).default_profile.clone();
 488        Self {
 489            id: ThreadId::new(),
 490            prompt_id: PromptId::new(),
 491            messages: Vec::new(),
 492            completion_mode: CompletionMode::Normal,
 493            running_turn: None,
 494            pending_message: None,
 495            tools: BTreeMap::default(),
 496            tool_use_limit_reached: false,
 497            context_server_registry,
 498            profile_id,
 499            project_context,
 500            templates,
 501            model,
 502            project,
 503            action_log,
 504        }
 505    }
 506
 507    pub fn project(&self) -> &Entity<Project> {
 508        &self.project
 509    }
 510
 511    pub fn action_log(&self) -> &Entity<ActionLog> {
 512        &self.action_log
 513    }
 514
 515    pub fn model(&self) -> Option<&Arc<dyn LanguageModel>> {
 516        self.model.as_ref()
 517    }
 518
 519    pub fn set_model(&mut self, model: Arc<dyn LanguageModel>) {
 520        self.model = Some(model);
 521    }
 522
 523    pub fn completion_mode(&self) -> CompletionMode {
 524        self.completion_mode
 525    }
 526
 527    pub fn set_completion_mode(&mut self, mode: CompletionMode) {
 528        self.completion_mode = mode;
 529    }
 530
 531    #[cfg(any(test, feature = "test-support"))]
 532    pub fn last_message(&self) -> Option<Message> {
 533        if let Some(message) = self.pending_message.clone() {
 534            Some(Message::Agent(message))
 535        } else {
 536            self.messages.last().cloned()
 537        }
 538    }
 539
 540    pub fn add_tool(&mut self, tool: impl AgentTool) {
 541        self.tools.insert(tool.name(), tool.erase());
 542    }
 543
 544    pub fn remove_tool(&mut self, name: &str) -> bool {
 545        self.tools.remove(name).is_some()
 546    }
 547
 548    pub fn profile(&self) -> &AgentProfileId {
 549        &self.profile_id
 550    }
 551
 552    pub fn set_profile(&mut self, profile_id: AgentProfileId) {
 553        self.profile_id = profile_id;
 554    }
 555
 556    pub fn cancel(&mut self) {
 557        if let Some(running_turn) = self.running_turn.take() {
 558            running_turn.cancel();
 559        }
 560        self.flush_pending_message();
 561    }
 562
 563    pub fn truncate(&mut self, message_id: UserMessageId) -> Result<()> {
 564        self.cancel();
 565        let Some(position) = self.messages.iter().position(
 566            |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
 567        ) else {
 568            return Err(anyhow!("Message not found"));
 569        };
 570        self.messages.truncate(position);
 571        Ok(())
 572    }
 573
 574    pub fn resume(
 575        &mut self,
 576        cx: &mut Context<Self>,
 577    ) -> Result<mpsc::UnboundedReceiver<Result<AgentResponseEvent>>> {
 578        anyhow::ensure!(self.model.is_some(), "Model not set");
 579        anyhow::ensure!(
 580            self.tool_use_limit_reached,
 581            "can only resume after tool use limit is reached"
 582        );
 583
 584        self.messages.push(Message::Resume);
 585        cx.notify();
 586
 587        log::info!("Total messages in thread: {}", self.messages.len());
 588        self.run_turn(cx)
 589    }
 590
 591    /// Sending a message results in the model streaming a response, which could include tool calls.
 592    /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
 593    /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
 594    pub fn send<T>(
 595        &mut self,
 596        id: UserMessageId,
 597        content: impl IntoIterator<Item = T>,
 598        cx: &mut Context<Self>,
 599    ) -> Result<mpsc::UnboundedReceiver<Result<AgentResponseEvent>>>
 600    where
 601        T: Into<UserMessageContent>,
 602    {
 603        let model = self.model().context("No language model configured")?;
 604
 605        log::info!("Thread::send called with model: {:?}", model.name());
 606        self.advance_prompt_id();
 607
 608        let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
 609        log::debug!("Thread::send content: {:?}", content);
 610
 611        self.messages
 612            .push(Message::User(UserMessage { id, content }));
 613        cx.notify();
 614
 615        log::info!("Total messages in thread: {}", self.messages.len());
 616        self.run_turn(cx)
 617    }
 618
 619    fn run_turn(
 620        &mut self,
 621        cx: &mut Context<Self>,
 622    ) -> Result<mpsc::UnboundedReceiver<Result<AgentResponseEvent>>> {
 623        self.cancel();
 624
 625        let model = self.model.clone().context("No language model configured")?;
 626        let (events_tx, events_rx) = mpsc::unbounded::<Result<AgentResponseEvent>>();
 627        let event_stream = AgentResponseEventStream(events_tx);
 628        let message_ix = self.messages.len().saturating_sub(1);
 629        self.tool_use_limit_reached = false;
 630        self.running_turn = Some(RunningTurn {
 631            event_stream: event_stream.clone(),
 632            _task: cx.spawn(async move |this, cx| {
 633                log::info!("Starting agent turn execution");
 634                let turn_result: Result<()> = async {
 635                    let mut completion_intent = CompletionIntent::UserPrompt;
 636                    loop {
 637                        log::debug!(
 638                            "Building completion request with intent: {:?}",
 639                            completion_intent
 640                        );
 641                        let request = this.update(cx, |this, cx| {
 642                            this.build_completion_request(completion_intent, cx)
 643                        })??;
 644
 645                        log::info!("Calling model.stream_completion");
 646                        let mut events = model.stream_completion(request, cx).await?;
 647                        log::debug!("Stream completion started successfully");
 648
 649                        let mut tool_use_limit_reached = false;
 650                        let mut tool_uses = FuturesUnordered::new();
 651                        while let Some(event) = events.next().await {
 652                            match event? {
 653                                LanguageModelCompletionEvent::StatusUpdate(
 654                                    CompletionRequestStatus::ToolUseLimitReached,
 655                                ) => {
 656                                    tool_use_limit_reached = true;
 657                                }
 658                                LanguageModelCompletionEvent::Stop(reason) => {
 659                                    event_stream.send_stop(reason);
 660                                    if reason == StopReason::Refusal {
 661                                        this.update(cx, |this, _cx| {
 662                                            this.flush_pending_message();
 663                                            this.messages.truncate(message_ix);
 664                                        })?;
 665                                        return Ok(());
 666                                    }
 667                                }
 668                                event => {
 669                                    log::trace!("Received completion event: {:?}", event);
 670                                    this.update(cx, |this, cx| {
 671                                        tool_uses.extend(this.handle_streamed_completion_event(
 672                                            event,
 673                                            &event_stream,
 674                                            cx,
 675                                        ));
 676                                    })
 677                                    .ok();
 678                                }
 679                            }
 680                        }
 681
 682                        let used_tools = tool_uses.is_empty();
 683                        while let Some(tool_result) = tool_uses.next().await {
 684                            log::info!("Tool finished {:?}", tool_result);
 685
 686                            event_stream.update_tool_call_fields(
 687                                &tool_result.tool_use_id,
 688                                acp::ToolCallUpdateFields {
 689                                    status: Some(if tool_result.is_error {
 690                                        acp::ToolCallStatus::Failed
 691                                    } else {
 692                                        acp::ToolCallStatus::Completed
 693                                    }),
 694                                    raw_output: tool_result.output.clone(),
 695                                    ..Default::default()
 696                                },
 697                            );
 698                            this.update(cx, |this, _cx| {
 699                                this.pending_message()
 700                                    .tool_results
 701                                    .insert(tool_result.tool_use_id.clone(), tool_result);
 702                            })
 703                            .ok();
 704                        }
 705
 706                        if tool_use_limit_reached {
 707                            log::info!("Tool use limit reached, completing turn");
 708                            this.update(cx, |this, _cx| this.tool_use_limit_reached = true)?;
 709                            return Err(language_model::ToolUseLimitReachedError.into());
 710                        } else if used_tools {
 711                            log::info!("No tool uses found, completing turn");
 712                            return Ok(());
 713                        } else {
 714                            this.update(cx, |this, _| this.flush_pending_message())?;
 715                            completion_intent = CompletionIntent::ToolResults;
 716                        }
 717                    }
 718                }
 719                .await;
 720
 721                if let Err(error) = turn_result {
 722                    log::error!("Turn execution failed: {:?}", error);
 723                    event_stream.send_error(error);
 724                } else {
 725                    log::info!("Turn execution completed successfully");
 726                }
 727
 728                this.update(cx, |this, _| {
 729                    this.flush_pending_message();
 730                    this.running_turn.take();
 731                })
 732                .ok();
 733            }),
 734        });
 735        Ok(events_rx)
 736    }
 737
 738    pub fn build_system_message(&self) -> LanguageModelRequestMessage {
 739        log::debug!("Building system message");
 740        let prompt = SystemPromptTemplate {
 741            project: &self.project_context.borrow(),
 742            available_tools: self.tools.keys().cloned().collect(),
 743        }
 744        .render(&self.templates)
 745        .context("failed to build system prompt")
 746        .expect("Invalid template");
 747        log::debug!("System message built");
 748        LanguageModelRequestMessage {
 749            role: Role::System,
 750            content: vec![prompt.into()],
 751            cache: true,
 752        }
 753    }
 754
 755    /// A helper method that's called on every streamed completion event.
 756    /// Returns an optional tool result task, which the main agentic loop in
 757    /// send will send back to the model when it resolves.
 758    fn handle_streamed_completion_event(
 759        &mut self,
 760        event: LanguageModelCompletionEvent,
 761        event_stream: &AgentResponseEventStream,
 762        cx: &mut Context<Self>,
 763    ) -> Option<Task<LanguageModelToolResult>> {
 764        log::trace!("Handling streamed completion event: {:?}", event);
 765        use LanguageModelCompletionEvent::*;
 766
 767        match event {
 768            StartMessage { .. } => {
 769                self.flush_pending_message();
 770                self.pending_message = Some(AgentMessage::default());
 771            }
 772            Text(new_text) => self.handle_text_event(new_text, event_stream, cx),
 773            Thinking { text, signature } => {
 774                self.handle_thinking_event(text, signature, event_stream, cx)
 775            }
 776            RedactedThinking { data } => self.handle_redacted_thinking_event(data, cx),
 777            ToolUse(tool_use) => {
 778                return self.handle_tool_use_event(tool_use, event_stream, cx);
 779            }
 780            ToolUseJsonParseError {
 781                id,
 782                tool_name,
 783                raw_input,
 784                json_parse_error,
 785            } => {
 786                return Some(Task::ready(self.handle_tool_use_json_parse_error_event(
 787                    id,
 788                    tool_name,
 789                    raw_input,
 790                    json_parse_error,
 791                )));
 792            }
 793            UsageUpdate(_) | StatusUpdate(_) => {}
 794            Stop(_) => unreachable!(),
 795        }
 796
 797        None
 798    }
 799
 800    fn handle_text_event(
 801        &mut self,
 802        new_text: String,
 803        event_stream: &AgentResponseEventStream,
 804        cx: &mut Context<Self>,
 805    ) {
 806        event_stream.send_text(&new_text);
 807
 808        let last_message = self.pending_message();
 809        if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
 810            text.push_str(&new_text);
 811        } else {
 812            last_message
 813                .content
 814                .push(AgentMessageContent::Text(new_text));
 815        }
 816
 817        cx.notify();
 818    }
 819
 820    fn handle_thinking_event(
 821        &mut self,
 822        new_text: String,
 823        new_signature: Option<String>,
 824        event_stream: &AgentResponseEventStream,
 825        cx: &mut Context<Self>,
 826    ) {
 827        event_stream.send_thinking(&new_text);
 828
 829        let last_message = self.pending_message();
 830        if let Some(AgentMessageContent::Thinking { text, signature }) =
 831            last_message.content.last_mut()
 832        {
 833            text.push_str(&new_text);
 834            *signature = new_signature.or(signature.take());
 835        } else {
 836            last_message.content.push(AgentMessageContent::Thinking {
 837                text: new_text,
 838                signature: new_signature,
 839            });
 840        }
 841
 842        cx.notify();
 843    }
 844
 845    fn handle_redacted_thinking_event(&mut self, data: String, cx: &mut Context<Self>) {
 846        let last_message = self.pending_message();
 847        last_message
 848            .content
 849            .push(AgentMessageContent::RedactedThinking(data));
 850        cx.notify();
 851    }
 852
 853    fn handle_tool_use_event(
 854        &mut self,
 855        tool_use: LanguageModelToolUse,
 856        event_stream: &AgentResponseEventStream,
 857        cx: &mut Context<Self>,
 858    ) -> Option<Task<LanguageModelToolResult>> {
 859        cx.notify();
 860
 861        let tool = self.tools.get(tool_use.name.as_ref()).cloned();
 862        let mut title = SharedString::from(&tool_use.name);
 863        let mut kind = acp::ToolKind::Other;
 864        if let Some(tool) = tool.as_ref() {
 865            title = tool.initial_title(tool_use.input.clone());
 866            kind = tool.kind();
 867        }
 868
 869        // Ensure the last message ends in the current tool use
 870        let last_message = self.pending_message();
 871        let push_new_tool_use = last_message.content.last_mut().map_or(true, |content| {
 872            if let AgentMessageContent::ToolUse(last_tool_use) = content {
 873                if last_tool_use.id == tool_use.id {
 874                    *last_tool_use = tool_use.clone();
 875                    false
 876                } else {
 877                    true
 878                }
 879            } else {
 880                true
 881            }
 882        });
 883
 884        if push_new_tool_use {
 885            event_stream.send_tool_call(&tool_use.id, title, kind, tool_use.input.clone());
 886            last_message
 887                .content
 888                .push(AgentMessageContent::ToolUse(tool_use.clone()));
 889        } else {
 890            event_stream.update_tool_call_fields(
 891                &tool_use.id,
 892                acp::ToolCallUpdateFields {
 893                    title: Some(title.into()),
 894                    kind: Some(kind),
 895                    raw_input: Some(tool_use.input.clone()),
 896                    ..Default::default()
 897                },
 898            );
 899        }
 900
 901        if !tool_use.is_input_complete {
 902            return None;
 903        }
 904
 905        let Some(tool) = tool else {
 906            let content = format!("No tool named {} exists", tool_use.name);
 907            return Some(Task::ready(LanguageModelToolResult {
 908                content: LanguageModelToolResultContent::Text(Arc::from(content)),
 909                tool_use_id: tool_use.id,
 910                tool_name: tool_use.name,
 911                is_error: true,
 912                output: None,
 913            }));
 914        };
 915
 916        let fs = self.project.read(cx).fs().clone();
 917        let tool_event_stream =
 918            ToolCallEventStream::new(tool_use.id.clone(), event_stream.clone(), Some(fs));
 919        tool_event_stream.update_fields(acp::ToolCallUpdateFields {
 920            status: Some(acp::ToolCallStatus::InProgress),
 921            ..Default::default()
 922        });
 923        let supports_images = self.model().map_or(false, |model| model.supports_images());
 924        let tool_result = tool.run(tool_use.input, tool_event_stream, cx);
 925        log::info!("Running tool {}", tool_use.name);
 926        Some(cx.foreground_executor().spawn(async move {
 927            let tool_result = tool_result.await.and_then(|output| {
 928                if let LanguageModelToolResultContent::Image(_) = &output.llm_output {
 929                    if !supports_images {
 930                        return Err(anyhow!(
 931                            "Attempted to read an image, but this model doesn't support it.",
 932                        ));
 933                    }
 934                }
 935                Ok(output)
 936            });
 937
 938            match tool_result {
 939                Ok(output) => LanguageModelToolResult {
 940                    tool_use_id: tool_use.id,
 941                    tool_name: tool_use.name,
 942                    is_error: false,
 943                    content: output.llm_output,
 944                    output: Some(output.raw_output),
 945                },
 946                Err(error) => LanguageModelToolResult {
 947                    tool_use_id: tool_use.id,
 948                    tool_name: tool_use.name,
 949                    is_error: true,
 950                    content: LanguageModelToolResultContent::Text(Arc::from(error.to_string())),
 951                    output: None,
 952                },
 953            }
 954        }))
 955    }
 956
 957    fn handle_tool_use_json_parse_error_event(
 958        &mut self,
 959        tool_use_id: LanguageModelToolUseId,
 960        tool_name: Arc<str>,
 961        raw_input: Arc<str>,
 962        json_parse_error: String,
 963    ) -> LanguageModelToolResult {
 964        let tool_output = format!("Error parsing input JSON: {json_parse_error}");
 965        LanguageModelToolResult {
 966            tool_use_id,
 967            tool_name,
 968            is_error: true,
 969            content: LanguageModelToolResultContent::Text(tool_output.into()),
 970            output: Some(serde_json::Value::String(raw_input.to_string())),
 971        }
 972    }
 973
 974    fn pending_message(&mut self) -> &mut AgentMessage {
 975        self.pending_message.get_or_insert_default()
 976    }
 977
 978    fn flush_pending_message(&mut self) {
 979        let Some(mut message) = self.pending_message.take() else {
 980            return;
 981        };
 982
 983        for content in &message.content {
 984            let AgentMessageContent::ToolUse(tool_use) = content else {
 985                continue;
 986            };
 987
 988            if !message.tool_results.contains_key(&tool_use.id) {
 989                message.tool_results.insert(
 990                    tool_use.id.clone(),
 991                    LanguageModelToolResult {
 992                        tool_use_id: tool_use.id.clone(),
 993                        tool_name: tool_use.name.clone(),
 994                        is_error: true,
 995                        content: LanguageModelToolResultContent::Text(
 996                            "Tool canceled by user".into(),
 997                        ),
 998                        output: None,
 999                    },
1000                );
1001            }
1002        }
1003
1004        self.messages.push(Message::Agent(message));
1005    }
1006
1007    pub(crate) fn build_completion_request(
1008        &self,
1009        completion_intent: CompletionIntent,
1010        cx: &mut App,
1011    ) -> Result<LanguageModelRequest> {
1012        let model = self.model().context("No language model configured")?;
1013
1014        log::debug!("Building completion request");
1015        log::debug!("Completion intent: {:?}", completion_intent);
1016        log::debug!("Completion mode: {:?}", self.completion_mode);
1017
1018        let messages = self.build_request_messages();
1019        log::info!("Request will include {} messages", messages.len());
1020
1021        let tools = if let Some(tools) = self.tools(cx).log_err() {
1022            tools
1023                .filter_map(|tool| {
1024                    let tool_name = tool.name().to_string();
1025                    log::trace!("Including tool: {}", tool_name);
1026                    Some(LanguageModelRequestTool {
1027                        name: tool_name,
1028                        description: tool.description().to_string(),
1029                        input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
1030                    })
1031                })
1032                .collect()
1033        } else {
1034            Vec::new()
1035        };
1036
1037        log::info!("Request includes {} tools", tools.len());
1038
1039        let request = LanguageModelRequest {
1040            thread_id: Some(self.id.to_string()),
1041            prompt_id: Some(self.prompt_id.to_string()),
1042            intent: Some(completion_intent),
1043            mode: Some(self.completion_mode.into()),
1044            messages,
1045            tools,
1046            tool_choice: None,
1047            stop: Vec::new(),
1048            temperature: AgentSettings::temperature_for_model(&model, cx),
1049            thinking_allowed: true,
1050        };
1051
1052        log::debug!("Completion request built successfully");
1053        Ok(request)
1054    }
1055
1056    fn tools<'a>(&'a self, cx: &'a App) -> Result<impl Iterator<Item = &'a Arc<dyn AnyAgentTool>>> {
1057        let model = self.model().context("No language model configured")?;
1058
1059        let profile = AgentSettings::get_global(cx)
1060            .profiles
1061            .get(&self.profile_id)
1062            .context("profile not found")?;
1063        let provider_id = model.provider_id();
1064
1065        Ok(self
1066            .tools
1067            .iter()
1068            .filter(move |(_, tool)| tool.supported_provider(&provider_id))
1069            .filter_map(|(tool_name, tool)| {
1070                if profile.is_tool_enabled(tool_name) {
1071                    Some(tool)
1072                } else {
1073                    None
1074                }
1075            })
1076            .chain(self.context_server_registry.read(cx).servers().flat_map(
1077                |(server_id, tools)| {
1078                    tools.iter().filter_map(|(tool_name, tool)| {
1079                        if profile.is_context_server_tool_enabled(&server_id.0, tool_name) {
1080                            Some(tool)
1081                        } else {
1082                            None
1083                        }
1084                    })
1085                },
1086            )))
1087    }
1088
1089    fn build_request_messages(&self) -> Vec<LanguageModelRequestMessage> {
1090        log::trace!(
1091            "Building request messages from {} thread messages",
1092            self.messages.len()
1093        );
1094        let mut messages = vec![self.build_system_message()];
1095        for message in &self.messages {
1096            match message {
1097                Message::User(message) => messages.push(message.to_request()),
1098                Message::Agent(message) => messages.extend(message.to_request()),
1099                Message::Resume => messages.push(LanguageModelRequestMessage {
1100                    role: Role::User,
1101                    content: vec!["Continue where you left off".into()],
1102                    cache: false,
1103                }),
1104            }
1105        }
1106
1107        if let Some(message) = self.pending_message.as_ref() {
1108            messages.extend(message.to_request());
1109        }
1110
1111        if let Some(last_user_message) = messages
1112            .iter_mut()
1113            .rev()
1114            .find(|message| message.role == Role::User)
1115        {
1116            last_user_message.cache = true;
1117        }
1118
1119        messages
1120    }
1121
1122    pub fn to_markdown(&self) -> String {
1123        let mut markdown = String::new();
1124        for (ix, message) in self.messages.iter().enumerate() {
1125            if ix > 0 {
1126                markdown.push('\n');
1127            }
1128            markdown.push_str(&message.to_markdown());
1129        }
1130
1131        if let Some(message) = self.pending_message.as_ref() {
1132            markdown.push('\n');
1133            markdown.push_str(&message.to_markdown());
1134        }
1135
1136        markdown
1137    }
1138
1139    fn advance_prompt_id(&mut self) {
1140        self.prompt_id = PromptId::new();
1141    }
1142}
1143
1144struct RunningTurn {
1145    /// Holds the task that handles agent interaction until the end of the turn.
1146    /// Survives across multiple requests as the model performs tool calls and
1147    /// we run tools, report their results.
1148    _task: Task<()>,
1149    /// The current event stream for the running turn. Used to report a final
1150    /// cancellation event if we cancel the turn.
1151    event_stream: AgentResponseEventStream,
1152}
1153
1154impl RunningTurn {
1155    fn cancel(self) {
1156        log::debug!("Cancelling in progress turn");
1157        self.event_stream.send_canceled();
1158    }
1159}
1160
1161pub trait AgentTool
1162where
1163    Self: 'static + Sized,
1164{
1165    type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
1166    type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
1167
1168    fn name(&self) -> SharedString;
1169
1170    fn description(&self) -> SharedString {
1171        let schema = schemars::schema_for!(Self::Input);
1172        SharedString::new(
1173            schema
1174                .get("description")
1175                .and_then(|description| description.as_str())
1176                .unwrap_or_default(),
1177        )
1178    }
1179
1180    fn kind(&self) -> acp::ToolKind;
1181
1182    /// The initial tool title to display. Can be updated during the tool run.
1183    fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString;
1184
1185    /// Returns the JSON schema that describes the tool's input.
1186    fn input_schema(&self) -> Schema {
1187        schemars::schema_for!(Self::Input)
1188    }
1189
1190    /// Some tools rely on a provider for the underlying billing or other reasons.
1191    /// Allow the tool to check if they are compatible, or should be filtered out.
1192    fn supported_provider(&self, _provider: &LanguageModelProviderId) -> bool {
1193        true
1194    }
1195
1196    /// Runs the tool with the provided input.
1197    fn run(
1198        self: Arc<Self>,
1199        input: Self::Input,
1200        event_stream: ToolCallEventStream,
1201        cx: &mut App,
1202    ) -> Task<Result<Self::Output>>;
1203
1204    fn erase(self) -> Arc<dyn AnyAgentTool> {
1205        Arc::new(Erased(Arc::new(self)))
1206    }
1207}
1208
1209pub struct Erased<T>(T);
1210
1211pub struct AgentToolOutput {
1212    pub llm_output: LanguageModelToolResultContent,
1213    pub raw_output: serde_json::Value,
1214}
1215
1216pub trait AnyAgentTool {
1217    fn name(&self) -> SharedString;
1218    fn description(&self) -> SharedString;
1219    fn kind(&self) -> acp::ToolKind;
1220    fn initial_title(&self, input: serde_json::Value) -> SharedString;
1221    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
1222    fn supported_provider(&self, _provider: &LanguageModelProviderId) -> bool {
1223        true
1224    }
1225    fn run(
1226        self: Arc<Self>,
1227        input: serde_json::Value,
1228        event_stream: ToolCallEventStream,
1229        cx: &mut App,
1230    ) -> Task<Result<AgentToolOutput>>;
1231}
1232
1233impl<T> AnyAgentTool for Erased<Arc<T>>
1234where
1235    T: AgentTool,
1236{
1237    fn name(&self) -> SharedString {
1238        self.0.name()
1239    }
1240
1241    fn description(&self) -> SharedString {
1242        self.0.description()
1243    }
1244
1245    fn kind(&self) -> agent_client_protocol::ToolKind {
1246        self.0.kind()
1247    }
1248
1249    fn initial_title(&self, input: serde_json::Value) -> SharedString {
1250        let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
1251        self.0.initial_title(parsed_input)
1252    }
1253
1254    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
1255        let mut json = serde_json::to_value(self.0.input_schema())?;
1256        adapt_schema_to_format(&mut json, format)?;
1257        Ok(json)
1258    }
1259
1260    fn supported_provider(&self, provider: &LanguageModelProviderId) -> bool {
1261        self.0.supported_provider(provider)
1262    }
1263
1264    fn run(
1265        self: Arc<Self>,
1266        input: serde_json::Value,
1267        event_stream: ToolCallEventStream,
1268        cx: &mut App,
1269    ) -> Task<Result<AgentToolOutput>> {
1270        cx.spawn(async move |cx| {
1271            let input = serde_json::from_value(input)?;
1272            let output = cx
1273                .update(|cx| self.0.clone().run(input, event_stream, cx))?
1274                .await?;
1275            let raw_output = serde_json::to_value(&output)?;
1276            Ok(AgentToolOutput {
1277                llm_output: output.into(),
1278                raw_output,
1279            })
1280        })
1281    }
1282}
1283
1284#[derive(Clone)]
1285struct AgentResponseEventStream(mpsc::UnboundedSender<Result<AgentResponseEvent>>);
1286
1287impl AgentResponseEventStream {
1288    fn send_text(&self, text: &str) {
1289        self.0
1290            .unbounded_send(Ok(AgentResponseEvent::Text(text.to_string())))
1291            .ok();
1292    }
1293
1294    fn send_thinking(&self, text: &str) {
1295        self.0
1296            .unbounded_send(Ok(AgentResponseEvent::Thinking(text.to_string())))
1297            .ok();
1298    }
1299
1300    fn send_tool_call(
1301        &self,
1302        id: &LanguageModelToolUseId,
1303        title: SharedString,
1304        kind: acp::ToolKind,
1305        input: serde_json::Value,
1306    ) {
1307        self.0
1308            .unbounded_send(Ok(AgentResponseEvent::ToolCall(Self::initial_tool_call(
1309                id,
1310                title.to_string(),
1311                kind,
1312                input,
1313            ))))
1314            .ok();
1315    }
1316
1317    fn initial_tool_call(
1318        id: &LanguageModelToolUseId,
1319        title: String,
1320        kind: acp::ToolKind,
1321        input: serde_json::Value,
1322    ) -> acp::ToolCall {
1323        acp::ToolCall {
1324            id: acp::ToolCallId(id.to_string().into()),
1325            title,
1326            kind,
1327            status: acp::ToolCallStatus::Pending,
1328            content: vec![],
1329            locations: vec![],
1330            raw_input: Some(input),
1331            raw_output: None,
1332        }
1333    }
1334
1335    fn update_tool_call_fields(
1336        &self,
1337        tool_use_id: &LanguageModelToolUseId,
1338        fields: acp::ToolCallUpdateFields,
1339    ) {
1340        self.0
1341            .unbounded_send(Ok(AgentResponseEvent::ToolCallUpdate(
1342                acp::ToolCallUpdate {
1343                    id: acp::ToolCallId(tool_use_id.to_string().into()),
1344                    fields,
1345                }
1346                .into(),
1347            )))
1348            .ok();
1349    }
1350
1351    fn send_stop(&self, reason: StopReason) {
1352        match reason {
1353            StopReason::EndTurn => {
1354                self.0
1355                    .unbounded_send(Ok(AgentResponseEvent::Stop(acp::StopReason::EndTurn)))
1356                    .ok();
1357            }
1358            StopReason::MaxTokens => {
1359                self.0
1360                    .unbounded_send(Ok(AgentResponseEvent::Stop(acp::StopReason::MaxTokens)))
1361                    .ok();
1362            }
1363            StopReason::Refusal => {
1364                self.0
1365                    .unbounded_send(Ok(AgentResponseEvent::Stop(acp::StopReason::Refusal)))
1366                    .ok();
1367            }
1368            StopReason::ToolUse => {}
1369        }
1370    }
1371
1372    fn send_canceled(&self) {
1373        self.0
1374            .unbounded_send(Ok(AgentResponseEvent::Stop(acp::StopReason::Canceled)))
1375            .ok();
1376    }
1377
1378    fn send_error(&self, error: impl Into<anyhow::Error>) {
1379        self.0.unbounded_send(Err(error.into())).ok();
1380    }
1381}
1382
1383#[derive(Clone)]
1384pub struct ToolCallEventStream {
1385    tool_use_id: LanguageModelToolUseId,
1386    stream: AgentResponseEventStream,
1387    fs: Option<Arc<dyn Fs>>,
1388}
1389
1390impl ToolCallEventStream {
1391    #[cfg(test)]
1392    pub fn test() -> (Self, ToolCallEventStreamReceiver) {
1393        let (events_tx, events_rx) = mpsc::unbounded::<Result<AgentResponseEvent>>();
1394
1395        let stream =
1396            ToolCallEventStream::new("test_id".into(), AgentResponseEventStream(events_tx), None);
1397
1398        (stream, ToolCallEventStreamReceiver(events_rx))
1399    }
1400
1401    fn new(
1402        tool_use_id: LanguageModelToolUseId,
1403        stream: AgentResponseEventStream,
1404        fs: Option<Arc<dyn Fs>>,
1405    ) -> Self {
1406        Self {
1407            tool_use_id,
1408            stream,
1409            fs,
1410        }
1411    }
1412
1413    pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
1414        self.stream
1415            .update_tool_call_fields(&self.tool_use_id, fields);
1416    }
1417
1418    pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
1419        self.stream
1420            .0
1421            .unbounded_send(Ok(AgentResponseEvent::ToolCallUpdate(
1422                acp_thread::ToolCallUpdateDiff {
1423                    id: acp::ToolCallId(self.tool_use_id.to_string().into()),
1424                    diff,
1425                }
1426                .into(),
1427            )))
1428            .ok();
1429    }
1430
1431    pub fn update_terminal(&self, terminal: Entity<acp_thread::Terminal>) {
1432        self.stream
1433            .0
1434            .unbounded_send(Ok(AgentResponseEvent::ToolCallUpdate(
1435                acp_thread::ToolCallUpdateTerminal {
1436                    id: acp::ToolCallId(self.tool_use_id.to_string().into()),
1437                    terminal,
1438                }
1439                .into(),
1440            )))
1441            .ok();
1442    }
1443
1444    pub fn authorize(&self, title: impl Into<String>, cx: &mut App) -> Task<Result<()>> {
1445        if agent_settings::AgentSettings::get_global(cx).always_allow_tool_actions {
1446            return Task::ready(Ok(()));
1447        }
1448
1449        let (response_tx, response_rx) = oneshot::channel();
1450        self.stream
1451            .0
1452            .unbounded_send(Ok(AgentResponseEvent::ToolCallAuthorization(
1453                ToolCallAuthorization {
1454                    tool_call: acp::ToolCallUpdate {
1455                        id: acp::ToolCallId(self.tool_use_id.to_string().into()),
1456                        fields: acp::ToolCallUpdateFields {
1457                            title: Some(title.into()),
1458                            ..Default::default()
1459                        },
1460                    },
1461                    options: vec![
1462                        acp::PermissionOption {
1463                            id: acp::PermissionOptionId("always_allow".into()),
1464                            name: "Always Allow".into(),
1465                            kind: acp::PermissionOptionKind::AllowAlways,
1466                        },
1467                        acp::PermissionOption {
1468                            id: acp::PermissionOptionId("allow".into()),
1469                            name: "Allow".into(),
1470                            kind: acp::PermissionOptionKind::AllowOnce,
1471                        },
1472                        acp::PermissionOption {
1473                            id: acp::PermissionOptionId("deny".into()),
1474                            name: "Deny".into(),
1475                            kind: acp::PermissionOptionKind::RejectOnce,
1476                        },
1477                    ],
1478                    response: response_tx,
1479                },
1480            )))
1481            .ok();
1482        let fs = self.fs.clone();
1483        cx.spawn(async move |cx| match response_rx.await?.0.as_ref() {
1484            "always_allow" => {
1485                if let Some(fs) = fs.clone() {
1486                    cx.update(|cx| {
1487                        update_settings_file::<AgentSettings>(fs, cx, |settings, _| {
1488                            settings.set_always_allow_tool_actions(true);
1489                        });
1490                    })?;
1491                }
1492
1493                Ok(())
1494            }
1495            "allow" => Ok(()),
1496            _ => Err(anyhow!("Permission to run tool denied by user")),
1497        })
1498    }
1499}
1500
1501#[cfg(test)]
1502pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<AgentResponseEvent>>);
1503
1504#[cfg(test)]
1505impl ToolCallEventStreamReceiver {
1506    pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
1507        let event = self.0.next().await;
1508        if let Some(Ok(AgentResponseEvent::ToolCallAuthorization(auth))) = event {
1509            auth
1510        } else {
1511            panic!("Expected ToolCallAuthorization but got: {:?}", event);
1512        }
1513    }
1514
1515    pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
1516        let event = self.0.next().await;
1517        if let Some(Ok(AgentResponseEvent::ToolCallUpdate(
1518            acp_thread::ToolCallUpdate::UpdateTerminal(update),
1519        ))) = event
1520        {
1521            update.terminal
1522        } else {
1523            panic!("Expected terminal but got: {:?}", event);
1524        }
1525    }
1526}
1527
1528#[cfg(test)]
1529impl std::ops::Deref for ToolCallEventStreamReceiver {
1530    type Target = mpsc::UnboundedReceiver<Result<AgentResponseEvent>>;
1531
1532    fn deref(&self) -> &Self::Target {
1533        &self.0
1534    }
1535}
1536
1537#[cfg(test)]
1538impl std::ops::DerefMut for ToolCallEventStreamReceiver {
1539    fn deref_mut(&mut self) -> &mut Self::Target {
1540        &mut self.0
1541    }
1542}
1543
1544impl From<&str> for UserMessageContent {
1545    fn from(text: &str) -> Self {
1546        Self::Text(text.into())
1547    }
1548}
1549
1550impl From<acp::ContentBlock> for UserMessageContent {
1551    fn from(value: acp::ContentBlock) -> Self {
1552        match value {
1553            acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
1554            acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
1555            acp::ContentBlock::Audio(_) => {
1556                // TODO
1557                Self::Text("[audio]".to_string())
1558            }
1559            acp::ContentBlock::ResourceLink(resource_link) => {
1560                match MentionUri::parse(&resource_link.uri) {
1561                    Ok(uri) => Self::Mention {
1562                        uri,
1563                        content: String::new(),
1564                    },
1565                    Err(err) => {
1566                        log::error!("Failed to parse mention link: {}", err);
1567                        Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
1568                    }
1569                }
1570            }
1571            acp::ContentBlock::Resource(resource) => match resource.resource {
1572                acp::EmbeddedResourceResource::TextResourceContents(resource) => {
1573                    match MentionUri::parse(&resource.uri) {
1574                        Ok(uri) => Self::Mention {
1575                            uri,
1576                            content: resource.text,
1577                        },
1578                        Err(err) => {
1579                            log::error!("Failed to parse mention link: {}", err);
1580                            Self::Text(
1581                                MarkdownCodeBlock {
1582                                    tag: &resource.uri,
1583                                    text: &resource.text,
1584                                }
1585                                .to_string(),
1586                            )
1587                        }
1588                    }
1589                }
1590                acp::EmbeddedResourceResource::BlobResourceContents(_) => {
1591                    // TODO
1592                    Self::Text("[blob]".to_string())
1593                }
1594            },
1595        }
1596    }
1597}
1598
1599fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
1600    LanguageModelImage {
1601        source: image_content.data.into(),
1602        // TODO: make this optional?
1603        size: gpui::Size::new(0.into(), 0.into()),
1604    }
1605}