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