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