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