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