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