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