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