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 max_output_tokens: model.max_output_tokens(),
1511 used_tokens: usage.total_tokens(),
1512 input_tokens: usage.input_tokens,
1513 output_tokens: usage.output_tokens,
1514 })
1515 }
1516
1517 /// Get the total input token count as of the message before the given message.
1518 ///
1519 /// Returns `None` if:
1520 /// - `target_id` is the first message (no previous message)
1521 /// - The previous message hasn't received a response yet (no usage data)
1522 /// - `target_id` is not found in the messages
1523 pub fn tokens_before_message(&self, target_id: &UserMessageId) -> Option<u64> {
1524 let mut previous_user_message_id: Option<&UserMessageId> = None;
1525
1526 for message in &self.messages {
1527 if let Message::User(user_msg) = message {
1528 if &user_msg.id == target_id {
1529 let prev_id = previous_user_message_id?;
1530 let usage = self.request_token_usage.get(prev_id)?;
1531 return Some(usage.input_tokens);
1532 }
1533 previous_user_message_id = Some(&user_msg.id);
1534 }
1535 }
1536 None
1537 }
1538
1539 /// Look up the active profile and resolve its preferred model if one is configured.
1540 fn resolve_profile_model(
1541 profile_id: &AgentProfileId,
1542 cx: &mut Context<Self>,
1543 ) -> Option<Arc<dyn LanguageModel>> {
1544 let selection = AgentSettings::get_global(cx)
1545 .profiles
1546 .get(profile_id)?
1547 .default_model
1548 .clone()?;
1549 Self::resolve_model_from_selection(&selection, cx)
1550 }
1551
1552 /// Translate a stored model selection into the configured model from the registry.
1553 fn resolve_model_from_selection(
1554 selection: &LanguageModelSelection,
1555 cx: &mut Context<Self>,
1556 ) -> Option<Arc<dyn LanguageModel>> {
1557 let selected = SelectedModel {
1558 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
1559 model: LanguageModelId::from(selection.model.clone()),
1560 };
1561 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1562 registry
1563 .select_model(&selected, cx)
1564 .map(|configured| configured.model)
1565 })
1566 }
1567
1568 pub fn resume(
1569 &mut self,
1570 cx: &mut Context<Self>,
1571 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1572 self.messages.push(Message::Resume);
1573 cx.notify();
1574
1575 log::debug!("Total messages in thread: {}", self.messages.len());
1576 self.run_turn(cx)
1577 }
1578
1579 /// Sending a message results in the model streaming a response, which could include tool calls.
1580 /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
1581 /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
1582 pub fn send<T>(
1583 &mut self,
1584 id: UserMessageId,
1585 content: impl IntoIterator<Item = T>,
1586 cx: &mut Context<Self>,
1587 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
1588 where
1589 T: Into<UserMessageContent>,
1590 {
1591 let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
1592 log::debug!("Thread::send content: {:?}", content);
1593
1594 self.messages
1595 .push(Message::User(UserMessage { id, content }));
1596 cx.notify();
1597
1598 self.send_existing(cx)
1599 }
1600
1601 pub fn send_existing(
1602 &mut self,
1603 cx: &mut Context<Self>,
1604 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1605 let model = self.model().context("No language model configured")?;
1606
1607 log::info!("Thread::send called with model: {}", model.name().0);
1608 self.advance_prompt_id();
1609
1610 log::debug!("Total messages in thread: {}", self.messages.len());
1611 self.run_turn(cx)
1612 }
1613
1614 pub fn push_acp_user_block(
1615 &mut self,
1616 id: UserMessageId,
1617 blocks: impl IntoIterator<Item = acp::ContentBlock>,
1618 path_style: PathStyle,
1619 cx: &mut Context<Self>,
1620 ) {
1621 let content = blocks
1622 .into_iter()
1623 .map(|block| UserMessageContent::from_content_block(block, path_style))
1624 .collect::<Vec<_>>();
1625 self.messages
1626 .push(Message::User(UserMessage { id, content }));
1627 cx.notify();
1628 }
1629
1630 pub fn push_acp_agent_block(&mut self, block: acp::ContentBlock, cx: &mut Context<Self>) {
1631 let text = match block {
1632 acp::ContentBlock::Text(text_content) => text_content.text,
1633 acp::ContentBlock::Image(_) => "[image]".to_string(),
1634 acp::ContentBlock::Audio(_) => "[audio]".to_string(),
1635 acp::ContentBlock::ResourceLink(resource_link) => resource_link.uri,
1636 acp::ContentBlock::Resource(resource) => match resource.resource {
1637 acp::EmbeddedResourceResource::TextResourceContents(resource) => resource.uri,
1638 acp::EmbeddedResourceResource::BlobResourceContents(resource) => resource.uri,
1639 _ => "[resource]".to_string(),
1640 },
1641 _ => "[unknown]".to_string(),
1642 };
1643
1644 self.messages.push(Message::Agent(AgentMessage {
1645 content: vec![AgentMessageContent::Text(text)],
1646 ..Default::default()
1647 }));
1648 cx.notify();
1649 }
1650
1651 #[cfg(feature = "eval")]
1652 pub fn proceed(
1653 &mut self,
1654 cx: &mut Context<Self>,
1655 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1656 self.run_turn(cx)
1657 }
1658
1659 fn run_turn(
1660 &mut self,
1661 cx: &mut Context<Self>,
1662 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1663 // Flush the old pending message synchronously before cancelling,
1664 // to avoid a race where the detached cancel task might flush the NEW
1665 // turn's pending message instead of the old one.
1666 self.flush_pending_message(cx);
1667 self.cancel(cx).detach();
1668
1669 let model = self.model.clone().context("No language model configured")?;
1670 let profile = AgentSettings::get_global(cx)
1671 .profiles
1672 .get(&self.profile_id)
1673 .context("Profile not found")?;
1674 let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1675 let event_stream = ThreadEventStream(events_tx);
1676 let message_ix = self.messages.len().saturating_sub(1);
1677 self.clear_summary();
1678 let (cancellation_tx, mut cancellation_rx) = watch::channel(false);
1679 self.running_turn = Some(RunningTurn {
1680 event_stream: event_stream.clone(),
1681 tools: self.enabled_tools(profile, &model, cx),
1682 cancellation_tx,
1683 _task: cx.spawn(async move |this, cx| {
1684 log::debug!("Starting agent turn execution");
1685
1686 let turn_result = Self::run_turn_internal(
1687 &this,
1688 model,
1689 &event_stream,
1690 cancellation_rx.clone(),
1691 cx,
1692 )
1693 .await;
1694
1695 // Check if we were cancelled - if so, cancel() already took running_turn
1696 // and we shouldn't touch it (it might be a NEW turn now)
1697 let was_cancelled = *cancellation_rx.borrow();
1698 if was_cancelled {
1699 log::debug!("Turn was cancelled, skipping cleanup");
1700 return;
1701 }
1702
1703 _ = this.update(cx, |this, cx| this.flush_pending_message(cx));
1704
1705 match turn_result {
1706 Ok(()) => {
1707 log::debug!("Turn execution completed");
1708 event_stream.send_stop(acp::StopReason::EndTurn);
1709 }
1710 Err(error) => {
1711 log::error!("Turn execution failed: {:?}", error);
1712 match error.downcast::<CompletionError>() {
1713 Ok(CompletionError::Refusal) => {
1714 event_stream.send_stop(acp::StopReason::Refusal);
1715 _ = this.update(cx, |this, _| this.messages.truncate(message_ix));
1716 }
1717 Ok(CompletionError::MaxTokens) => {
1718 event_stream.send_stop(acp::StopReason::MaxTokens);
1719 }
1720 Ok(CompletionError::Other(error)) | Err(error) => {
1721 event_stream.send_error(error);
1722 }
1723 }
1724 }
1725 }
1726
1727 _ = this.update(cx, |this, _| this.running_turn.take());
1728 }),
1729 });
1730 Ok(events_rx)
1731 }
1732
1733 async fn run_turn_internal(
1734 this: &WeakEntity<Self>,
1735 model: Arc<dyn LanguageModel>,
1736 event_stream: &ThreadEventStream,
1737 mut cancellation_rx: watch::Receiver<bool>,
1738 cx: &mut AsyncApp,
1739 ) -> Result<()> {
1740 let mut attempt = 0;
1741 let mut intent = CompletionIntent::UserPrompt;
1742 loop {
1743 let request =
1744 this.update(cx, |this, cx| this.build_completion_request(intent, cx))??;
1745
1746 telemetry::event!(
1747 "Agent Thread Completion",
1748 thread_id = this.read_with(cx, |this, _| this.id.to_string())?,
1749 prompt_id = this.read_with(cx, |this, _| this.prompt_id.to_string())?,
1750 model = model.telemetry_id(),
1751 model_provider = model.provider_id().to_string(),
1752 attempt
1753 );
1754
1755 log::debug!("Calling model.stream_completion, attempt {}", attempt);
1756
1757 let (mut events, mut error) = match model.stream_completion(request, cx).await {
1758 Ok(events) => (events.fuse(), None),
1759 Err(err) => (stream::empty().boxed().fuse(), Some(err)),
1760 };
1761 let mut tool_results = FuturesUnordered::new();
1762 let mut cancelled = false;
1763 loop {
1764 // Race between getting the first event and cancellation
1765 let first_event = futures::select! {
1766 event = events.next().fuse() => event,
1767 _ = cancellation_rx.changed().fuse() => {
1768 if *cancellation_rx.borrow() {
1769 cancelled = true;
1770 break;
1771 }
1772 continue;
1773 }
1774 };
1775 let Some(first_event) = first_event else {
1776 break;
1777 };
1778
1779 // Collect all immediately available events to process as a batch
1780 let mut batch = vec![first_event];
1781 while let Some(event) = events.next().now_or_never().flatten() {
1782 batch.push(event);
1783 }
1784
1785 // Process the batch in a single update
1786 let batch_result = this.update(cx, |this, cx| {
1787 let mut batch_tool_results = Vec::new();
1788 let mut batch_error = None;
1789
1790 for event in batch {
1791 log::trace!("Received completion event: {:?}", event);
1792 match event {
1793 Ok(event) => {
1794 match this.handle_completion_event(
1795 event,
1796 event_stream,
1797 cancellation_rx.clone(),
1798 cx,
1799 ) {
1800 Ok(Some(task)) => batch_tool_results.push(task),
1801 Ok(None) => {}
1802 Err(err) => {
1803 batch_error = Some(err);
1804 break;
1805 }
1806 }
1807 }
1808 Err(err) => {
1809 batch_error = Some(err.into());
1810 break;
1811 }
1812 }
1813 }
1814
1815 cx.notify();
1816 (batch_tool_results, batch_error)
1817 })?;
1818
1819 tool_results.extend(batch_result.0);
1820 if let Some(err) = batch_result.1 {
1821 error = Some(err.downcast()?);
1822 break;
1823 }
1824 }
1825
1826 // Drop the stream to release the rate limit permit before tool execution.
1827 // The stream holds a semaphore guard that limits concurrent requests.
1828 // Without this, the permit would be held during potentially long-running
1829 // tool execution, which could cause deadlocks when tools spawn subagents
1830 // that need their own permits.
1831 drop(events);
1832
1833 let end_turn = tool_results.is_empty();
1834 while let Some(tool_result) = tool_results.next().await {
1835 log::debug!("Tool finished {:?}", tool_result);
1836
1837 event_stream.update_tool_call_fields(
1838 &tool_result.tool_use_id,
1839 acp::ToolCallUpdateFields::new()
1840 .status(if tool_result.is_error {
1841 acp::ToolCallStatus::Failed
1842 } else {
1843 acp::ToolCallStatus::Completed
1844 })
1845 .raw_output(tool_result.output.clone()),
1846 None,
1847 );
1848 this.update(cx, |this, _cx| {
1849 this.pending_message()
1850 .tool_results
1851 .insert(tool_result.tool_use_id.clone(), tool_result);
1852 })?;
1853 }
1854
1855 this.update(cx, |this, cx| {
1856 this.flush_pending_message(cx);
1857 if this.title.is_none() && this.pending_title_generation.is_none() {
1858 this.generate_title(cx);
1859 }
1860 })?;
1861
1862 if cancelled {
1863 log::debug!("Turn cancelled by user, exiting");
1864 return Ok(());
1865 }
1866
1867 if let Some(error) = error {
1868 attempt += 1;
1869 let retry = this.update(cx, |this, cx| {
1870 let user_store = this.user_store.read(cx);
1871 this.handle_completion_error(error, attempt, user_store.plan())
1872 })??;
1873 let timer = cx.background_executor().timer(retry.duration);
1874 event_stream.send_retry(retry);
1875 timer.await;
1876 this.update(cx, |this, _cx| {
1877 if let Some(Message::Agent(message)) = this.messages.last() {
1878 if message.tool_results.is_empty() {
1879 intent = CompletionIntent::UserPrompt;
1880 this.messages.push(Message::Resume);
1881 }
1882 }
1883 })?;
1884 } else if end_turn {
1885 return Ok(());
1886 } else {
1887 let has_queued = this.update(cx, |this, _| this.has_queued_message())?;
1888 if has_queued {
1889 log::debug!("Queued message found, ending turn at message boundary");
1890 return Ok(());
1891 }
1892 intent = CompletionIntent::ToolResults;
1893 attempt = 0;
1894 }
1895 }
1896 }
1897
1898 fn handle_completion_error(
1899 &mut self,
1900 error: LanguageModelCompletionError,
1901 attempt: u8,
1902 plan: Option<Plan>,
1903 ) -> Result<acp_thread::RetryStatus> {
1904 let Some(model) = self.model.as_ref() else {
1905 return Err(anyhow!(error));
1906 };
1907
1908 let auto_retry = if model.provider_id() == ZED_CLOUD_PROVIDER_ID {
1909 plan.is_some()
1910 } else {
1911 true
1912 };
1913
1914 if !auto_retry {
1915 return Err(anyhow!(error));
1916 }
1917
1918 let Some(strategy) = Self::retry_strategy_for(&error) else {
1919 return Err(anyhow!(error));
1920 };
1921
1922 let max_attempts = match &strategy {
1923 RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
1924 RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
1925 };
1926
1927 if attempt > max_attempts {
1928 return Err(anyhow!(error));
1929 }
1930
1931 let delay = match &strategy {
1932 RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
1933 let delay_secs = initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
1934 Duration::from_secs(delay_secs)
1935 }
1936 RetryStrategy::Fixed { delay, .. } => *delay,
1937 };
1938 log::debug!("Retry attempt {attempt} with delay {delay:?}");
1939
1940 Ok(acp_thread::RetryStatus {
1941 last_error: error.to_string().into(),
1942 attempt: attempt as usize,
1943 max_attempts: max_attempts as usize,
1944 started_at: Instant::now(),
1945 duration: delay,
1946 })
1947 }
1948
1949 /// A helper method that's called on every streamed completion event.
1950 /// Returns an optional tool result task, which the main agentic loop will
1951 /// send back to the model when it resolves.
1952 fn handle_completion_event(
1953 &mut self,
1954 event: LanguageModelCompletionEvent,
1955 event_stream: &ThreadEventStream,
1956 cancellation_rx: watch::Receiver<bool>,
1957 cx: &mut Context<Self>,
1958 ) -> Result<Option<Task<LanguageModelToolResult>>> {
1959 log::trace!("Handling streamed completion event: {:?}", event);
1960 use LanguageModelCompletionEvent::*;
1961
1962 match event {
1963 StartMessage { .. } => {
1964 self.flush_pending_message(cx);
1965 self.pending_message = Some(AgentMessage::default());
1966 }
1967 Text(new_text) => self.handle_text_event(new_text, event_stream),
1968 Thinking { text, signature } => {
1969 self.handle_thinking_event(text, signature, event_stream)
1970 }
1971 RedactedThinking { data } => self.handle_redacted_thinking_event(data),
1972 ReasoningDetails(details) => {
1973 let last_message = self.pending_message();
1974 // Store the last non-empty reasoning_details (overwrites earlier ones)
1975 // This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
1976 if let serde_json::Value::Array(ref arr) = details {
1977 if !arr.is_empty() {
1978 last_message.reasoning_details = Some(details);
1979 }
1980 } else {
1981 last_message.reasoning_details = Some(details);
1982 }
1983 }
1984 ToolUse(tool_use) => {
1985 return Ok(self.handle_tool_use_event(tool_use, event_stream, cancellation_rx, cx));
1986 }
1987 ToolUseJsonParseError {
1988 id,
1989 tool_name,
1990 raw_input,
1991 json_parse_error,
1992 } => {
1993 return Ok(Some(Task::ready(
1994 self.handle_tool_use_json_parse_error_event(
1995 id,
1996 tool_name,
1997 raw_input,
1998 json_parse_error,
1999 event_stream,
2000 ),
2001 )));
2002 }
2003 UsageUpdate(usage) => {
2004 telemetry::event!(
2005 "Agent Thread Completion Usage Updated",
2006 thread_id = self.id.to_string(),
2007 prompt_id = self.prompt_id.to_string(),
2008 model = self.model.as_ref().map(|m| m.telemetry_id()),
2009 model_provider = self.model.as_ref().map(|m| m.provider_id().to_string()),
2010 input_tokens = usage.input_tokens,
2011 output_tokens = usage.output_tokens,
2012 cache_creation_input_tokens = usage.cache_creation_input_tokens,
2013 cache_read_input_tokens = usage.cache_read_input_tokens,
2014 );
2015 self.update_token_usage(usage, cx);
2016 }
2017 Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()),
2018 Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()),
2019 Stop(StopReason::ToolUse | StopReason::EndTurn) => {}
2020 Started | Queued { .. } => {}
2021 }
2022
2023 Ok(None)
2024 }
2025
2026 fn handle_text_event(&mut self, new_text: String, event_stream: &ThreadEventStream) {
2027 event_stream.send_text(&new_text);
2028
2029 let last_message = self.pending_message();
2030 if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
2031 text.push_str(&new_text);
2032 } else {
2033 last_message
2034 .content
2035 .push(AgentMessageContent::Text(new_text));
2036 }
2037 }
2038
2039 fn handle_thinking_event(
2040 &mut self,
2041 new_text: String,
2042 new_signature: Option<String>,
2043 event_stream: &ThreadEventStream,
2044 ) {
2045 event_stream.send_thinking(&new_text);
2046
2047 let last_message = self.pending_message();
2048 if let Some(AgentMessageContent::Thinking { text, signature }) =
2049 last_message.content.last_mut()
2050 {
2051 text.push_str(&new_text);
2052 *signature = new_signature.or(signature.take());
2053 } else {
2054 last_message.content.push(AgentMessageContent::Thinking {
2055 text: new_text,
2056 signature: new_signature,
2057 });
2058 }
2059 }
2060
2061 fn handle_redacted_thinking_event(&mut self, data: String) {
2062 let last_message = self.pending_message();
2063 last_message
2064 .content
2065 .push(AgentMessageContent::RedactedThinking(data));
2066 }
2067
2068 fn handle_tool_use_event(
2069 &mut self,
2070 tool_use: LanguageModelToolUse,
2071 event_stream: &ThreadEventStream,
2072 cancellation_rx: watch::Receiver<bool>,
2073 cx: &mut Context<Self>,
2074 ) -> Option<Task<LanguageModelToolResult>> {
2075 cx.notify();
2076
2077 let tool = self.tool(tool_use.name.as_ref());
2078 let mut title = SharedString::from(&tool_use.name);
2079 let mut kind = acp::ToolKind::Other;
2080 if let Some(tool) = tool.as_ref() {
2081 title = tool.initial_title(tool_use.input.clone(), cx);
2082 kind = tool.kind();
2083 }
2084
2085 self.send_or_update_tool_use(&tool_use, title, kind, event_stream);
2086
2087 if !tool_use.is_input_complete {
2088 return None;
2089 }
2090
2091 let Some(tool) = tool else {
2092 let content = format!("No tool named {} exists", tool_use.name);
2093 return Some(Task::ready(LanguageModelToolResult {
2094 content: LanguageModelToolResultContent::Text(Arc::from(content)),
2095 tool_use_id: tool_use.id,
2096 tool_name: tool_use.name,
2097 is_error: true,
2098 output: None,
2099 }));
2100 };
2101
2102 let fs = self.project.read(cx).fs().clone();
2103 let tool_event_stream = ToolCallEventStream::new(
2104 tool_use.id.clone(),
2105 event_stream.clone(),
2106 Some(fs),
2107 cancellation_rx,
2108 );
2109 tool_event_stream.update_fields(
2110 acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
2111 );
2112 let supports_images = self.model().is_some_and(|model| model.supports_images());
2113 let tool_result = tool.run(tool_use.input, tool_event_stream, cx);
2114 log::debug!("Running tool {}", tool_use.name);
2115 Some(cx.foreground_executor().spawn(async move {
2116 let tool_result = tool_result.await.and_then(|output| {
2117 if let LanguageModelToolResultContent::Image(_) = &output.llm_output
2118 && !supports_images
2119 {
2120 return Err(anyhow!(
2121 "Attempted to read an image, but this model doesn't support it.",
2122 ));
2123 }
2124 Ok(output)
2125 });
2126
2127 match tool_result {
2128 Ok(output) => LanguageModelToolResult {
2129 tool_use_id: tool_use.id,
2130 tool_name: tool_use.name,
2131 is_error: false,
2132 content: output.llm_output,
2133 output: Some(output.raw_output),
2134 },
2135 Err(error) => LanguageModelToolResult {
2136 tool_use_id: tool_use.id,
2137 tool_name: tool_use.name,
2138 is_error: true,
2139 content: LanguageModelToolResultContent::Text(Arc::from(error.to_string())),
2140 output: Some(error.to_string().into()),
2141 },
2142 }
2143 }))
2144 }
2145
2146 fn handle_tool_use_json_parse_error_event(
2147 &mut self,
2148 tool_use_id: LanguageModelToolUseId,
2149 tool_name: Arc<str>,
2150 raw_input: Arc<str>,
2151 json_parse_error: String,
2152 event_stream: &ThreadEventStream,
2153 ) -> LanguageModelToolResult {
2154 let tool_use = LanguageModelToolUse {
2155 id: tool_use_id.clone(),
2156 name: tool_name.clone(),
2157 raw_input: raw_input.to_string(),
2158 input: serde_json::json!({}),
2159 is_input_complete: true,
2160 thought_signature: None,
2161 };
2162 self.send_or_update_tool_use(
2163 &tool_use,
2164 SharedString::from(&tool_use.name),
2165 acp::ToolKind::Other,
2166 event_stream,
2167 );
2168
2169 let tool_output = format!("Error parsing input JSON: {json_parse_error}");
2170 LanguageModelToolResult {
2171 tool_use_id,
2172 tool_name,
2173 is_error: true,
2174 content: LanguageModelToolResultContent::Text(tool_output.into()),
2175 output: Some(serde_json::Value::String(raw_input.to_string())),
2176 }
2177 }
2178
2179 fn send_or_update_tool_use(
2180 &mut self,
2181 tool_use: &LanguageModelToolUse,
2182 title: SharedString,
2183 kind: acp::ToolKind,
2184 event_stream: &ThreadEventStream,
2185 ) {
2186 // Ensure the last message ends in the current tool use
2187 let last_message = self.pending_message();
2188 let push_new_tool_use = last_message.content.last_mut().is_none_or(|content| {
2189 if let AgentMessageContent::ToolUse(last_tool_use) = content {
2190 if last_tool_use.id == tool_use.id {
2191 *last_tool_use = tool_use.clone();
2192 false
2193 } else {
2194 true
2195 }
2196 } else {
2197 true
2198 }
2199 });
2200
2201 if push_new_tool_use {
2202 event_stream.send_tool_call(
2203 &tool_use.id,
2204 &tool_use.name,
2205 title,
2206 kind,
2207 tool_use.input.clone(),
2208 );
2209 last_message
2210 .content
2211 .push(AgentMessageContent::ToolUse(tool_use.clone()));
2212 } else {
2213 event_stream.update_tool_call_fields(
2214 &tool_use.id,
2215 acp::ToolCallUpdateFields::new()
2216 .title(title.as_str())
2217 .kind(kind)
2218 .raw_input(tool_use.input.clone()),
2219 None,
2220 );
2221 }
2222 }
2223
2224 pub fn title(&self) -> SharedString {
2225 self.title.clone().unwrap_or("New Thread".into())
2226 }
2227
2228 pub fn is_generating_summary(&self) -> bool {
2229 self.pending_summary_generation.is_some()
2230 }
2231
2232 pub fn is_generating_title(&self) -> bool {
2233 self.pending_title_generation.is_some()
2234 }
2235
2236 pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
2237 if let Some(summary) = self.summary.as_ref() {
2238 return Task::ready(Some(summary.clone())).shared();
2239 }
2240 if let Some(task) = self.pending_summary_generation.clone() {
2241 return task;
2242 }
2243 let Some(model) = self.summarization_model.clone() else {
2244 log::error!("No summarization model available");
2245 return Task::ready(None).shared();
2246 };
2247 let mut request = LanguageModelRequest {
2248 intent: Some(CompletionIntent::ThreadContextSummarization),
2249 temperature: AgentSettings::temperature_for_model(&model, cx),
2250 ..Default::default()
2251 };
2252
2253 for message in &self.messages {
2254 request.messages.extend(message.to_request());
2255 }
2256
2257 request.messages.push(LanguageModelRequestMessage {
2258 role: Role::User,
2259 content: vec![SUMMARIZE_THREAD_DETAILED_PROMPT.into()],
2260 cache: false,
2261 reasoning_details: None,
2262 });
2263
2264 let task = cx
2265 .spawn(async move |this, cx| {
2266 let mut summary = String::new();
2267 let mut messages = model.stream_completion(request, cx).await.log_err()?;
2268 while let Some(event) = messages.next().await {
2269 let event = event.log_err()?;
2270 let text = match event {
2271 LanguageModelCompletionEvent::Text(text) => text,
2272 _ => continue,
2273 };
2274
2275 let mut lines = text.lines();
2276 summary.extend(lines.next());
2277 }
2278
2279 log::debug!("Setting summary: {}", summary);
2280 let summary = SharedString::from(summary);
2281
2282 this.update(cx, |this, cx| {
2283 this.summary = Some(summary.clone());
2284 this.pending_summary_generation = None;
2285 cx.notify()
2286 })
2287 .ok()?;
2288
2289 Some(summary)
2290 })
2291 .shared();
2292 self.pending_summary_generation = Some(task.clone());
2293 task
2294 }
2295
2296 pub fn generate_title(&mut self, cx: &mut Context<Self>) {
2297 let Some(model) = self.summarization_model.clone() else {
2298 return;
2299 };
2300
2301 log::debug!(
2302 "Generating title with model: {:?}",
2303 self.summarization_model.as_ref().map(|model| model.name())
2304 );
2305 let mut request = LanguageModelRequest {
2306 intent: Some(CompletionIntent::ThreadSummarization),
2307 temperature: AgentSettings::temperature_for_model(&model, cx),
2308 ..Default::default()
2309 };
2310
2311 for message in &self.messages {
2312 request.messages.extend(message.to_request());
2313 }
2314
2315 request.messages.push(LanguageModelRequestMessage {
2316 role: Role::User,
2317 content: vec![SUMMARIZE_THREAD_PROMPT.into()],
2318 cache: false,
2319 reasoning_details: None,
2320 });
2321 self.pending_title_generation = Some(cx.spawn(async move |this, cx| {
2322 let mut title = String::new();
2323
2324 let generate = async {
2325 let mut messages = model.stream_completion(request, cx).await?;
2326 while let Some(event) = messages.next().await {
2327 let event = event?;
2328 let text = match event {
2329 LanguageModelCompletionEvent::Text(text) => text,
2330 _ => continue,
2331 };
2332
2333 let mut lines = text.lines();
2334 title.extend(lines.next());
2335
2336 // Stop if the LLM generated multiple lines.
2337 if lines.next().is_some() {
2338 break;
2339 }
2340 }
2341 anyhow::Ok(())
2342 };
2343
2344 if generate.await.context("failed to generate title").is_ok() {
2345 _ = this.update(cx, |this, cx| this.set_title(title.into(), cx));
2346 }
2347 _ = this.update(cx, |this, _| this.pending_title_generation = None);
2348 }));
2349 }
2350
2351 pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
2352 self.pending_title_generation = None;
2353 if Some(&title) != self.title.as_ref() {
2354 self.title = Some(title);
2355 cx.emit(TitleUpdated);
2356 cx.notify();
2357 }
2358 }
2359
2360 fn clear_summary(&mut self) {
2361 self.summary = None;
2362 self.pending_summary_generation = None;
2363 }
2364
2365 fn last_user_message(&self) -> Option<&UserMessage> {
2366 self.messages
2367 .iter()
2368 .rev()
2369 .find_map(|message| match message {
2370 Message::User(user_message) => Some(user_message),
2371 Message::Agent(_) => None,
2372 Message::Resume => None,
2373 })
2374 }
2375
2376 fn pending_message(&mut self) -> &mut AgentMessage {
2377 self.pending_message.get_or_insert_default()
2378 }
2379
2380 fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
2381 let Some(mut message) = self.pending_message.take() else {
2382 return;
2383 };
2384
2385 if message.content.is_empty() {
2386 return;
2387 }
2388
2389 for content in &message.content {
2390 let AgentMessageContent::ToolUse(tool_use) = content else {
2391 continue;
2392 };
2393
2394 if !message.tool_results.contains_key(&tool_use.id) {
2395 message.tool_results.insert(
2396 tool_use.id.clone(),
2397 LanguageModelToolResult {
2398 tool_use_id: tool_use.id.clone(),
2399 tool_name: tool_use.name.clone(),
2400 is_error: true,
2401 content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
2402 output: None,
2403 },
2404 );
2405 }
2406 }
2407
2408 self.messages.push(Message::Agent(message));
2409 self.updated_at = Utc::now();
2410 self.clear_summary();
2411 cx.notify()
2412 }
2413
2414 pub(crate) fn build_completion_request(
2415 &self,
2416 completion_intent: CompletionIntent,
2417 cx: &App,
2418 ) -> Result<LanguageModelRequest> {
2419 let model = self.model().context("No language model configured")?;
2420 let tools = if let Some(turn) = self.running_turn.as_ref() {
2421 turn.tools
2422 .iter()
2423 .filter_map(|(tool_name, tool)| {
2424 log::trace!("Including tool: {}", tool_name);
2425 Some(LanguageModelRequestTool {
2426 name: tool_name.to_string(),
2427 description: tool.description().to_string(),
2428 input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
2429 })
2430 })
2431 .collect::<Vec<_>>()
2432 } else {
2433 Vec::new()
2434 };
2435
2436 log::debug!("Building completion request");
2437 log::debug!("Completion intent: {:?}", completion_intent);
2438
2439 let available_tools: Vec<_> = self
2440 .running_turn
2441 .as_ref()
2442 .map(|turn| turn.tools.keys().cloned().collect())
2443 .unwrap_or_default();
2444
2445 log::debug!("Request includes {} tools", available_tools.len());
2446 let messages = self.build_request_messages(available_tools, cx);
2447 log::debug!("Request will include {} messages", messages.len());
2448
2449 let request = LanguageModelRequest {
2450 thread_id: Some(self.id.to_string()),
2451 prompt_id: Some(self.prompt_id.to_string()),
2452 intent: Some(completion_intent),
2453 messages,
2454 tools,
2455 tool_choice: None,
2456 stop: Vec::new(),
2457 temperature: AgentSettings::temperature_for_model(model, cx),
2458 thinking_allowed: self.thinking_enabled,
2459 thinking_effort: self.thinking_effort.clone(),
2460 };
2461
2462 log::debug!("Completion request built successfully");
2463 Ok(request)
2464 }
2465
2466 fn enabled_tools(
2467 &self,
2468 profile: &AgentProfileSettings,
2469 model: &Arc<dyn LanguageModel>,
2470 cx: &App,
2471 ) -> BTreeMap<SharedString, Arc<dyn AnyAgentTool>> {
2472 fn truncate(tool_name: &SharedString) -> SharedString {
2473 if tool_name.len() > MAX_TOOL_NAME_LENGTH {
2474 let mut truncated = tool_name.to_string();
2475 truncated.truncate(MAX_TOOL_NAME_LENGTH);
2476 truncated.into()
2477 } else {
2478 tool_name.clone()
2479 }
2480 }
2481
2482 let use_streaming_edit_tool = false;
2483
2484 let mut tools = self
2485 .tools
2486 .iter()
2487 .filter_map(|(tool_name, tool)| {
2488 // For streaming_edit_file, check profile against "edit_file" since that's what users configure
2489 let profile_tool_name = if tool_name == StreamingEditFileTool::NAME {
2490 EditFileTool::NAME
2491 } else {
2492 tool_name.as_ref()
2493 };
2494
2495 if tool.supports_provider(&model.provider_id())
2496 && profile.is_tool_enabled(profile_tool_name)
2497 {
2498 match (tool_name.as_ref(), use_streaming_edit_tool) {
2499 (StreamingEditFileTool::NAME, false) | (EditFileTool::NAME, true) => None,
2500 (StreamingEditFileTool::NAME, true) => {
2501 // Expose streaming tool as "edit_file"
2502 Some((SharedString::from(EditFileTool::NAME), tool.clone()))
2503 }
2504 _ => Some((truncate(tool_name), tool.clone())),
2505 }
2506 } else {
2507 None
2508 }
2509 })
2510 .collect::<BTreeMap<_, _>>();
2511
2512 let mut context_server_tools = Vec::new();
2513 let mut seen_tools = tools.keys().cloned().collect::<HashSet<_>>();
2514 let mut duplicate_tool_names = HashSet::default();
2515 for (server_id, server_tools) in self.context_server_registry.read(cx).servers() {
2516 for (tool_name, tool) in server_tools {
2517 if profile.is_context_server_tool_enabled(&server_id.0, &tool_name) {
2518 let tool_name = truncate(tool_name);
2519 if !seen_tools.insert(tool_name.clone()) {
2520 duplicate_tool_names.insert(tool_name.clone());
2521 }
2522 context_server_tools.push((server_id.clone(), tool_name, tool.clone()));
2523 }
2524 }
2525 }
2526
2527 // When there are duplicate tool names, disambiguate by prefixing them
2528 // with the server ID (converted to snake_case for API compatibility).
2529 // In the rare case there isn't enough space for the disambiguated tool
2530 // name, keep only the last tool with this name.
2531 for (server_id, tool_name, tool) in context_server_tools {
2532 if duplicate_tool_names.contains(&tool_name) {
2533 let available = MAX_TOOL_NAME_LENGTH.saturating_sub(tool_name.len());
2534 if available >= 2 {
2535 let mut disambiguated = server_id.0.to_snake_case();
2536 disambiguated.truncate(available - 1);
2537 disambiguated.push('_');
2538 disambiguated.push_str(&tool_name);
2539 tools.insert(disambiguated.into(), tool.clone());
2540 } else {
2541 tools.insert(tool_name, tool.clone());
2542 }
2543 } else {
2544 tools.insert(tool_name, tool.clone());
2545 }
2546 }
2547
2548 tools
2549 }
2550
2551 fn tool(&self, name: &str) -> Option<Arc<dyn AnyAgentTool>> {
2552 self.running_turn.as_ref()?.tools.get(name).cloned()
2553 }
2554
2555 pub fn has_tool(&self, name: &str) -> bool {
2556 self.running_turn
2557 .as_ref()
2558 .is_some_and(|turn| turn.tools.contains_key(name))
2559 }
2560
2561 #[cfg(any(test, feature = "test-support"))]
2562 pub fn has_registered_tool(&self, name: &str) -> bool {
2563 self.tools.contains_key(name)
2564 }
2565
2566 pub fn registered_tool_names(&self) -> Vec<SharedString> {
2567 self.tools.keys().cloned().collect()
2568 }
2569
2570 pub(crate) fn register_running_subagent(&mut self, subagent: WeakEntity<Thread>) {
2571 self.running_subagents.push(subagent);
2572 }
2573
2574 pub(crate) fn unregister_running_subagent(
2575 &mut self,
2576 subagent_session_id: &acp::SessionId,
2577 cx: &App,
2578 ) {
2579 self.running_subagents.retain(|s| {
2580 s.upgrade()
2581 .map_or(false, |s| s.read(cx).id() != subagent_session_id)
2582 });
2583 }
2584
2585 #[cfg(any(test, feature = "test-support"))]
2586 pub fn running_subagent_ids(&self, cx: &App) -> Vec<acp::SessionId> {
2587 self.running_subagents
2588 .iter()
2589 .filter_map(|s| s.upgrade().map(|s| s.read(cx).id().clone()))
2590 .collect()
2591 }
2592
2593 pub fn running_subagent_count(&self) -> usize {
2594 self.running_subagents
2595 .iter()
2596 .filter(|s| s.upgrade().is_some())
2597 .count()
2598 }
2599
2600 pub fn is_subagent(&self) -> bool {
2601 self.subagent_context.is_some()
2602 }
2603
2604 pub fn parent_thread_id(&self) -> Option<acp::SessionId> {
2605 self.subagent_context
2606 .as_ref()
2607 .map(|c| c.parent_thread_id.clone())
2608 }
2609
2610 pub fn depth(&self) -> u8 {
2611 self.subagent_context.as_ref().map(|c| c.depth).unwrap_or(0)
2612 }
2613
2614 #[cfg(any(test, feature = "test-support"))]
2615 pub fn set_subagent_context(&mut self, context: SubagentContext) {
2616 self.subagent_context = Some(context);
2617 }
2618
2619 pub fn is_turn_complete(&self) -> bool {
2620 self.running_turn.is_none()
2621 }
2622
2623 fn build_request_messages(
2624 &self,
2625 available_tools: Vec<SharedString>,
2626 cx: &App,
2627 ) -> Vec<LanguageModelRequestMessage> {
2628 log::trace!(
2629 "Building request messages from {} thread messages",
2630 self.messages.len()
2631 );
2632
2633 let system_prompt = SystemPromptTemplate {
2634 project: self.project_context.read(cx),
2635 available_tools,
2636 model_name: self.model.as_ref().map(|m| m.name().0.to_string()),
2637 }
2638 .render(&self.templates)
2639 .context("failed to build system prompt")
2640 .expect("Invalid template");
2641 let mut messages = vec![LanguageModelRequestMessage {
2642 role: Role::System,
2643 content: vec![system_prompt.into()],
2644 cache: false,
2645 reasoning_details: None,
2646 }];
2647 for message in &self.messages {
2648 messages.extend(message.to_request());
2649 }
2650
2651 if let Some(last_message) = messages.last_mut() {
2652 last_message.cache = true;
2653 }
2654
2655 if let Some(message) = self.pending_message.as_ref() {
2656 messages.extend(message.to_request());
2657 }
2658
2659 messages
2660 }
2661
2662 pub fn to_markdown(&self) -> String {
2663 let mut markdown = String::new();
2664 for (ix, message) in self.messages.iter().enumerate() {
2665 if ix > 0 {
2666 markdown.push('\n');
2667 }
2668 match message {
2669 Message::User(_) => markdown.push_str("## User\n\n"),
2670 Message::Agent(_) => markdown.push_str("## Assistant\n\n"),
2671 Message::Resume => {}
2672 }
2673 markdown.push_str(&message.to_markdown());
2674 }
2675
2676 if let Some(message) = self.pending_message.as_ref() {
2677 markdown.push_str("\n## Assistant\n\n");
2678 markdown.push_str(&message.to_markdown());
2679 }
2680
2681 markdown
2682 }
2683
2684 fn advance_prompt_id(&mut self) {
2685 self.prompt_id = PromptId::new();
2686 }
2687
2688 fn retry_strategy_for(error: &LanguageModelCompletionError) -> Option<RetryStrategy> {
2689 use LanguageModelCompletionError::*;
2690 use http_client::StatusCode;
2691
2692 // General strategy here:
2693 // - If retrying won't help (e.g. invalid API key or payload too large), return None so we don't retry at all.
2694 // - If it's a time-based issue (e.g. server overloaded, rate limit exceeded), retry up to 4 times with exponential backoff.
2695 // - If it's an issue that *might* be fixed by retrying (e.g. internal server error), retry up to 3 times.
2696 match error {
2697 HttpResponseError {
2698 status_code: StatusCode::TOO_MANY_REQUESTS,
2699 ..
2700 } => Some(RetryStrategy::ExponentialBackoff {
2701 initial_delay: BASE_RETRY_DELAY,
2702 max_attempts: MAX_RETRY_ATTEMPTS,
2703 }),
2704 ServerOverloaded { retry_after, .. } | RateLimitExceeded { retry_after, .. } => {
2705 Some(RetryStrategy::Fixed {
2706 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2707 max_attempts: MAX_RETRY_ATTEMPTS,
2708 })
2709 }
2710 UpstreamProviderError {
2711 status,
2712 retry_after,
2713 ..
2714 } => match *status {
2715 StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
2716 Some(RetryStrategy::Fixed {
2717 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2718 max_attempts: MAX_RETRY_ATTEMPTS,
2719 })
2720 }
2721 StatusCode::INTERNAL_SERVER_ERROR => Some(RetryStrategy::Fixed {
2722 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2723 // Internal Server Error could be anything, retry up to 3 times.
2724 max_attempts: 3,
2725 }),
2726 status => {
2727 // There is no StatusCode variant for the unofficial HTTP 529 ("The service is overloaded"),
2728 // but we frequently get them in practice. See https://http.dev/529
2729 if status.as_u16() == 529 {
2730 Some(RetryStrategy::Fixed {
2731 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2732 max_attempts: MAX_RETRY_ATTEMPTS,
2733 })
2734 } else {
2735 Some(RetryStrategy::Fixed {
2736 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2737 max_attempts: 2,
2738 })
2739 }
2740 }
2741 },
2742 ApiInternalServerError { .. } => Some(RetryStrategy::Fixed {
2743 delay: BASE_RETRY_DELAY,
2744 max_attempts: 3,
2745 }),
2746 ApiReadResponseError { .. }
2747 | HttpSend { .. }
2748 | DeserializeResponse { .. }
2749 | BadRequestFormat { .. } => Some(RetryStrategy::Fixed {
2750 delay: BASE_RETRY_DELAY,
2751 max_attempts: 3,
2752 }),
2753 // Retrying these errors definitely shouldn't help.
2754 HttpResponseError {
2755 status_code:
2756 StatusCode::PAYLOAD_TOO_LARGE | StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED,
2757 ..
2758 }
2759 | AuthenticationError { .. }
2760 | PermissionError { .. }
2761 | NoApiKey { .. }
2762 | ApiEndpointNotFound { .. }
2763 | PromptTooLarge { .. } => None,
2764 // These errors might be transient, so retry them
2765 SerializeRequest { .. } | BuildRequestBody { .. } | StreamEndedUnexpectedly { .. } => {
2766 Some(RetryStrategy::Fixed {
2767 delay: BASE_RETRY_DELAY,
2768 max_attempts: 1,
2769 })
2770 }
2771 // Retry all other 4xx and 5xx errors once.
2772 HttpResponseError { status_code, .. }
2773 if status_code.is_client_error() || status_code.is_server_error() =>
2774 {
2775 Some(RetryStrategy::Fixed {
2776 delay: BASE_RETRY_DELAY,
2777 max_attempts: 3,
2778 })
2779 }
2780 Other(err) if err.is::<language_model::PaymentRequiredError>() => {
2781 // Retrying won't help for Payment Required errors.
2782 None
2783 }
2784 // Conservatively assume that any other errors are non-retryable
2785 HttpResponseError { .. } | Other(..) => Some(RetryStrategy::Fixed {
2786 delay: BASE_RETRY_DELAY,
2787 max_attempts: 2,
2788 }),
2789 }
2790 }
2791}
2792
2793struct RunningTurn {
2794 /// Holds the task that handles agent interaction until the end of the turn.
2795 /// Survives across multiple requests as the model performs tool calls and
2796 /// we run tools, report their results.
2797 _task: Task<()>,
2798 /// The current event stream for the running turn. Used to report a final
2799 /// cancellation event if we cancel the turn.
2800 event_stream: ThreadEventStream,
2801 /// The tools that were enabled for this turn.
2802 tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
2803 /// Sender to signal tool cancellation. When cancel is called, this is
2804 /// set to true so all tools can detect user-initiated cancellation.
2805 cancellation_tx: watch::Sender<bool>,
2806}
2807
2808impl RunningTurn {
2809 fn cancel(mut self) -> Task<()> {
2810 log::debug!("Cancelling in progress turn");
2811 self.cancellation_tx.send(true).ok();
2812 self.event_stream.send_canceled();
2813 self._task
2814 }
2815}
2816
2817pub struct TokenUsageUpdated(pub Option<acp_thread::TokenUsage>);
2818
2819impl EventEmitter<TokenUsageUpdated> for Thread {}
2820
2821pub struct TitleUpdated;
2822
2823impl EventEmitter<TitleUpdated> for Thread {}
2824
2825pub trait AgentTool
2826where
2827 Self: 'static + Sized,
2828{
2829 type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
2830 type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
2831
2832 const NAME: &'static str;
2833
2834 fn description() -> SharedString {
2835 let schema = schemars::schema_for!(Self::Input);
2836 SharedString::new(
2837 schema
2838 .get("description")
2839 .and_then(|description| description.as_str())
2840 .unwrap_or_default(),
2841 )
2842 }
2843
2844 fn kind() -> acp::ToolKind;
2845
2846 /// The initial tool title to display. Can be updated during the tool run.
2847 fn initial_title(
2848 &self,
2849 input: Result<Self::Input, serde_json::Value>,
2850 cx: &mut App,
2851 ) -> SharedString;
2852
2853 /// Returns the JSON schema that describes the tool's input.
2854 fn input_schema(format: LanguageModelToolSchemaFormat) -> Schema {
2855 language_model::tool_schema::root_schema_for::<Self::Input>(format)
2856 }
2857
2858 /// Some tools rely on a provider for the underlying billing or other reasons.
2859 /// Allow the tool to check if they are compatible, or should be filtered out.
2860 fn supports_provider(_provider: &LanguageModelProviderId) -> bool {
2861 true
2862 }
2863
2864 /// Runs the tool with the provided input.
2865 fn run(
2866 self: Arc<Self>,
2867 input: Self::Input,
2868 event_stream: ToolCallEventStream,
2869 cx: &mut App,
2870 ) -> Task<Result<Self::Output>>;
2871
2872 /// Emits events for a previous execution of the tool.
2873 fn replay(
2874 &self,
2875 _input: Self::Input,
2876 _output: Self::Output,
2877 _event_stream: ToolCallEventStream,
2878 _cx: &mut App,
2879 ) -> Result<()> {
2880 Ok(())
2881 }
2882
2883 fn erase(self) -> Arc<dyn AnyAgentTool> {
2884 Arc::new(Erased(Arc::new(self)))
2885 }
2886}
2887
2888pub struct Erased<T>(T);
2889
2890pub struct AgentToolOutput {
2891 pub llm_output: LanguageModelToolResultContent,
2892 pub raw_output: serde_json::Value,
2893}
2894
2895pub trait AnyAgentTool {
2896 fn name(&self) -> SharedString;
2897 fn description(&self) -> SharedString;
2898 fn kind(&self) -> acp::ToolKind;
2899 fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString;
2900 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
2901 fn supports_provider(&self, _provider: &LanguageModelProviderId) -> bool {
2902 true
2903 }
2904 fn run(
2905 self: Arc<Self>,
2906 input: serde_json::Value,
2907 event_stream: ToolCallEventStream,
2908 cx: &mut App,
2909 ) -> Task<Result<AgentToolOutput>>;
2910 fn replay(
2911 &self,
2912 input: serde_json::Value,
2913 output: serde_json::Value,
2914 event_stream: ToolCallEventStream,
2915 cx: &mut App,
2916 ) -> Result<()>;
2917}
2918
2919impl<T> AnyAgentTool for Erased<Arc<T>>
2920where
2921 T: AgentTool,
2922{
2923 fn name(&self) -> SharedString {
2924 T::NAME.into()
2925 }
2926
2927 fn description(&self) -> SharedString {
2928 T::description()
2929 }
2930
2931 fn kind(&self) -> agent_client_protocol::ToolKind {
2932 T::kind()
2933 }
2934
2935 fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString {
2936 let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
2937 self.0.initial_title(parsed_input, _cx)
2938 }
2939
2940 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
2941 let mut json = serde_json::to_value(T::input_schema(format))?;
2942 language_model::tool_schema::adapt_schema_to_format(&mut json, format)?;
2943 Ok(json)
2944 }
2945
2946 fn supports_provider(&self, provider: &LanguageModelProviderId) -> bool {
2947 T::supports_provider(provider)
2948 }
2949
2950 fn run(
2951 self: Arc<Self>,
2952 input: serde_json::Value,
2953 event_stream: ToolCallEventStream,
2954 cx: &mut App,
2955 ) -> Task<Result<AgentToolOutput>> {
2956 cx.spawn(async move |cx| {
2957 let input = serde_json::from_value(input)?;
2958 let output = cx
2959 .update(|cx| self.0.clone().run(input, event_stream, cx))
2960 .await?;
2961 let raw_output = serde_json::to_value(&output)?;
2962 Ok(AgentToolOutput {
2963 llm_output: output.into(),
2964 raw_output,
2965 })
2966 })
2967 }
2968
2969 fn replay(
2970 &self,
2971 input: serde_json::Value,
2972 output: serde_json::Value,
2973 event_stream: ToolCallEventStream,
2974 cx: &mut App,
2975 ) -> Result<()> {
2976 let input = serde_json::from_value(input)?;
2977 let output = serde_json::from_value(output)?;
2978 self.0.replay(input, output, event_stream, cx)
2979 }
2980}
2981
2982#[derive(Clone)]
2983struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
2984
2985impl ThreadEventStream {
2986 fn send_user_message(&self, message: &UserMessage) {
2987 self.0
2988 .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
2989 .ok();
2990 }
2991
2992 fn send_text(&self, text: &str) {
2993 self.0
2994 .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
2995 .ok();
2996 }
2997
2998 fn send_thinking(&self, text: &str) {
2999 self.0
3000 .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
3001 .ok();
3002 }
3003
3004 fn send_tool_call(
3005 &self,
3006 id: &LanguageModelToolUseId,
3007 tool_name: &str,
3008 title: SharedString,
3009 kind: acp::ToolKind,
3010 input: serde_json::Value,
3011 ) {
3012 self.0
3013 .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
3014 id,
3015 tool_name,
3016 title.to_string(),
3017 kind,
3018 input,
3019 ))))
3020 .ok();
3021 }
3022
3023 fn initial_tool_call(
3024 id: &LanguageModelToolUseId,
3025 tool_name: &str,
3026 title: String,
3027 kind: acp::ToolKind,
3028 input: serde_json::Value,
3029 ) -> acp::ToolCall {
3030 acp::ToolCall::new(id.to_string(), title)
3031 .kind(kind)
3032 .raw_input(input)
3033 .meta(acp_thread::meta_with_tool_name(tool_name))
3034 }
3035
3036 fn update_tool_call_fields(
3037 &self,
3038 tool_use_id: &LanguageModelToolUseId,
3039 fields: acp::ToolCallUpdateFields,
3040 meta: Option<acp::Meta>,
3041 ) {
3042 self.0
3043 .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3044 acp::ToolCallUpdate::new(tool_use_id.to_string(), fields)
3045 .meta(meta)
3046 .into(),
3047 )))
3048 .ok();
3049 }
3050
3051 fn send_retry(&self, status: acp_thread::RetryStatus) {
3052 self.0.unbounded_send(Ok(ThreadEvent::Retry(status))).ok();
3053 }
3054
3055 fn send_stop(&self, reason: acp::StopReason) {
3056 self.0.unbounded_send(Ok(ThreadEvent::Stop(reason))).ok();
3057 }
3058
3059 fn send_canceled(&self) {
3060 self.0
3061 .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))
3062 .ok();
3063 }
3064
3065 fn send_error(&self, error: impl Into<anyhow::Error>) {
3066 self.0.unbounded_send(Err(error.into())).ok();
3067 }
3068}
3069
3070#[derive(Clone)]
3071pub struct ToolCallEventStream {
3072 tool_use_id: LanguageModelToolUseId,
3073 stream: ThreadEventStream,
3074 fs: Option<Arc<dyn Fs>>,
3075 cancellation_rx: watch::Receiver<bool>,
3076}
3077
3078impl ToolCallEventStream {
3079 #[cfg(any(test, feature = "test-support"))]
3080 pub fn test() -> (Self, ToolCallEventStreamReceiver) {
3081 let (stream, receiver, _cancellation_tx) = Self::test_with_cancellation();
3082 (stream, receiver)
3083 }
3084
3085 #[cfg(any(test, feature = "test-support"))]
3086 pub fn test_with_cancellation() -> (Self, ToolCallEventStreamReceiver, watch::Sender<bool>) {
3087 let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
3088 let (cancellation_tx, cancellation_rx) = watch::channel(false);
3089
3090 let stream = ToolCallEventStream::new(
3091 "test_id".into(),
3092 ThreadEventStream(events_tx),
3093 None,
3094 cancellation_rx,
3095 );
3096
3097 (
3098 stream,
3099 ToolCallEventStreamReceiver(events_rx),
3100 cancellation_tx,
3101 )
3102 }
3103
3104 /// Signal cancellation for this event stream. Only available in tests.
3105 #[cfg(any(test, feature = "test-support"))]
3106 pub fn signal_cancellation_with_sender(cancellation_tx: &mut watch::Sender<bool>) {
3107 cancellation_tx.send(true).ok();
3108 }
3109
3110 fn new(
3111 tool_use_id: LanguageModelToolUseId,
3112 stream: ThreadEventStream,
3113 fs: Option<Arc<dyn Fs>>,
3114 cancellation_rx: watch::Receiver<bool>,
3115 ) -> Self {
3116 Self {
3117 tool_use_id,
3118 stream,
3119 fs,
3120 cancellation_rx,
3121 }
3122 }
3123
3124 /// Returns a future that resolves when the user cancels the tool call.
3125 /// Tools should select on this alongside their main work to detect user cancellation.
3126 pub fn cancelled_by_user(&self) -> impl std::future::Future<Output = ()> + '_ {
3127 let mut rx = self.cancellation_rx.clone();
3128 async move {
3129 loop {
3130 if *rx.borrow() {
3131 return;
3132 }
3133 if rx.changed().await.is_err() {
3134 // Sender dropped, will never be cancelled
3135 std::future::pending::<()>().await;
3136 }
3137 }
3138 }
3139 }
3140
3141 /// Returns true if the user has cancelled this tool call.
3142 /// This is useful for checking cancellation state after an operation completes,
3143 /// to determine if the completion was due to user cancellation.
3144 pub fn was_cancelled_by_user(&self) -> bool {
3145 *self.cancellation_rx.clone().borrow()
3146 }
3147
3148 pub fn tool_use_id(&self) -> &LanguageModelToolUseId {
3149 &self.tool_use_id
3150 }
3151
3152 pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
3153 self.stream
3154 .update_tool_call_fields(&self.tool_use_id, fields, None);
3155 }
3156
3157 pub fn update_fields_with_meta(
3158 &self,
3159 fields: acp::ToolCallUpdateFields,
3160 meta: Option<acp::Meta>,
3161 ) {
3162 self.stream
3163 .update_tool_call_fields(&self.tool_use_id, fields, meta);
3164 }
3165
3166 pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
3167 self.stream
3168 .0
3169 .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3170 acp_thread::ToolCallUpdateDiff {
3171 id: acp::ToolCallId::new(self.tool_use_id.to_string()),
3172 diff,
3173 }
3174 .into(),
3175 )))
3176 .ok();
3177 }
3178
3179 pub fn subagent_spawned(&self, id: acp::SessionId) {
3180 self.stream
3181 .0
3182 .unbounded_send(Ok(ThreadEvent::SubagentSpawned(id)))
3183 .ok();
3184 }
3185
3186 /// Authorize a third-party tool (e.g., MCP tool from a context server).
3187 ///
3188 /// Unlike built-in tools, third-party tools don't support pattern-based permissions.
3189 /// They only support `default` (allow/deny/confirm) per tool.
3190 ///
3191 /// Uses the dropdown authorization flow with two granularities:
3192 /// - "Always for <display_name> MCP tool" → sets `tools.<tool_id>.default = "allow"` or "deny"
3193 /// - "Only this time" → allow/deny once
3194 pub fn authorize_third_party_tool(
3195 &self,
3196 title: impl Into<String>,
3197 tool_id: String,
3198 display_name: String,
3199 cx: &mut App,
3200 ) -> Task<Result<()>> {
3201 let settings = agent_settings::AgentSettings::get_global(cx);
3202
3203 let decision = decide_permission_from_settings(&tool_id, &[String::new()], &settings);
3204
3205 match decision {
3206 ToolPermissionDecision::Allow => return Task::ready(Ok(())),
3207 ToolPermissionDecision::Deny(reason) => return Task::ready(Err(anyhow!(reason))),
3208 ToolPermissionDecision::Confirm => {}
3209 }
3210
3211 let (response_tx, response_rx) = oneshot::channel();
3212 if let Err(error) = self
3213 .stream
3214 .0
3215 .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3216 ToolCallAuthorization {
3217 tool_call: acp::ToolCallUpdate::new(
3218 self.tool_use_id.to_string(),
3219 acp::ToolCallUpdateFields::new().title(title.into()),
3220 ),
3221 options: acp_thread::PermissionOptions::Dropdown(vec![
3222 acp_thread::PermissionOptionChoice {
3223 allow: acp::PermissionOption::new(
3224 acp::PermissionOptionId::new(format!(
3225 "always_allow_mcp:{}",
3226 tool_id
3227 )),
3228 format!("Always for {} MCP tool", display_name),
3229 acp::PermissionOptionKind::AllowAlways,
3230 ),
3231 deny: acp::PermissionOption::new(
3232 acp::PermissionOptionId::new(format!(
3233 "always_deny_mcp:{}",
3234 tool_id
3235 )),
3236 format!("Always for {} MCP tool", display_name),
3237 acp::PermissionOptionKind::RejectAlways,
3238 ),
3239 },
3240 acp_thread::PermissionOptionChoice {
3241 allow: acp::PermissionOption::new(
3242 acp::PermissionOptionId::new("allow"),
3243 "Only this time",
3244 acp::PermissionOptionKind::AllowOnce,
3245 ),
3246 deny: acp::PermissionOption::new(
3247 acp::PermissionOptionId::new("deny"),
3248 "Only this time",
3249 acp::PermissionOptionKind::RejectOnce,
3250 ),
3251 },
3252 ]),
3253 response: response_tx,
3254 context: None,
3255 },
3256 )))
3257 {
3258 log::error!("Failed to send tool call authorization: {error}");
3259 return Task::ready(Err(anyhow!(
3260 "Failed to send tool call authorization: {error}"
3261 )));
3262 }
3263
3264 let fs = self.fs.clone();
3265 cx.spawn(async move |cx| {
3266 let response_str = response_rx.await?.0.to_string();
3267
3268 if response_str == format!("always_allow_mcp:{}", tool_id) {
3269 if let Some(fs) = fs.clone() {
3270 cx.update(|cx| {
3271 update_settings_file(fs, cx, move |settings, _| {
3272 settings
3273 .agent
3274 .get_or_insert_default()
3275 .set_tool_default_permission(&tool_id, ToolPermissionMode::Allow);
3276 });
3277 });
3278 }
3279 return Ok(());
3280 }
3281 if response_str == format!("always_deny_mcp:{}", tool_id) {
3282 if let Some(fs) = fs.clone() {
3283 cx.update(|cx| {
3284 update_settings_file(fs, cx, move |settings, _| {
3285 settings
3286 .agent
3287 .get_or_insert_default()
3288 .set_tool_default_permission(&tool_id, ToolPermissionMode::Deny);
3289 });
3290 });
3291 }
3292 return Err(anyhow!("Permission to run tool denied by user"));
3293 }
3294
3295 if response_str == "allow" {
3296 return Ok(());
3297 }
3298
3299 Err(anyhow!("Permission to run tool denied by user"))
3300 })
3301 }
3302
3303 pub fn authorize(
3304 &self,
3305 title: impl Into<String>,
3306 context: ToolPermissionContext,
3307 cx: &mut App,
3308 ) -> Task<Result<()>> {
3309 use settings::ToolPermissionMode;
3310
3311 let options = context.build_permission_options();
3312
3313 let (response_tx, response_rx) = oneshot::channel();
3314 if let Err(error) = self
3315 .stream
3316 .0
3317 .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3318 ToolCallAuthorization {
3319 tool_call: acp::ToolCallUpdate::new(
3320 self.tool_use_id.to_string(),
3321 acp::ToolCallUpdateFields::new().title(title.into()),
3322 ),
3323 options,
3324 response: response_tx,
3325 context: Some(context),
3326 },
3327 )))
3328 {
3329 log::error!("Failed to send tool call authorization: {error}");
3330 return Task::ready(Err(anyhow!(
3331 "Failed to send tool call authorization: {error}"
3332 )));
3333 }
3334
3335 let fs = self.fs.clone();
3336 cx.spawn(async move |cx| {
3337 let response_str = response_rx.await?.0.to_string();
3338
3339 // Handle "always allow tool" - e.g., "always_allow:terminal"
3340 if let Some(tool) = response_str.strip_prefix("always_allow:") {
3341 if let Some(fs) = fs.clone() {
3342 let tool = tool.to_string();
3343 cx.update(|cx| {
3344 update_settings_file(fs, cx, move |settings, _| {
3345 settings
3346 .agent
3347 .get_or_insert_default()
3348 .set_tool_default_permission(&tool, ToolPermissionMode::Allow);
3349 });
3350 });
3351 }
3352 return Ok(());
3353 }
3354
3355 // Handle "always deny tool" - e.g., "always_deny:terminal"
3356 if let Some(tool) = response_str.strip_prefix("always_deny:") {
3357 if let Some(fs) = fs.clone() {
3358 let tool = tool.to_string();
3359 cx.update(|cx| {
3360 update_settings_file(fs, cx, move |settings, _| {
3361 settings
3362 .agent
3363 .get_or_insert_default()
3364 .set_tool_default_permission(&tool, ToolPermissionMode::Deny);
3365 });
3366 });
3367 }
3368 return Err(anyhow!("Permission to run tool denied by user"));
3369 }
3370
3371 // Handle "always allow pattern" - e.g., "always_allow_pattern:mcp:server:tool\n^cargo\s"
3372 if let Some(rest) = response_str.strip_prefix("always_allow_pattern:") {
3373 if let Some((pattern_tool_name, pattern)) = rest.split_once('\n') {
3374 let pattern_tool_name = pattern_tool_name.to_string();
3375 let pattern = pattern.to_string();
3376 if let Some(fs) = fs.clone() {
3377 cx.update(|cx| {
3378 update_settings_file(fs, cx, move |settings, _| {
3379 settings
3380 .agent
3381 .get_or_insert_default()
3382 .add_tool_allow_pattern(&pattern_tool_name, pattern);
3383 });
3384 });
3385 }
3386 } else {
3387 log::error!("Failed to parse always allow pattern: missing newline separator in '{rest}'");
3388 }
3389 return Ok(());
3390 }
3391
3392 // Handle "always deny pattern" - e.g., "always_deny_pattern:mcp:server:tool\n^cargo\s"
3393 if let Some(rest) = response_str.strip_prefix("always_deny_pattern:") {
3394 if let Some((pattern_tool_name, pattern)) = rest.split_once('\n') {
3395 let pattern_tool_name = pattern_tool_name.to_string();
3396 let pattern = pattern.to_string();
3397 if let Some(fs) = fs.clone() {
3398 cx.update(|cx| {
3399 update_settings_file(fs, cx, move |settings, _| {
3400 settings
3401 .agent
3402 .get_or_insert_default()
3403 .add_tool_deny_pattern(&pattern_tool_name, pattern);
3404 });
3405 });
3406 }
3407 } else {
3408 log::error!("Failed to parse always deny pattern: missing newline separator in '{rest}'");
3409 }
3410 return Err(anyhow!("Permission to run tool denied by user"));
3411 }
3412
3413 // Handle simple "allow" (allow once)
3414 if response_str == "allow" {
3415 return Ok(());
3416 }
3417
3418 // Handle simple "deny" (deny once)
3419 Err(anyhow!("Permission to run tool denied by user"))
3420 })
3421 }
3422}
3423
3424#[cfg(any(test, feature = "test-support"))]
3425pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
3426
3427#[cfg(any(test, feature = "test-support"))]
3428impl ToolCallEventStreamReceiver {
3429 pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
3430 let event = self.0.next().await;
3431 if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
3432 auth
3433 } else {
3434 panic!("Expected ToolCallAuthorization but got: {:?}", event);
3435 }
3436 }
3437
3438 pub async fn expect_update_fields(&mut self) -> acp::ToolCallUpdateFields {
3439 let event = self.0.next().await;
3440 if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
3441 update,
3442 )))) = event
3443 {
3444 update.fields
3445 } else {
3446 panic!("Expected update fields but got: {:?}", event);
3447 }
3448 }
3449
3450 pub async fn expect_diff(&mut self) -> Entity<acp_thread::Diff> {
3451 let event = self.0.next().await;
3452 if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateDiff(
3453 update,
3454 )))) = event
3455 {
3456 update.diff
3457 } else {
3458 panic!("Expected diff but got: {:?}", event);
3459 }
3460 }
3461
3462 pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
3463 let event = self.0.next().await;
3464 if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
3465 update,
3466 )))) = event
3467 {
3468 update.terminal
3469 } else {
3470 panic!("Expected terminal but got: {:?}", event);
3471 }
3472 }
3473}
3474
3475#[cfg(any(test, feature = "test-support"))]
3476impl std::ops::Deref for ToolCallEventStreamReceiver {
3477 type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
3478
3479 fn deref(&self) -> &Self::Target {
3480 &self.0
3481 }
3482}
3483
3484#[cfg(any(test, feature = "test-support"))]
3485impl std::ops::DerefMut for ToolCallEventStreamReceiver {
3486 fn deref_mut(&mut self) -> &mut Self::Target {
3487 &mut self.0
3488 }
3489}
3490
3491impl From<&str> for UserMessageContent {
3492 fn from(text: &str) -> Self {
3493 Self::Text(text.into())
3494 }
3495}
3496
3497impl From<String> for UserMessageContent {
3498 fn from(text: String) -> Self {
3499 Self::Text(text)
3500 }
3501}
3502
3503impl UserMessageContent {
3504 pub fn from_content_block(value: acp::ContentBlock, path_style: PathStyle) -> Self {
3505 match value {
3506 acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
3507 acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
3508 acp::ContentBlock::Audio(_) => {
3509 // TODO
3510 Self::Text("[audio]".to_string())
3511 }
3512 acp::ContentBlock::ResourceLink(resource_link) => {
3513 match MentionUri::parse(&resource_link.uri, path_style) {
3514 Ok(uri) => Self::Mention {
3515 uri,
3516 content: String::new(),
3517 },
3518 Err(err) => {
3519 log::error!("Failed to parse mention link: {}", err);
3520 Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
3521 }
3522 }
3523 }
3524 acp::ContentBlock::Resource(resource) => match resource.resource {
3525 acp::EmbeddedResourceResource::TextResourceContents(resource) => {
3526 match MentionUri::parse(&resource.uri, path_style) {
3527 Ok(uri) => Self::Mention {
3528 uri,
3529 content: resource.text,
3530 },
3531 Err(err) => {
3532 log::error!("Failed to parse mention link: {}", err);
3533 Self::Text(
3534 MarkdownCodeBlock {
3535 tag: &resource.uri,
3536 text: &resource.text,
3537 }
3538 .to_string(),
3539 )
3540 }
3541 }
3542 }
3543 acp::EmbeddedResourceResource::BlobResourceContents(_) => {
3544 // TODO
3545 Self::Text("[blob]".to_string())
3546 }
3547 other => {
3548 log::warn!("Unexpected content type: {:?}", other);
3549 Self::Text("[unknown]".to_string())
3550 }
3551 },
3552 other => {
3553 log::warn!("Unexpected content type: {:?}", other);
3554 Self::Text("[unknown]".to_string())
3555 }
3556 }
3557 }
3558}
3559
3560impl From<UserMessageContent> for acp::ContentBlock {
3561 fn from(content: UserMessageContent) -> Self {
3562 match content {
3563 UserMessageContent::Text(text) => text.into(),
3564 UserMessageContent::Image(image) => {
3565 acp::ContentBlock::Image(acp::ImageContent::new(image.source, "image/png"))
3566 }
3567 UserMessageContent::Mention { uri, content } => acp::ContentBlock::Resource(
3568 acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(
3569 acp::TextResourceContents::new(content, uri.to_uri().to_string()),
3570 )),
3571 ),
3572 }
3573 }
3574}
3575
3576fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
3577 LanguageModelImage {
3578 source: image_content.data.into(),
3579 size: None,
3580 }
3581}
3582
3583#[cfg(test)]
3584mod tests {
3585 use super::*;
3586 use gpui::TestAppContext;
3587 use language_model::LanguageModelToolUseId;
3588 use serde_json::json;
3589 use std::sync::Arc;
3590
3591 async fn setup_thread_for_test(cx: &mut TestAppContext) -> (Entity<Thread>, ThreadEventStream) {
3592 cx.update(|cx| {
3593 let settings_store = settings::SettingsStore::test(cx);
3594 cx.set_global(settings_store);
3595 });
3596
3597 let fs = fs::FakeFs::new(cx.background_executor.clone());
3598 let templates = Templates::new();
3599 let project = Project::test(fs.clone(), [], cx).await;
3600
3601 cx.update(|cx| {
3602 let project_context = cx.new(|_cx| prompt_store::ProjectContext::default());
3603 let context_server_store = project.read(cx).context_server_store();
3604 let context_server_registry =
3605 cx.new(|cx| ContextServerRegistry::new(context_server_store, cx));
3606
3607 let thread = cx.new(|cx| {
3608 Thread::new(
3609 project,
3610 project_context,
3611 context_server_registry,
3612 templates,
3613 None,
3614 cx,
3615 )
3616 });
3617
3618 let (event_tx, _event_rx) = mpsc::unbounded();
3619 let event_stream = ThreadEventStream(event_tx);
3620
3621 (thread, event_stream)
3622 })
3623 }
3624
3625 #[gpui::test]
3626 async fn test_handle_tool_use_json_parse_error_adds_tool_use_to_content(
3627 cx: &mut TestAppContext,
3628 ) {
3629 let (thread, event_stream) = setup_thread_for_test(cx).await;
3630
3631 cx.update(|cx| {
3632 thread.update(cx, |thread, _cx| {
3633 let tool_use_id = LanguageModelToolUseId::from("test_tool_id");
3634 let tool_name: Arc<str> = Arc::from("test_tool");
3635 let raw_input: Arc<str> = Arc::from("{invalid json");
3636 let json_parse_error = "expected value at line 1 column 1".to_string();
3637
3638 // Call the function under test
3639 let result = thread.handle_tool_use_json_parse_error_event(
3640 tool_use_id.clone(),
3641 tool_name.clone(),
3642 raw_input.clone(),
3643 json_parse_error,
3644 &event_stream,
3645 );
3646
3647 // Verify the result is an error
3648 assert!(result.is_error);
3649 assert_eq!(result.tool_use_id, tool_use_id);
3650 assert_eq!(result.tool_name, tool_name);
3651 assert!(matches!(
3652 result.content,
3653 LanguageModelToolResultContent::Text(_)
3654 ));
3655
3656 // Verify the tool use was added to the message content
3657 {
3658 let last_message = thread.pending_message();
3659 assert_eq!(
3660 last_message.content.len(),
3661 1,
3662 "Should have one tool_use in content"
3663 );
3664
3665 match &last_message.content[0] {
3666 AgentMessageContent::ToolUse(tool_use) => {
3667 assert_eq!(tool_use.id, tool_use_id);
3668 assert_eq!(tool_use.name, tool_name);
3669 assert_eq!(tool_use.raw_input, raw_input.to_string());
3670 assert!(tool_use.is_input_complete);
3671 // Should fall back to empty object for invalid JSON
3672 assert_eq!(tool_use.input, json!({}));
3673 }
3674 _ => panic!("Expected ToolUse content"),
3675 }
3676 }
3677
3678 // Insert the tool result (simulating what the caller does)
3679 thread
3680 .pending_message()
3681 .tool_results
3682 .insert(result.tool_use_id.clone(), result);
3683
3684 // Verify the tool result was added
3685 let last_message = thread.pending_message();
3686 assert_eq!(
3687 last_message.tool_results.len(),
3688 1,
3689 "Should have one tool_result"
3690 );
3691 assert!(last_message.tool_results.contains_key(&tool_use_id));
3692 });
3693 });
3694 }
3695}