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