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<Task<()>>,
 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: 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: 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) -> &Arc<dyn LanguageModel> {
 516        &self.model
 517    }
 518
 519    pub fn set_model(&mut self, model: Arc<dyn LanguageModel>) {
 520        self.model = 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        // TODO: do we need to emit a stop::cancel for ACP?
 558        self.running_turn.take();
 559        self.flush_pending_message();
 560    }
 561
 562    pub fn truncate(&mut self, message_id: UserMessageId) -> Result<()> {
 563        self.cancel();
 564        let Some(position) = self.messages.iter().position(
 565            |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
 566        ) else {
 567            return Err(anyhow!("Message not found"));
 568        };
 569        self.messages.truncate(position);
 570        Ok(())
 571    }
 572
 573    pub fn resume(
 574        &mut self,
 575        cx: &mut Context<Self>,
 576    ) -> Result<mpsc::UnboundedReceiver<Result<AgentResponseEvent>>> {
 577        anyhow::ensure!(
 578            self.tool_use_limit_reached,
 579            "can only resume after tool use limit is reached"
 580        );
 581
 582        self.messages.push(Message::Resume);
 583        cx.notify();
 584
 585        log::info!("Total messages in thread: {}", self.messages.len());
 586        Ok(self.run_turn(cx))
 587    }
 588
 589    /// Sending a message results in the model streaming a response, which could include tool calls.
 590    /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
 591    /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
 592    pub fn send<T>(
 593        &mut self,
 594        id: UserMessageId,
 595        content: impl IntoIterator<Item = T>,
 596        cx: &mut Context<Self>,
 597    ) -> mpsc::UnboundedReceiver<Result<AgentResponseEvent>>
 598    where
 599        T: Into<UserMessageContent>,
 600    {
 601        log::info!("Thread::send called with model: {:?}", self.model.name());
 602        self.advance_prompt_id();
 603
 604        let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
 605        log::debug!("Thread::send content: {:?}", content);
 606
 607        self.messages
 608            .push(Message::User(UserMessage { id, content }));
 609        cx.notify();
 610
 611        log::info!("Total messages in thread: {}", self.messages.len());
 612        self.run_turn(cx)
 613    }
 614
 615    fn run_turn(
 616        &mut self,
 617        cx: &mut Context<Self>,
 618    ) -> mpsc::UnboundedReceiver<Result<AgentResponseEvent>> {
 619        let model = self.model.clone();
 620        let (events_tx, events_rx) = mpsc::unbounded::<Result<AgentResponseEvent>>();
 621        let event_stream = AgentResponseEventStream(events_tx);
 622        let message_ix = self.messages.len().saturating_sub(1);
 623        self.tool_use_limit_reached = false;
 624        self.running_turn = Some(cx.spawn(async move |this, cx| {
 625            log::info!("Starting agent turn execution");
 626            let turn_result: Result<()> = async {
 627                let mut completion_intent = CompletionIntent::UserPrompt;
 628                loop {
 629                    log::debug!(
 630                        "Building completion request with intent: {:?}",
 631                        completion_intent
 632                    );
 633                    let request = this.update(cx, |this, cx| {
 634                        this.build_completion_request(completion_intent, cx)
 635                    })?;
 636
 637                    log::info!("Calling model.stream_completion");
 638                    let mut events = model.stream_completion(request, cx).await?;
 639                    log::debug!("Stream completion started successfully");
 640
 641                    let mut tool_use_limit_reached = false;
 642                    let mut tool_uses = FuturesUnordered::new();
 643                    while let Some(event) = events.next().await {
 644                        match event? {
 645                            LanguageModelCompletionEvent::StatusUpdate(
 646                                CompletionRequestStatus::ToolUseLimitReached,
 647                            ) => {
 648                                tool_use_limit_reached = true;
 649                            }
 650                            LanguageModelCompletionEvent::Stop(reason) => {
 651                                event_stream.send_stop(reason);
 652                                if reason == StopReason::Refusal {
 653                                    this.update(cx, |this, _cx| {
 654                                        this.flush_pending_message();
 655                                        this.messages.truncate(message_ix);
 656                                    })?;
 657                                    return Ok(());
 658                                }
 659                            }
 660                            event => {
 661                                log::trace!("Received completion event: {:?}", event);
 662                                this.update(cx, |this, cx| {
 663                                    tool_uses.extend(this.handle_streamed_completion_event(
 664                                        event,
 665                                        &event_stream,
 666                                        cx,
 667                                    ));
 668                                })
 669                                .ok();
 670                            }
 671                        }
 672                    }
 673
 674                    let used_tools = tool_uses.is_empty();
 675                    while let Some(tool_result) = tool_uses.next().await {
 676                        log::info!("Tool finished {:?}", tool_result);
 677
 678                        event_stream.update_tool_call_fields(
 679                            &tool_result.tool_use_id,
 680                            acp::ToolCallUpdateFields {
 681                                status: Some(if tool_result.is_error {
 682                                    acp::ToolCallStatus::Failed
 683                                } else {
 684                                    acp::ToolCallStatus::Completed
 685                                }),
 686                                raw_output: tool_result.output.clone(),
 687                                ..Default::default()
 688                            },
 689                        );
 690                        this.update(cx, |this, _cx| {
 691                            this.pending_message()
 692                                .tool_results
 693                                .insert(tool_result.tool_use_id.clone(), tool_result);
 694                        })
 695                        .ok();
 696                    }
 697
 698                    if tool_use_limit_reached {
 699                        log::info!("Tool use limit reached, completing turn");
 700                        this.update(cx, |this, _cx| this.tool_use_limit_reached = true)?;
 701                        return Err(language_model::ToolUseLimitReachedError.into());
 702                    } else if used_tools {
 703                        log::info!("No tool uses found, completing turn");
 704                        return Ok(());
 705                    } else {
 706                        this.update(cx, |this, _| this.flush_pending_message())?;
 707                        completion_intent = CompletionIntent::ToolResults;
 708                    }
 709                }
 710            }
 711            .await;
 712
 713            this.update(cx, |this, _| this.flush_pending_message()).ok();
 714            if let Err(error) = turn_result {
 715                log::error!("Turn execution failed: {:?}", error);
 716                event_stream.send_error(error);
 717            } else {
 718                log::info!("Turn execution completed successfully");
 719            }
 720        }));
 721        events_rx
 722    }
 723
 724    pub fn build_system_message(&self) -> LanguageModelRequestMessage {
 725        log::debug!("Building system message");
 726        let prompt = SystemPromptTemplate {
 727            project: &self.project_context.borrow(),
 728            available_tools: self.tools.keys().cloned().collect(),
 729        }
 730        .render(&self.templates)
 731        .context("failed to build system prompt")
 732        .expect("Invalid template");
 733        log::debug!("System message built");
 734        LanguageModelRequestMessage {
 735            role: Role::System,
 736            content: vec![prompt.into()],
 737            cache: true,
 738        }
 739    }
 740
 741    /// A helper method that's called on every streamed completion event.
 742    /// Returns an optional tool result task, which the main agentic loop in
 743    /// send will send back to the model when it resolves.
 744    fn handle_streamed_completion_event(
 745        &mut self,
 746        event: LanguageModelCompletionEvent,
 747        event_stream: &AgentResponseEventStream,
 748        cx: &mut Context<Self>,
 749    ) -> Option<Task<LanguageModelToolResult>> {
 750        log::trace!("Handling streamed completion event: {:?}", event);
 751        use LanguageModelCompletionEvent::*;
 752
 753        match event {
 754            StartMessage { .. } => {
 755                self.flush_pending_message();
 756                self.pending_message = Some(AgentMessage::default());
 757            }
 758            Text(new_text) => self.handle_text_event(new_text, event_stream, cx),
 759            Thinking { text, signature } => {
 760                self.handle_thinking_event(text, signature, event_stream, cx)
 761            }
 762            RedactedThinking { data } => self.handle_redacted_thinking_event(data, cx),
 763            ToolUse(tool_use) => {
 764                return self.handle_tool_use_event(tool_use, event_stream, cx);
 765            }
 766            ToolUseJsonParseError {
 767                id,
 768                tool_name,
 769                raw_input,
 770                json_parse_error,
 771            } => {
 772                return Some(Task::ready(self.handle_tool_use_json_parse_error_event(
 773                    id,
 774                    tool_name,
 775                    raw_input,
 776                    json_parse_error,
 777                )));
 778            }
 779            UsageUpdate(_) | StatusUpdate(_) => {}
 780            Stop(_) => unreachable!(),
 781        }
 782
 783        None
 784    }
 785
 786    fn handle_text_event(
 787        &mut self,
 788        new_text: String,
 789        event_stream: &AgentResponseEventStream,
 790        cx: &mut Context<Self>,
 791    ) {
 792        event_stream.send_text(&new_text);
 793
 794        let last_message = self.pending_message();
 795        if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
 796            text.push_str(&new_text);
 797        } else {
 798            last_message
 799                .content
 800                .push(AgentMessageContent::Text(new_text));
 801        }
 802
 803        cx.notify();
 804    }
 805
 806    fn handle_thinking_event(
 807        &mut self,
 808        new_text: String,
 809        new_signature: Option<String>,
 810        event_stream: &AgentResponseEventStream,
 811        cx: &mut Context<Self>,
 812    ) {
 813        event_stream.send_thinking(&new_text);
 814
 815        let last_message = self.pending_message();
 816        if let Some(AgentMessageContent::Thinking { text, signature }) =
 817            last_message.content.last_mut()
 818        {
 819            text.push_str(&new_text);
 820            *signature = new_signature.or(signature.take());
 821        } else {
 822            last_message.content.push(AgentMessageContent::Thinking {
 823                text: new_text,
 824                signature: new_signature,
 825            });
 826        }
 827
 828        cx.notify();
 829    }
 830
 831    fn handle_redacted_thinking_event(&mut self, data: String, cx: &mut Context<Self>) {
 832        let last_message = self.pending_message();
 833        last_message
 834            .content
 835            .push(AgentMessageContent::RedactedThinking(data));
 836        cx.notify();
 837    }
 838
 839    fn handle_tool_use_event(
 840        &mut self,
 841        tool_use: LanguageModelToolUse,
 842        event_stream: &AgentResponseEventStream,
 843        cx: &mut Context<Self>,
 844    ) -> Option<Task<LanguageModelToolResult>> {
 845        cx.notify();
 846
 847        let tool = self.tools.get(tool_use.name.as_ref()).cloned();
 848        let mut title = SharedString::from(&tool_use.name);
 849        let mut kind = acp::ToolKind::Other;
 850        if let Some(tool) = tool.as_ref() {
 851            title = tool.initial_title(tool_use.input.clone());
 852            kind = tool.kind();
 853        }
 854
 855        // Ensure the last message ends in the current tool use
 856        let last_message = self.pending_message();
 857        let push_new_tool_use = last_message.content.last_mut().map_or(true, |content| {
 858            if let AgentMessageContent::ToolUse(last_tool_use) = content {
 859                if last_tool_use.id == tool_use.id {
 860                    *last_tool_use = tool_use.clone();
 861                    false
 862                } else {
 863                    true
 864                }
 865            } else {
 866                true
 867            }
 868        });
 869
 870        if push_new_tool_use {
 871            event_stream.send_tool_call(&tool_use.id, title, kind, tool_use.input.clone());
 872            last_message
 873                .content
 874                .push(AgentMessageContent::ToolUse(tool_use.clone()));
 875        } else {
 876            event_stream.update_tool_call_fields(
 877                &tool_use.id,
 878                acp::ToolCallUpdateFields {
 879                    title: Some(title.into()),
 880                    kind: Some(kind),
 881                    raw_input: Some(tool_use.input.clone()),
 882                    ..Default::default()
 883                },
 884            );
 885        }
 886
 887        if !tool_use.is_input_complete {
 888            return None;
 889        }
 890
 891        let Some(tool) = tool else {
 892            let content = format!("No tool named {} exists", tool_use.name);
 893            return Some(Task::ready(LanguageModelToolResult {
 894                content: LanguageModelToolResultContent::Text(Arc::from(content)),
 895                tool_use_id: tool_use.id,
 896                tool_name: tool_use.name,
 897                is_error: true,
 898                output: None,
 899            }));
 900        };
 901
 902        let fs = self.project.read(cx).fs().clone();
 903        let tool_event_stream =
 904            ToolCallEventStream::new(tool_use.id.clone(), event_stream.clone(), Some(fs));
 905        tool_event_stream.update_fields(acp::ToolCallUpdateFields {
 906            status: Some(acp::ToolCallStatus::InProgress),
 907            ..Default::default()
 908        });
 909        let supports_images = self.model.supports_images();
 910        let tool_result = tool.run(tool_use.input, tool_event_stream, cx);
 911        log::info!("Running tool {}", tool_use.name);
 912        Some(cx.foreground_executor().spawn(async move {
 913            let tool_result = tool_result.await.and_then(|output| {
 914                if let LanguageModelToolResultContent::Image(_) = &output.llm_output {
 915                    if !supports_images {
 916                        return Err(anyhow!(
 917                            "Attempted to read an image, but this model doesn't support it.",
 918                        ));
 919                    }
 920                }
 921                Ok(output)
 922            });
 923
 924            match tool_result {
 925                Ok(output) => LanguageModelToolResult {
 926                    tool_use_id: tool_use.id,
 927                    tool_name: tool_use.name,
 928                    is_error: false,
 929                    content: output.llm_output,
 930                    output: Some(output.raw_output),
 931                },
 932                Err(error) => LanguageModelToolResult {
 933                    tool_use_id: tool_use.id,
 934                    tool_name: tool_use.name,
 935                    is_error: true,
 936                    content: LanguageModelToolResultContent::Text(Arc::from(error.to_string())),
 937                    output: None,
 938                },
 939            }
 940        }))
 941    }
 942
 943    fn handle_tool_use_json_parse_error_event(
 944        &mut self,
 945        tool_use_id: LanguageModelToolUseId,
 946        tool_name: Arc<str>,
 947        raw_input: Arc<str>,
 948        json_parse_error: String,
 949    ) -> LanguageModelToolResult {
 950        let tool_output = format!("Error parsing input JSON: {json_parse_error}");
 951        LanguageModelToolResult {
 952            tool_use_id,
 953            tool_name,
 954            is_error: true,
 955            content: LanguageModelToolResultContent::Text(tool_output.into()),
 956            output: Some(serde_json::Value::String(raw_input.to_string())),
 957        }
 958    }
 959
 960    fn pending_message(&mut self) -> &mut AgentMessage {
 961        self.pending_message.get_or_insert_default()
 962    }
 963
 964    fn flush_pending_message(&mut self) {
 965        let Some(mut message) = self.pending_message.take() else {
 966            return;
 967        };
 968
 969        for content in &message.content {
 970            let AgentMessageContent::ToolUse(tool_use) = content else {
 971                continue;
 972            };
 973
 974            if !message.tool_results.contains_key(&tool_use.id) {
 975                message.tool_results.insert(
 976                    tool_use.id.clone(),
 977                    LanguageModelToolResult {
 978                        tool_use_id: tool_use.id.clone(),
 979                        tool_name: tool_use.name.clone(),
 980                        is_error: true,
 981                        content: LanguageModelToolResultContent::Text(
 982                            "Tool canceled by user".into(),
 983                        ),
 984                        output: None,
 985                    },
 986                );
 987            }
 988        }
 989
 990        self.messages.push(Message::Agent(message));
 991    }
 992
 993    pub(crate) fn build_completion_request(
 994        &self,
 995        completion_intent: CompletionIntent,
 996        cx: &mut App,
 997    ) -> LanguageModelRequest {
 998        log::debug!("Building completion request");
 999        log::debug!("Completion intent: {:?}", completion_intent);
1000        log::debug!("Completion mode: {:?}", self.completion_mode);
1001
1002        let messages = self.build_request_messages();
1003        log::info!("Request will include {} messages", messages.len());
1004
1005        let tools = if let Some(tools) = self.tools(cx).log_err() {
1006            tools
1007                .filter_map(|tool| {
1008                    let tool_name = tool.name().to_string();
1009                    log::trace!("Including tool: {}", tool_name);
1010                    Some(LanguageModelRequestTool {
1011                        name: tool_name,
1012                        description: tool.description().to_string(),
1013                        input_schema: tool
1014                            .input_schema(self.model.tool_input_format())
1015                            .log_err()?,
1016                    })
1017                })
1018                .collect()
1019        } else {
1020            Vec::new()
1021        };
1022
1023        log::info!("Request includes {} tools", tools.len());
1024
1025        let request = LanguageModelRequest {
1026            thread_id: Some(self.id.to_string()),
1027            prompt_id: Some(self.prompt_id.to_string()),
1028            intent: Some(completion_intent),
1029            mode: Some(self.completion_mode.into()),
1030            messages,
1031            tools,
1032            tool_choice: None,
1033            stop: Vec::new(),
1034            temperature: AgentSettings::temperature_for_model(self.model(), cx),
1035            thinking_allowed: true,
1036        };
1037
1038        log::debug!("Completion request built successfully");
1039        request
1040    }
1041
1042    fn tools<'a>(&'a self, cx: &'a App) -> Result<impl Iterator<Item = &'a Arc<dyn AnyAgentTool>>> {
1043        let profile = AgentSettings::get_global(cx)
1044            .profiles
1045            .get(&self.profile_id)
1046            .context("profile not found")?;
1047        let provider_id = self.model.provider_id();
1048
1049        Ok(self
1050            .tools
1051            .iter()
1052            .filter(move |(_, tool)| tool.supported_provider(&provider_id))
1053            .filter_map(|(tool_name, tool)| {
1054                if profile.is_tool_enabled(tool_name) {
1055                    Some(tool)
1056                } else {
1057                    None
1058                }
1059            })
1060            .chain(self.context_server_registry.read(cx).servers().flat_map(
1061                |(server_id, tools)| {
1062                    tools.iter().filter_map(|(tool_name, tool)| {
1063                        if profile.is_context_server_tool_enabled(&server_id.0, tool_name) {
1064                            Some(tool)
1065                        } else {
1066                            None
1067                        }
1068                    })
1069                },
1070            )))
1071    }
1072
1073    fn build_request_messages(&self) -> Vec<LanguageModelRequestMessage> {
1074        log::trace!(
1075            "Building request messages from {} thread messages",
1076            self.messages.len()
1077        );
1078        let mut messages = vec![self.build_system_message()];
1079        for message in &self.messages {
1080            match message {
1081                Message::User(message) => messages.push(message.to_request()),
1082                Message::Agent(message) => messages.extend(message.to_request()),
1083                Message::Resume => messages.push(LanguageModelRequestMessage {
1084                    role: Role::User,
1085                    content: vec!["Continue where you left off".into()],
1086                    cache: false,
1087                }),
1088            }
1089        }
1090
1091        if let Some(message) = self.pending_message.as_ref() {
1092            messages.extend(message.to_request());
1093        }
1094
1095        if let Some(last_user_message) = messages
1096            .iter_mut()
1097            .rev()
1098            .find(|message| message.role == Role::User)
1099        {
1100            last_user_message.cache = true;
1101        }
1102
1103        messages
1104    }
1105
1106    pub fn to_markdown(&self) -> String {
1107        let mut markdown = String::new();
1108        for (ix, message) in self.messages.iter().enumerate() {
1109            if ix > 0 {
1110                markdown.push('\n');
1111            }
1112            markdown.push_str(&message.to_markdown());
1113        }
1114
1115        if let Some(message) = self.pending_message.as_ref() {
1116            markdown.push('\n');
1117            markdown.push_str(&message.to_markdown());
1118        }
1119
1120        markdown
1121    }
1122
1123    fn advance_prompt_id(&mut self) {
1124        self.prompt_id = PromptId::new();
1125    }
1126}
1127
1128pub trait AgentTool
1129where
1130    Self: 'static + Sized,
1131{
1132    type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
1133    type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
1134
1135    fn name(&self) -> SharedString;
1136
1137    fn description(&self) -> SharedString {
1138        let schema = schemars::schema_for!(Self::Input);
1139        SharedString::new(
1140            schema
1141                .get("description")
1142                .and_then(|description| description.as_str())
1143                .unwrap_or_default(),
1144        )
1145    }
1146
1147    fn kind(&self) -> acp::ToolKind;
1148
1149    /// The initial tool title to display. Can be updated during the tool run.
1150    fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString;
1151
1152    /// Returns the JSON schema that describes the tool's input.
1153    fn input_schema(&self) -> Schema {
1154        schemars::schema_for!(Self::Input)
1155    }
1156
1157    /// Some tools rely on a provider for the underlying billing or other reasons.
1158    /// Allow the tool to check if they are compatible, or should be filtered out.
1159    fn supported_provider(&self, _provider: &LanguageModelProviderId) -> bool {
1160        true
1161    }
1162
1163    /// Runs the tool with the provided input.
1164    fn run(
1165        self: Arc<Self>,
1166        input: Self::Input,
1167        event_stream: ToolCallEventStream,
1168        cx: &mut App,
1169    ) -> Task<Result<Self::Output>>;
1170
1171    fn erase(self) -> Arc<dyn AnyAgentTool> {
1172        Arc::new(Erased(Arc::new(self)))
1173    }
1174}
1175
1176pub struct Erased<T>(T);
1177
1178pub struct AgentToolOutput {
1179    pub llm_output: LanguageModelToolResultContent,
1180    pub raw_output: serde_json::Value,
1181}
1182
1183pub trait AnyAgentTool {
1184    fn name(&self) -> SharedString;
1185    fn description(&self) -> SharedString;
1186    fn kind(&self) -> acp::ToolKind;
1187    fn initial_title(&self, input: serde_json::Value) -> SharedString;
1188    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
1189    fn supported_provider(&self, _provider: &LanguageModelProviderId) -> bool {
1190        true
1191    }
1192    fn run(
1193        self: Arc<Self>,
1194        input: serde_json::Value,
1195        event_stream: ToolCallEventStream,
1196        cx: &mut App,
1197    ) -> Task<Result<AgentToolOutput>>;
1198}
1199
1200impl<T> AnyAgentTool for Erased<Arc<T>>
1201where
1202    T: AgentTool,
1203{
1204    fn name(&self) -> SharedString {
1205        self.0.name()
1206    }
1207
1208    fn description(&self) -> SharedString {
1209        self.0.description()
1210    }
1211
1212    fn kind(&self) -> agent_client_protocol::ToolKind {
1213        self.0.kind()
1214    }
1215
1216    fn initial_title(&self, input: serde_json::Value) -> SharedString {
1217        let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
1218        self.0.initial_title(parsed_input)
1219    }
1220
1221    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
1222        let mut json = serde_json::to_value(self.0.input_schema())?;
1223        adapt_schema_to_format(&mut json, format)?;
1224        Ok(json)
1225    }
1226
1227    fn supported_provider(&self, provider: &LanguageModelProviderId) -> bool {
1228        self.0.supported_provider(provider)
1229    }
1230
1231    fn run(
1232        self: Arc<Self>,
1233        input: serde_json::Value,
1234        event_stream: ToolCallEventStream,
1235        cx: &mut App,
1236    ) -> Task<Result<AgentToolOutput>> {
1237        cx.spawn(async move |cx| {
1238            let input = serde_json::from_value(input)?;
1239            let output = cx
1240                .update(|cx| self.0.clone().run(input, event_stream, cx))?
1241                .await?;
1242            let raw_output = serde_json::to_value(&output)?;
1243            Ok(AgentToolOutput {
1244                llm_output: output.into(),
1245                raw_output,
1246            })
1247        })
1248    }
1249}
1250
1251#[derive(Clone)]
1252struct AgentResponseEventStream(mpsc::UnboundedSender<Result<AgentResponseEvent>>);
1253
1254impl AgentResponseEventStream {
1255    fn send_text(&self, text: &str) {
1256        self.0
1257            .unbounded_send(Ok(AgentResponseEvent::Text(text.to_string())))
1258            .ok();
1259    }
1260
1261    fn send_thinking(&self, text: &str) {
1262        self.0
1263            .unbounded_send(Ok(AgentResponseEvent::Thinking(text.to_string())))
1264            .ok();
1265    }
1266
1267    fn send_tool_call(
1268        &self,
1269        id: &LanguageModelToolUseId,
1270        title: SharedString,
1271        kind: acp::ToolKind,
1272        input: serde_json::Value,
1273    ) {
1274        self.0
1275            .unbounded_send(Ok(AgentResponseEvent::ToolCall(Self::initial_tool_call(
1276                id,
1277                title.to_string(),
1278                kind,
1279                input,
1280            ))))
1281            .ok();
1282    }
1283
1284    fn initial_tool_call(
1285        id: &LanguageModelToolUseId,
1286        title: String,
1287        kind: acp::ToolKind,
1288        input: serde_json::Value,
1289    ) -> acp::ToolCall {
1290        acp::ToolCall {
1291            id: acp::ToolCallId(id.to_string().into()),
1292            title,
1293            kind,
1294            status: acp::ToolCallStatus::Pending,
1295            content: vec![],
1296            locations: vec![],
1297            raw_input: Some(input),
1298            raw_output: None,
1299        }
1300    }
1301
1302    fn update_tool_call_fields(
1303        &self,
1304        tool_use_id: &LanguageModelToolUseId,
1305        fields: acp::ToolCallUpdateFields,
1306    ) {
1307        self.0
1308            .unbounded_send(Ok(AgentResponseEvent::ToolCallUpdate(
1309                acp::ToolCallUpdate {
1310                    id: acp::ToolCallId(tool_use_id.to_string().into()),
1311                    fields,
1312                }
1313                .into(),
1314            )))
1315            .ok();
1316    }
1317
1318    fn send_stop(&self, reason: StopReason) {
1319        match reason {
1320            StopReason::EndTurn => {
1321                self.0
1322                    .unbounded_send(Ok(AgentResponseEvent::Stop(acp::StopReason::EndTurn)))
1323                    .ok();
1324            }
1325            StopReason::MaxTokens => {
1326                self.0
1327                    .unbounded_send(Ok(AgentResponseEvent::Stop(acp::StopReason::MaxTokens)))
1328                    .ok();
1329            }
1330            StopReason::Refusal => {
1331                self.0
1332                    .unbounded_send(Ok(AgentResponseEvent::Stop(acp::StopReason::Refusal)))
1333                    .ok();
1334            }
1335            StopReason::ToolUse => {}
1336        }
1337    }
1338
1339    fn send_error(&self, error: impl Into<anyhow::Error>) {
1340        self.0.unbounded_send(Err(error.into())).ok();
1341    }
1342}
1343
1344#[derive(Clone)]
1345pub struct ToolCallEventStream {
1346    tool_use_id: LanguageModelToolUseId,
1347    stream: AgentResponseEventStream,
1348    fs: Option<Arc<dyn Fs>>,
1349}
1350
1351impl ToolCallEventStream {
1352    #[cfg(test)]
1353    pub fn test() -> (Self, ToolCallEventStreamReceiver) {
1354        let (events_tx, events_rx) = mpsc::unbounded::<Result<AgentResponseEvent>>();
1355
1356        let stream =
1357            ToolCallEventStream::new("test_id".into(), AgentResponseEventStream(events_tx), None);
1358
1359        (stream, ToolCallEventStreamReceiver(events_rx))
1360    }
1361
1362    fn new(
1363        tool_use_id: LanguageModelToolUseId,
1364        stream: AgentResponseEventStream,
1365        fs: Option<Arc<dyn Fs>>,
1366    ) -> Self {
1367        Self {
1368            tool_use_id,
1369            stream,
1370            fs,
1371        }
1372    }
1373
1374    pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
1375        self.stream
1376            .update_tool_call_fields(&self.tool_use_id, fields);
1377    }
1378
1379    pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
1380        self.stream
1381            .0
1382            .unbounded_send(Ok(AgentResponseEvent::ToolCallUpdate(
1383                acp_thread::ToolCallUpdateDiff {
1384                    id: acp::ToolCallId(self.tool_use_id.to_string().into()),
1385                    diff,
1386                }
1387                .into(),
1388            )))
1389            .ok();
1390    }
1391
1392    pub fn update_terminal(&self, terminal: Entity<acp_thread::Terminal>) {
1393        self.stream
1394            .0
1395            .unbounded_send(Ok(AgentResponseEvent::ToolCallUpdate(
1396                acp_thread::ToolCallUpdateTerminal {
1397                    id: acp::ToolCallId(self.tool_use_id.to_string().into()),
1398                    terminal,
1399                }
1400                .into(),
1401            )))
1402            .ok();
1403    }
1404
1405    pub fn authorize(&self, title: impl Into<String>, cx: &mut App) -> Task<Result<()>> {
1406        if agent_settings::AgentSettings::get_global(cx).always_allow_tool_actions {
1407            return Task::ready(Ok(()));
1408        }
1409
1410        let (response_tx, response_rx) = oneshot::channel();
1411        self.stream
1412            .0
1413            .unbounded_send(Ok(AgentResponseEvent::ToolCallAuthorization(
1414                ToolCallAuthorization {
1415                    tool_call: acp::ToolCallUpdate {
1416                        id: acp::ToolCallId(self.tool_use_id.to_string().into()),
1417                        fields: acp::ToolCallUpdateFields {
1418                            title: Some(title.into()),
1419                            ..Default::default()
1420                        },
1421                    },
1422                    options: vec![
1423                        acp::PermissionOption {
1424                            id: acp::PermissionOptionId("always_allow".into()),
1425                            name: "Always Allow".into(),
1426                            kind: acp::PermissionOptionKind::AllowAlways,
1427                        },
1428                        acp::PermissionOption {
1429                            id: acp::PermissionOptionId("allow".into()),
1430                            name: "Allow".into(),
1431                            kind: acp::PermissionOptionKind::AllowOnce,
1432                        },
1433                        acp::PermissionOption {
1434                            id: acp::PermissionOptionId("deny".into()),
1435                            name: "Deny".into(),
1436                            kind: acp::PermissionOptionKind::RejectOnce,
1437                        },
1438                    ],
1439                    response: response_tx,
1440                },
1441            )))
1442            .ok();
1443        let fs = self.fs.clone();
1444        cx.spawn(async move |cx| match response_rx.await?.0.as_ref() {
1445            "always_allow" => {
1446                if let Some(fs) = fs.clone() {
1447                    cx.update(|cx| {
1448                        update_settings_file::<AgentSettings>(fs, cx, |settings, _| {
1449                            settings.set_always_allow_tool_actions(true);
1450                        });
1451                    })?;
1452                }
1453
1454                Ok(())
1455            }
1456            "allow" => Ok(()),
1457            _ => Err(anyhow!("Permission to run tool denied by user")),
1458        })
1459    }
1460}
1461
1462#[cfg(test)]
1463pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<AgentResponseEvent>>);
1464
1465#[cfg(test)]
1466impl ToolCallEventStreamReceiver {
1467    pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
1468        let event = self.0.next().await;
1469        if let Some(Ok(AgentResponseEvent::ToolCallAuthorization(auth))) = event {
1470            auth
1471        } else {
1472            panic!("Expected ToolCallAuthorization but got: {:?}", event);
1473        }
1474    }
1475
1476    pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
1477        let event = self.0.next().await;
1478        if let Some(Ok(AgentResponseEvent::ToolCallUpdate(
1479            acp_thread::ToolCallUpdate::UpdateTerminal(update),
1480        ))) = event
1481        {
1482            update.terminal
1483        } else {
1484            panic!("Expected terminal but got: {:?}", event);
1485        }
1486    }
1487}
1488
1489#[cfg(test)]
1490impl std::ops::Deref for ToolCallEventStreamReceiver {
1491    type Target = mpsc::UnboundedReceiver<Result<AgentResponseEvent>>;
1492
1493    fn deref(&self) -> &Self::Target {
1494        &self.0
1495    }
1496}
1497
1498#[cfg(test)]
1499impl std::ops::DerefMut for ToolCallEventStreamReceiver {
1500    fn deref_mut(&mut self) -> &mut Self::Target {
1501        &mut self.0
1502    }
1503}
1504
1505impl From<&str> for UserMessageContent {
1506    fn from(text: &str) -> Self {
1507        Self::Text(text.into())
1508    }
1509}
1510
1511impl From<acp::ContentBlock> for UserMessageContent {
1512    fn from(value: acp::ContentBlock) -> Self {
1513        match value {
1514            acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
1515            acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
1516            acp::ContentBlock::Audio(_) => {
1517                // TODO
1518                Self::Text("[audio]".to_string())
1519            }
1520            acp::ContentBlock::ResourceLink(resource_link) => {
1521                match MentionUri::parse(&resource_link.uri) {
1522                    Ok(uri) => Self::Mention {
1523                        uri,
1524                        content: String::new(),
1525                    },
1526                    Err(err) => {
1527                        log::error!("Failed to parse mention link: {}", err);
1528                        Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
1529                    }
1530                }
1531            }
1532            acp::ContentBlock::Resource(resource) => match resource.resource {
1533                acp::EmbeddedResourceResource::TextResourceContents(resource) => {
1534                    match MentionUri::parse(&resource.uri) {
1535                        Ok(uri) => Self::Mention {
1536                            uri,
1537                            content: resource.text,
1538                        },
1539                        Err(err) => {
1540                            log::error!("Failed to parse mention link: {}", err);
1541                            Self::Text(
1542                                MarkdownCodeBlock {
1543                                    tag: &resource.uri,
1544                                    text: &resource.text,
1545                                }
1546                                .to_string(),
1547                            )
1548                        }
1549                    }
1550                }
1551                acp::EmbeddedResourceResource::BlobResourceContents(_) => {
1552                    // TODO
1553                    Self::Text("[blob]".to_string())
1554                }
1555            },
1556        }
1557    }
1558}
1559
1560fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
1561    LanguageModelImage {
1562        source: image_content.data.into(),
1563        // TODO: make this optional?
1564        size: gpui::Size::new(0.into(), 0.into()),
1565    }
1566}