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