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