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