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