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