1use crate::{
2 ContextServerRegistry, CopyPathTool, CreateDirectoryTool, DbLanguageModel, DbThread,
3 DeletePathTool, DiagnosticsTool, EditFileTool, FetchTool, FindPathTool, GrepTool,
4 ListDirectoryTool, MovePathTool, NowTool, OpenTool, ProjectSnapshot, ReadFileTool,
5 RestoreFileFromDiskTool, SaveFileTool, SubagentTool, SystemPromptTemplate, Template, Templates,
6 TerminalTool, ThinkingTool, ToolPermissionDecision, WebSearchTool,
7 decide_permission_from_settings,
8};
9use acp_thread::{MentionUri, UserMessageId};
10use action_log::ActionLog;
11use feature_flags::{FeatureFlagAppExt as _, SubagentsFeatureFlag};
12
13use agent_client_protocol as acp;
14use agent_settings::{
15 AgentProfileId, AgentProfileSettings, AgentSettings, SUMMARIZE_THREAD_DETAILED_PROMPT,
16 SUMMARIZE_THREAD_PROMPT,
17};
18use anyhow::{Context as _, Result, anyhow};
19use chrono::{DateTime, Utc};
20use client::UserStore;
21use cloud_llm_client::{CompletionIntent, Plan};
22use collections::{HashMap, HashSet, IndexMap};
23use fs::Fs;
24use futures::stream;
25use futures::{
26 FutureExt,
27 channel::{mpsc, oneshot},
28 future::Shared,
29 stream::FuturesUnordered,
30};
31use gpui::{
32 App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task, WeakEntity,
33};
34use language_model::{
35 LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelId,
36 LanguageModelImage, LanguageModelProviderId, LanguageModelRegistry, LanguageModelRequest,
37 LanguageModelRequestMessage, LanguageModelRequestTool, LanguageModelToolResult,
38 LanguageModelToolResultContent, LanguageModelToolSchemaFormat, LanguageModelToolUse,
39 LanguageModelToolUseId, Role, SelectedModel, StopReason, TokenUsage, ZED_CLOUD_PROVIDER_ID,
40};
41use project::Project;
42use prompt_store::ProjectContext;
43use schemars::{JsonSchema, Schema};
44use serde::{Deserialize, Serialize};
45use settings::{LanguageModelSelection, Settings, ToolPermissionMode, update_settings_file};
46use smol::stream::StreamExt;
47use std::{
48 collections::BTreeMap,
49 ops::RangeInclusive,
50 path::Path,
51 rc::Rc,
52 sync::Arc,
53 time::{Duration, Instant},
54};
55use std::{fmt::Write, path::PathBuf};
56use util::{ResultExt, debug_panic, markdown::MarkdownCodeBlock, paths::PathStyle};
57use uuid::Uuid;
58
59const TOOL_CANCELED_MESSAGE: &str = "Tool canceled by user";
60pub const MAX_TOOL_NAME_LENGTH: usize = 64;
61pub const MAX_SUBAGENT_DEPTH: u8 = 4;
62pub const MAX_PARALLEL_SUBAGENTS: usize = 8;
63
64/// Context passed to a subagent thread for lifecycle management
65#[derive(Clone)]
66pub struct SubagentContext {
67 /// ID of the parent thread
68 pub parent_thread_id: acp::SessionId,
69
70 /// ID of the tool call that spawned this subagent
71 pub tool_use_id: LanguageModelToolUseId,
72
73 /// Current depth level (0 = root agent, 1 = first-level subagent, etc.)
74 pub depth: u8,
75
76 /// Prompt to send when subagent completes successfully
77 pub summary_prompt: String,
78
79 /// Prompt to send when context is running low (≤25% remaining)
80 pub context_low_prompt: String,
81}
82
83/// The ID of the user prompt that initiated a request.
84///
85/// This equates to the user physically submitting a message to the model (e.g., by pressing the Enter key).
86#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
87pub struct PromptId(Arc<str>);
88
89impl PromptId {
90 pub fn new() -> Self {
91 Self(Uuid::new_v4().to_string().into())
92 }
93}
94
95impl std::fmt::Display for PromptId {
96 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97 write!(f, "{}", self.0)
98 }
99}
100
101pub(crate) const MAX_RETRY_ATTEMPTS: u8 = 4;
102pub(crate) const BASE_RETRY_DELAY: Duration = Duration::from_secs(5);
103
104#[derive(Debug, Clone)]
105enum RetryStrategy {
106 ExponentialBackoff {
107 initial_delay: Duration,
108 max_attempts: u8,
109 },
110 Fixed {
111 delay: Duration,
112 max_attempts: u8,
113 },
114}
115
116#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117pub enum Message {
118 User(UserMessage),
119 Agent(AgentMessage),
120 Resume,
121}
122
123impl Message {
124 pub fn as_agent_message(&self) -> Option<&AgentMessage> {
125 match self {
126 Message::Agent(agent_message) => Some(agent_message),
127 _ => None,
128 }
129 }
130
131 pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
132 match self {
133 Message::User(message) => {
134 if message.content.is_empty() {
135 vec![]
136 } else {
137 vec![message.to_request()]
138 }
139 }
140 Message::Agent(message) => message.to_request(),
141 Message::Resume => vec![LanguageModelRequestMessage {
142 role: Role::User,
143 content: vec!["Continue where you left off".into()],
144 cache: false,
145 reasoning_details: None,
146 }],
147 }
148 }
149
150 pub fn to_markdown(&self) -> String {
151 match self {
152 Message::User(message) => message.to_markdown(),
153 Message::Agent(message) => message.to_markdown(),
154 Message::Resume => "[resume]\n".into(),
155 }
156 }
157
158 pub fn role(&self) -> Role {
159 match self {
160 Message::User(_) | Message::Resume => Role::User,
161 Message::Agent(_) => Role::Assistant,
162 }
163 }
164}
165
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
167pub struct UserMessage {
168 pub id: UserMessageId,
169 pub content: Vec<UserMessageContent>,
170}
171
172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173pub enum UserMessageContent {
174 Text(String),
175 Mention { uri: MentionUri, content: String },
176 Image(LanguageModelImage),
177}
178
179impl UserMessage {
180 pub fn to_markdown(&self) -> String {
181 let mut markdown = String::from("## User\n\n");
182
183 for content in &self.content {
184 match content {
185 UserMessageContent::Text(text) => {
186 markdown.push_str(text);
187 markdown.push('\n');
188 }
189 UserMessageContent::Image(_) => {
190 markdown.push_str("<image />\n");
191 }
192 UserMessageContent::Mention { uri, content } => {
193 if !content.is_empty() {
194 let _ = writeln!(&mut markdown, "{}\n\n{}", uri.as_link(), content);
195 } else {
196 let _ = writeln!(&mut markdown, "{}", uri.as_link());
197 }
198 }
199 }
200 }
201
202 markdown
203 }
204
205 fn to_request(&self) -> LanguageModelRequestMessage {
206 let mut message = LanguageModelRequestMessage {
207 role: Role::User,
208 content: Vec::with_capacity(self.content.len()),
209 cache: false,
210 reasoning_details: None,
211 };
212
213 const OPEN_CONTEXT: &str = "<context>\n\
214 The following items were attached by the user. \
215 They are up-to-date and don't need to be re-read.\n\n";
216
217 const OPEN_FILES_TAG: &str = "<files>";
218 const OPEN_DIRECTORIES_TAG: &str = "<directories>";
219 const OPEN_SYMBOLS_TAG: &str = "<symbols>";
220 const OPEN_SELECTIONS_TAG: &str = "<selections>";
221 const OPEN_THREADS_TAG: &str = "<threads>";
222 const OPEN_FETCH_TAG: &str = "<fetched_urls>";
223 const OPEN_RULES_TAG: &str =
224 "<rules>\nThe user has specified the following rules that should be applied:\n";
225
226 let mut file_context = OPEN_FILES_TAG.to_string();
227 let mut directory_context = OPEN_DIRECTORIES_TAG.to_string();
228 let mut symbol_context = OPEN_SYMBOLS_TAG.to_string();
229 let mut selection_context = OPEN_SELECTIONS_TAG.to_string();
230 let mut thread_context = OPEN_THREADS_TAG.to_string();
231 let mut fetch_context = OPEN_FETCH_TAG.to_string();
232 let mut rules_context = OPEN_RULES_TAG.to_string();
233
234 for chunk in &self.content {
235 let chunk = match chunk {
236 UserMessageContent::Text(text) => {
237 language_model::MessageContent::Text(text.clone())
238 }
239 UserMessageContent::Image(value) => {
240 language_model::MessageContent::Image(value.clone())
241 }
242 UserMessageContent::Mention { uri, content } => {
243 match uri {
244 MentionUri::File { abs_path } => {
245 write!(
246 &mut file_context,
247 "\n{}",
248 MarkdownCodeBlock {
249 tag: &codeblock_tag(abs_path, None),
250 text: &content.to_string(),
251 }
252 )
253 .ok();
254 }
255 MentionUri::PastedImage => {
256 debug_panic!("pasted image URI should not be used in mention content")
257 }
258 MentionUri::Directory { .. } => {
259 write!(&mut directory_context, "\n{}\n", content).ok();
260 }
261 MentionUri::Symbol {
262 abs_path: path,
263 line_range,
264 ..
265 } => {
266 write!(
267 &mut symbol_context,
268 "\n{}",
269 MarkdownCodeBlock {
270 tag: &codeblock_tag(path, Some(line_range)),
271 text: content
272 }
273 )
274 .ok();
275 }
276 MentionUri::Selection {
277 abs_path: path,
278 line_range,
279 ..
280 } => {
281 write!(
282 &mut selection_context,
283 "\n{}",
284 MarkdownCodeBlock {
285 tag: &codeblock_tag(
286 path.as_deref().unwrap_or("Untitled".as_ref()),
287 Some(line_range)
288 ),
289 text: content
290 }
291 )
292 .ok();
293 }
294 MentionUri::Thread { .. } => {
295 write!(&mut thread_context, "\n{}\n", content).ok();
296 }
297 MentionUri::TextThread { .. } => {
298 write!(&mut thread_context, "\n{}\n", content).ok();
299 }
300 MentionUri::Rule { .. } => {
301 write!(
302 &mut rules_context,
303 "\n{}",
304 MarkdownCodeBlock {
305 tag: "",
306 text: content
307 }
308 )
309 .ok();
310 }
311 MentionUri::Fetch { url } => {
312 write!(&mut fetch_context, "\nFetch: {}\n\n{}", url, content).ok();
313 }
314 }
315
316 language_model::MessageContent::Text(uri.as_link().to_string())
317 }
318 };
319
320 message.content.push(chunk);
321 }
322
323 let len_before_context = message.content.len();
324
325 if file_context.len() > OPEN_FILES_TAG.len() {
326 file_context.push_str("</files>\n");
327 message
328 .content
329 .push(language_model::MessageContent::Text(file_context));
330 }
331
332 if directory_context.len() > OPEN_DIRECTORIES_TAG.len() {
333 directory_context.push_str("</directories>\n");
334 message
335 .content
336 .push(language_model::MessageContent::Text(directory_context));
337 }
338
339 if symbol_context.len() > OPEN_SYMBOLS_TAG.len() {
340 symbol_context.push_str("</symbols>\n");
341 message
342 .content
343 .push(language_model::MessageContent::Text(symbol_context));
344 }
345
346 if selection_context.len() > OPEN_SELECTIONS_TAG.len() {
347 selection_context.push_str("</selections>\n");
348 message
349 .content
350 .push(language_model::MessageContent::Text(selection_context));
351 }
352
353 if thread_context.len() > OPEN_THREADS_TAG.len() {
354 thread_context.push_str("</threads>\n");
355 message
356 .content
357 .push(language_model::MessageContent::Text(thread_context));
358 }
359
360 if fetch_context.len() > OPEN_FETCH_TAG.len() {
361 fetch_context.push_str("</fetched_urls>\n");
362 message
363 .content
364 .push(language_model::MessageContent::Text(fetch_context));
365 }
366
367 if rules_context.len() > OPEN_RULES_TAG.len() {
368 rules_context.push_str("</user_rules>\n");
369 message
370 .content
371 .push(language_model::MessageContent::Text(rules_context));
372 }
373
374 if message.content.len() > len_before_context {
375 message.content.insert(
376 len_before_context,
377 language_model::MessageContent::Text(OPEN_CONTEXT.into()),
378 );
379 message
380 .content
381 .push(language_model::MessageContent::Text("</context>".into()));
382 }
383
384 message
385 }
386}
387
388fn codeblock_tag(full_path: &Path, line_range: Option<&RangeInclusive<u32>>) -> String {
389 let mut result = String::new();
390
391 if let Some(extension) = full_path.extension().and_then(|ext| ext.to_str()) {
392 let _ = write!(result, "{} ", extension);
393 }
394
395 let _ = write!(result, "{}", full_path.display());
396
397 if let Some(range) = line_range {
398 if range.start() == range.end() {
399 let _ = write!(result, ":{}", range.start() + 1);
400 } else {
401 let _ = write!(result, ":{}-{}", range.start() + 1, range.end() + 1);
402 }
403 }
404
405 result
406}
407
408impl AgentMessage {
409 pub fn to_markdown(&self) -> String {
410 let mut markdown = String::from("## Assistant\n\n");
411
412 for content in &self.content {
413 match content {
414 AgentMessageContent::Text(text) => {
415 markdown.push_str(text);
416 markdown.push('\n');
417 }
418 AgentMessageContent::Thinking { text, .. } => {
419 markdown.push_str("<think>");
420 markdown.push_str(text);
421 markdown.push_str("</think>\n");
422 }
423 AgentMessageContent::RedactedThinking(_) => {
424 markdown.push_str("<redacted_thinking />\n")
425 }
426 AgentMessageContent::ToolUse(tool_use) => {
427 markdown.push_str(&format!(
428 "**Tool Use**: {} (ID: {})\n",
429 tool_use.name, tool_use.id
430 ));
431 markdown.push_str(&format!(
432 "{}\n",
433 MarkdownCodeBlock {
434 tag: "json",
435 text: &format!("{:#}", tool_use.input)
436 }
437 ));
438 }
439 }
440 }
441
442 for tool_result in self.tool_results.values() {
443 markdown.push_str(&format!(
444 "**Tool Result**: {} (ID: {})\n\n",
445 tool_result.tool_name, tool_result.tool_use_id
446 ));
447 if tool_result.is_error {
448 markdown.push_str("**ERROR:**\n");
449 }
450
451 match &tool_result.content {
452 LanguageModelToolResultContent::Text(text) => {
453 writeln!(markdown, "{text}\n").ok();
454 }
455 LanguageModelToolResultContent::Image(_) => {
456 writeln!(markdown, "<image />\n").ok();
457 }
458 }
459
460 if let Some(output) = tool_result.output.as_ref() {
461 writeln!(
462 markdown,
463 "**Debug Output**:\n\n```json\n{}\n```\n",
464 serde_json::to_string_pretty(output).unwrap()
465 )
466 .unwrap();
467 }
468 }
469
470 markdown
471 }
472
473 pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
474 let mut assistant_message = LanguageModelRequestMessage {
475 role: Role::Assistant,
476 content: Vec::with_capacity(self.content.len()),
477 cache: false,
478 reasoning_details: self.reasoning_details.clone(),
479 };
480 for chunk in &self.content {
481 match chunk {
482 AgentMessageContent::Text(text) => {
483 assistant_message
484 .content
485 .push(language_model::MessageContent::Text(text.clone()));
486 }
487 AgentMessageContent::Thinking { text, signature } => {
488 assistant_message
489 .content
490 .push(language_model::MessageContent::Thinking {
491 text: text.clone(),
492 signature: signature.clone(),
493 });
494 }
495 AgentMessageContent::RedactedThinking(value) => {
496 assistant_message.content.push(
497 language_model::MessageContent::RedactedThinking(value.clone()),
498 );
499 }
500 AgentMessageContent::ToolUse(tool_use) => {
501 if self.tool_results.contains_key(&tool_use.id) {
502 assistant_message
503 .content
504 .push(language_model::MessageContent::ToolUse(tool_use.clone()));
505 }
506 }
507 };
508 }
509
510 let mut user_message = LanguageModelRequestMessage {
511 role: Role::User,
512 content: Vec::new(),
513 cache: false,
514 reasoning_details: None,
515 };
516
517 for tool_result in self.tool_results.values() {
518 let mut tool_result = tool_result.clone();
519 // Surprisingly, the API fails if we return an empty string here.
520 // It thinks we are sending a tool use without a tool result.
521 if tool_result.content.is_empty() {
522 tool_result.content = "<Tool returned an empty string>".into();
523 }
524 user_message
525 .content
526 .push(language_model::MessageContent::ToolResult(tool_result));
527 }
528
529 let mut messages = Vec::new();
530 if !assistant_message.content.is_empty() {
531 messages.push(assistant_message);
532 }
533 if !user_message.content.is_empty() {
534 messages.push(user_message);
535 }
536 messages
537 }
538}
539
540#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
541pub struct AgentMessage {
542 pub content: Vec<AgentMessageContent>,
543 pub tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
544 pub reasoning_details: Option<serde_json::Value>,
545}
546
547#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
548pub enum AgentMessageContent {
549 Text(String),
550 Thinking {
551 text: String,
552 signature: Option<String>,
553 },
554 RedactedThinking(String),
555 ToolUse(LanguageModelToolUse),
556}
557
558pub trait TerminalHandle {
559 fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId>;
560 fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse>;
561 fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>>;
562 fn kill(&self, cx: &AsyncApp) -> Result<()>;
563 fn was_stopped_by_user(&self, cx: &AsyncApp) -> Result<bool>;
564}
565
566pub trait ThreadEnvironment {
567 fn create_terminal(
568 &self,
569 command: String,
570 cwd: Option<PathBuf>,
571 output_byte_limit: Option<u64>,
572 cx: &mut AsyncApp,
573 ) -> Task<Result<Rc<dyn TerminalHandle>>>;
574}
575
576#[derive(Debug)]
577pub enum ThreadEvent {
578 UserMessage(UserMessage),
579 AgentText(String),
580 AgentThinking(String),
581 ToolCall(acp::ToolCall),
582 ToolCallUpdate(acp_thread::ToolCallUpdate),
583 ToolCallAuthorization(ToolCallAuthorization),
584 Retry(acp_thread::RetryStatus),
585 Stop(acp::StopReason),
586}
587
588#[derive(Debug)]
589pub struct NewTerminal {
590 pub command: String,
591 pub output_byte_limit: Option<u64>,
592 pub cwd: Option<PathBuf>,
593 pub response: oneshot::Sender<Result<Entity<acp_thread::Terminal>>>,
594}
595
596#[derive(Debug, Clone)]
597pub struct ToolPermissionContext {
598 pub tool_name: String,
599 pub input_value: String,
600}
601
602impl ToolPermissionContext {
603 pub fn new(tool_name: impl Into<String>, input_value: impl Into<String>) -> Self {
604 Self {
605 tool_name: tool_name.into(),
606 input_value: input_value.into(),
607 }
608 }
609
610 /// Builds the permission options for this tool context.
611 ///
612 /// This is the canonical source for permission option generation.
613 /// Tests should use this function rather than manually constructing options.
614 pub fn build_permission_options(&self) -> Vec<acp::PermissionOption> {
615 use crate::pattern_extraction::*;
616
617 let tool_name = &self.tool_name;
618 let input_value = &self.input_value;
619
620 let (pattern, pattern_display) = match tool_name.as_str() {
621 "terminal" => (
622 extract_terminal_pattern(input_value),
623 extract_terminal_pattern_display(input_value),
624 ),
625 "edit_file" | "delete_path" | "move_path" | "create_directory" | "save_file" => (
626 extract_path_pattern(input_value),
627 extract_path_pattern_display(input_value),
628 ),
629 "fetch" => (
630 extract_url_pattern(input_value),
631 extract_url_pattern_display(input_value),
632 ),
633 _ => (None, None),
634 };
635
636 let mut options = vec![acp::PermissionOption::new(
637 acp::PermissionOptionId::new(format!("always:{}", tool_name)),
638 format!("Always for {}", tool_name.replace('_', " ")),
639 acp::PermissionOptionKind::AllowAlways,
640 )];
641
642 if let (Some(pattern), Some(display)) = (pattern, pattern_display) {
643 let button_text = match tool_name.as_str() {
644 "terminal" => format!("Always for `{}` commands", display),
645 "fetch" => format!("Always for `{}`", display),
646 _ => format!("Always for `{}`", display),
647 };
648 options.push(acp::PermissionOption::new(
649 acp::PermissionOptionId::new(format!("always_pattern:{}:{}", tool_name, pattern)),
650 button_text,
651 acp::PermissionOptionKind::AllowAlways,
652 ));
653 }
654
655 options.push(acp::PermissionOption::new(
656 acp::PermissionOptionId::new("once"),
657 "Only this time",
658 acp::PermissionOptionKind::AllowOnce,
659 ));
660
661 options
662 }
663}
664
665#[derive(Debug)]
666pub struct ToolCallAuthorization {
667 pub tool_call: acp::ToolCallUpdate,
668 pub options: Vec<acp::PermissionOption>,
669 pub response: oneshot::Sender<acp::PermissionOptionId>,
670 pub context: Option<ToolPermissionContext>,
671}
672
673#[derive(Debug, thiserror::Error)]
674enum CompletionError {
675 #[error("max tokens")]
676 MaxTokens,
677 #[error("refusal")]
678 Refusal,
679 #[error(transparent)]
680 Other(#[from] anyhow::Error),
681}
682
683pub struct Thread {
684 id: acp::SessionId,
685 prompt_id: PromptId,
686 updated_at: DateTime<Utc>,
687 title: Option<SharedString>,
688 pending_title_generation: Option<Task<()>>,
689 pending_summary_generation: Option<Shared<Task<Option<SharedString>>>>,
690 summary: Option<SharedString>,
691 messages: Vec<Message>,
692 user_store: Entity<UserStore>,
693 /// Holds the task that handles agent interaction until the end of the turn.
694 /// Survives across multiple requests as the model performs tool calls and
695 /// we run tools, report their results.
696 running_turn: Option<RunningTurn>,
697 pending_message: Option<AgentMessage>,
698 tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
699 request_token_usage: HashMap<UserMessageId, language_model::TokenUsage>,
700 #[allow(unused)]
701 cumulative_token_usage: TokenUsage,
702 #[allow(unused)]
703 initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
704 context_server_registry: Entity<ContextServerRegistry>,
705 profile_id: AgentProfileId,
706 project_context: Entity<ProjectContext>,
707 templates: Arc<Templates>,
708 model: Option<Arc<dyn LanguageModel>>,
709 summarization_model: Option<Arc<dyn LanguageModel>>,
710 prompt_capabilities_tx: watch::Sender<acp::PromptCapabilities>,
711 pub(crate) prompt_capabilities_rx: watch::Receiver<acp::PromptCapabilities>,
712 pub(crate) project: Entity<Project>,
713 pub(crate) action_log: Entity<ActionLog>,
714 /// Tracks the last time files were read by the agent, to detect external modifications
715 pub(crate) file_read_times: HashMap<PathBuf, fs::MTime>,
716 /// True if this thread was imported from a shared thread and can be synced.
717 imported: bool,
718 /// If this is a subagent thread, contains context about the parent
719 subagent_context: Option<SubagentContext>,
720 /// Weak references to running subagent threads for cancellation propagation
721 running_subagents: Vec<WeakEntity<Thread>>,
722}
723
724impl Thread {
725 fn prompt_capabilities(model: Option<&dyn LanguageModel>) -> acp::PromptCapabilities {
726 let image = model.map_or(true, |model| model.supports_images());
727 acp::PromptCapabilities::new()
728 .image(image)
729 .embedded_context(true)
730 }
731
732 pub fn new(
733 project: Entity<Project>,
734 project_context: Entity<ProjectContext>,
735 context_server_registry: Entity<ContextServerRegistry>,
736 templates: Arc<Templates>,
737 model: Option<Arc<dyn LanguageModel>>,
738 cx: &mut Context<Self>,
739 ) -> Self {
740 let profile_id = AgentSettings::get_global(cx).default_profile.clone();
741 let action_log = cx.new(|_cx| ActionLog::new(project.clone()));
742 let (prompt_capabilities_tx, prompt_capabilities_rx) =
743 watch::channel(Self::prompt_capabilities(model.as_deref()));
744 Self {
745 id: acp::SessionId::new(uuid::Uuid::new_v4().to_string()),
746 prompt_id: PromptId::new(),
747 updated_at: Utc::now(),
748 title: None,
749 pending_title_generation: None,
750 pending_summary_generation: None,
751 summary: None,
752 messages: Vec::new(),
753 user_store: project.read(cx).user_store(),
754 running_turn: None,
755 pending_message: None,
756 tools: BTreeMap::default(),
757 request_token_usage: HashMap::default(),
758 cumulative_token_usage: TokenUsage::default(),
759 initial_project_snapshot: {
760 let project_snapshot = Self::project_snapshot(project.clone(), cx);
761 cx.foreground_executor()
762 .spawn(async move { Some(project_snapshot.await) })
763 .shared()
764 },
765 context_server_registry,
766 profile_id,
767 project_context,
768 templates,
769 model,
770 summarization_model: None,
771 prompt_capabilities_tx,
772 prompt_capabilities_rx,
773 project,
774 action_log,
775 file_read_times: HashMap::default(),
776 imported: false,
777 subagent_context: None,
778 running_subagents: Vec::new(),
779 }
780 }
781
782 pub fn new_subagent(
783 project: Entity<Project>,
784 project_context: Entity<ProjectContext>,
785 context_server_registry: Entity<ContextServerRegistry>,
786 templates: Arc<Templates>,
787 model: Arc<dyn LanguageModel>,
788 subagent_context: SubagentContext,
789 parent_tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
790 cx: &mut Context<Self>,
791 ) -> Self {
792 let profile_id = AgentSettings::get_global(cx).default_profile.clone();
793 let action_log = cx.new(|_cx| ActionLog::new(project.clone()));
794 let (prompt_capabilities_tx, prompt_capabilities_rx) =
795 watch::channel(Self::prompt_capabilities(Some(model.as_ref())));
796 Self {
797 id: acp::SessionId::new(uuid::Uuid::new_v4().to_string()),
798 prompt_id: PromptId::new(),
799 updated_at: Utc::now(),
800 title: None,
801 pending_title_generation: None,
802 pending_summary_generation: None,
803 summary: None,
804 messages: Vec::new(),
805 user_store: project.read(cx).user_store(),
806 running_turn: None,
807 pending_message: None,
808 tools: parent_tools,
809 request_token_usage: HashMap::default(),
810 cumulative_token_usage: TokenUsage::default(),
811 initial_project_snapshot: Task::ready(None).shared(),
812 context_server_registry,
813 profile_id,
814 project_context,
815 templates,
816 model: Some(model),
817 summarization_model: None,
818 prompt_capabilities_tx,
819 prompt_capabilities_rx,
820 project,
821 action_log,
822 file_read_times: HashMap::default(),
823 imported: false,
824 subagent_context: Some(subagent_context),
825 running_subagents: Vec::new(),
826 }
827 }
828
829 pub fn id(&self) -> &acp::SessionId {
830 &self.id
831 }
832
833 /// Returns true if this thread was imported from a shared thread.
834 pub fn is_imported(&self) -> bool {
835 self.imported
836 }
837
838 pub fn replay(
839 &mut self,
840 cx: &mut Context<Self>,
841 ) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {
842 let (tx, rx) = mpsc::unbounded();
843 let stream = ThreadEventStream(tx);
844 for message in &self.messages {
845 match message {
846 Message::User(user_message) => stream.send_user_message(user_message),
847 Message::Agent(assistant_message) => {
848 for content in &assistant_message.content {
849 match content {
850 AgentMessageContent::Text(text) => stream.send_text(text),
851 AgentMessageContent::Thinking { text, .. } => {
852 stream.send_thinking(text)
853 }
854 AgentMessageContent::RedactedThinking(_) => {}
855 AgentMessageContent::ToolUse(tool_use) => {
856 self.replay_tool_call(
857 tool_use,
858 assistant_message.tool_results.get(&tool_use.id),
859 &stream,
860 cx,
861 );
862 }
863 }
864 }
865 }
866 Message::Resume => {}
867 }
868 }
869 rx
870 }
871
872 fn replay_tool_call(
873 &self,
874 tool_use: &LanguageModelToolUse,
875 tool_result: Option<&LanguageModelToolResult>,
876 stream: &ThreadEventStream,
877 cx: &mut Context<Self>,
878 ) {
879 let tool = self.tools.get(tool_use.name.as_ref()).cloned().or_else(|| {
880 self.context_server_registry
881 .read(cx)
882 .servers()
883 .find_map(|(_, tools)| {
884 if let Some(tool) = tools.get(tool_use.name.as_ref()) {
885 Some(tool.clone())
886 } else {
887 None
888 }
889 })
890 });
891
892 let Some(tool) = tool else {
893 stream
894 .0
895 .unbounded_send(Ok(ThreadEvent::ToolCall(
896 acp::ToolCall::new(tool_use.id.to_string(), tool_use.name.to_string())
897 .status(acp::ToolCallStatus::Failed)
898 .raw_input(tool_use.input.clone()),
899 )))
900 .ok();
901 return;
902 };
903
904 let title = tool.initial_title(tool_use.input.clone(), cx);
905 let kind = tool.kind();
906 stream.send_tool_call(
907 &tool_use.id,
908 &tool_use.name,
909 title,
910 kind,
911 tool_use.input.clone(),
912 );
913
914 let output = tool_result
915 .as_ref()
916 .and_then(|result| result.output.clone());
917 if let Some(output) = output.clone() {
918 // For replay, we use a dummy cancellation receiver since the tool already completed
919 let (_cancellation_tx, cancellation_rx) = watch::channel(false);
920 let tool_event_stream = ToolCallEventStream::new(
921 tool_use.id.clone(),
922 stream.clone(),
923 Some(self.project.read(cx).fs().clone()),
924 cancellation_rx,
925 );
926 tool.replay(tool_use.input.clone(), output, tool_event_stream, cx)
927 .log_err();
928 }
929
930 stream.update_tool_call_fields(
931 &tool_use.id,
932 acp::ToolCallUpdateFields::new()
933 .status(
934 tool_result
935 .as_ref()
936 .map_or(acp::ToolCallStatus::Failed, |result| {
937 if result.is_error {
938 acp::ToolCallStatus::Failed
939 } else {
940 acp::ToolCallStatus::Completed
941 }
942 }),
943 )
944 .raw_output(output),
945 );
946 }
947
948 pub fn from_db(
949 id: acp::SessionId,
950 db_thread: DbThread,
951 project: Entity<Project>,
952 project_context: Entity<ProjectContext>,
953 context_server_registry: Entity<ContextServerRegistry>,
954 templates: Arc<Templates>,
955 cx: &mut Context<Self>,
956 ) -> Self {
957 let profile_id = db_thread
958 .profile
959 .unwrap_or_else(|| AgentSettings::get_global(cx).default_profile.clone());
960
961 let mut model = LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
962 db_thread
963 .model
964 .and_then(|model| {
965 let model = SelectedModel {
966 provider: model.provider.clone().into(),
967 model: model.model.into(),
968 };
969 registry.select_model(&model, cx)
970 })
971 .or_else(|| registry.default_model())
972 .map(|model| model.model)
973 });
974
975 if model.is_none() {
976 model = Self::resolve_profile_model(&profile_id, cx);
977 }
978 if model.is_none() {
979 model = LanguageModelRegistry::global(cx).update(cx, |registry, _cx| {
980 registry.default_model().map(|model| model.model)
981 });
982 }
983
984 let (prompt_capabilities_tx, prompt_capabilities_rx) =
985 watch::channel(Self::prompt_capabilities(model.as_deref()));
986
987 let action_log = cx.new(|_| ActionLog::new(project.clone()));
988
989 Self {
990 id,
991 prompt_id: PromptId::new(),
992 title: if db_thread.title.is_empty() {
993 None
994 } else {
995 Some(db_thread.title.clone())
996 },
997 pending_title_generation: None,
998 pending_summary_generation: None,
999 summary: db_thread.detailed_summary,
1000 messages: db_thread.messages,
1001 user_store: project.read(cx).user_store(),
1002 running_turn: None,
1003 pending_message: None,
1004 tools: BTreeMap::default(),
1005 request_token_usage: db_thread.request_token_usage.clone(),
1006 cumulative_token_usage: db_thread.cumulative_token_usage,
1007 initial_project_snapshot: Task::ready(db_thread.initial_project_snapshot).shared(),
1008 context_server_registry,
1009 profile_id,
1010 project_context,
1011 templates,
1012 model,
1013 summarization_model: None,
1014 project,
1015 action_log,
1016 updated_at: db_thread.updated_at,
1017 prompt_capabilities_tx,
1018 prompt_capabilities_rx,
1019 file_read_times: HashMap::default(),
1020 imported: db_thread.imported,
1021 subagent_context: None,
1022 running_subagents: Vec::new(),
1023 }
1024 }
1025
1026 pub fn to_db(&self, cx: &App) -> Task<DbThread> {
1027 let initial_project_snapshot = self.initial_project_snapshot.clone();
1028 let mut thread = DbThread {
1029 title: self.title(),
1030 messages: self.messages.clone(),
1031 updated_at: self.updated_at,
1032 detailed_summary: self.summary.clone(),
1033 initial_project_snapshot: None,
1034 cumulative_token_usage: self.cumulative_token_usage,
1035 request_token_usage: self.request_token_usage.clone(),
1036 model: self.model.as_ref().map(|model| DbLanguageModel {
1037 provider: model.provider_id().to_string(),
1038 model: model.name().0.to_string(),
1039 }),
1040 profile: Some(self.profile_id.clone()),
1041 imported: self.imported,
1042 };
1043
1044 cx.background_spawn(async move {
1045 let initial_project_snapshot = initial_project_snapshot.await;
1046 thread.initial_project_snapshot = initial_project_snapshot;
1047 thread
1048 })
1049 }
1050
1051 /// Create a snapshot of the current project state including git information and unsaved buffers.
1052 fn project_snapshot(
1053 project: Entity<Project>,
1054 cx: &mut Context<Self>,
1055 ) -> Task<Arc<ProjectSnapshot>> {
1056 let task = project::telemetry_snapshot::TelemetrySnapshot::new(&project, cx);
1057 cx.spawn(async move |_, _| {
1058 let snapshot = task.await;
1059
1060 Arc::new(ProjectSnapshot {
1061 worktree_snapshots: snapshot.worktree_snapshots,
1062 timestamp: Utc::now(),
1063 })
1064 })
1065 }
1066
1067 pub fn project_context(&self) -> &Entity<ProjectContext> {
1068 &self.project_context
1069 }
1070
1071 pub fn project(&self) -> &Entity<Project> {
1072 &self.project
1073 }
1074
1075 pub fn action_log(&self) -> &Entity<ActionLog> {
1076 &self.action_log
1077 }
1078
1079 pub fn is_empty(&self) -> bool {
1080 self.messages.is_empty() && self.title.is_none()
1081 }
1082
1083 pub fn model(&self) -> Option<&Arc<dyn LanguageModel>> {
1084 self.model.as_ref()
1085 }
1086
1087 pub fn set_model(&mut self, model: Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
1088 let old_usage = self.latest_token_usage();
1089 self.model = Some(model);
1090 let new_caps = Self::prompt_capabilities(self.model.as_deref());
1091 let new_usage = self.latest_token_usage();
1092 if old_usage != new_usage {
1093 cx.emit(TokenUsageUpdated(new_usage));
1094 }
1095 self.prompt_capabilities_tx.send(new_caps).log_err();
1096 cx.notify()
1097 }
1098
1099 pub fn summarization_model(&self) -> Option<&Arc<dyn LanguageModel>> {
1100 self.summarization_model.as_ref()
1101 }
1102
1103 pub fn set_summarization_model(
1104 &mut self,
1105 model: Option<Arc<dyn LanguageModel>>,
1106 cx: &mut Context<Self>,
1107 ) {
1108 self.summarization_model = model;
1109 cx.notify()
1110 }
1111
1112 pub fn last_message(&self) -> Option<Message> {
1113 if let Some(message) = self.pending_message.clone() {
1114 Some(Message::Agent(message))
1115 } else {
1116 self.messages.last().cloned()
1117 }
1118 }
1119
1120 pub fn add_default_tools(
1121 &mut self,
1122 environment: Rc<dyn ThreadEnvironment>,
1123 cx: &mut Context<Self>,
1124 ) {
1125 let language_registry = self.project.read(cx).languages().clone();
1126 self.add_tool(CopyPathTool::new(self.project.clone()));
1127 self.add_tool(CreateDirectoryTool::new(self.project.clone()));
1128 self.add_tool(DeletePathTool::new(
1129 self.project.clone(),
1130 self.action_log.clone(),
1131 ));
1132 self.add_tool(DiagnosticsTool::new(self.project.clone()));
1133 self.add_tool(EditFileTool::new(
1134 self.project.clone(),
1135 cx.weak_entity(),
1136 language_registry,
1137 Templates::new(),
1138 ));
1139 self.add_tool(FetchTool::new(self.project.read(cx).client().http_client()));
1140 self.add_tool(FindPathTool::new(self.project.clone()));
1141 self.add_tool(GrepTool::new(self.project.clone()));
1142 self.add_tool(ListDirectoryTool::new(self.project.clone()));
1143 self.add_tool(MovePathTool::new(self.project.clone()));
1144 self.add_tool(NowTool);
1145 self.add_tool(OpenTool::new(self.project.clone()));
1146 self.add_tool(ReadFileTool::new(
1147 cx.weak_entity(),
1148 self.project.clone(),
1149 self.action_log.clone(),
1150 ));
1151 self.add_tool(SaveFileTool::new(self.project.clone()));
1152 self.add_tool(RestoreFileFromDiskTool::new(self.project.clone()));
1153 self.add_tool(TerminalTool::new(self.project.clone(), environment));
1154 self.add_tool(ThinkingTool);
1155 self.add_tool(WebSearchTool);
1156
1157 if cx.has_flag::<SubagentsFeatureFlag>() && self.depth() < MAX_SUBAGENT_DEPTH {
1158 let parent_tools = self.tools.clone();
1159 self.add_tool(SubagentTool::new(
1160 cx.weak_entity(),
1161 self.project.clone(),
1162 self.project_context.clone(),
1163 self.context_server_registry.clone(),
1164 self.templates.clone(),
1165 self.depth(),
1166 parent_tools,
1167 ));
1168 }
1169 }
1170
1171 pub fn add_tool<T: AgentTool>(&mut self, tool: T) {
1172 self.tools.insert(T::name().into(), tool.erase());
1173 }
1174
1175 pub fn remove_tool(&mut self, name: &str) -> bool {
1176 self.tools.remove(name).is_some()
1177 }
1178
1179 pub fn restrict_tools(&mut self, allowed: &collections::HashSet<SharedString>) {
1180 self.tools.retain(|name, _| allowed.contains(name));
1181 }
1182
1183 pub fn profile(&self) -> &AgentProfileId {
1184 &self.profile_id
1185 }
1186
1187 pub fn set_profile(&mut self, profile_id: AgentProfileId, cx: &mut Context<Self>) {
1188 if self.profile_id == profile_id {
1189 return;
1190 }
1191
1192 self.profile_id = profile_id;
1193
1194 // Swap to the profile's preferred model when available.
1195 if let Some(model) = Self::resolve_profile_model(&self.profile_id, cx) {
1196 self.set_model(model, cx);
1197 }
1198 }
1199
1200 pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
1201 for subagent in self.running_subagents.drain(..) {
1202 if let Some(subagent) = subagent.upgrade() {
1203 subagent.update(cx, |thread, cx| thread.cancel(cx)).detach();
1204 }
1205 }
1206
1207 let Some(running_turn) = self.running_turn.take() else {
1208 self.flush_pending_message(cx);
1209 return Task::ready(());
1210 };
1211
1212 let turn_task = running_turn.cancel();
1213
1214 cx.spawn(async move |this, cx| {
1215 turn_task.await;
1216 this.update(cx, |this, cx| {
1217 this.flush_pending_message(cx);
1218 })
1219 .ok();
1220 })
1221 }
1222
1223 fn update_token_usage(&mut self, update: language_model::TokenUsage, cx: &mut Context<Self>) {
1224 let Some(last_user_message) = self.last_user_message() else {
1225 return;
1226 };
1227
1228 self.request_token_usage
1229 .insert(last_user_message.id.clone(), update);
1230 cx.emit(TokenUsageUpdated(self.latest_token_usage()));
1231 cx.notify();
1232 }
1233
1234 pub fn truncate(&mut self, message_id: UserMessageId, cx: &mut Context<Self>) -> Result<()> {
1235 self.cancel(cx).detach();
1236 // Clear pending message since cancel will try to flush it asynchronously,
1237 // and we don't want that content to be added after we truncate
1238 self.pending_message.take();
1239 let Some(position) = self.messages.iter().position(
1240 |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
1241 ) else {
1242 return Err(anyhow!("Message not found"));
1243 };
1244
1245 for message in self.messages.drain(position..) {
1246 match message {
1247 Message::User(message) => {
1248 self.request_token_usage.remove(&message.id);
1249 }
1250 Message::Agent(_) | Message::Resume => {}
1251 }
1252 }
1253 self.clear_summary();
1254 cx.notify();
1255 Ok(())
1256 }
1257
1258 pub fn latest_request_token_usage(&self) -> Option<language_model::TokenUsage> {
1259 let last_user_message = self.last_user_message()?;
1260 let tokens = self.request_token_usage.get(&last_user_message.id)?;
1261 Some(*tokens)
1262 }
1263
1264 pub fn latest_token_usage(&self) -> Option<acp_thread::TokenUsage> {
1265 let usage = self.latest_request_token_usage()?;
1266 let model = self.model.clone()?;
1267 Some(acp_thread::TokenUsage {
1268 max_tokens: model.max_token_count(),
1269 used_tokens: usage.total_tokens(),
1270 input_tokens: usage.input_tokens,
1271 output_tokens: usage.output_tokens,
1272 })
1273 }
1274
1275 /// Get the total input token count as of the message before the given message.
1276 ///
1277 /// Returns `None` if:
1278 /// - `target_id` is the first message (no previous message)
1279 /// - The previous message hasn't received a response yet (no usage data)
1280 /// - `target_id` is not found in the messages
1281 pub fn tokens_before_message(&self, target_id: &UserMessageId) -> Option<u64> {
1282 let mut previous_user_message_id: Option<&UserMessageId> = None;
1283
1284 for message in &self.messages {
1285 if let Message::User(user_msg) = message {
1286 if &user_msg.id == target_id {
1287 let prev_id = previous_user_message_id?;
1288 let usage = self.request_token_usage.get(prev_id)?;
1289 return Some(usage.input_tokens);
1290 }
1291 previous_user_message_id = Some(&user_msg.id);
1292 }
1293 }
1294 None
1295 }
1296
1297 /// Look up the active profile and resolve its preferred model if one is configured.
1298 fn resolve_profile_model(
1299 profile_id: &AgentProfileId,
1300 cx: &mut Context<Self>,
1301 ) -> Option<Arc<dyn LanguageModel>> {
1302 let selection = AgentSettings::get_global(cx)
1303 .profiles
1304 .get(profile_id)?
1305 .default_model
1306 .clone()?;
1307 Self::resolve_model_from_selection(&selection, cx)
1308 }
1309
1310 /// Translate a stored model selection into the configured model from the registry.
1311 fn resolve_model_from_selection(
1312 selection: &LanguageModelSelection,
1313 cx: &mut Context<Self>,
1314 ) -> Option<Arc<dyn LanguageModel>> {
1315 let selected = SelectedModel {
1316 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
1317 model: LanguageModelId::from(selection.model.clone()),
1318 };
1319 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1320 registry
1321 .select_model(&selected, cx)
1322 .map(|configured| configured.model)
1323 })
1324 }
1325
1326 pub fn resume(
1327 &mut self,
1328 cx: &mut Context<Self>,
1329 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1330 self.messages.push(Message::Resume);
1331 cx.notify();
1332
1333 log::debug!("Total messages in thread: {}", self.messages.len());
1334 self.run_turn(cx)
1335 }
1336
1337 /// Sending a message results in the model streaming a response, which could include tool calls.
1338 /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
1339 /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
1340 pub fn send<T>(
1341 &mut self,
1342 id: UserMessageId,
1343 content: impl IntoIterator<Item = T>,
1344 cx: &mut Context<Self>,
1345 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
1346 where
1347 T: Into<UserMessageContent>,
1348 {
1349 let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
1350 log::debug!("Thread::send content: {:?}", content);
1351
1352 self.messages
1353 .push(Message::User(UserMessage { id, content }));
1354 cx.notify();
1355
1356 self.send_existing(cx)
1357 }
1358
1359 pub fn send_existing(
1360 &mut self,
1361 cx: &mut Context<Self>,
1362 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1363 let model = self.model().context("No language model configured")?;
1364
1365 log::info!("Thread::send called with model: {}", model.name().0);
1366 self.advance_prompt_id();
1367
1368 log::debug!("Total messages in thread: {}", self.messages.len());
1369 self.run_turn(cx)
1370 }
1371
1372 pub fn push_acp_user_block(
1373 &mut self,
1374 id: UserMessageId,
1375 blocks: impl IntoIterator<Item = acp::ContentBlock>,
1376 path_style: PathStyle,
1377 cx: &mut Context<Self>,
1378 ) {
1379 let content = blocks
1380 .into_iter()
1381 .map(|block| UserMessageContent::from_content_block(block, path_style))
1382 .collect::<Vec<_>>();
1383 self.messages
1384 .push(Message::User(UserMessage { id, content }));
1385 cx.notify();
1386 }
1387
1388 pub fn push_acp_agent_block(&mut self, block: acp::ContentBlock, cx: &mut Context<Self>) {
1389 let text = match block {
1390 acp::ContentBlock::Text(text_content) => text_content.text,
1391 acp::ContentBlock::Image(_) => "[image]".to_string(),
1392 acp::ContentBlock::Audio(_) => "[audio]".to_string(),
1393 acp::ContentBlock::ResourceLink(resource_link) => resource_link.uri,
1394 acp::ContentBlock::Resource(resource) => match resource.resource {
1395 acp::EmbeddedResourceResource::TextResourceContents(resource) => resource.uri,
1396 acp::EmbeddedResourceResource::BlobResourceContents(resource) => resource.uri,
1397 _ => "[resource]".to_string(),
1398 },
1399 _ => "[unknown]".to_string(),
1400 };
1401
1402 self.messages.push(Message::Agent(AgentMessage {
1403 content: vec![AgentMessageContent::Text(text)],
1404 ..Default::default()
1405 }));
1406 cx.notify();
1407 }
1408
1409 #[cfg(feature = "eval")]
1410 pub fn proceed(
1411 &mut self,
1412 cx: &mut Context<Self>,
1413 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1414 self.run_turn(cx)
1415 }
1416
1417 fn run_turn(
1418 &mut self,
1419 cx: &mut Context<Self>,
1420 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1421 // Flush the old pending message synchronously before cancelling,
1422 // to avoid a race where the detached cancel task might flush the NEW
1423 // turn's pending message instead of the old one.
1424 self.flush_pending_message(cx);
1425 self.cancel(cx).detach();
1426
1427 let model = self.model.clone().context("No language model configured")?;
1428 let profile = AgentSettings::get_global(cx)
1429 .profiles
1430 .get(&self.profile_id)
1431 .context("Profile not found")?;
1432 let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1433 let event_stream = ThreadEventStream(events_tx);
1434 let message_ix = self.messages.len().saturating_sub(1);
1435 self.clear_summary();
1436 let (cancellation_tx, mut cancellation_rx) = watch::channel(false);
1437 self.running_turn = Some(RunningTurn {
1438 event_stream: event_stream.clone(),
1439 tools: self.enabled_tools(profile, &model, cx),
1440 cancellation_tx,
1441 _task: cx.spawn(async move |this, cx| {
1442 log::debug!("Starting agent turn execution");
1443
1444 let turn_result = Self::run_turn_internal(
1445 &this,
1446 model,
1447 &event_stream,
1448 cancellation_rx.clone(),
1449 cx,
1450 )
1451 .await;
1452
1453 // Check if we were cancelled - if so, cancel() already took running_turn
1454 // and we shouldn't touch it (it might be a NEW turn now)
1455 let was_cancelled = *cancellation_rx.borrow();
1456 if was_cancelled {
1457 log::debug!("Turn was cancelled, skipping cleanup");
1458 return;
1459 }
1460
1461 _ = this.update(cx, |this, cx| this.flush_pending_message(cx));
1462
1463 match turn_result {
1464 Ok(()) => {
1465 log::debug!("Turn execution completed");
1466 event_stream.send_stop(acp::StopReason::EndTurn);
1467 }
1468 Err(error) => {
1469 log::error!("Turn execution failed: {:?}", error);
1470 match error.downcast::<CompletionError>() {
1471 Ok(CompletionError::Refusal) => {
1472 event_stream.send_stop(acp::StopReason::Refusal);
1473 _ = this.update(cx, |this, _| this.messages.truncate(message_ix));
1474 }
1475 Ok(CompletionError::MaxTokens) => {
1476 event_stream.send_stop(acp::StopReason::MaxTokens);
1477 }
1478 Ok(CompletionError::Other(error)) | Err(error) => {
1479 event_stream.send_error(error);
1480 }
1481 }
1482 }
1483 }
1484
1485 _ = this.update(cx, |this, _| this.running_turn.take());
1486 }),
1487 });
1488 Ok(events_rx)
1489 }
1490
1491 async fn run_turn_internal(
1492 this: &WeakEntity<Self>,
1493 model: Arc<dyn LanguageModel>,
1494 event_stream: &ThreadEventStream,
1495 mut cancellation_rx: watch::Receiver<bool>,
1496 cx: &mut AsyncApp,
1497 ) -> Result<()> {
1498 let mut attempt = 0;
1499 let mut intent = CompletionIntent::UserPrompt;
1500 loop {
1501 let request =
1502 this.update(cx, |this, cx| this.build_completion_request(intent, cx))??;
1503
1504 telemetry::event!(
1505 "Agent Thread Completion",
1506 thread_id = this.read_with(cx, |this, _| this.id.to_string())?,
1507 prompt_id = this.read_with(cx, |this, _| this.prompt_id.to_string())?,
1508 model = model.telemetry_id(),
1509 model_provider = model.provider_id().to_string(),
1510 attempt
1511 );
1512
1513 log::debug!("Calling model.stream_completion, attempt {}", attempt);
1514
1515 let (mut events, mut error) = match model.stream_completion(request, cx).await {
1516 Ok(events) => (events.fuse(), None),
1517 Err(err) => (stream::empty().boxed().fuse(), Some(err)),
1518 };
1519 let mut tool_results = FuturesUnordered::new();
1520 let mut cancelled = false;
1521 loop {
1522 // Race between getting the first event and cancellation
1523 let first_event = futures::select! {
1524 event = events.next().fuse() => event,
1525 _ = cancellation_rx.changed().fuse() => {
1526 if *cancellation_rx.borrow() {
1527 cancelled = true;
1528 break;
1529 }
1530 continue;
1531 }
1532 };
1533 let Some(first_event) = first_event else {
1534 break;
1535 };
1536
1537 // Collect all immediately available events to process as a batch
1538 let mut batch = vec![first_event];
1539 while let Some(event) = events.next().now_or_never().flatten() {
1540 batch.push(event);
1541 }
1542
1543 // Process the batch in a single update
1544 let batch_result = this.update(cx, |this, cx| {
1545 let mut batch_tool_results = Vec::new();
1546 let mut batch_error = None;
1547
1548 for event in batch {
1549 log::trace!("Received completion event: {:?}", event);
1550 match event {
1551 Ok(event) => {
1552 match this.handle_completion_event(
1553 event,
1554 event_stream,
1555 cancellation_rx.clone(),
1556 cx,
1557 ) {
1558 Ok(Some(task)) => batch_tool_results.push(task),
1559 Ok(None) => {}
1560 Err(err) => {
1561 batch_error = Some(err);
1562 break;
1563 }
1564 }
1565 }
1566 Err(err) => {
1567 batch_error = Some(err.into());
1568 break;
1569 }
1570 }
1571 }
1572
1573 cx.notify();
1574 (batch_tool_results, batch_error)
1575 })?;
1576
1577 tool_results.extend(batch_result.0);
1578 if let Some(err) = batch_result.1 {
1579 error = Some(err.downcast()?);
1580 break;
1581 }
1582 }
1583
1584 let end_turn = tool_results.is_empty();
1585 while let Some(tool_result) = tool_results.next().await {
1586 log::debug!("Tool finished {:?}", tool_result);
1587
1588 event_stream.update_tool_call_fields(
1589 &tool_result.tool_use_id,
1590 acp::ToolCallUpdateFields::new()
1591 .status(if tool_result.is_error {
1592 acp::ToolCallStatus::Failed
1593 } else {
1594 acp::ToolCallStatus::Completed
1595 })
1596 .raw_output(tool_result.output.clone()),
1597 );
1598 this.update(cx, |this, _cx| {
1599 this.pending_message()
1600 .tool_results
1601 .insert(tool_result.tool_use_id.clone(), tool_result);
1602 })?;
1603 }
1604
1605 this.update(cx, |this, cx| {
1606 this.flush_pending_message(cx);
1607 if this.title.is_none() && this.pending_title_generation.is_none() {
1608 this.generate_title(cx);
1609 }
1610 })?;
1611
1612 if cancelled {
1613 log::debug!("Turn cancelled by user, exiting");
1614 return Ok(());
1615 }
1616
1617 if let Some(error) = error {
1618 attempt += 1;
1619 let retry = this.update(cx, |this, cx| {
1620 let user_store = this.user_store.read(cx);
1621 this.handle_completion_error(error, attempt, user_store.plan())
1622 })??;
1623 let timer = cx.background_executor().timer(retry.duration);
1624 event_stream.send_retry(retry);
1625 timer.await;
1626 this.update(cx, |this, _cx| {
1627 if let Some(Message::Agent(message)) = this.messages.last() {
1628 if message.tool_results.is_empty() {
1629 intent = CompletionIntent::UserPrompt;
1630 this.messages.push(Message::Resume);
1631 }
1632 }
1633 })?;
1634 } else if end_turn {
1635 return Ok(());
1636 } else {
1637 intent = CompletionIntent::ToolResults;
1638 attempt = 0;
1639 }
1640 }
1641 }
1642
1643 fn handle_completion_error(
1644 &mut self,
1645 error: LanguageModelCompletionError,
1646 attempt: u8,
1647 plan: Option<Plan>,
1648 ) -> Result<acp_thread::RetryStatus> {
1649 let Some(model) = self.model.as_ref() else {
1650 return Err(anyhow!(error));
1651 };
1652
1653 let auto_retry = if model.provider_id() == ZED_CLOUD_PROVIDER_ID {
1654 match plan {
1655 Some(Plan::V2(_)) => true,
1656 None => false,
1657 }
1658 } else {
1659 true
1660 };
1661
1662 if !auto_retry {
1663 return Err(anyhow!(error));
1664 }
1665
1666 let Some(strategy) = Self::retry_strategy_for(&error) else {
1667 return Err(anyhow!(error));
1668 };
1669
1670 let max_attempts = match &strategy {
1671 RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
1672 RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
1673 };
1674
1675 if attempt > max_attempts {
1676 return Err(anyhow!(error));
1677 }
1678
1679 let delay = match &strategy {
1680 RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
1681 let delay_secs = initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
1682 Duration::from_secs(delay_secs)
1683 }
1684 RetryStrategy::Fixed { delay, .. } => *delay,
1685 };
1686 log::debug!("Retry attempt {attempt} with delay {delay:?}");
1687
1688 Ok(acp_thread::RetryStatus {
1689 last_error: error.to_string().into(),
1690 attempt: attempt as usize,
1691 max_attempts: max_attempts as usize,
1692 started_at: Instant::now(),
1693 duration: delay,
1694 })
1695 }
1696
1697 /// A helper method that's called on every streamed completion event.
1698 /// Returns an optional tool result task, which the main agentic loop will
1699 /// send back to the model when it resolves.
1700 fn handle_completion_event(
1701 &mut self,
1702 event: LanguageModelCompletionEvent,
1703 event_stream: &ThreadEventStream,
1704 cancellation_rx: watch::Receiver<bool>,
1705 cx: &mut Context<Self>,
1706 ) -> Result<Option<Task<LanguageModelToolResult>>> {
1707 log::trace!("Handling streamed completion event: {:?}", event);
1708 use LanguageModelCompletionEvent::*;
1709
1710 match event {
1711 StartMessage { .. } => {
1712 self.flush_pending_message(cx);
1713 self.pending_message = Some(AgentMessage::default());
1714 }
1715 Text(new_text) => self.handle_text_event(new_text, event_stream),
1716 Thinking { text, signature } => {
1717 self.handle_thinking_event(text, signature, event_stream)
1718 }
1719 RedactedThinking { data } => self.handle_redacted_thinking_event(data),
1720 ReasoningDetails(details) => {
1721 let last_message = self.pending_message();
1722 // Store the last non-empty reasoning_details (overwrites earlier ones)
1723 // This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
1724 if let serde_json::Value::Array(ref arr) = details {
1725 if !arr.is_empty() {
1726 last_message.reasoning_details = Some(details);
1727 }
1728 } else {
1729 last_message.reasoning_details = Some(details);
1730 }
1731 }
1732 ToolUse(tool_use) => {
1733 return Ok(self.handle_tool_use_event(tool_use, event_stream, cancellation_rx, cx));
1734 }
1735 ToolUseJsonParseError {
1736 id,
1737 tool_name,
1738 raw_input,
1739 json_parse_error,
1740 } => {
1741 return Ok(Some(Task::ready(
1742 self.handle_tool_use_json_parse_error_event(
1743 id,
1744 tool_name,
1745 raw_input,
1746 json_parse_error,
1747 ),
1748 )));
1749 }
1750 UsageUpdate(usage) => {
1751 telemetry::event!(
1752 "Agent Thread Completion Usage Updated",
1753 thread_id = self.id.to_string(),
1754 prompt_id = self.prompt_id.to_string(),
1755 model = self.model.as_ref().map(|m| m.telemetry_id()),
1756 model_provider = self.model.as_ref().map(|m| m.provider_id().to_string()),
1757 input_tokens = usage.input_tokens,
1758 output_tokens = usage.output_tokens,
1759 cache_creation_input_tokens = usage.cache_creation_input_tokens,
1760 cache_read_input_tokens = usage.cache_read_input_tokens,
1761 );
1762 self.update_token_usage(usage, cx);
1763 }
1764 Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()),
1765 Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()),
1766 Stop(StopReason::ToolUse | StopReason::EndTurn) => {}
1767 Started | Queued { .. } => {}
1768 }
1769
1770 Ok(None)
1771 }
1772
1773 fn handle_text_event(&mut self, new_text: String, event_stream: &ThreadEventStream) {
1774 event_stream.send_text(&new_text);
1775
1776 let last_message = self.pending_message();
1777 if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
1778 text.push_str(&new_text);
1779 } else {
1780 last_message
1781 .content
1782 .push(AgentMessageContent::Text(new_text));
1783 }
1784 }
1785
1786 fn handle_thinking_event(
1787 &mut self,
1788 new_text: String,
1789 new_signature: Option<String>,
1790 event_stream: &ThreadEventStream,
1791 ) {
1792 event_stream.send_thinking(&new_text);
1793
1794 let last_message = self.pending_message();
1795 if let Some(AgentMessageContent::Thinking { text, signature }) =
1796 last_message.content.last_mut()
1797 {
1798 text.push_str(&new_text);
1799 *signature = new_signature.or(signature.take());
1800 } else {
1801 last_message.content.push(AgentMessageContent::Thinking {
1802 text: new_text,
1803 signature: new_signature,
1804 });
1805 }
1806 }
1807
1808 fn handle_redacted_thinking_event(&mut self, data: String) {
1809 let last_message = self.pending_message();
1810 last_message
1811 .content
1812 .push(AgentMessageContent::RedactedThinking(data));
1813 }
1814
1815 fn handle_tool_use_event(
1816 &mut self,
1817 tool_use: LanguageModelToolUse,
1818 event_stream: &ThreadEventStream,
1819 cancellation_rx: watch::Receiver<bool>,
1820 cx: &mut Context<Self>,
1821 ) -> Option<Task<LanguageModelToolResult>> {
1822 cx.notify();
1823
1824 let tool = self.tool(tool_use.name.as_ref());
1825 let mut title = SharedString::from(&tool_use.name);
1826 let mut kind = acp::ToolKind::Other;
1827 if let Some(tool) = tool.as_ref() {
1828 title = tool.initial_title(tool_use.input.clone(), cx);
1829 kind = tool.kind();
1830 }
1831
1832 // Ensure the last message ends in the current tool use
1833 let last_message = self.pending_message();
1834 let push_new_tool_use = last_message.content.last_mut().is_none_or(|content| {
1835 if let AgentMessageContent::ToolUse(last_tool_use) = content {
1836 if last_tool_use.id == tool_use.id {
1837 *last_tool_use = tool_use.clone();
1838 false
1839 } else {
1840 true
1841 }
1842 } else {
1843 true
1844 }
1845 });
1846
1847 if push_new_tool_use {
1848 event_stream.send_tool_call(
1849 &tool_use.id,
1850 &tool_use.name,
1851 title,
1852 kind,
1853 tool_use.input.clone(),
1854 );
1855 last_message
1856 .content
1857 .push(AgentMessageContent::ToolUse(tool_use.clone()));
1858 } else {
1859 event_stream.update_tool_call_fields(
1860 &tool_use.id,
1861 acp::ToolCallUpdateFields::new()
1862 .title(title.as_str())
1863 .kind(kind)
1864 .raw_input(tool_use.input.clone()),
1865 );
1866 }
1867
1868 if !tool_use.is_input_complete {
1869 return None;
1870 }
1871
1872 let Some(tool) = tool else {
1873 let content = format!("No tool named {} exists", tool_use.name);
1874 return Some(Task::ready(LanguageModelToolResult {
1875 content: LanguageModelToolResultContent::Text(Arc::from(content)),
1876 tool_use_id: tool_use.id,
1877 tool_name: tool_use.name,
1878 is_error: true,
1879 output: None,
1880 }));
1881 };
1882
1883 let fs = self.project.read(cx).fs().clone();
1884 let tool_event_stream = ToolCallEventStream::new(
1885 tool_use.id.clone(),
1886 event_stream.clone(),
1887 Some(fs),
1888 cancellation_rx,
1889 );
1890 tool_event_stream.update_fields(
1891 acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
1892 );
1893 let supports_images = self.model().is_some_and(|model| model.supports_images());
1894 let tool_result = tool.run(tool_use.input, tool_event_stream, cx);
1895 log::debug!("Running tool {}", tool_use.name);
1896 Some(cx.foreground_executor().spawn(async move {
1897 let tool_result = tool_result.await.and_then(|output| {
1898 if let LanguageModelToolResultContent::Image(_) = &output.llm_output
1899 && !supports_images
1900 {
1901 return Err(anyhow!(
1902 "Attempted to read an image, but this model doesn't support it.",
1903 ));
1904 }
1905 Ok(output)
1906 });
1907
1908 match tool_result {
1909 Ok(output) => LanguageModelToolResult {
1910 tool_use_id: tool_use.id,
1911 tool_name: tool_use.name,
1912 is_error: false,
1913 content: output.llm_output,
1914 output: Some(output.raw_output),
1915 },
1916 Err(error) => LanguageModelToolResult {
1917 tool_use_id: tool_use.id,
1918 tool_name: tool_use.name,
1919 is_error: true,
1920 content: LanguageModelToolResultContent::Text(Arc::from(error.to_string())),
1921 output: Some(error.to_string().into()),
1922 },
1923 }
1924 }))
1925 }
1926
1927 fn handle_tool_use_json_parse_error_event(
1928 &mut self,
1929 tool_use_id: LanguageModelToolUseId,
1930 tool_name: Arc<str>,
1931 raw_input: Arc<str>,
1932 json_parse_error: String,
1933 ) -> LanguageModelToolResult {
1934 let tool_output = format!("Error parsing input JSON: {json_parse_error}");
1935 LanguageModelToolResult {
1936 tool_use_id,
1937 tool_name,
1938 is_error: true,
1939 content: LanguageModelToolResultContent::Text(tool_output.into()),
1940 output: Some(serde_json::Value::String(raw_input.to_string())),
1941 }
1942 }
1943
1944 pub fn title(&self) -> SharedString {
1945 self.title.clone().unwrap_or("New Thread".into())
1946 }
1947
1948 pub fn is_generating_summary(&self) -> bool {
1949 self.pending_summary_generation.is_some()
1950 }
1951
1952 pub fn is_generating_title(&self) -> bool {
1953 self.pending_title_generation.is_some()
1954 }
1955
1956 pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
1957 if let Some(summary) = self.summary.as_ref() {
1958 return Task::ready(Some(summary.clone())).shared();
1959 }
1960 if let Some(task) = self.pending_summary_generation.clone() {
1961 return task;
1962 }
1963 let Some(model) = self.summarization_model.clone() else {
1964 log::error!("No summarization model available");
1965 return Task::ready(None).shared();
1966 };
1967 let mut request = LanguageModelRequest {
1968 intent: Some(CompletionIntent::ThreadContextSummarization),
1969 temperature: AgentSettings::temperature_for_model(&model, cx),
1970 ..Default::default()
1971 };
1972
1973 for message in &self.messages {
1974 request.messages.extend(message.to_request());
1975 }
1976
1977 request.messages.push(LanguageModelRequestMessage {
1978 role: Role::User,
1979 content: vec![SUMMARIZE_THREAD_DETAILED_PROMPT.into()],
1980 cache: false,
1981 reasoning_details: None,
1982 });
1983
1984 let task = cx
1985 .spawn(async move |this, cx| {
1986 let mut summary = String::new();
1987 let mut messages = model.stream_completion(request, cx).await.log_err()?;
1988 while let Some(event) = messages.next().await {
1989 let event = event.log_err()?;
1990 let text = match event {
1991 LanguageModelCompletionEvent::Text(text) => text,
1992 _ => continue,
1993 };
1994
1995 let mut lines = text.lines();
1996 summary.extend(lines.next());
1997 }
1998
1999 log::debug!("Setting summary: {}", summary);
2000 let summary = SharedString::from(summary);
2001
2002 this.update(cx, |this, cx| {
2003 this.summary = Some(summary.clone());
2004 this.pending_summary_generation = None;
2005 cx.notify()
2006 })
2007 .ok()?;
2008
2009 Some(summary)
2010 })
2011 .shared();
2012 self.pending_summary_generation = Some(task.clone());
2013 task
2014 }
2015
2016 pub fn generate_title(&mut self, cx: &mut Context<Self>) {
2017 let Some(model) = self.summarization_model.clone() else {
2018 return;
2019 };
2020
2021 log::debug!(
2022 "Generating title with model: {:?}",
2023 self.summarization_model.as_ref().map(|model| model.name())
2024 );
2025 let mut request = LanguageModelRequest {
2026 intent: Some(CompletionIntent::ThreadSummarization),
2027 temperature: AgentSettings::temperature_for_model(&model, cx),
2028 ..Default::default()
2029 };
2030
2031 for message in &self.messages {
2032 request.messages.extend(message.to_request());
2033 }
2034
2035 request.messages.push(LanguageModelRequestMessage {
2036 role: Role::User,
2037 content: vec![SUMMARIZE_THREAD_PROMPT.into()],
2038 cache: false,
2039 reasoning_details: None,
2040 });
2041 self.pending_title_generation = Some(cx.spawn(async move |this, cx| {
2042 let mut title = String::new();
2043
2044 let generate = async {
2045 let mut messages = model.stream_completion(request, cx).await?;
2046 while let Some(event) = messages.next().await {
2047 let event = event?;
2048 let text = match event {
2049 LanguageModelCompletionEvent::Text(text) => text,
2050 _ => continue,
2051 };
2052
2053 let mut lines = text.lines();
2054 title.extend(lines.next());
2055
2056 // Stop if the LLM generated multiple lines.
2057 if lines.next().is_some() {
2058 break;
2059 }
2060 }
2061 anyhow::Ok(())
2062 };
2063
2064 if generate.await.context("failed to generate title").is_ok() {
2065 _ = this.update(cx, |this, cx| this.set_title(title.into(), cx));
2066 }
2067 _ = this.update(cx, |this, _| this.pending_title_generation = None);
2068 }));
2069 }
2070
2071 pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
2072 self.pending_title_generation = None;
2073 if Some(&title) != self.title.as_ref() {
2074 self.title = Some(title);
2075 cx.emit(TitleUpdated);
2076 cx.notify();
2077 }
2078 }
2079
2080 fn clear_summary(&mut self) {
2081 self.summary = None;
2082 self.pending_summary_generation = None;
2083 }
2084
2085 fn last_user_message(&self) -> Option<&UserMessage> {
2086 self.messages
2087 .iter()
2088 .rev()
2089 .find_map(|message| match message {
2090 Message::User(user_message) => Some(user_message),
2091 Message::Agent(_) => None,
2092 Message::Resume => None,
2093 })
2094 }
2095
2096 fn pending_message(&mut self) -> &mut AgentMessage {
2097 self.pending_message.get_or_insert_default()
2098 }
2099
2100 fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
2101 let Some(mut message) = self.pending_message.take() else {
2102 return;
2103 };
2104
2105 if message.content.is_empty() {
2106 return;
2107 }
2108
2109 for content in &message.content {
2110 let AgentMessageContent::ToolUse(tool_use) = content else {
2111 continue;
2112 };
2113
2114 if !message.tool_results.contains_key(&tool_use.id) {
2115 message.tool_results.insert(
2116 tool_use.id.clone(),
2117 LanguageModelToolResult {
2118 tool_use_id: tool_use.id.clone(),
2119 tool_name: tool_use.name.clone(),
2120 is_error: true,
2121 content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
2122 output: None,
2123 },
2124 );
2125 }
2126 }
2127
2128 self.messages.push(Message::Agent(message));
2129 self.updated_at = Utc::now();
2130 self.clear_summary();
2131 cx.notify()
2132 }
2133
2134 pub(crate) fn build_completion_request(
2135 &self,
2136 completion_intent: CompletionIntent,
2137 cx: &App,
2138 ) -> Result<LanguageModelRequest> {
2139 let model = self.model().context("No language model configured")?;
2140 let tools = if let Some(turn) = self.running_turn.as_ref() {
2141 turn.tools
2142 .iter()
2143 .filter_map(|(tool_name, tool)| {
2144 log::trace!("Including tool: {}", tool_name);
2145 Some(LanguageModelRequestTool {
2146 name: tool_name.to_string(),
2147 description: tool.description().to_string(),
2148 input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
2149 })
2150 })
2151 .collect::<Vec<_>>()
2152 } else {
2153 Vec::new()
2154 };
2155
2156 log::debug!("Building completion request");
2157 log::debug!("Completion intent: {:?}", completion_intent);
2158
2159 let available_tools: Vec<_> = self
2160 .running_turn
2161 .as_ref()
2162 .map(|turn| turn.tools.keys().cloned().collect())
2163 .unwrap_or_default();
2164
2165 log::debug!("Request includes {} tools", available_tools.len());
2166 let messages = self.build_request_messages(available_tools, cx);
2167 log::debug!("Request will include {} messages", messages.len());
2168
2169 let request = LanguageModelRequest {
2170 thread_id: Some(self.id.to_string()),
2171 prompt_id: Some(self.prompt_id.to_string()),
2172 intent: Some(completion_intent),
2173 messages,
2174 tools,
2175 tool_choice: None,
2176 stop: Vec::new(),
2177 temperature: AgentSettings::temperature_for_model(model, cx),
2178 thinking_allowed: true,
2179 };
2180
2181 log::debug!("Completion request built successfully");
2182 Ok(request)
2183 }
2184
2185 fn enabled_tools(
2186 &self,
2187 profile: &AgentProfileSettings,
2188 model: &Arc<dyn LanguageModel>,
2189 cx: &App,
2190 ) -> BTreeMap<SharedString, Arc<dyn AnyAgentTool>> {
2191 fn truncate(tool_name: &SharedString) -> SharedString {
2192 if tool_name.len() > MAX_TOOL_NAME_LENGTH {
2193 let mut truncated = tool_name.to_string();
2194 truncated.truncate(MAX_TOOL_NAME_LENGTH);
2195 truncated.into()
2196 } else {
2197 tool_name.clone()
2198 }
2199 }
2200
2201 let mut tools = self
2202 .tools
2203 .iter()
2204 .filter_map(|(tool_name, tool)| {
2205 if tool.supports_provider(&model.provider_id())
2206 && profile.is_tool_enabled(tool_name)
2207 {
2208 Some((truncate(tool_name), tool.clone()))
2209 } else {
2210 None
2211 }
2212 })
2213 .collect::<BTreeMap<_, _>>();
2214
2215 let mut context_server_tools = Vec::new();
2216 let mut seen_tools = tools.keys().cloned().collect::<HashSet<_>>();
2217 let mut duplicate_tool_names = HashSet::default();
2218 for (server_id, server_tools) in self.context_server_registry.read(cx).servers() {
2219 for (tool_name, tool) in server_tools {
2220 if profile.is_context_server_tool_enabled(&server_id.0, &tool_name) {
2221 let tool_name = truncate(tool_name);
2222 if !seen_tools.insert(tool_name.clone()) {
2223 duplicate_tool_names.insert(tool_name.clone());
2224 }
2225 context_server_tools.push((server_id.clone(), tool_name, tool.clone()));
2226 }
2227 }
2228 }
2229
2230 // When there are duplicate tool names, disambiguate by prefixing them
2231 // with the server ID. In the rare case there isn't enough space for the
2232 // disambiguated tool name, keep only the last tool with this name.
2233 for (server_id, tool_name, tool) in context_server_tools {
2234 if duplicate_tool_names.contains(&tool_name) {
2235 let available = MAX_TOOL_NAME_LENGTH.saturating_sub(tool_name.len());
2236 if available >= 2 {
2237 let mut disambiguated = server_id.0.to_string();
2238 disambiguated.truncate(available - 1);
2239 disambiguated.push('_');
2240 disambiguated.push_str(&tool_name);
2241 tools.insert(disambiguated.into(), tool.clone());
2242 } else {
2243 tools.insert(tool_name, tool.clone());
2244 }
2245 } else {
2246 tools.insert(tool_name, tool.clone());
2247 }
2248 }
2249
2250 tools
2251 }
2252
2253 fn tool(&self, name: &str) -> Option<Arc<dyn AnyAgentTool>> {
2254 self.running_turn.as_ref()?.tools.get(name).cloned()
2255 }
2256
2257 pub fn has_tool(&self, name: &str) -> bool {
2258 self.running_turn
2259 .as_ref()
2260 .is_some_and(|turn| turn.tools.contains_key(name))
2261 }
2262
2263 #[cfg(any(test, feature = "test-support"))]
2264 pub fn has_registered_tool(&self, name: &str) -> bool {
2265 self.tools.contains_key(name)
2266 }
2267
2268 pub fn registered_tool_names(&self) -> Vec<SharedString> {
2269 self.tools.keys().cloned().collect()
2270 }
2271
2272 pub fn register_running_subagent(&mut self, subagent: WeakEntity<Thread>) {
2273 self.running_subagents.push(subagent);
2274 }
2275
2276 pub fn unregister_running_subagent(&mut self, subagent: &WeakEntity<Thread>) {
2277 self.running_subagents
2278 .retain(|s| s.entity_id() != subagent.entity_id());
2279 }
2280
2281 pub fn running_subagent_count(&self) -> usize {
2282 self.running_subagents
2283 .iter()
2284 .filter(|s| s.upgrade().is_some())
2285 .count()
2286 }
2287
2288 pub fn is_subagent(&self) -> bool {
2289 self.subagent_context.is_some()
2290 }
2291
2292 pub fn depth(&self) -> u8 {
2293 self.subagent_context.as_ref().map(|c| c.depth).unwrap_or(0)
2294 }
2295
2296 pub fn is_turn_complete(&self) -> bool {
2297 self.running_turn.is_none()
2298 }
2299
2300 pub fn submit_user_message(
2301 &mut self,
2302 content: impl Into<String>,
2303 cx: &mut Context<Self>,
2304 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
2305 let content = content.into();
2306 self.messages.push(Message::User(UserMessage {
2307 id: UserMessageId::new(),
2308 content: vec![UserMessageContent::Text(content)],
2309 }));
2310 cx.notify();
2311 self.send_existing(cx)
2312 }
2313
2314 pub fn interrupt_for_summary(
2315 &mut self,
2316 cx: &mut Context<Self>,
2317 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
2318 let context = self
2319 .subagent_context
2320 .as_ref()
2321 .context("Not a subagent thread")?;
2322 let prompt = context.context_low_prompt.clone();
2323 self.cancel(cx).detach();
2324 self.submit_user_message(prompt, cx)
2325 }
2326
2327 pub fn request_final_summary(
2328 &mut self,
2329 cx: &mut Context<Self>,
2330 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
2331 let context = self
2332 .subagent_context
2333 .as_ref()
2334 .context("Not a subagent thread")?;
2335 let prompt = context.summary_prompt.clone();
2336 self.submit_user_message(prompt, cx)
2337 }
2338
2339 fn build_request_messages(
2340 &self,
2341 available_tools: Vec<SharedString>,
2342 cx: &App,
2343 ) -> Vec<LanguageModelRequestMessage> {
2344 log::trace!(
2345 "Building request messages from {} thread messages",
2346 self.messages.len()
2347 );
2348
2349 let system_prompt = SystemPromptTemplate {
2350 project: self.project_context.read(cx),
2351 available_tools,
2352 model_name: self.model.as_ref().map(|m| m.name().0.to_string()),
2353 }
2354 .render(&self.templates)
2355 .context("failed to build system prompt")
2356 .expect("Invalid template");
2357 let mut messages = vec![LanguageModelRequestMessage {
2358 role: Role::System,
2359 content: vec![system_prompt.into()],
2360 cache: false,
2361 reasoning_details: None,
2362 }];
2363 for message in &self.messages {
2364 messages.extend(message.to_request());
2365 }
2366
2367 if let Some(last_message) = messages.last_mut() {
2368 last_message.cache = true;
2369 }
2370
2371 if let Some(message) = self.pending_message.as_ref() {
2372 messages.extend(message.to_request());
2373 }
2374
2375 messages
2376 }
2377
2378 pub fn to_markdown(&self) -> String {
2379 let mut markdown = String::new();
2380 for (ix, message) in self.messages.iter().enumerate() {
2381 if ix > 0 {
2382 markdown.push('\n');
2383 }
2384 markdown.push_str(&message.to_markdown());
2385 }
2386
2387 if let Some(message) = self.pending_message.as_ref() {
2388 markdown.push('\n');
2389 markdown.push_str(&message.to_markdown());
2390 }
2391
2392 markdown
2393 }
2394
2395 fn advance_prompt_id(&mut self) {
2396 self.prompt_id = PromptId::new();
2397 }
2398
2399 fn retry_strategy_for(error: &LanguageModelCompletionError) -> Option<RetryStrategy> {
2400 use LanguageModelCompletionError::*;
2401 use http_client::StatusCode;
2402
2403 // General strategy here:
2404 // - If retrying won't help (e.g. invalid API key or payload too large), return None so we don't retry at all.
2405 // - If it's a time-based issue (e.g. server overloaded, rate limit exceeded), retry up to 4 times with exponential backoff.
2406 // - If it's an issue that *might* be fixed by retrying (e.g. internal server error), retry up to 3 times.
2407 match error {
2408 HttpResponseError {
2409 status_code: StatusCode::TOO_MANY_REQUESTS,
2410 ..
2411 } => Some(RetryStrategy::ExponentialBackoff {
2412 initial_delay: BASE_RETRY_DELAY,
2413 max_attempts: MAX_RETRY_ATTEMPTS,
2414 }),
2415 ServerOverloaded { retry_after, .. } | RateLimitExceeded { retry_after, .. } => {
2416 Some(RetryStrategy::Fixed {
2417 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2418 max_attempts: MAX_RETRY_ATTEMPTS,
2419 })
2420 }
2421 UpstreamProviderError {
2422 status,
2423 retry_after,
2424 ..
2425 } => match *status {
2426 StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
2427 Some(RetryStrategy::Fixed {
2428 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2429 max_attempts: MAX_RETRY_ATTEMPTS,
2430 })
2431 }
2432 StatusCode::INTERNAL_SERVER_ERROR => Some(RetryStrategy::Fixed {
2433 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2434 // Internal Server Error could be anything, retry up to 3 times.
2435 max_attempts: 3,
2436 }),
2437 status => {
2438 // There is no StatusCode variant for the unofficial HTTP 529 ("The service is overloaded"),
2439 // but we frequently get them in practice. See https://http.dev/529
2440 if status.as_u16() == 529 {
2441 Some(RetryStrategy::Fixed {
2442 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2443 max_attempts: MAX_RETRY_ATTEMPTS,
2444 })
2445 } else {
2446 Some(RetryStrategy::Fixed {
2447 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2448 max_attempts: 2,
2449 })
2450 }
2451 }
2452 },
2453 ApiInternalServerError { .. } => Some(RetryStrategy::Fixed {
2454 delay: BASE_RETRY_DELAY,
2455 max_attempts: 3,
2456 }),
2457 ApiReadResponseError { .. }
2458 | HttpSend { .. }
2459 | DeserializeResponse { .. }
2460 | BadRequestFormat { .. } => Some(RetryStrategy::Fixed {
2461 delay: BASE_RETRY_DELAY,
2462 max_attempts: 3,
2463 }),
2464 // Retrying these errors definitely shouldn't help.
2465 HttpResponseError {
2466 status_code:
2467 StatusCode::PAYLOAD_TOO_LARGE | StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED,
2468 ..
2469 }
2470 | AuthenticationError { .. }
2471 | PermissionError { .. }
2472 | NoApiKey { .. }
2473 | ApiEndpointNotFound { .. }
2474 | PromptTooLarge { .. } => None,
2475 // These errors might be transient, so retry them
2476 SerializeRequest { .. } | BuildRequestBody { .. } => Some(RetryStrategy::Fixed {
2477 delay: BASE_RETRY_DELAY,
2478 max_attempts: 1,
2479 }),
2480 // Retry all other 4xx and 5xx errors once.
2481 HttpResponseError { status_code, .. }
2482 if status_code.is_client_error() || status_code.is_server_error() =>
2483 {
2484 Some(RetryStrategy::Fixed {
2485 delay: BASE_RETRY_DELAY,
2486 max_attempts: 3,
2487 })
2488 }
2489 Other(err) if err.is::<language_model::PaymentRequiredError>() => {
2490 // Retrying won't help for Payment Required errors.
2491 None
2492 }
2493 // Conservatively assume that any other errors are non-retryable
2494 HttpResponseError { .. } | Other(..) => Some(RetryStrategy::Fixed {
2495 delay: BASE_RETRY_DELAY,
2496 max_attempts: 2,
2497 }),
2498 }
2499 }
2500}
2501
2502struct RunningTurn {
2503 /// Holds the task that handles agent interaction until the end of the turn.
2504 /// Survives across multiple requests as the model performs tool calls and
2505 /// we run tools, report their results.
2506 _task: Task<()>,
2507 /// The current event stream for the running turn. Used to report a final
2508 /// cancellation event if we cancel the turn.
2509 event_stream: ThreadEventStream,
2510 /// The tools that were enabled for this turn.
2511 tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
2512 /// Sender to signal tool cancellation. When cancel is called, this is
2513 /// set to true so all tools can detect user-initiated cancellation.
2514 cancellation_tx: watch::Sender<bool>,
2515}
2516
2517impl RunningTurn {
2518 fn cancel(mut self) -> Task<()> {
2519 log::debug!("Cancelling in progress turn");
2520 self.cancellation_tx.send(true).ok();
2521 self.event_stream.send_canceled();
2522 self._task
2523 }
2524}
2525
2526pub struct TokenUsageUpdated(pub Option<acp_thread::TokenUsage>);
2527
2528impl EventEmitter<TokenUsageUpdated> for Thread {}
2529
2530pub struct TitleUpdated;
2531
2532impl EventEmitter<TitleUpdated> for Thread {}
2533
2534pub trait AgentTool
2535where
2536 Self: 'static + Sized,
2537{
2538 type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
2539 type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
2540
2541 fn name() -> &'static str;
2542
2543 fn description() -> SharedString {
2544 let schema = schemars::schema_for!(Self::Input);
2545 SharedString::new(
2546 schema
2547 .get("description")
2548 .and_then(|description| description.as_str())
2549 .unwrap_or_default(),
2550 )
2551 }
2552
2553 fn kind() -> acp::ToolKind;
2554
2555 /// The initial tool title to display. Can be updated during the tool run.
2556 fn initial_title(
2557 &self,
2558 input: Result<Self::Input, serde_json::Value>,
2559 cx: &mut App,
2560 ) -> SharedString;
2561
2562 /// Returns the JSON schema that describes the tool's input.
2563 fn input_schema(format: LanguageModelToolSchemaFormat) -> Schema {
2564 language_model::tool_schema::root_schema_for::<Self::Input>(format)
2565 }
2566
2567 /// Some tools rely on a provider for the underlying billing or other reasons.
2568 /// Allow the tool to check if they are compatible, or should be filtered out.
2569 fn supports_provider(_provider: &LanguageModelProviderId) -> bool {
2570 true
2571 }
2572
2573 /// Runs the tool with the provided input.
2574 fn run(
2575 self: Arc<Self>,
2576 input: Self::Input,
2577 event_stream: ToolCallEventStream,
2578 cx: &mut App,
2579 ) -> Task<Result<Self::Output>>;
2580
2581 /// Emits events for a previous execution of the tool.
2582 fn replay(
2583 &self,
2584 _input: Self::Input,
2585 _output: Self::Output,
2586 _event_stream: ToolCallEventStream,
2587 _cx: &mut App,
2588 ) -> Result<()> {
2589 Ok(())
2590 }
2591
2592 fn erase(self) -> Arc<dyn AnyAgentTool> {
2593 Arc::new(Erased(Arc::new(self)))
2594 }
2595}
2596
2597pub struct Erased<T>(T);
2598
2599pub struct AgentToolOutput {
2600 pub llm_output: LanguageModelToolResultContent,
2601 pub raw_output: serde_json::Value,
2602}
2603
2604pub trait AnyAgentTool {
2605 fn name(&self) -> SharedString;
2606 fn description(&self) -> SharedString;
2607 fn kind(&self) -> acp::ToolKind;
2608 fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString;
2609 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
2610 fn supports_provider(&self, _provider: &LanguageModelProviderId) -> bool {
2611 true
2612 }
2613 fn run(
2614 self: Arc<Self>,
2615 input: serde_json::Value,
2616 event_stream: ToolCallEventStream,
2617 cx: &mut App,
2618 ) -> Task<Result<AgentToolOutput>>;
2619 fn replay(
2620 &self,
2621 input: serde_json::Value,
2622 output: serde_json::Value,
2623 event_stream: ToolCallEventStream,
2624 cx: &mut App,
2625 ) -> Result<()>;
2626}
2627
2628impl<T> AnyAgentTool for Erased<Arc<T>>
2629where
2630 T: AgentTool,
2631{
2632 fn name(&self) -> SharedString {
2633 T::name().into()
2634 }
2635
2636 fn description(&self) -> SharedString {
2637 T::description()
2638 }
2639
2640 fn kind(&self) -> agent_client_protocol::ToolKind {
2641 T::kind()
2642 }
2643
2644 fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString {
2645 let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
2646 self.0.initial_title(parsed_input, _cx)
2647 }
2648
2649 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
2650 let mut json = serde_json::to_value(T::input_schema(format))?;
2651 language_model::tool_schema::adapt_schema_to_format(&mut json, format)?;
2652 Ok(json)
2653 }
2654
2655 fn supports_provider(&self, provider: &LanguageModelProviderId) -> bool {
2656 T::supports_provider(provider)
2657 }
2658
2659 fn run(
2660 self: Arc<Self>,
2661 input: serde_json::Value,
2662 event_stream: ToolCallEventStream,
2663 cx: &mut App,
2664 ) -> Task<Result<AgentToolOutput>> {
2665 cx.spawn(async move |cx| {
2666 let input = serde_json::from_value(input)?;
2667 let output = cx
2668 .update(|cx| self.0.clone().run(input, event_stream, cx))
2669 .await?;
2670 let raw_output = serde_json::to_value(&output)?;
2671 Ok(AgentToolOutput {
2672 llm_output: output.into(),
2673 raw_output,
2674 })
2675 })
2676 }
2677
2678 fn replay(
2679 &self,
2680 input: serde_json::Value,
2681 output: serde_json::Value,
2682 event_stream: ToolCallEventStream,
2683 cx: &mut App,
2684 ) -> Result<()> {
2685 let input = serde_json::from_value(input)?;
2686 let output = serde_json::from_value(output)?;
2687 self.0.replay(input, output, event_stream, cx)
2688 }
2689}
2690
2691#[derive(Clone)]
2692struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
2693
2694impl ThreadEventStream {
2695 fn send_user_message(&self, message: &UserMessage) {
2696 self.0
2697 .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
2698 .ok();
2699 }
2700
2701 fn send_text(&self, text: &str) {
2702 self.0
2703 .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
2704 .ok();
2705 }
2706
2707 fn send_thinking(&self, text: &str) {
2708 self.0
2709 .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
2710 .ok();
2711 }
2712
2713 fn send_tool_call(
2714 &self,
2715 id: &LanguageModelToolUseId,
2716 tool_name: &str,
2717 title: SharedString,
2718 kind: acp::ToolKind,
2719 input: serde_json::Value,
2720 ) {
2721 self.0
2722 .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
2723 id,
2724 tool_name,
2725 title.to_string(),
2726 kind,
2727 input,
2728 ))))
2729 .ok();
2730 }
2731
2732 fn initial_tool_call(
2733 id: &LanguageModelToolUseId,
2734 tool_name: &str,
2735 title: String,
2736 kind: acp::ToolKind,
2737 input: serde_json::Value,
2738 ) -> acp::ToolCall {
2739 acp::ToolCall::new(id.to_string(), title)
2740 .kind(kind)
2741 .raw_input(input)
2742 .meta(acp_thread::meta_with_tool_name(tool_name))
2743 }
2744
2745 fn update_tool_call_fields(
2746 &self,
2747 tool_use_id: &LanguageModelToolUseId,
2748 fields: acp::ToolCallUpdateFields,
2749 ) {
2750 self.0
2751 .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
2752 acp::ToolCallUpdate::new(tool_use_id.to_string(), fields).into(),
2753 )))
2754 .ok();
2755 }
2756
2757 fn send_retry(&self, status: acp_thread::RetryStatus) {
2758 self.0.unbounded_send(Ok(ThreadEvent::Retry(status))).ok();
2759 }
2760
2761 fn send_stop(&self, reason: acp::StopReason) {
2762 self.0.unbounded_send(Ok(ThreadEvent::Stop(reason))).ok();
2763 }
2764
2765 fn send_canceled(&self) {
2766 self.0
2767 .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))
2768 .ok();
2769 }
2770
2771 fn send_error(&self, error: impl Into<anyhow::Error>) {
2772 self.0.unbounded_send(Err(error.into())).ok();
2773 }
2774}
2775
2776#[derive(Clone)]
2777pub struct ToolCallEventStream {
2778 tool_use_id: LanguageModelToolUseId,
2779 stream: ThreadEventStream,
2780 fs: Option<Arc<dyn Fs>>,
2781 cancellation_rx: watch::Receiver<bool>,
2782}
2783
2784impl ToolCallEventStream {
2785 #[cfg(any(test, feature = "test-support"))]
2786 pub fn test() -> (Self, ToolCallEventStreamReceiver) {
2787 let (stream, receiver, _cancellation_tx) = Self::test_with_cancellation();
2788 (stream, receiver)
2789 }
2790
2791 #[cfg(any(test, feature = "test-support"))]
2792 pub fn test_with_cancellation() -> (Self, ToolCallEventStreamReceiver, watch::Sender<bool>) {
2793 let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
2794 let (cancellation_tx, cancellation_rx) = watch::channel(false);
2795
2796 let stream = ToolCallEventStream::new(
2797 "test_id".into(),
2798 ThreadEventStream(events_tx),
2799 None,
2800 cancellation_rx,
2801 );
2802
2803 (
2804 stream,
2805 ToolCallEventStreamReceiver(events_rx),
2806 cancellation_tx,
2807 )
2808 }
2809
2810 /// Signal cancellation for this event stream. Only available in tests.
2811 #[cfg(any(test, feature = "test-support"))]
2812 pub fn signal_cancellation_with_sender(cancellation_tx: &mut watch::Sender<bool>) {
2813 cancellation_tx.send(true).ok();
2814 }
2815
2816 fn new(
2817 tool_use_id: LanguageModelToolUseId,
2818 stream: ThreadEventStream,
2819 fs: Option<Arc<dyn Fs>>,
2820 cancellation_rx: watch::Receiver<bool>,
2821 ) -> Self {
2822 Self {
2823 tool_use_id,
2824 stream,
2825 fs,
2826 cancellation_rx,
2827 }
2828 }
2829
2830 /// Returns a future that resolves when the user cancels the tool call.
2831 /// Tools should select on this alongside their main work to detect user cancellation.
2832 pub fn cancelled_by_user(&self) -> impl std::future::Future<Output = ()> + '_ {
2833 let mut rx = self.cancellation_rx.clone();
2834 async move {
2835 loop {
2836 if *rx.borrow() {
2837 return;
2838 }
2839 if rx.changed().await.is_err() {
2840 // Sender dropped, will never be cancelled
2841 std::future::pending::<()>().await;
2842 }
2843 }
2844 }
2845 }
2846
2847 /// Returns true if the user has cancelled this tool call.
2848 /// This is useful for checking cancellation state after an operation completes,
2849 /// to determine if the completion was due to user cancellation.
2850 pub fn was_cancelled_by_user(&self) -> bool {
2851 *self.cancellation_rx.clone().borrow()
2852 }
2853
2854 pub fn tool_use_id(&self) -> &LanguageModelToolUseId {
2855 &self.tool_use_id
2856 }
2857
2858 pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
2859 self.stream
2860 .update_tool_call_fields(&self.tool_use_id, fields);
2861 }
2862
2863 pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
2864 self.stream
2865 .0
2866 .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
2867 acp_thread::ToolCallUpdateDiff {
2868 id: acp::ToolCallId::new(self.tool_use_id.to_string()),
2869 diff,
2870 }
2871 .into(),
2872 )))
2873 .ok();
2874 }
2875
2876 pub fn update_subagent_thread(&self, thread: Entity<acp_thread::AcpThread>) {
2877 self.stream
2878 .0
2879 .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
2880 acp_thread::ToolCallUpdateSubagentThread {
2881 id: acp::ToolCallId::new(self.tool_use_id.to_string()),
2882 thread,
2883 }
2884 .into(),
2885 )))
2886 .ok();
2887 }
2888
2889 /// Authorize a third-party tool (e.g., MCP tool from a context server).
2890 ///
2891 /// Unlike built-in tools, third-party tools don't support pattern-based permissions.
2892 /// They only support `default_mode` (allow/deny/confirm) per tool.
2893 ///
2894 /// Shows 3 buttons:
2895 /// - "Always allow <display_name> MCP tool" → sets `tools.<tool_id>.default_mode = "allow"`
2896 /// - "Allow" → approve once
2897 /// - "Deny" → reject once
2898 pub fn authorize_third_party_tool(
2899 &self,
2900 title: impl Into<String>,
2901 tool_id: String,
2902 display_name: String,
2903 cx: &mut App,
2904 ) -> Task<Result<()>> {
2905 let settings = agent_settings::AgentSettings::get_global(cx);
2906
2907 let decision = decide_permission_from_settings(&tool_id, "", &settings);
2908
2909 match decision {
2910 ToolPermissionDecision::Allow => return Task::ready(Ok(())),
2911 ToolPermissionDecision::Deny(reason) => return Task::ready(Err(anyhow!(reason))),
2912 ToolPermissionDecision::Confirm => {}
2913 }
2914
2915 let (response_tx, response_rx) = oneshot::channel();
2916 self.stream
2917 .0
2918 .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
2919 ToolCallAuthorization {
2920 tool_call: acp::ToolCallUpdate::new(
2921 self.tool_use_id.to_string(),
2922 acp::ToolCallUpdateFields::new().title(title.into()),
2923 ),
2924 options: vec![
2925 acp::PermissionOption::new(
2926 acp::PermissionOptionId::new(format!("always_allow_mcp:{}", tool_id)),
2927 format!("Always allow {} MCP tool", display_name),
2928 acp::PermissionOptionKind::AllowAlways,
2929 ),
2930 acp::PermissionOption::new(
2931 acp::PermissionOptionId::new("allow"),
2932 "Allow once",
2933 acp::PermissionOptionKind::AllowOnce,
2934 ),
2935 acp::PermissionOption::new(
2936 acp::PermissionOptionId::new("deny"),
2937 "Deny",
2938 acp::PermissionOptionKind::RejectOnce,
2939 ),
2940 ],
2941 response: response_tx,
2942 context: None,
2943 },
2944 )))
2945 .ok();
2946
2947 let fs = self.fs.clone();
2948 cx.spawn(async move |cx| {
2949 let response_str = response_rx.await?.0.to_string();
2950
2951 if response_str == format!("always_allow_mcp:{}", tool_id) {
2952 if let Some(fs) = fs.clone() {
2953 cx.update(|cx| {
2954 update_settings_file(fs, cx, move |settings, _| {
2955 settings
2956 .agent
2957 .get_or_insert_default()
2958 .set_tool_default_mode(&tool_id, ToolPermissionMode::Allow);
2959 });
2960 });
2961 }
2962 return Ok(());
2963 }
2964
2965 if response_str == "allow" {
2966 return Ok(());
2967 }
2968
2969 Err(anyhow!("Permission to run tool denied by user"))
2970 })
2971 }
2972
2973 pub fn authorize(
2974 &self,
2975 title: impl Into<String>,
2976 context: ToolPermissionContext,
2977 cx: &mut App,
2978 ) -> Task<Result<()>> {
2979 use settings::ToolPermissionMode;
2980
2981 let options = context.build_permission_options();
2982
2983 let (response_tx, response_rx) = oneshot::channel();
2984 self.stream
2985 .0
2986 .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
2987 ToolCallAuthorization {
2988 tool_call: acp::ToolCallUpdate::new(
2989 self.tool_use_id.to_string(),
2990 acp::ToolCallUpdateFields::new().title(title.into()),
2991 ),
2992 options,
2993 response: response_tx,
2994 context: Some(context),
2995 },
2996 )))
2997 .ok();
2998
2999 let fs = self.fs.clone();
3000 cx.spawn(async move |cx| {
3001 let response_str = response_rx.await?.0.to_string();
3002
3003 // Handle "always allow tool" - e.g., "always_allow:terminal"
3004 if let Some(tool) = response_str.strip_prefix("always_allow:") {
3005 if let Some(fs) = fs.clone() {
3006 let tool = tool.to_string();
3007 cx.update(|cx| {
3008 update_settings_file(fs, cx, move |settings, _| {
3009 settings
3010 .agent
3011 .get_or_insert_default()
3012 .set_tool_default_mode(&tool, ToolPermissionMode::Allow);
3013 });
3014 });
3015 }
3016 return Ok(());
3017 }
3018
3019 // Handle "always deny tool" - e.g., "always_deny:terminal"
3020 if let Some(tool) = response_str.strip_prefix("always_deny:") {
3021 if let Some(fs) = fs.clone() {
3022 let tool = tool.to_string();
3023 cx.update(|cx| {
3024 update_settings_file(fs, cx, move |settings, _| {
3025 settings
3026 .agent
3027 .get_or_insert_default()
3028 .set_tool_default_mode(&tool, ToolPermissionMode::Deny);
3029 });
3030 });
3031 }
3032 return Err(anyhow!("Permission to run tool denied by user"));
3033 }
3034
3035 // Handle "always allow pattern" - e.g., "always_allow_pattern:terminal:^cargo\s"
3036 if response_str.starts_with("always_allow_pattern:") {
3037 let parts: Vec<&str> = response_str.splitn(3, ':').collect();
3038 if parts.len() == 3 {
3039 let pattern_tool_name = parts[1].to_string();
3040 let pattern = parts[2].to_string();
3041 if let Some(fs) = fs.clone() {
3042 cx.update(|cx| {
3043 update_settings_file(fs, cx, move |settings, _| {
3044 settings
3045 .agent
3046 .get_or_insert_default()
3047 .add_tool_allow_pattern(&pattern_tool_name, pattern);
3048 });
3049 });
3050 }
3051 }
3052 return Ok(());
3053 }
3054
3055 // Handle "always deny pattern" - e.g., "always_deny_pattern:terminal:^cargo\s"
3056 if response_str.starts_with("always_deny_pattern:") {
3057 let parts: Vec<&str> = response_str.splitn(3, ':').collect();
3058 if parts.len() == 3 {
3059 let pattern_tool_name = parts[1].to_string();
3060 let pattern = parts[2].to_string();
3061 if let Some(fs) = fs.clone() {
3062 cx.update(|cx| {
3063 update_settings_file(fs, cx, move |settings, _| {
3064 settings
3065 .agent
3066 .get_or_insert_default()
3067 .add_tool_deny_pattern(&pattern_tool_name, pattern);
3068 });
3069 });
3070 }
3071 }
3072 return Err(anyhow!("Permission to run tool denied by user"));
3073 }
3074
3075 // Handle simple "allow" (allow once)
3076 if response_str == "allow" {
3077 return Ok(());
3078 }
3079
3080 // Handle simple "deny" (deny once)
3081 Err(anyhow!("Permission to run tool denied by user"))
3082 })
3083 }
3084}
3085
3086#[cfg(any(test, feature = "test-support"))]
3087pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
3088
3089#[cfg(any(test, feature = "test-support"))]
3090impl ToolCallEventStreamReceiver {
3091 pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
3092 let event = self.0.next().await;
3093 if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
3094 auth
3095 } else {
3096 panic!("Expected ToolCallAuthorization but got: {:?}", event);
3097 }
3098 }
3099
3100 pub async fn expect_update_fields(&mut self) -> acp::ToolCallUpdateFields {
3101 let event = self.0.next().await;
3102 if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
3103 update,
3104 )))) = event
3105 {
3106 update.fields
3107 } else {
3108 panic!("Expected update fields but got: {:?}", event);
3109 }
3110 }
3111
3112 pub async fn expect_diff(&mut self) -> Entity<acp_thread::Diff> {
3113 let event = self.0.next().await;
3114 if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateDiff(
3115 update,
3116 )))) = event
3117 {
3118 update.diff
3119 } else {
3120 panic!("Expected diff but got: {:?}", event);
3121 }
3122 }
3123
3124 pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
3125 let event = self.0.next().await;
3126 if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
3127 update,
3128 )))) = event
3129 {
3130 update.terminal
3131 } else {
3132 panic!("Expected terminal but got: {:?}", event);
3133 }
3134 }
3135}
3136
3137#[cfg(any(test, feature = "test-support"))]
3138impl std::ops::Deref for ToolCallEventStreamReceiver {
3139 type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
3140
3141 fn deref(&self) -> &Self::Target {
3142 &self.0
3143 }
3144}
3145
3146#[cfg(any(test, feature = "test-support"))]
3147impl std::ops::DerefMut for ToolCallEventStreamReceiver {
3148 fn deref_mut(&mut self) -> &mut Self::Target {
3149 &mut self.0
3150 }
3151}
3152
3153impl From<&str> for UserMessageContent {
3154 fn from(text: &str) -> Self {
3155 Self::Text(text.into())
3156 }
3157}
3158
3159impl UserMessageContent {
3160 pub fn from_content_block(value: acp::ContentBlock, path_style: PathStyle) -> Self {
3161 match value {
3162 acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
3163 acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
3164 acp::ContentBlock::Audio(_) => {
3165 // TODO
3166 Self::Text("[audio]".to_string())
3167 }
3168 acp::ContentBlock::ResourceLink(resource_link) => {
3169 match MentionUri::parse(&resource_link.uri, path_style) {
3170 Ok(uri) => Self::Mention {
3171 uri,
3172 content: String::new(),
3173 },
3174 Err(err) => {
3175 log::error!("Failed to parse mention link: {}", err);
3176 Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
3177 }
3178 }
3179 }
3180 acp::ContentBlock::Resource(resource) => match resource.resource {
3181 acp::EmbeddedResourceResource::TextResourceContents(resource) => {
3182 match MentionUri::parse(&resource.uri, path_style) {
3183 Ok(uri) => Self::Mention {
3184 uri,
3185 content: resource.text,
3186 },
3187 Err(err) => {
3188 log::error!("Failed to parse mention link: {}", err);
3189 Self::Text(
3190 MarkdownCodeBlock {
3191 tag: &resource.uri,
3192 text: &resource.text,
3193 }
3194 .to_string(),
3195 )
3196 }
3197 }
3198 }
3199 acp::EmbeddedResourceResource::BlobResourceContents(_) => {
3200 // TODO
3201 Self::Text("[blob]".to_string())
3202 }
3203 other => {
3204 log::warn!("Unexpected content type: {:?}", other);
3205 Self::Text("[unknown]".to_string())
3206 }
3207 },
3208 other => {
3209 log::warn!("Unexpected content type: {:?}", other);
3210 Self::Text("[unknown]".to_string())
3211 }
3212 }
3213 }
3214}
3215
3216impl From<UserMessageContent> for acp::ContentBlock {
3217 fn from(content: UserMessageContent) -> Self {
3218 match content {
3219 UserMessageContent::Text(text) => text.into(),
3220 UserMessageContent::Image(image) => {
3221 acp::ContentBlock::Image(acp::ImageContent::new(image.source, "image/png"))
3222 }
3223 UserMessageContent::Mention { uri, content } => acp::ContentBlock::Resource(
3224 acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(
3225 acp::TextResourceContents::new(content, uri.to_uri().to_string()),
3226 )),
3227 ),
3228 }
3229 }
3230}
3231
3232fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
3233 LanguageModelImage {
3234 source: image_content.data.into(),
3235 size: None,
3236 }
3237}