thread.rs

   1use crate::{
   2    ContextServerRegistry, DbLanguageModel, DbThread, SystemPromptTemplate, Template, Templates,
   3};
   4use acp_thread::{MentionUri, UserMessageId};
   5use action_log::ActionLog;
   6use agent::thread::{DetailedSummaryState, GitState, ProjectSnapshot, WorktreeSnapshot};
   7use agent_client_protocol as acp;
   8use agent_settings::{AgentProfileId, AgentSettings, CompletionMode, SUMMARIZE_THREAD_PROMPT};
   9use anyhow::{Context as _, Result, anyhow};
  10use assistant_tool::adapt_schema_to_format;
  11use chrono::{DateTime, Utc};
  12use cloud_llm_client::{CompletionIntent, CompletionRequestStatus};
  13use collections::IndexMap;
  14use fs::Fs;
  15use futures::{
  16    FutureExt,
  17    channel::{mpsc, oneshot},
  18    future::Shared,
  19    stream::FuturesUnordered,
  20};
  21use git::repository::DiffType;
  22use gpui::{App, AppContext, Context, Entity, SharedString, Task};
  23use language_model::{
  24    LanguageModel, LanguageModelCompletionEvent, LanguageModelImage, LanguageModelProviderId,
  25    LanguageModelRequest, LanguageModelRequestMessage, LanguageModelRequestTool,
  26    LanguageModelToolResult, LanguageModelToolResultContent, LanguageModelToolSchemaFormat,
  27    LanguageModelToolUse, LanguageModelToolUseId, MessageContent, Role, StopReason, TokenUsage,
  28};
  29use project::{
  30    Project,
  31    git_store::{GitStore, RepositoryState},
  32};
  33use prompt_store::ProjectContext;
  34use schemars::{JsonSchema, Schema};
  35use serde::{Deserialize, Serialize};
  36use settings::{Settings, update_settings_file};
  37use smol::stream::StreamExt;
  38use std::{cell::RefCell, collections::BTreeMap, path::Path, rc::Rc, sync::Arc};
  39use std::{fmt::Write, ops::Range};
  40use util::{ResultExt, markdown::MarkdownCodeBlock};
  41use uuid::Uuid;
  42
  43const TOOL_CANCELED_MESSAGE: &str = "Tool canceled by user";
  44
  45/// The ID of the user prompt that initiated a request.
  46///
  47/// This equates to the user physically submitting a message to the model (e.g., by pressing the Enter key).
  48#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
  49pub struct PromptId(Arc<str>);
  50
  51impl PromptId {
  52    pub fn new() -> Self {
  53        Self(Uuid::new_v4().to_string().into())
  54    }
  55}
  56
  57impl std::fmt::Display for PromptId {
  58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  59        write!(f, "{}", self.0)
  60    }
  61}
  62
  63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  64pub enum Message {
  65    User(UserMessage),
  66    Agent(AgentMessage),
  67    Resume,
  68}
  69
  70impl Message {
  71    pub fn as_agent_message(&self) -> Option<&AgentMessage> {
  72        match self {
  73            Message::Agent(agent_message) => Some(agent_message),
  74            _ => None,
  75        }
  76    }
  77
  78    pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
  79        match self {
  80            Message::User(message) => vec![message.to_request()],
  81            Message::Agent(message) => message.to_request(),
  82            Message::Resume => vec![LanguageModelRequestMessage {
  83                role: Role::User,
  84                content: vec!["Continue where you left off".into()],
  85                cache: false,
  86            }],
  87        }
  88    }
  89
  90    pub fn to_markdown(&self) -> String {
  91        match self {
  92            Message::User(message) => message.to_markdown(),
  93            Message::Agent(message) => message.to_markdown(),
  94            Message::Resume => "[resumed after tool use limit was reached]".into(),
  95        }
  96    }
  97
  98    pub fn role(&self) -> Role {
  99        match self {
 100            Message::User(_) | Message::Resume => Role::User,
 101            Message::Agent(_) => Role::Assistant,
 102        }
 103    }
 104}
 105
 106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 107pub struct UserMessage {
 108    pub id: UserMessageId,
 109    pub content: Vec<UserMessageContent>,
 110}
 111
 112#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 113pub enum UserMessageContent {
 114    Text(String),
 115    Mention { uri: MentionUri, content: String },
 116    Image(LanguageModelImage),
 117}
 118
 119impl UserMessage {
 120    pub fn to_markdown(&self) -> String {
 121        let mut markdown = String::from("## User\n\n");
 122
 123        for content in &self.content {
 124            match content {
 125                UserMessageContent::Text(text) => {
 126                    markdown.push_str(text);
 127                    markdown.push('\n');
 128                }
 129                UserMessageContent::Image(_) => {
 130                    markdown.push_str("<image />\n");
 131                }
 132                UserMessageContent::Mention { uri, content } => {
 133                    if !content.is_empty() {
 134                        let _ = write!(&mut markdown, "{}\n\n{}\n", uri.as_link(), content);
 135                    } else {
 136                        let _ = write!(&mut markdown, "{}\n", uri.as_link());
 137                    }
 138                }
 139            }
 140        }
 141
 142        markdown
 143    }
 144
 145    fn to_request(&self) -> LanguageModelRequestMessage {
 146        let mut message = LanguageModelRequestMessage {
 147            role: Role::User,
 148            content: Vec::with_capacity(self.content.len()),
 149            cache: false,
 150        };
 151
 152        const OPEN_CONTEXT: &str = "<context>\n\
 153            The following items were attached by the user. \
 154            They are up-to-date and don't need to be re-read.\n\n";
 155
 156        const OPEN_FILES_TAG: &str = "<files>";
 157        const OPEN_SYMBOLS_TAG: &str = "<symbols>";
 158        const OPEN_THREADS_TAG: &str = "<threads>";
 159        const OPEN_FETCH_TAG: &str = "<fetched_urls>";
 160        const OPEN_RULES_TAG: &str =
 161            "<rules>\nThe user has specified the following rules that should be applied:\n";
 162
 163        let mut file_context = OPEN_FILES_TAG.to_string();
 164        let mut symbol_context = OPEN_SYMBOLS_TAG.to_string();
 165        let mut thread_context = OPEN_THREADS_TAG.to_string();
 166        let mut fetch_context = OPEN_FETCH_TAG.to_string();
 167        let mut rules_context = OPEN_RULES_TAG.to_string();
 168
 169        for chunk in &self.content {
 170            let chunk = match chunk {
 171                UserMessageContent::Text(text) => {
 172                    language_model::MessageContent::Text(text.clone())
 173                }
 174                UserMessageContent::Image(value) => {
 175                    language_model::MessageContent::Image(value.clone())
 176                }
 177                UserMessageContent::Mention { uri, content } => {
 178                    match uri {
 179                        MentionUri::File { abs_path, .. } => {
 180                            write!(
 181                                &mut symbol_context,
 182                                "\n{}",
 183                                MarkdownCodeBlock {
 184                                    tag: &codeblock_tag(&abs_path, None),
 185                                    text: &content.to_string(),
 186                                }
 187                            )
 188                            .ok();
 189                        }
 190                        MentionUri::Symbol {
 191                            path, line_range, ..
 192                        }
 193                        | MentionUri::Selection {
 194                            path, line_range, ..
 195                        } => {
 196                            write!(
 197                                &mut rules_context,
 198                                "\n{}",
 199                                MarkdownCodeBlock {
 200                                    tag: &codeblock_tag(&path, Some(line_range)),
 201                                    text: &content
 202                                }
 203                            )
 204                            .ok();
 205                        }
 206                        MentionUri::Thread { .. } => {
 207                            write!(&mut thread_context, "\n{}\n", content).ok();
 208                        }
 209                        MentionUri::TextThread { .. } => {
 210                            write!(&mut thread_context, "\n{}\n", content).ok();
 211                        }
 212                        MentionUri::Rule { .. } => {
 213                            write!(
 214                                &mut rules_context,
 215                                "\n{}",
 216                                MarkdownCodeBlock {
 217                                    tag: "",
 218                                    text: &content
 219                                }
 220                            )
 221                            .ok();
 222                        }
 223                        MentionUri::Fetch { url } => {
 224                            write!(&mut fetch_context, "\nFetch: {}\n\n{}", url, content).ok();
 225                        }
 226                    }
 227
 228                    language_model::MessageContent::Text(uri.as_link().to_string())
 229                }
 230            };
 231
 232            message.content.push(chunk);
 233        }
 234
 235        let len_before_context = message.content.len();
 236
 237        if file_context.len() > OPEN_FILES_TAG.len() {
 238            file_context.push_str("</files>\n");
 239            message
 240                .content
 241                .push(language_model::MessageContent::Text(file_context));
 242        }
 243
 244        if symbol_context.len() > OPEN_SYMBOLS_TAG.len() {
 245            symbol_context.push_str("</symbols>\n");
 246            message
 247                .content
 248                .push(language_model::MessageContent::Text(symbol_context));
 249        }
 250
 251        if thread_context.len() > OPEN_THREADS_TAG.len() {
 252            thread_context.push_str("</threads>\n");
 253            message
 254                .content
 255                .push(language_model::MessageContent::Text(thread_context));
 256        }
 257
 258        if fetch_context.len() > OPEN_FETCH_TAG.len() {
 259            fetch_context.push_str("</fetched_urls>\n");
 260            message
 261                .content
 262                .push(language_model::MessageContent::Text(fetch_context));
 263        }
 264
 265        if rules_context.len() > OPEN_RULES_TAG.len() {
 266            rules_context.push_str("</user_rules>\n");
 267            message
 268                .content
 269                .push(language_model::MessageContent::Text(rules_context));
 270        }
 271
 272        if message.content.len() > len_before_context {
 273            message.content.insert(
 274                len_before_context,
 275                language_model::MessageContent::Text(OPEN_CONTEXT.into()),
 276            );
 277            message
 278                .content
 279                .push(language_model::MessageContent::Text("</context>".into()));
 280        }
 281
 282        message
 283    }
 284}
 285
 286fn codeblock_tag(full_path: &Path, line_range: Option<&Range<u32>>) -> String {
 287    let mut result = String::new();
 288
 289    if let Some(extension) = full_path.extension().and_then(|ext| ext.to_str()) {
 290        let _ = write!(result, "{} ", extension);
 291    }
 292
 293    let _ = write!(result, "{}", full_path.display());
 294
 295    if let Some(range) = line_range {
 296        if range.start == range.end {
 297            let _ = write!(result, ":{}", range.start + 1);
 298        } else {
 299            let _ = write!(result, ":{}-{}", range.start + 1, range.end + 1);
 300        }
 301    }
 302
 303    result
 304}
 305
 306impl AgentMessage {
 307    pub fn to_markdown(&self) -> String {
 308        let mut markdown = String::from("## Assistant\n\n");
 309
 310        for content in &self.content {
 311            match content {
 312                AgentMessageContent::Text(text) => {
 313                    markdown.push_str(text);
 314                    markdown.push('\n');
 315                }
 316                AgentMessageContent::Thinking { text, .. } => {
 317                    markdown.push_str("<think>");
 318                    markdown.push_str(text);
 319                    markdown.push_str("</think>\n");
 320                }
 321                AgentMessageContent::RedactedThinking(_) => {
 322                    markdown.push_str("<redacted_thinking />\n")
 323                }
 324                AgentMessageContent::ToolUse(tool_use) => {
 325                    markdown.push_str(&format!(
 326                        "**Tool Use**: {} (ID: {})\n",
 327                        tool_use.name, tool_use.id
 328                    ));
 329                    markdown.push_str(&format!(
 330                        "{}\n",
 331                        MarkdownCodeBlock {
 332                            tag: "json",
 333                            text: &format!("{:#}", tool_use.input)
 334                        }
 335                    ));
 336                }
 337            }
 338        }
 339
 340        for tool_result in self.tool_results.values() {
 341            markdown.push_str(&format!(
 342                "**Tool Result**: {} (ID: {})\n\n",
 343                tool_result.tool_name, tool_result.tool_use_id
 344            ));
 345            if tool_result.is_error {
 346                markdown.push_str("**ERROR:**\n");
 347            }
 348
 349            match &tool_result.content {
 350                LanguageModelToolResultContent::Text(text) => {
 351                    writeln!(markdown, "{text}\n").ok();
 352                }
 353                LanguageModelToolResultContent::Image(_) => {
 354                    writeln!(markdown, "<image />\n").ok();
 355                }
 356            }
 357
 358            if let Some(output) = tool_result.output.as_ref() {
 359                writeln!(
 360                    markdown,
 361                    "**Debug Output**:\n\n```json\n{}\n```\n",
 362                    serde_json::to_string_pretty(output).unwrap()
 363                )
 364                .unwrap();
 365            }
 366        }
 367
 368        markdown
 369    }
 370
 371    pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
 372        let mut assistant_message = LanguageModelRequestMessage {
 373            role: Role::Assistant,
 374            content: Vec::with_capacity(self.content.len()),
 375            cache: false,
 376        };
 377        for chunk in &self.content {
 378            let chunk = match chunk {
 379                AgentMessageContent::Text(text) => {
 380                    language_model::MessageContent::Text(text.clone())
 381                }
 382                AgentMessageContent::Thinking { text, signature } => {
 383                    language_model::MessageContent::Thinking {
 384                        text: text.clone(),
 385                        signature: signature.clone(),
 386                    }
 387                }
 388                AgentMessageContent::RedactedThinking(value) => {
 389                    language_model::MessageContent::RedactedThinking(value.clone())
 390                }
 391                AgentMessageContent::ToolUse(value) => {
 392                    language_model::MessageContent::ToolUse(value.clone())
 393                }
 394            };
 395            assistant_message.content.push(chunk);
 396        }
 397
 398        let mut user_message = LanguageModelRequestMessage {
 399            role: Role::User,
 400            content: Vec::new(),
 401            cache: false,
 402        };
 403
 404        for tool_result in self.tool_results.values() {
 405            user_message
 406                .content
 407                .push(language_model::MessageContent::ToolResult(
 408                    tool_result.clone(),
 409                ));
 410        }
 411
 412        let mut messages = Vec::new();
 413        if !assistant_message.content.is_empty() {
 414            messages.push(assistant_message);
 415        }
 416        if !user_message.content.is_empty() {
 417            messages.push(user_message);
 418        }
 419        messages
 420    }
 421}
 422
 423#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 424pub struct AgentMessage {
 425    pub content: Vec<AgentMessageContent>,
 426    pub tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
 427}
 428
 429#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
 430pub enum AgentMessageContent {
 431    Text(String),
 432    Thinking {
 433        text: String,
 434        signature: Option<String>,
 435    },
 436    RedactedThinking(String),
 437    ToolUse(LanguageModelToolUse),
 438}
 439
 440#[derive(Debug)]
 441pub enum ThreadEvent {
 442    UserMessage(UserMessage),
 443    AgentText(String),
 444    AgentThinking(String),
 445    ToolCall(acp::ToolCall),
 446    ToolCallUpdate(acp_thread::ToolCallUpdate),
 447    ToolCallAuthorization(ToolCallAuthorization),
 448    TitleUpdate(SharedString),
 449    Stop(acp::StopReason),
 450}
 451
 452#[derive(Debug)]
 453pub struct ToolCallAuthorization {
 454    pub tool_call: acp::ToolCallUpdate,
 455    pub options: Vec<acp::PermissionOption>,
 456    pub response: oneshot::Sender<acp::PermissionOptionId>,
 457}
 458
 459enum ThreadTitle {
 460    None,
 461    Pending(Shared<Task<()>>),
 462    Done(Result<SharedString>),
 463}
 464
 465impl ThreadTitle {
 466    pub fn unwrap_or_default(&self) -> SharedString {
 467        if let ThreadTitle::Done(Ok(title)) = self {
 468            title.clone()
 469        } else {
 470            "New Thread".into()
 471        }
 472    }
 473}
 474
 475pub struct Thread {
 476    id: acp::SessionId,
 477    prompt_id: PromptId,
 478    updated_at: DateTime<Utc>,
 479    title: ThreadTitle,
 480    summary: DetailedSummaryState,
 481    messages: Vec<Message>,
 482    completion_mode: CompletionMode,
 483    /// Holds the task that handles agent interaction until the end of the turn.
 484    /// Survives across multiple requests as the model performs tool calls and
 485    /// we run tools, report their results.
 486    running_turn: Option<RunningTurn>,
 487    pending_message: Option<AgentMessage>,
 488    tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
 489    tool_use_limit_reached: bool,
 490    request_token_usage: Vec<TokenUsage>,
 491    cumulative_token_usage: TokenUsage,
 492    initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
 493    context_server_registry: Entity<ContextServerRegistry>,
 494    profile_id: AgentProfileId,
 495    project_context: Rc<RefCell<ProjectContext>>,
 496    templates: Arc<Templates>,
 497    model: Option<Arc<dyn LanguageModel>>,
 498    summarization_model: Option<Arc<dyn LanguageModel>>,
 499    project: Entity<Project>,
 500    action_log: Entity<ActionLog>,
 501}
 502
 503impl Thread {
 504    pub fn new(
 505        id: acp::SessionId,
 506        project: Entity<Project>,
 507        project_context: Rc<RefCell<ProjectContext>>,
 508        context_server_registry: Entity<ContextServerRegistry>,
 509        action_log: Entity<ActionLog>,
 510        templates: Arc<Templates>,
 511        model: Option<Arc<dyn LanguageModel>>,
 512        summarization_model: Option<Arc<dyn LanguageModel>>,
 513        cx: &mut Context<Self>,
 514    ) -> Self {
 515        let profile_id = AgentSettings::get_global(cx).default_profile.clone();
 516        Self {
 517            id,
 518            prompt_id: PromptId::new(),
 519            updated_at: Utc::now(),
 520            title: ThreadTitle::None,
 521            summary: DetailedSummaryState::default(),
 522            messages: Vec::new(),
 523            completion_mode: CompletionMode::Normal,
 524            running_turn: None,
 525            pending_message: None,
 526            tools: BTreeMap::default(),
 527            tool_use_limit_reached: false,
 528            request_token_usage: Vec::new(),
 529            cumulative_token_usage: TokenUsage::default(),
 530            initial_project_snapshot: {
 531                let project_snapshot = Self::project_snapshot(project.clone(), cx);
 532                cx.foreground_executor()
 533                    .spawn(async move { Some(project_snapshot.await) })
 534                    .shared()
 535            },
 536            context_server_registry,
 537            profile_id,
 538            project_context,
 539            templates,
 540            model,
 541            summarization_model,
 542            project,
 543            action_log,
 544        }
 545    }
 546
 547    #[cfg(any(test, feature = "test-support"))]
 548    pub fn test(
 549        model: Arc<dyn LanguageModel>,
 550        project: Entity<Project>,
 551        action_log: Entity<ActionLog>,
 552        cx: &mut Context<Self>,
 553    ) -> Self {
 554        use crate::generate_session_id;
 555
 556        let context_server_registry =
 557            cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
 558
 559        Self::new(
 560            generate_session_id(),
 561            project,
 562            Rc::default(),
 563            context_server_registry,
 564            action_log,
 565            Templates::new(),
 566            Some(model),
 567            None,
 568            cx,
 569        )
 570    }
 571
 572    pub fn id(&self) -> &acp::SessionId {
 573        &self.id
 574    }
 575
 576    pub fn from_db(
 577        id: acp::SessionId,
 578        db_thread: DbThread,
 579        project: Entity<Project>,
 580        project_context: Rc<RefCell<ProjectContext>>,
 581        context_server_registry: Entity<ContextServerRegistry>,
 582        action_log: Entity<ActionLog>,
 583        templates: Arc<Templates>,
 584        model: Arc<dyn LanguageModel>,
 585        summarization_model: Option<Arc<dyn LanguageModel>>,
 586        cx: &mut Context<Self>,
 587    ) -> Self {
 588        let profile_id = db_thread
 589            .profile
 590            .unwrap_or_else(|| AgentSettings::get_global(cx).default_profile.clone());
 591        Self {
 592            id,
 593            prompt_id: PromptId::new(),
 594            title: ThreadTitle::Done(Ok(db_thread.title.clone())),
 595            summary: db_thread.summary,
 596            messages: db_thread.messages,
 597            completion_mode: CompletionMode::Normal,
 598            running_turn: None,
 599            pending_message: None,
 600            tools: BTreeMap::default(),
 601            tool_use_limit_reached: false,
 602            request_token_usage: db_thread.request_token_usage.clone(),
 603            cumulative_token_usage: db_thread.cumulative_token_usage.clone(),
 604            initial_project_snapshot: Task::ready(db_thread.initial_project_snapshot).shared(),
 605            context_server_registry,
 606            profile_id,
 607            project_context,
 608            templates,
 609            model: Some(model),
 610            summarization_model,
 611            project,
 612            action_log,
 613            updated_at: db_thread.updated_at,
 614        }
 615    }
 616
 617    pub fn to_db(&self, cx: &App) -> Task<DbThread> {
 618        let initial_project_snapshot = self.initial_project_snapshot.clone();
 619        let mut thread = DbThread {
 620            title: self.title.unwrap_or_default(),
 621            messages: self.messages.clone(),
 622            updated_at: self.updated_at.clone(),
 623            summary: self.summary.clone(),
 624            initial_project_snapshot: None,
 625            cumulative_token_usage: self.cumulative_token_usage.clone(),
 626            request_token_usage: self.request_token_usage.clone(),
 627            model: self.model.as_ref().map(|model| DbLanguageModel {
 628                provider: model.provider_id().to_string(),
 629                model: model.name().0.to_string(),
 630            }),
 631            completion_mode: Some(self.completion_mode.into()),
 632            profile: Some(self.profile_id.clone()),
 633        };
 634
 635        cx.background_spawn(async move {
 636            let initial_project_snapshot = initial_project_snapshot.await;
 637            thread.initial_project_snapshot = initial_project_snapshot;
 638            thread
 639        })
 640    }
 641
 642    pub fn replay(
 643        &mut self,
 644        cx: &mut Context<Self>,
 645    ) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {
 646        let (tx, rx) = mpsc::unbounded();
 647        let stream = ThreadEventStream(tx);
 648        for message in &self.messages {
 649            match message {
 650                Message::User(user_message) => stream.send_user_message(&user_message),
 651                Message::Agent(assistant_message) => {
 652                    for content in &assistant_message.content {
 653                        match content {
 654                            AgentMessageContent::Text(text) => stream.send_text(text),
 655                            AgentMessageContent::Thinking { text, .. } => {
 656                                stream.send_thinking(text)
 657                            }
 658                            AgentMessageContent::RedactedThinking(_) => {}
 659                            AgentMessageContent::ToolUse(tool_use) => {
 660                                self.replay_tool_call(
 661                                    tool_use,
 662                                    assistant_message.tool_results.get(&tool_use.id),
 663                                    &stream,
 664                                    cx,
 665                                );
 666                            }
 667                        }
 668                    }
 669                }
 670                Message::Resume => {}
 671            }
 672        }
 673        rx
 674    }
 675
 676    fn replay_tool_call(
 677        &self,
 678        tool_use: &LanguageModelToolUse,
 679        tool_result: Option<&LanguageModelToolResult>,
 680        stream: &ThreadEventStream,
 681        cx: &mut Context<Self>,
 682    ) {
 683        let Some(tool) = self.tools.get(tool_use.name.as_ref()) else {
 684            stream
 685                .0
 686                .unbounded_send(Ok(ThreadEvent::ToolCall(acp::ToolCall {
 687                    id: acp::ToolCallId(tool_use.id.to_string().into()),
 688                    title: tool_use.name.to_string(),
 689                    kind: acp::ToolKind::Other,
 690                    status: acp::ToolCallStatus::Failed,
 691                    content: Vec::new(),
 692                    locations: Vec::new(),
 693                    raw_input: Some(tool_use.input.clone()),
 694                    raw_output: None,
 695                })))
 696                .ok();
 697            return;
 698        };
 699
 700        let title = tool.initial_title(tool_use.input.clone());
 701        let kind = tool.kind();
 702        stream.send_tool_call(&tool_use.id, title, kind, tool_use.input.clone());
 703
 704        let output = tool_result
 705            .as_ref()
 706            .and_then(|result| result.output.clone());
 707        if let Some(output) = output.clone() {
 708            let tool_event_stream = ToolCallEventStream::new(
 709                tool_use.id.clone(),
 710                stream.clone(),
 711                Some(self.project.read(cx).fs().clone()),
 712            );
 713            tool.replay(tool_use.input.clone(), output, tool_event_stream, cx)
 714                .log_err();
 715        }
 716
 717        stream.update_tool_call_fields(
 718            &tool_use.id,
 719            acp::ToolCallUpdateFields {
 720                status: Some(acp::ToolCallStatus::Completed),
 721                raw_output: output,
 722                ..Default::default()
 723            },
 724        );
 725    }
 726
 727    /// Create a snapshot of the current project state including git information and unsaved buffers.
 728    fn project_snapshot(
 729        project: Entity<Project>,
 730        cx: &mut Context<Self>,
 731    ) -> Task<Arc<agent::thread::ProjectSnapshot>> {
 732        let git_store = project.read(cx).git_store().clone();
 733        let worktree_snapshots: Vec<_> = project
 734            .read(cx)
 735            .visible_worktrees(cx)
 736            .map(|worktree| Self::worktree_snapshot(worktree, git_store.clone(), cx))
 737            .collect();
 738
 739        cx.spawn(async move |_, cx| {
 740            let worktree_snapshots = futures::future::join_all(worktree_snapshots).await;
 741
 742            let mut unsaved_buffers = Vec::new();
 743            cx.update(|app_cx| {
 744                let buffer_store = project.read(app_cx).buffer_store();
 745                for buffer_handle in buffer_store.read(app_cx).buffers() {
 746                    let buffer = buffer_handle.read(app_cx);
 747                    if buffer.is_dirty() {
 748                        if let Some(file) = buffer.file() {
 749                            let path = file.path().to_string_lossy().to_string();
 750                            unsaved_buffers.push(path);
 751                        }
 752                    }
 753                }
 754            })
 755            .ok();
 756
 757            Arc::new(ProjectSnapshot {
 758                worktree_snapshots,
 759                unsaved_buffer_paths: unsaved_buffers,
 760                timestamp: Utc::now(),
 761            })
 762        })
 763    }
 764
 765    fn worktree_snapshot(
 766        worktree: Entity<project::Worktree>,
 767        git_store: Entity<GitStore>,
 768        cx: &App,
 769    ) -> Task<agent::thread::WorktreeSnapshot> {
 770        cx.spawn(async move |cx| {
 771            // Get worktree path and snapshot
 772            let worktree_info = cx.update(|app_cx| {
 773                let worktree = worktree.read(app_cx);
 774                let path = worktree.abs_path().to_string_lossy().to_string();
 775                let snapshot = worktree.snapshot();
 776                (path, snapshot)
 777            });
 778
 779            let Ok((worktree_path, _snapshot)) = worktree_info else {
 780                return WorktreeSnapshot {
 781                    worktree_path: String::new(),
 782                    git_state: None,
 783                };
 784            };
 785
 786            let git_state = git_store
 787                .update(cx, |git_store, cx| {
 788                    git_store
 789                        .repositories()
 790                        .values()
 791                        .find(|repo| {
 792                            repo.read(cx)
 793                                .abs_path_to_repo_path(&worktree.read(cx).abs_path())
 794                                .is_some()
 795                        })
 796                        .cloned()
 797                })
 798                .ok()
 799                .flatten()
 800                .map(|repo| {
 801                    repo.update(cx, |repo, _| {
 802                        let current_branch =
 803                            repo.branch.as_ref().map(|branch| branch.name().to_owned());
 804                        repo.send_job(None, |state, _| async move {
 805                            let RepositoryState::Local { backend, .. } = state else {
 806                                return GitState {
 807                                    remote_url: None,
 808                                    head_sha: None,
 809                                    current_branch,
 810                                    diff: None,
 811                                };
 812                            };
 813
 814                            let remote_url = backend.remote_url("origin");
 815                            let head_sha = backend.head_sha().await;
 816                            let diff = backend.diff(DiffType::HeadToWorktree).await.ok();
 817
 818                            GitState {
 819                                remote_url,
 820                                head_sha,
 821                                current_branch,
 822                                diff,
 823                            }
 824                        })
 825                    })
 826                });
 827
 828            let git_state = match git_state {
 829                Some(git_state) => match git_state.ok() {
 830                    Some(git_state) => git_state.await.ok(),
 831                    None => None,
 832                },
 833                None => None,
 834            };
 835
 836            WorktreeSnapshot {
 837                worktree_path,
 838                git_state,
 839            }
 840        })
 841    }
 842
 843    pub fn project(&self) -> &Entity<Project> {
 844        &self.project
 845    }
 846
 847    pub fn action_log(&self) -> &Entity<ActionLog> {
 848        &self.action_log
 849    }
 850
 851    pub fn model(&self) -> Option<&Arc<dyn LanguageModel>> {
 852        self.model.as_ref()
 853    }
 854
 855    pub fn set_model(&mut self, model: Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
 856        self.model = Some(model);
 857        cx.notify()
 858    }
 859
 860    pub fn set_summarization_model(
 861        &mut self,
 862        model: Option<Arc<dyn LanguageModel>>,
 863        cx: &mut Context<Self>,
 864    ) {
 865        self.summarization_model = model;
 866        cx.notify()
 867    }
 868
 869    pub fn completion_mode(&self) -> CompletionMode {
 870        self.completion_mode
 871    }
 872
 873    pub fn set_completion_mode(&mut self, mode: CompletionMode, cx: &mut Context<Self>) {
 874        self.completion_mode = mode;
 875        cx.notify()
 876    }
 877
 878    #[cfg(any(test, feature = "test-support"))]
 879    pub fn last_message(&self) -> Option<Message> {
 880        if let Some(message) = self.pending_message.clone() {
 881            Some(Message::Agent(message))
 882        } else {
 883            self.messages.last().cloned()
 884        }
 885    }
 886
 887    pub fn add_tool(&mut self, tool: impl AgentTool) {
 888        self.tools.insert(tool.name(), tool.erase());
 889    }
 890
 891    pub fn remove_tool(&mut self, name: &str) -> bool {
 892        self.tools.remove(name).is_some()
 893    }
 894
 895    pub fn profile(&self) -> &AgentProfileId {
 896        &self.profile_id
 897    }
 898
 899    pub fn set_profile(&mut self, profile_id: AgentProfileId) {
 900        self.profile_id = profile_id;
 901    }
 902
 903    pub fn cancel(&mut self, cx: &mut Context<Self>) {
 904        if let Some(running_turn) = self.running_turn.take() {
 905            running_turn.cancel();
 906        }
 907        self.flush_pending_message(cx);
 908    }
 909
 910    pub fn truncate(&mut self, message_id: UserMessageId, cx: &mut Context<Self>) -> Result<()> {
 911        self.cancel(cx);
 912        let Some(position) = self.messages.iter().position(
 913            |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
 914        ) else {
 915            return Err(anyhow!("Message not found"));
 916        };
 917        self.messages.truncate(position);
 918        cx.notify();
 919        Ok(())
 920    }
 921
 922    pub fn resume(
 923        &mut self,
 924        cx: &mut Context<Self>,
 925    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
 926        anyhow::ensure!(
 927            self.tool_use_limit_reached,
 928            "can only resume after tool use limit is reached"
 929        );
 930
 931        self.messages.push(Message::Resume);
 932        cx.notify();
 933
 934        log::info!("Total messages in thread: {}", self.messages.len());
 935        self.run_turn(cx)
 936    }
 937
 938    /// Sending a message results in the model streaming a response, which could include tool calls.
 939    /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
 940    /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
 941    pub fn send<T>(
 942        &mut self,
 943        id: UserMessageId,
 944        content: impl IntoIterator<Item = T>,
 945        cx: &mut Context<Self>,
 946    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
 947    where
 948        T: Into<UserMessageContent>,
 949    {
 950        let model = self.model().context("No language model configured")?;
 951
 952        log::info!("Thread::send called with model: {:?}", model.name());
 953        self.advance_prompt_id();
 954
 955        let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
 956        log::debug!("Thread::send content: {:?}", content);
 957
 958        self.messages
 959            .push(Message::User(UserMessage { id, content }));
 960        cx.notify();
 961
 962        log::info!("Total messages in thread: {}", self.messages.len());
 963        self.run_turn(cx)
 964    }
 965
 966    fn run_turn(
 967        &mut self,
 968        cx: &mut Context<Self>,
 969    ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
 970        self.cancel(cx);
 971
 972        let model = self.model.clone().context("No language model configured")?;
 973        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
 974        let event_stream = ThreadEventStream(events_tx);
 975        let message_ix = self.messages.len().saturating_sub(1);
 976        self.tool_use_limit_reached = false;
 977        self.running_turn = Some(RunningTurn {
 978            event_stream: event_stream.clone(),
 979            _task: cx.spawn(async move |this, cx| {
 980                log::info!("Starting agent turn execution");
 981                let turn_result: Result<()> = async {
 982                    let mut completion_intent = CompletionIntent::UserPrompt;
 983                    loop {
 984                        log::debug!(
 985                            "Building completion request with intent: {:?}",
 986                            completion_intent
 987                        );
 988                        let request = this.update(cx, |this, cx| {
 989                            this.build_completion_request(completion_intent, cx)
 990                        })??;
 991
 992                        log::info!("Calling model.stream_completion");
 993                        let mut events = model.stream_completion(request, cx).await?;
 994                        log::debug!("Stream completion started successfully");
 995
 996                        let mut tool_use_limit_reached = false;
 997                        let mut tool_uses = FuturesUnordered::new();
 998                        while let Some(event) = events.next().await {
 999                            match event? {
1000                                LanguageModelCompletionEvent::StatusUpdate(
1001                                    CompletionRequestStatus::ToolUseLimitReached,
1002                                ) => {
1003                                    tool_use_limit_reached = true;
1004                                }
1005                                LanguageModelCompletionEvent::Stop(reason) => {
1006                                    event_stream.send_stop(reason);
1007                                    if reason == StopReason::Refusal {
1008                                        this.update(cx, |this, cx| {
1009                                            this.flush_pending_message(cx);
1010                                            this.messages.truncate(message_ix);
1011                                        })?;
1012                                        return Ok(());
1013                                    }
1014                                }
1015                                event => {
1016                                    log::trace!("Received completion event: {:?}", event);
1017                                    this.update(cx, |this, cx| {
1018                                        tool_uses.extend(this.handle_streamed_completion_event(
1019                                            event,
1020                                            &event_stream,
1021                                            cx,
1022                                        ));
1023                                    })
1024                                    .ok();
1025                                }
1026                            }
1027                        }
1028
1029                        let used_tools = tool_uses.is_empty();
1030                        while let Some(tool_result) = tool_uses.next().await {
1031                            log::info!("Tool finished {:?}", tool_result);
1032
1033                            event_stream.update_tool_call_fields(
1034                                &tool_result.tool_use_id,
1035                                acp::ToolCallUpdateFields {
1036                                    status: Some(if tool_result.is_error {
1037                                        acp::ToolCallStatus::Failed
1038                                    } else {
1039                                        acp::ToolCallStatus::Completed
1040                                    }),
1041                                    raw_output: tool_result.output.clone(),
1042                                    ..Default::default()
1043                                },
1044                            );
1045                            this.update(cx, |this, _cx| {
1046                                this.pending_message()
1047                                    .tool_results
1048                                    .insert(tool_result.tool_use_id.clone(), tool_result);
1049                            })
1050                            .ok();
1051                        }
1052
1053                        if tool_use_limit_reached {
1054                            log::info!("Tool use limit reached, completing turn");
1055                            this.update(cx, |this, _cx| this.tool_use_limit_reached = true)?;
1056                            return Err(language_model::ToolUseLimitReachedError.into());
1057                        } else if used_tools {
1058                            log::info!("No tool uses found, completing turn");
1059                            return Ok(());
1060                        } else {
1061                            this.update(cx, |this, cx| this.flush_pending_message(cx))?;
1062                            completion_intent = CompletionIntent::ToolResults;
1063                        }
1064                    }
1065                }
1066                .await;
1067
1068                if let Err(error) = turn_result {
1069                    log::error!("Turn execution failed: {:?}", error);
1070                    event_stream.send_error(error);
1071                } else {
1072                    log::info!("Turn execution completed successfully");
1073                }
1074
1075                this.update(cx, |this, cx| {
1076                    this.flush_pending_message(cx);
1077                    this.running_turn.take();
1078                })
1079                .ok();
1080            }),
1081        });
1082        Ok(events_rx)
1083    }
1084
1085    pub fn generate_title_if_needed(
1086        &mut self,
1087        cx: &mut Context<Self>,
1088    ) -> Option<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1089        if !matches!(self.title, ThreadTitle::None) {
1090            return None;
1091        }
1092
1093        // todo!() copy logic from agent1 re: tool calls, etc.?
1094        if self.messages.len() < 2 {
1095            return None;
1096        }
1097        let Some(model) = self.summarization_model.clone() else {
1098            return None;
1099        };
1100        let (tx, rx) = mpsc::unbounded();
1101
1102        self.generate_title(model, ThreadEventStream(tx), cx);
1103        Some(rx)
1104    }
1105
1106    fn generate_title(
1107        &mut self,
1108        model: Arc<dyn LanguageModel>,
1109        event_stream: ThreadEventStream,
1110        cx: &mut Context<Self>,
1111    ) {
1112        let mut request = LanguageModelRequest {
1113            intent: Some(CompletionIntent::ThreadSummarization),
1114            temperature: AgentSettings::temperature_for_model(&model, cx),
1115            ..Default::default()
1116        };
1117
1118        for message in &self.messages {
1119            request.messages.extend(message.to_request());
1120        }
1121
1122        request.messages.push(LanguageModelRequestMessage {
1123            role: Role::User,
1124            content: vec![MessageContent::Text(SUMMARIZE_THREAD_PROMPT.into())],
1125            cache: false,
1126        });
1127
1128        let task = cx
1129            .spawn(async move |this, cx| {
1130                let result: anyhow::Result<SharedString> = async {
1131                    let mut messages = model.stream_completion(request, &cx).await?;
1132
1133                    let mut new_summary = String::new();
1134                    while let Some(event) = messages.next().await {
1135                        let Ok(event) = event else {
1136                            continue;
1137                        };
1138                        let text = match event {
1139                            LanguageModelCompletionEvent::Text(text) => text,
1140                            LanguageModelCompletionEvent::StatusUpdate(
1141                                CompletionRequestStatus::UsageUpdated { .. },
1142                            ) => {
1143                                // this.update(cx, |thread, cx| {
1144                                //     thread.update_model_request_usage(amount as u32, limit, cx);
1145                                // })?;
1146                                // todo!()? not sure if this is the right place to do this.
1147                                continue;
1148                            }
1149                            _ => continue,
1150                        };
1151
1152                        let mut lines = text.lines();
1153                        new_summary.extend(lines.next());
1154
1155                        // Stop if the LLM generated multiple lines.
1156                        if lines.next().is_some() {
1157                            break;
1158                        }
1159                    }
1160
1161                    anyhow::Ok(new_summary.into())
1162                }
1163                .await;
1164
1165                this.update(cx, |this, cx| {
1166                    if let Ok(title) = &result {
1167                        event_stream.send_title_update(title.clone());
1168                    }
1169                    this.title = ThreadTitle::Done(result);
1170                    cx.notify();
1171                })
1172                .log_err();
1173            })
1174            .shared();
1175
1176        self.title = ThreadTitle::Pending(task.clone());
1177        cx.notify()
1178    }
1179
1180    pub fn build_system_message(&self) -> LanguageModelRequestMessage {
1181        log::debug!("Building system message");
1182        let prompt = SystemPromptTemplate {
1183            project: &self.project_context.borrow(),
1184            available_tools: self.tools.keys().cloned().collect(),
1185        }
1186        .render(&self.templates)
1187        .context("failed to build system prompt")
1188        .expect("Invalid template");
1189        log::debug!("System message built");
1190        LanguageModelRequestMessage {
1191            role: Role::System,
1192            content: vec![prompt.into()],
1193            cache: true,
1194        }
1195    }
1196
1197    /// A helper method that's called on every streamed completion event.
1198    /// Returns an optional tool result task, which the main agentic loop in
1199    /// send will send back to the model when it resolves.
1200    fn handle_streamed_completion_event(
1201        &mut self,
1202        event: LanguageModelCompletionEvent,
1203        event_stream: &ThreadEventStream,
1204        cx: &mut Context<Self>,
1205    ) -> Option<Task<LanguageModelToolResult>> {
1206        log::trace!("Handling streamed completion event: {:?}", event);
1207        use LanguageModelCompletionEvent::*;
1208
1209        match event {
1210            StartMessage { .. } => {
1211                self.flush_pending_message(cx);
1212                self.pending_message = Some(AgentMessage::default());
1213            }
1214            Text(new_text) => self.handle_text_event(new_text, event_stream, cx),
1215            Thinking { text, signature } => {
1216                self.handle_thinking_event(text, signature, event_stream, cx)
1217            }
1218            RedactedThinking { data } => self.handle_redacted_thinking_event(data, cx),
1219            ToolUse(tool_use) => {
1220                return self.handle_tool_use_event(tool_use, event_stream, cx);
1221            }
1222            ToolUseJsonParseError {
1223                id,
1224                tool_name,
1225                raw_input,
1226                json_parse_error,
1227            } => {
1228                return Some(Task::ready(self.handle_tool_use_json_parse_error_event(
1229                    id,
1230                    tool_name,
1231                    raw_input,
1232                    json_parse_error,
1233                )));
1234            }
1235            UsageUpdate(_) | StatusUpdate(_) => {}
1236            Stop(_) => unreachable!(),
1237        }
1238
1239        None
1240    }
1241
1242    fn handle_text_event(
1243        &mut self,
1244        new_text: String,
1245        event_stream: &ThreadEventStream,
1246        cx: &mut Context<Self>,
1247    ) {
1248        event_stream.send_text(&new_text);
1249
1250        let last_message = self.pending_message();
1251        if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
1252            text.push_str(&new_text);
1253        } else {
1254            last_message
1255                .content
1256                .push(AgentMessageContent::Text(new_text));
1257        }
1258
1259        cx.notify();
1260    }
1261
1262    fn handle_thinking_event(
1263        &mut self,
1264        new_text: String,
1265        new_signature: Option<String>,
1266        event_stream: &ThreadEventStream,
1267        cx: &mut Context<Self>,
1268    ) {
1269        event_stream.send_thinking(&new_text);
1270
1271        let last_message = self.pending_message();
1272        if let Some(AgentMessageContent::Thinking { text, signature }) =
1273            last_message.content.last_mut()
1274        {
1275            text.push_str(&new_text);
1276            *signature = new_signature.or(signature.take());
1277        } else {
1278            last_message.content.push(AgentMessageContent::Thinking {
1279                text: new_text,
1280                signature: new_signature,
1281            });
1282        }
1283
1284        cx.notify();
1285    }
1286
1287    fn handle_redacted_thinking_event(&mut self, data: String, cx: &mut Context<Self>) {
1288        let last_message = self.pending_message();
1289        last_message
1290            .content
1291            .push(AgentMessageContent::RedactedThinking(data));
1292        cx.notify();
1293    }
1294
1295    fn handle_tool_use_event(
1296        &mut self,
1297        tool_use: LanguageModelToolUse,
1298        event_stream: &ThreadEventStream,
1299        cx: &mut Context<Self>,
1300    ) -> Option<Task<LanguageModelToolResult>> {
1301        cx.notify();
1302
1303        let tool = self.tools.get(tool_use.name.as_ref()).cloned();
1304        let mut title = SharedString::from(&tool_use.name);
1305        let mut kind = acp::ToolKind::Other;
1306        if let Some(tool) = tool.as_ref() {
1307            title = tool.initial_title(tool_use.input.clone());
1308            kind = tool.kind();
1309        }
1310
1311        // Ensure the last message ends in the current tool use
1312        let last_message = self.pending_message();
1313        let push_new_tool_use = last_message.content.last_mut().map_or(true, |content| {
1314            if let AgentMessageContent::ToolUse(last_tool_use) = content {
1315                if last_tool_use.id == tool_use.id {
1316                    *last_tool_use = tool_use.clone();
1317                    false
1318                } else {
1319                    true
1320                }
1321            } else {
1322                true
1323            }
1324        });
1325
1326        if push_new_tool_use {
1327            event_stream.send_tool_call(&tool_use.id, title, kind, tool_use.input.clone());
1328            last_message
1329                .content
1330                .push(AgentMessageContent::ToolUse(tool_use.clone()));
1331        } else {
1332            event_stream.update_tool_call_fields(
1333                &tool_use.id,
1334                acp::ToolCallUpdateFields {
1335                    title: Some(title.into()),
1336                    kind: Some(kind),
1337                    raw_input: Some(tool_use.input.clone()),
1338                    ..Default::default()
1339                },
1340            );
1341        }
1342
1343        if !tool_use.is_input_complete {
1344            return None;
1345        }
1346
1347        let Some(tool) = tool else {
1348            let content = format!("No tool named {} exists", tool_use.name);
1349            return Some(Task::ready(LanguageModelToolResult {
1350                content: LanguageModelToolResultContent::Text(Arc::from(content)),
1351                tool_use_id: tool_use.id,
1352                tool_name: tool_use.name,
1353                is_error: true,
1354                output: None,
1355            }));
1356        };
1357
1358        let fs = self.project.read(cx).fs().clone();
1359        let tool_event_stream =
1360            ToolCallEventStream::new(tool_use.id.clone(), event_stream.clone(), Some(fs));
1361        tool_event_stream.update_fields(acp::ToolCallUpdateFields {
1362            status: Some(acp::ToolCallStatus::InProgress),
1363            ..Default::default()
1364        });
1365        let supports_images = self.model().map_or(false, |model| model.supports_images());
1366        let tool_result = tool.run(tool_use.input, tool_event_stream, cx);
1367        log::info!("Running tool {}", tool_use.name);
1368        Some(cx.foreground_executor().spawn(async move {
1369            let tool_result = tool_result.await.and_then(|output| {
1370                if let LanguageModelToolResultContent::Image(_) = &output.llm_output {
1371                    if !supports_images {
1372                        return Err(anyhow!(
1373                            "Attempted to read an image, but this model doesn't support it.",
1374                        ));
1375                    }
1376                }
1377                Ok(output)
1378            });
1379
1380            match tool_result {
1381                Ok(output) => LanguageModelToolResult {
1382                    tool_use_id: tool_use.id,
1383                    tool_name: tool_use.name,
1384                    is_error: false,
1385                    content: output.llm_output,
1386                    output: Some(output.raw_output),
1387                },
1388                Err(error) => LanguageModelToolResult {
1389                    tool_use_id: tool_use.id,
1390                    tool_name: tool_use.name,
1391                    is_error: true,
1392                    content: LanguageModelToolResultContent::Text(Arc::from(error.to_string())),
1393                    output: None,
1394                },
1395            }
1396        }))
1397    }
1398
1399    fn handle_tool_use_json_parse_error_event(
1400        &mut self,
1401        tool_use_id: LanguageModelToolUseId,
1402        tool_name: Arc<str>,
1403        raw_input: Arc<str>,
1404        json_parse_error: String,
1405    ) -> LanguageModelToolResult {
1406        let tool_output = format!("Error parsing input JSON: {json_parse_error}");
1407        LanguageModelToolResult {
1408            tool_use_id,
1409            tool_name,
1410            is_error: true,
1411            content: LanguageModelToolResultContent::Text(tool_output.into()),
1412            output: Some(serde_json::Value::String(raw_input.to_string())),
1413        }
1414    }
1415
1416    fn pending_message(&mut self) -> &mut AgentMessage {
1417        self.pending_message.get_or_insert_default()
1418    }
1419
1420    fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
1421        let Some(mut message) = self.pending_message.take() else {
1422            return;
1423        };
1424
1425        for content in &message.content {
1426            let AgentMessageContent::ToolUse(tool_use) = content else {
1427                continue;
1428            };
1429
1430            if !message.tool_results.contains_key(&tool_use.id) {
1431                message.tool_results.insert(
1432                    tool_use.id.clone(),
1433                    LanguageModelToolResult {
1434                        tool_use_id: tool_use.id.clone(),
1435                        tool_name: tool_use.name.clone(),
1436                        is_error: true,
1437                        content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
1438                        output: None,
1439                    },
1440                );
1441            }
1442        }
1443
1444        self.messages.push(Message::Agent(message));
1445        cx.notify()
1446    }
1447
1448    pub(crate) fn build_completion_request(
1449        &self,
1450        completion_intent: CompletionIntent,
1451        cx: &mut App,
1452    ) -> Result<LanguageModelRequest> {
1453        let model = self.model().context("No language model configured")?;
1454
1455        log::debug!("Building completion request");
1456        log::debug!("Completion intent: {:?}", completion_intent);
1457        log::debug!("Completion mode: {:?}", self.completion_mode);
1458
1459        let messages = self.build_request_messages();
1460        log::info!("Request will include {} messages", messages.len());
1461
1462        let tools = if let Some(tools) = self.tools(cx).log_err() {
1463            tools
1464                .filter_map(|tool| {
1465                    let tool_name = tool.name().to_string();
1466                    log::trace!("Including tool: {}", tool_name);
1467                    Some(LanguageModelRequestTool {
1468                        name: tool_name,
1469                        description: tool.description().to_string(),
1470                        input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
1471                    })
1472                })
1473                .collect()
1474        } else {
1475            Vec::new()
1476        };
1477
1478        log::info!("Request includes {} tools", tools.len());
1479
1480        let request = LanguageModelRequest {
1481            thread_id: Some(self.id.to_string()),
1482            prompt_id: Some(self.prompt_id.to_string()),
1483            intent: Some(completion_intent),
1484            mode: Some(self.completion_mode.into()),
1485            messages,
1486            tools,
1487            tool_choice: None,
1488            stop: Vec::new(),
1489            temperature: AgentSettings::temperature_for_model(&model, cx),
1490            thinking_allowed: true,
1491        };
1492
1493        log::debug!("Completion request built successfully");
1494        Ok(request)
1495    }
1496
1497    fn tools<'a>(&'a self, cx: &'a App) -> Result<impl Iterator<Item = &'a Arc<dyn AnyAgentTool>>> {
1498        let model = self.model().context("No language model configured")?;
1499
1500        let profile = AgentSettings::get_global(cx)
1501            .profiles
1502            .get(&self.profile_id)
1503            .context("profile not found")?;
1504        let provider_id = model.provider_id();
1505
1506        Ok(self
1507            .tools
1508            .iter()
1509            .filter(move |(_, tool)| tool.supported_provider(&provider_id))
1510            .filter_map(|(tool_name, tool)| {
1511                if profile.is_tool_enabled(tool_name) {
1512                    Some(tool)
1513                } else {
1514                    None
1515                }
1516            })
1517            .chain(self.context_server_registry.read(cx).servers().flat_map(
1518                |(server_id, tools)| {
1519                    tools.iter().filter_map(|(tool_name, tool)| {
1520                        if profile.is_context_server_tool_enabled(&server_id.0, tool_name) {
1521                            Some(tool)
1522                        } else {
1523                            None
1524                        }
1525                    })
1526                },
1527            )))
1528    }
1529
1530    fn build_request_messages(&self) -> Vec<LanguageModelRequestMessage> {
1531        log::trace!(
1532            "Building request messages from {} thread messages",
1533            self.messages.len()
1534        );
1535        let mut messages = vec![self.build_system_message()];
1536        for message in &self.messages {
1537            messages.extend(message.to_request());
1538        }
1539
1540        if let Some(message) = self.pending_message.as_ref() {
1541            messages.extend(message.to_request());
1542        }
1543
1544        if let Some(last_user_message) = messages
1545            .iter_mut()
1546            .rev()
1547            .find(|message| message.role == Role::User)
1548        {
1549            last_user_message.cache = true;
1550        }
1551
1552        messages
1553    }
1554
1555    pub fn to_markdown(&self) -> String {
1556        let mut markdown = String::new();
1557        for (ix, message) in self.messages.iter().enumerate() {
1558            if ix > 0 {
1559                markdown.push('\n');
1560            }
1561            markdown.push_str(&message.to_markdown());
1562        }
1563
1564        if let Some(message) = self.pending_message.as_ref() {
1565            markdown.push('\n');
1566            markdown.push_str(&message.to_markdown());
1567        }
1568
1569        markdown
1570    }
1571
1572    fn advance_prompt_id(&mut self) {
1573        self.prompt_id = PromptId::new();
1574    }
1575}
1576
1577struct RunningTurn {
1578    /// Holds the task that handles agent interaction until the end of the turn.
1579    /// Survives across multiple requests as the model performs tool calls and
1580    /// we run tools, report their results.
1581    _task: Task<()>,
1582    /// The current event stream for the running turn. Used to report a final
1583    /// cancellation event if we cancel the turn.
1584    event_stream: ThreadEventStream,
1585}
1586
1587impl RunningTurn {
1588    fn cancel(self) {
1589        log::debug!("Cancelling in progress turn");
1590        self.event_stream.send_canceled();
1591    }
1592}
1593
1594pub trait AgentTool
1595where
1596    Self: 'static + Sized,
1597{
1598    type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
1599    type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
1600
1601    fn name(&self) -> SharedString;
1602
1603    fn description(&self) -> SharedString {
1604        let schema = schemars::schema_for!(Self::Input);
1605        SharedString::new(
1606            schema
1607                .get("description")
1608                .and_then(|description| description.as_str())
1609                .unwrap_or_default(),
1610        )
1611    }
1612
1613    fn kind(&self) -> acp::ToolKind;
1614
1615    /// The initial tool title to display. Can be updated during the tool run.
1616    fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString;
1617
1618    /// Returns the JSON schema that describes the tool's input.
1619    fn input_schema(&self) -> Schema {
1620        schemars::schema_for!(Self::Input)
1621    }
1622
1623    /// Some tools rely on a provider for the underlying billing or other reasons.
1624    /// Allow the tool to check if they are compatible, or should be filtered out.
1625    fn supported_provider(&self, _provider: &LanguageModelProviderId) -> bool {
1626        true
1627    }
1628
1629    /// Runs the tool with the provided input.
1630    fn run(
1631        self: Arc<Self>,
1632        input: Self::Input,
1633        event_stream: ToolCallEventStream,
1634        cx: &mut App,
1635    ) -> Task<Result<Self::Output>>;
1636
1637    /// Emits events for a previous execution of the tool.
1638    fn replay(
1639        &self,
1640        _input: Self::Input,
1641        _output: Self::Output,
1642        _event_stream: ToolCallEventStream,
1643        _cx: &mut App,
1644    ) -> Result<()> {
1645        Ok(())
1646    }
1647
1648    fn erase(self) -> Arc<dyn AnyAgentTool> {
1649        Arc::new(Erased(Arc::new(self)))
1650    }
1651}
1652
1653pub struct Erased<T>(T);
1654
1655pub struct AgentToolOutput {
1656    pub llm_output: LanguageModelToolResultContent,
1657    pub raw_output: serde_json::Value,
1658}
1659
1660pub trait AnyAgentTool {
1661    fn name(&self) -> SharedString;
1662    fn description(&self) -> SharedString;
1663    fn kind(&self) -> acp::ToolKind;
1664    fn initial_title(&self, input: serde_json::Value) -> SharedString;
1665    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
1666    fn supported_provider(&self, _provider: &LanguageModelProviderId) -> bool {
1667        true
1668    }
1669    fn run(
1670        self: Arc<Self>,
1671        input: serde_json::Value,
1672        event_stream: ToolCallEventStream,
1673        cx: &mut App,
1674    ) -> Task<Result<AgentToolOutput>>;
1675    fn replay(
1676        &self,
1677        input: serde_json::Value,
1678        output: serde_json::Value,
1679        event_stream: ToolCallEventStream,
1680        cx: &mut App,
1681    ) -> Result<()>;
1682}
1683
1684impl<T> AnyAgentTool for Erased<Arc<T>>
1685where
1686    T: AgentTool,
1687{
1688    fn name(&self) -> SharedString {
1689        self.0.name()
1690    }
1691
1692    fn description(&self) -> SharedString {
1693        self.0.description()
1694    }
1695
1696    fn kind(&self) -> agent_client_protocol::ToolKind {
1697        self.0.kind()
1698    }
1699
1700    fn initial_title(&self, input: serde_json::Value) -> SharedString {
1701        let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
1702        self.0.initial_title(parsed_input)
1703    }
1704
1705    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
1706        let mut json = serde_json::to_value(self.0.input_schema())?;
1707        adapt_schema_to_format(&mut json, format)?;
1708        Ok(json)
1709    }
1710
1711    fn supported_provider(&self, provider: &LanguageModelProviderId) -> bool {
1712        self.0.supported_provider(provider)
1713    }
1714
1715    fn run(
1716        self: Arc<Self>,
1717        input: serde_json::Value,
1718        event_stream: ToolCallEventStream,
1719        cx: &mut App,
1720    ) -> Task<Result<AgentToolOutput>> {
1721        cx.spawn(async move |cx| {
1722            let input = serde_json::from_value(input)?;
1723            let output = cx
1724                .update(|cx| self.0.clone().run(input, event_stream, cx))?
1725                .await?;
1726            let raw_output = serde_json::to_value(&output)?;
1727            Ok(AgentToolOutput {
1728                llm_output: output.into(),
1729                raw_output,
1730            })
1731        })
1732    }
1733
1734    fn replay(
1735        &self,
1736        input: serde_json::Value,
1737        output: serde_json::Value,
1738        event_stream: ToolCallEventStream,
1739        cx: &mut App,
1740    ) -> Result<()> {
1741        let input = serde_json::from_value(input)?;
1742        let output = serde_json::from_value(output)?;
1743        self.0.replay(input, output, event_stream, cx)
1744    }
1745}
1746
1747#[derive(Clone)]
1748struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
1749
1750impl ThreadEventStream {
1751    fn send_user_message(&self, message: &UserMessage) {
1752        self.0
1753            .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
1754            .ok();
1755    }
1756
1757    fn send_text(&self, text: &str) {
1758        self.0
1759            .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
1760            .ok();
1761    }
1762
1763    fn send_title_update(&self, text: SharedString) {
1764        self.0
1765            .unbounded_send(Ok(ThreadEvent::TitleUpdate(text)))
1766            .ok();
1767    }
1768
1769    fn send_thinking(&self, text: &str) {
1770        self.0
1771            .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
1772            .ok();
1773    }
1774
1775    fn send_tool_call(
1776        &self,
1777        id: &LanguageModelToolUseId,
1778        title: SharedString,
1779        kind: acp::ToolKind,
1780        input: serde_json::Value,
1781    ) {
1782        self.0
1783            .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
1784                id,
1785                title.to_string(),
1786                kind,
1787                input,
1788            ))))
1789            .ok();
1790    }
1791
1792    fn initial_tool_call(
1793        id: &LanguageModelToolUseId,
1794        title: String,
1795        kind: acp::ToolKind,
1796        input: serde_json::Value,
1797    ) -> acp::ToolCall {
1798        acp::ToolCall {
1799            id: acp::ToolCallId(id.to_string().into()),
1800            title,
1801            kind,
1802            status: acp::ToolCallStatus::Pending,
1803            content: vec![],
1804            locations: vec![],
1805            raw_input: Some(input),
1806            raw_output: None,
1807        }
1808    }
1809
1810    fn update_tool_call_fields(
1811        &self,
1812        tool_use_id: &LanguageModelToolUseId,
1813        fields: acp::ToolCallUpdateFields,
1814    ) {
1815        self.0
1816            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
1817                acp::ToolCallUpdate {
1818                    id: acp::ToolCallId(tool_use_id.to_string().into()),
1819                    fields,
1820                }
1821                .into(),
1822            )))
1823            .ok();
1824    }
1825
1826    fn send_stop(&self, reason: StopReason) {
1827        match reason {
1828            StopReason::EndTurn => {
1829                self.0
1830                    .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::EndTurn)))
1831                    .ok();
1832            }
1833            StopReason::MaxTokens => {
1834                self.0
1835                    .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::MaxTokens)))
1836                    .ok();
1837            }
1838            StopReason::Refusal => {
1839                self.0
1840                    .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Refusal)))
1841                    .ok();
1842            }
1843            StopReason::ToolUse => {}
1844        }
1845    }
1846
1847    fn send_canceled(&self) {
1848        self.0
1849            .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Canceled)))
1850            .ok();
1851    }
1852
1853    fn send_error(&self, error: impl Into<anyhow::Error>) {
1854        self.0.unbounded_send(Err(error.into())).ok();
1855    }
1856}
1857
1858#[derive(Clone)]
1859pub struct ToolCallEventStream {
1860    tool_use_id: LanguageModelToolUseId,
1861    stream: ThreadEventStream,
1862    fs: Option<Arc<dyn Fs>>,
1863}
1864
1865impl ToolCallEventStream {
1866    #[cfg(test)]
1867    pub fn test() -> (Self, ToolCallEventStreamReceiver) {
1868        let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1869
1870        let stream = ToolCallEventStream::new("test_id".into(), ThreadEventStream(events_tx), None);
1871
1872        (stream, ToolCallEventStreamReceiver(events_rx))
1873    }
1874
1875    fn new(
1876        tool_use_id: LanguageModelToolUseId,
1877        stream: ThreadEventStream,
1878        fs: Option<Arc<dyn Fs>>,
1879    ) -> Self {
1880        Self {
1881            tool_use_id,
1882            stream,
1883            fs,
1884        }
1885    }
1886
1887    pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
1888        self.stream
1889            .update_tool_call_fields(&self.tool_use_id, fields);
1890    }
1891
1892    pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
1893        self.stream
1894            .0
1895            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
1896                acp_thread::ToolCallUpdateDiff {
1897                    id: acp::ToolCallId(self.tool_use_id.to_string().into()),
1898                    diff,
1899                }
1900                .into(),
1901            )))
1902            .ok();
1903    }
1904
1905    pub fn update_terminal(&self, terminal: Entity<acp_thread::Terminal>) {
1906        self.stream
1907            .0
1908            .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
1909                acp_thread::ToolCallUpdateTerminal {
1910                    id: acp::ToolCallId(self.tool_use_id.to_string().into()),
1911                    terminal,
1912                }
1913                .into(),
1914            )))
1915            .ok();
1916    }
1917
1918    pub fn authorize(&self, title: impl Into<String>, cx: &mut App) -> Task<Result<()>> {
1919        if agent_settings::AgentSettings::get_global(cx).always_allow_tool_actions {
1920            return Task::ready(Ok(()));
1921        }
1922
1923        let (response_tx, response_rx) = oneshot::channel();
1924        self.stream
1925            .0
1926            .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
1927                ToolCallAuthorization {
1928                    tool_call: acp::ToolCallUpdate {
1929                        id: acp::ToolCallId(self.tool_use_id.to_string().into()),
1930                        fields: acp::ToolCallUpdateFields {
1931                            title: Some(title.into()),
1932                            ..Default::default()
1933                        },
1934                    },
1935                    options: vec![
1936                        acp::PermissionOption {
1937                            id: acp::PermissionOptionId("always_allow".into()),
1938                            name: "Always Allow".into(),
1939                            kind: acp::PermissionOptionKind::AllowAlways,
1940                        },
1941                        acp::PermissionOption {
1942                            id: acp::PermissionOptionId("allow".into()),
1943                            name: "Allow".into(),
1944                            kind: acp::PermissionOptionKind::AllowOnce,
1945                        },
1946                        acp::PermissionOption {
1947                            id: acp::PermissionOptionId("deny".into()),
1948                            name: "Deny".into(),
1949                            kind: acp::PermissionOptionKind::RejectOnce,
1950                        },
1951                    ],
1952                    response: response_tx,
1953                },
1954            )))
1955            .ok();
1956        let fs = self.fs.clone();
1957        cx.spawn(async move |cx| match response_rx.await?.0.as_ref() {
1958            "always_allow" => {
1959                if let Some(fs) = fs.clone() {
1960                    cx.update(|cx| {
1961                        update_settings_file::<AgentSettings>(fs, cx, |settings, _| {
1962                            settings.set_always_allow_tool_actions(true);
1963                        });
1964                    })?;
1965                }
1966
1967                Ok(())
1968            }
1969            "allow" => Ok(()),
1970            _ => Err(anyhow!("Permission to run tool denied by user")),
1971        })
1972    }
1973}
1974
1975#[cfg(test)]
1976pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
1977
1978#[cfg(test)]
1979impl ToolCallEventStreamReceiver {
1980    pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
1981        let event = self.0.next().await;
1982        if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
1983            auth
1984        } else {
1985            panic!("Expected ToolCallAuthorization but got: {:?}", event);
1986        }
1987    }
1988
1989    pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
1990        let event = self.0.next().await;
1991        if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
1992            update,
1993        )))) = event
1994        {
1995            update.terminal
1996        } else {
1997            panic!("Expected terminal but got: {:?}", event);
1998        }
1999    }
2000}
2001
2002#[cfg(test)]
2003impl std::ops::Deref for ToolCallEventStreamReceiver {
2004    type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
2005
2006    fn deref(&self) -> &Self::Target {
2007        &self.0
2008    }
2009}
2010
2011#[cfg(test)]
2012impl std::ops::DerefMut for ToolCallEventStreamReceiver {
2013    fn deref_mut(&mut self) -> &mut Self::Target {
2014        &mut self.0
2015    }
2016}
2017
2018impl From<&str> for UserMessageContent {
2019    fn from(text: &str) -> Self {
2020        Self::Text(text.into())
2021    }
2022}
2023
2024impl From<acp::ContentBlock> for UserMessageContent {
2025    fn from(value: acp::ContentBlock) -> Self {
2026        match value {
2027            acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
2028            acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
2029            acp::ContentBlock::Audio(_) => {
2030                // TODO
2031                Self::Text("[audio]".to_string())
2032            }
2033            acp::ContentBlock::ResourceLink(resource_link) => {
2034                match MentionUri::parse(&resource_link.uri) {
2035                    Ok(uri) => Self::Mention {
2036                        uri,
2037                        content: String::new(),
2038                    },
2039                    Err(err) => {
2040                        log::error!("Failed to parse mention link: {}", err);
2041                        Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
2042                    }
2043                }
2044            }
2045            acp::ContentBlock::Resource(resource) => match resource.resource {
2046                acp::EmbeddedResourceResource::TextResourceContents(resource) => {
2047                    match MentionUri::parse(&resource.uri) {
2048                        Ok(uri) => Self::Mention {
2049                            uri,
2050                            content: resource.text,
2051                        },
2052                        Err(err) => {
2053                            log::error!("Failed to parse mention link: {}", err);
2054                            Self::Text(
2055                                MarkdownCodeBlock {
2056                                    tag: &resource.uri,
2057                                    text: &resource.text,
2058                                }
2059                                .to_string(),
2060                            )
2061                        }
2062                    }
2063                }
2064                acp::EmbeddedResourceResource::BlobResourceContents(_) => {
2065                    // TODO
2066                    Self::Text("[blob]".to_string())
2067                }
2068            },
2069        }
2070    }
2071}
2072
2073impl From<UserMessageContent> for acp::ContentBlock {
2074    fn from(content: UserMessageContent) -> Self {
2075        match content {
2076            UserMessageContent::Text(text) => acp::ContentBlock::Text(acp::TextContent {
2077                text,
2078                annotations: None,
2079            }),
2080            UserMessageContent::Image(image) => acp::ContentBlock::Image(acp::ImageContent {
2081                data: image.source.to_string(),
2082                mime_type: "image/png".to_string(),
2083                annotations: None,
2084                uri: None,
2085            }),
2086            UserMessageContent::Mention { .. } => {
2087                todo!()
2088            }
2089        }
2090    }
2091}
2092
2093fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
2094    LanguageModelImage {
2095        source: image_content.data.into(),
2096        // TODO: make this optional?
2097        size: gpui::Size::new(0.into(), 0.into()),
2098    }
2099}