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