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