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