thread.rs

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