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, Speed, StopReason, TokenUsage,
44 ZED_CLOUD_PROVIDER_ID,
45};
46use project::Project;
47use prompt_store::ProjectContext;
48use schemars::{JsonSchema, Schema};
49use serde::de::DeserializeOwned;
50use serde::{Deserialize, Serialize};
51use settings::{LanguageModelSelection, Settings, ToolPermissionMode, update_settings_file};
52use smol::stream::StreamExt;
53use std::{
54 collections::BTreeMap,
55 marker::PhantomData,
56 ops::RangeInclusive,
57 path::Path,
58 rc::Rc,
59 sync::Arc,
60 time::{Duration, Instant},
61};
62use std::{fmt::Write, path::PathBuf};
63use util::{ResultExt, debug_panic, markdown::MarkdownCodeBlock, paths::PathStyle};
64use uuid::Uuid;
65
66const TOOL_CANCELED_MESSAGE: &str = "Tool canceled by user";
67pub const MAX_TOOL_NAME_LENGTH: usize = 64;
68pub const MAX_SUBAGENT_DEPTH: u8 = 1;
69
70/// Context passed to a subagent thread for lifecycle management
71#[derive(Clone, Debug, Serialize, Deserialize)]
72pub struct SubagentContext {
73 /// ID of the parent thread
74 pub parent_thread_id: acp::SessionId,
75
76 /// Current depth level (0 = root agent, 1 = first-level subagent, etc.)
77 pub depth: u8,
78}
79
80/// The ID of the user prompt that initiated a request.
81///
82/// This equates to the user physically submitting a message to the model (e.g., by pressing the Enter key).
83#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
84pub struct PromptId(Arc<str>);
85
86impl PromptId {
87 pub fn new() -> Self {
88 Self(Uuid::new_v4().to_string().into())
89 }
90}
91
92impl std::fmt::Display for PromptId {
93 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94 write!(f, "{}", self.0)
95 }
96}
97
98pub(crate) const MAX_RETRY_ATTEMPTS: u8 = 4;
99pub(crate) const BASE_RETRY_DELAY: Duration = Duration::from_secs(5);
100
101#[derive(Debug, Clone)]
102enum RetryStrategy {
103 ExponentialBackoff {
104 initial_delay: Duration,
105 max_attempts: u8,
106 },
107 Fixed {
108 delay: Duration,
109 max_attempts: u8,
110 },
111}
112
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
114pub enum Message {
115 User(UserMessage),
116 Agent(AgentMessage),
117 Resume,
118}
119
120impl Message {
121 pub fn as_agent_message(&self) -> Option<&AgentMessage> {
122 match self {
123 Message::Agent(agent_message) => Some(agent_message),
124 _ => None,
125 }
126 }
127
128 pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
129 match self {
130 Message::User(message) => {
131 if message.content.is_empty() {
132 vec![]
133 } else {
134 vec![message.to_request()]
135 }
136 }
137 Message::Agent(message) => message.to_request(),
138 Message::Resume => vec![LanguageModelRequestMessage {
139 role: Role::User,
140 content: vec!["Continue where you left off".into()],
141 cache: false,
142 reasoning_details: None,
143 }],
144 }
145 }
146
147 pub fn to_markdown(&self) -> String {
148 match self {
149 Message::User(message) => message.to_markdown(),
150 Message::Agent(message) => message.to_markdown(),
151 Message::Resume => "[resume]\n".into(),
152 }
153 }
154
155 pub fn role(&self) -> Role {
156 match self {
157 Message::User(_) | Message::Resume => Role::User,
158 Message::Agent(_) => Role::Assistant,
159 }
160 }
161}
162
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
164pub struct UserMessage {
165 pub id: UserMessageId,
166 pub content: Vec<UserMessageContent>,
167}
168
169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
170pub enum UserMessageContent {
171 Text(String),
172 Mention { uri: MentionUri, content: String },
173 Image(LanguageModelImage),
174}
175
176impl UserMessage {
177 pub fn to_markdown(&self) -> String {
178 let mut markdown = String::new();
179
180 for content in &self.content {
181 match content {
182 UserMessageContent::Text(text) => {
183 markdown.push_str(text);
184 markdown.push('\n');
185 }
186 UserMessageContent::Image(_) => {
187 markdown.push_str("<image />\n");
188 }
189 UserMessageContent::Mention { uri, content } => {
190 if !content.is_empty() {
191 let _ = writeln!(&mut markdown, "{}\n\n{}", uri.as_link(), content);
192 } else {
193 let _ = writeln!(&mut markdown, "{}", uri.as_link());
194 }
195 }
196 }
197 }
198
199 markdown
200 }
201
202 fn to_request(&self) -> LanguageModelRequestMessage {
203 let mut message = LanguageModelRequestMessage {
204 role: Role::User,
205 content: Vec::with_capacity(self.content.len()),
206 cache: false,
207 reasoning_details: None,
208 };
209
210 const OPEN_CONTEXT: &str = "<context>\n\
211 The following items were attached by the user. \
212 They are up-to-date and don't need to be re-read.\n\n";
213
214 const OPEN_FILES_TAG: &str = "<files>";
215 const OPEN_DIRECTORIES_TAG: &str = "<directories>";
216 const OPEN_SYMBOLS_TAG: &str = "<symbols>";
217 const OPEN_SELECTIONS_TAG: &str = "<selections>";
218 const OPEN_THREADS_TAG: &str = "<threads>";
219 const OPEN_FETCH_TAG: &str = "<fetched_urls>";
220 const OPEN_RULES_TAG: &str =
221 "<rules>\nThe user has specified the following rules that should be applied:\n";
222 const OPEN_DIAGNOSTICS_TAG: &str = "<diagnostics>";
223 const OPEN_DIFFS_TAG: &str = "<diffs>";
224
225 let mut file_context = OPEN_FILES_TAG.to_string();
226 let mut directory_context = OPEN_DIRECTORIES_TAG.to_string();
227 let mut symbol_context = OPEN_SYMBOLS_TAG.to_string();
228 let mut selection_context = OPEN_SELECTIONS_TAG.to_string();
229 let mut thread_context = OPEN_THREADS_TAG.to_string();
230 let mut fetch_context = OPEN_FETCH_TAG.to_string();
231 let mut rules_context = OPEN_RULES_TAG.to_string();
232 let mut diagnostics_context = OPEN_DIAGNOSTICS_TAG.to_string();
233 let mut diffs_context = OPEN_DIFFS_TAG.to_string();
234
235 for chunk in &self.content {
236 let chunk = match chunk {
237 UserMessageContent::Text(text) => {
238 language_model::MessageContent::Text(text.clone())
239 }
240 UserMessageContent::Image(value) => {
241 language_model::MessageContent::Image(value.clone())
242 }
243 UserMessageContent::Mention { uri, content } => {
244 match uri {
245 MentionUri::File { abs_path } => {
246 write!(
247 &mut file_context,
248 "\n{}",
249 MarkdownCodeBlock {
250 tag: &codeblock_tag(abs_path, None),
251 text: &content.to_string(),
252 }
253 )
254 .ok();
255 }
256 MentionUri::PastedImage => {
257 debug_panic!("pasted image URI should not be used in mention content")
258 }
259 MentionUri::Directory { .. } => {
260 write!(&mut directory_context, "\n{}\n", content).ok();
261 }
262 MentionUri::Symbol {
263 abs_path: path,
264 line_range,
265 ..
266 } => {
267 write!(
268 &mut symbol_context,
269 "\n{}",
270 MarkdownCodeBlock {
271 tag: &codeblock_tag(path, Some(line_range)),
272 text: content
273 }
274 )
275 .ok();
276 }
277 MentionUri::Selection {
278 abs_path: path,
279 line_range,
280 ..
281 } => {
282 write!(
283 &mut selection_context,
284 "\n{}",
285 MarkdownCodeBlock {
286 tag: &codeblock_tag(
287 path.as_deref().unwrap_or("Untitled".as_ref()),
288 Some(line_range)
289 ),
290 text: content
291 }
292 )
293 .ok();
294 }
295 MentionUri::Thread { .. } => {
296 write!(&mut thread_context, "\n{}\n", content).ok();
297 }
298 MentionUri::TextThread { .. } => {
299 write!(&mut thread_context, "\n{}\n", content).ok();
300 }
301 MentionUri::Rule { .. } => {
302 write!(
303 &mut rules_context,
304 "\n{}",
305 MarkdownCodeBlock {
306 tag: "",
307 text: content
308 }
309 )
310 .ok();
311 }
312 MentionUri::Fetch { url } => {
313 write!(&mut fetch_context, "\nFetch: {}\n\n{}", url, content).ok();
314 }
315 MentionUri::Diagnostics { .. } => {
316 write!(&mut diagnostics_context, "\n{}\n", content).ok();
317 }
318 MentionUri::TerminalSelection { .. } => {
319 write!(
320 &mut selection_context,
321 "\n{}",
322 MarkdownCodeBlock {
323 tag: "console",
324 text: content
325 }
326 )
327 .ok();
328 }
329 MentionUri::GitDiff { base_ref } => {
330 write!(
331 &mut diffs_context,
332 "\nBranch diff against {}:\n{}",
333 base_ref,
334 MarkdownCodeBlock {
335 tag: "diff",
336 text: content
337 }
338 )
339 .ok();
340 }
341 }
342
343 language_model::MessageContent::Text(uri.as_link().to_string())
344 }
345 };
346
347 message.content.push(chunk);
348 }
349
350 let len_before_context = message.content.len();
351
352 if file_context.len() > OPEN_FILES_TAG.len() {
353 file_context.push_str("</files>\n");
354 message
355 .content
356 .push(language_model::MessageContent::Text(file_context));
357 }
358
359 if directory_context.len() > OPEN_DIRECTORIES_TAG.len() {
360 directory_context.push_str("</directories>\n");
361 message
362 .content
363 .push(language_model::MessageContent::Text(directory_context));
364 }
365
366 if symbol_context.len() > OPEN_SYMBOLS_TAG.len() {
367 symbol_context.push_str("</symbols>\n");
368 message
369 .content
370 .push(language_model::MessageContent::Text(symbol_context));
371 }
372
373 if selection_context.len() > OPEN_SELECTIONS_TAG.len() {
374 selection_context.push_str("</selections>\n");
375 message
376 .content
377 .push(language_model::MessageContent::Text(selection_context));
378 }
379
380 if diffs_context.len() > OPEN_DIFFS_TAG.len() {
381 diffs_context.push_str("</diffs>\n");
382 message
383 .content
384 .push(language_model::MessageContent::Text(diffs_context));
385 }
386
387 if thread_context.len() > OPEN_THREADS_TAG.len() {
388 thread_context.push_str("</threads>\n");
389 message
390 .content
391 .push(language_model::MessageContent::Text(thread_context));
392 }
393
394 if fetch_context.len() > OPEN_FETCH_TAG.len() {
395 fetch_context.push_str("</fetched_urls>\n");
396 message
397 .content
398 .push(language_model::MessageContent::Text(fetch_context));
399 }
400
401 if rules_context.len() > OPEN_RULES_TAG.len() {
402 rules_context.push_str("</user_rules>\n");
403 message
404 .content
405 .push(language_model::MessageContent::Text(rules_context));
406 }
407
408 if diagnostics_context.len() > OPEN_DIAGNOSTICS_TAG.len() {
409 diagnostics_context.push_str("</diagnostics>\n");
410 message
411 .content
412 .push(language_model::MessageContent::Text(diagnostics_context));
413 }
414
415 if message.content.len() > len_before_context {
416 message.content.insert(
417 len_before_context,
418 language_model::MessageContent::Text(OPEN_CONTEXT.into()),
419 );
420 message
421 .content
422 .push(language_model::MessageContent::Text("</context>".into()));
423 }
424
425 message
426 }
427}
428
429fn codeblock_tag(full_path: &Path, line_range: Option<&RangeInclusive<u32>>) -> String {
430 let mut result = String::new();
431
432 if let Some(extension) = full_path.extension().and_then(|ext| ext.to_str()) {
433 let _ = write!(result, "{} ", extension);
434 }
435
436 let _ = write!(result, "{}", full_path.display());
437
438 if let Some(range) = line_range {
439 if range.start() == range.end() {
440 let _ = write!(result, ":{}", range.start() + 1);
441 } else {
442 let _ = write!(result, ":{}-{}", range.start() + 1, range.end() + 1);
443 }
444 }
445
446 result
447}
448
449impl AgentMessage {
450 pub fn to_markdown(&self) -> String {
451 let mut markdown = String::new();
452
453 for content in &self.content {
454 match content {
455 AgentMessageContent::Text(text) => {
456 markdown.push_str(text);
457 markdown.push('\n');
458 }
459 AgentMessageContent::Thinking { text, .. } => {
460 markdown.push_str("<think>");
461 markdown.push_str(text);
462 markdown.push_str("</think>\n");
463 }
464 AgentMessageContent::RedactedThinking(_) => {
465 markdown.push_str("<redacted_thinking />\n")
466 }
467 AgentMessageContent::ToolUse(tool_use) => {
468 markdown.push_str(&format!(
469 "**Tool Use**: {} (ID: {})\n",
470 tool_use.name, tool_use.id
471 ));
472 markdown.push_str(&format!(
473 "{}\n",
474 MarkdownCodeBlock {
475 tag: "json",
476 text: &format!("{:#}", tool_use.input)
477 }
478 ));
479 }
480 }
481 }
482
483 for tool_result in self.tool_results.values() {
484 markdown.push_str(&format!(
485 "**Tool Result**: {} (ID: {})\n\n",
486 tool_result.tool_name, tool_result.tool_use_id
487 ));
488 if tool_result.is_error {
489 markdown.push_str("**ERROR:**\n");
490 }
491
492 match &tool_result.content {
493 LanguageModelToolResultContent::Text(text) => {
494 writeln!(markdown, "{text}\n").ok();
495 }
496 LanguageModelToolResultContent::Image(_) => {
497 writeln!(markdown, "<image />\n").ok();
498 }
499 }
500
501 if let Some(output) = tool_result.output.as_ref() {
502 writeln!(
503 markdown,
504 "**Debug Output**:\n\n```json\n{}\n```\n",
505 serde_json::to_string_pretty(output).unwrap()
506 )
507 .unwrap();
508 }
509 }
510
511 markdown
512 }
513
514 pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
515 let mut assistant_message = LanguageModelRequestMessage {
516 role: Role::Assistant,
517 content: Vec::with_capacity(self.content.len()),
518 cache: false,
519 reasoning_details: self.reasoning_details.clone(),
520 };
521 for chunk in &self.content {
522 match chunk {
523 AgentMessageContent::Text(text) => {
524 assistant_message
525 .content
526 .push(language_model::MessageContent::Text(text.clone()));
527 }
528 AgentMessageContent::Thinking { text, signature } => {
529 assistant_message
530 .content
531 .push(language_model::MessageContent::Thinking {
532 text: text.clone(),
533 signature: signature.clone(),
534 });
535 }
536 AgentMessageContent::RedactedThinking(value) => {
537 assistant_message.content.push(
538 language_model::MessageContent::RedactedThinking(value.clone()),
539 );
540 }
541 AgentMessageContent::ToolUse(tool_use) => {
542 if self.tool_results.contains_key(&tool_use.id) {
543 assistant_message
544 .content
545 .push(language_model::MessageContent::ToolUse(tool_use.clone()));
546 }
547 }
548 };
549 }
550
551 let mut user_message = LanguageModelRequestMessage {
552 role: Role::User,
553 content: Vec::new(),
554 cache: false,
555 reasoning_details: None,
556 };
557
558 for tool_result in self.tool_results.values() {
559 let mut tool_result = tool_result.clone();
560 // Surprisingly, the API fails if we return an empty string here.
561 // It thinks we are sending a tool use without a tool result.
562 if tool_result.content.is_empty() {
563 tool_result.content = "<Tool returned an empty string>".into();
564 }
565 user_message
566 .content
567 .push(language_model::MessageContent::ToolResult(tool_result));
568 }
569
570 let mut messages = Vec::new();
571 if !assistant_message.content.is_empty() {
572 messages.push(assistant_message);
573 }
574 if !user_message.content.is_empty() {
575 messages.push(user_message);
576 }
577 messages
578 }
579}
580
581#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
582pub struct AgentMessage {
583 pub content: Vec<AgentMessageContent>,
584 pub tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
585 pub reasoning_details: Option<serde_json::Value>,
586}
587
588#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
589pub enum AgentMessageContent {
590 Text(String),
591 Thinking {
592 text: String,
593 signature: Option<String>,
594 },
595 RedactedThinking(String),
596 ToolUse(LanguageModelToolUse),
597}
598
599pub trait TerminalHandle {
600 fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId>;
601 fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse>;
602 fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>>;
603 fn kill(&self, cx: &AsyncApp) -> Result<()>;
604 fn was_stopped_by_user(&self, cx: &AsyncApp) -> Result<bool>;
605}
606
607pub trait SubagentHandle {
608 fn id(&self) -> acp::SessionId;
609 fn send(&self, message: String, cx: &AsyncApp) -> Task<Result<String>>;
610}
611
612pub trait ThreadEnvironment {
613 fn create_terminal(
614 &self,
615 command: String,
616 cwd: Option<PathBuf>,
617 output_byte_limit: Option<u64>,
618 cx: &mut AsyncApp,
619 ) -> Task<Result<Rc<dyn TerminalHandle>>>;
620
621 fn create_subagent(&self, label: String, cx: &mut App) -> Result<Rc<dyn SubagentHandle>>;
622
623 fn resume_subagent(
624 &self,
625 _session_id: acp::SessionId,
626 _cx: &mut App,
627 ) -> Result<Rc<dyn SubagentHandle>> {
628 Err(anyhow::anyhow!(
629 "Resuming subagent sessions is not supported"
630 ))
631 }
632}
633
634#[derive(Debug)]
635pub enum ThreadEvent {
636 UserMessage(UserMessage),
637 AgentText(String),
638 AgentThinking(String),
639 ToolCall(acp::ToolCall),
640 ToolCallUpdate(acp_thread::ToolCallUpdate),
641 ToolCallAuthorization(ToolCallAuthorization),
642 SubagentSpawned(acp::SessionId),
643 Retry(acp_thread::RetryStatus),
644 Stop(acp::StopReason),
645}
646
647#[derive(Debug)]
648pub struct NewTerminal {
649 pub command: String,
650 pub output_byte_limit: Option<u64>,
651 pub cwd: Option<PathBuf>,
652 pub response: oneshot::Sender<Result<Entity<acp_thread::Terminal>>>,
653}
654
655#[derive(Debug, Clone)]
656pub struct ToolPermissionContext {
657 pub tool_name: String,
658 pub input_values: Vec<String>,
659 pub scope: ToolPermissionScope,
660}
661
662#[derive(Debug, Clone, Copy, PartialEq, Eq)]
663pub enum ToolPermissionScope {
664 ToolInput,
665 SymlinkTarget,
666}
667
668impl ToolPermissionContext {
669 pub fn new(tool_name: impl Into<String>, input_values: Vec<String>) -> Self {
670 Self {
671 tool_name: tool_name.into(),
672 input_values,
673 scope: ToolPermissionScope::ToolInput,
674 }
675 }
676
677 pub fn symlink_target(tool_name: impl Into<String>, target_paths: Vec<String>) -> Self {
678 Self {
679 tool_name: tool_name.into(),
680 input_values: target_paths,
681 scope: ToolPermissionScope::SymlinkTarget,
682 }
683 }
684
685 /// Builds the permission options for this tool context.
686 ///
687 /// This is the canonical source for permission option generation.
688 /// Tests should use this function rather than manually constructing options.
689 ///
690 /// # Shell Compatibility for Terminal Tool
691 ///
692 /// For the terminal tool, "Always allow" options are only shown when the user's
693 /// shell supports POSIX-like command chaining syntax (`&&`, `||`, `;`, `|`).
694 ///
695 /// **Why this matters:** When a user sets up an "always allow" pattern like `^cargo`,
696 /// we need to parse the command to extract all sub-commands and verify that EVERY
697 /// sub-command matches the pattern. Otherwise, an attacker could craft a command like
698 /// `cargo build && rm -rf /` that would bypass the security check.
699 ///
700 /// **Supported shells:** Posix (sh, bash, dash, zsh), Fish 3.0+, PowerShell 7+/Pwsh,
701 /// Cmd, Xonsh, Csh, Tcsh
702 ///
703 /// **Unsupported shells:** Nushell (uses `and`/`or` keywords), Elvish (uses `and`/`or`
704 /// keywords), Rc (Plan 9 shell - no `&&`/`||` operators)
705 ///
706 /// For unsupported shells, we hide the "Always allow" UI options entirely, and if
707 /// the user has `always_allow` rules configured in settings, `ToolPermissionDecision::from_input`
708 /// will return a `Deny` with an explanatory error message.
709 pub fn build_permission_options(&self) -> acp_thread::PermissionOptions {
710 use crate::pattern_extraction::*;
711 use util::shell::ShellKind;
712
713 let tool_name = &self.tool_name;
714 let input_values = &self.input_values;
715 if self.scope == ToolPermissionScope::SymlinkTarget {
716 return acp_thread::PermissionOptions::Flat(vec![
717 acp::PermissionOption::new(
718 acp::PermissionOptionId::new("allow"),
719 "Yes",
720 acp::PermissionOptionKind::AllowOnce,
721 ),
722 acp::PermissionOption::new(
723 acp::PermissionOptionId::new("deny"),
724 "No",
725 acp::PermissionOptionKind::RejectOnce,
726 ),
727 ]);
728 }
729
730 // Check if the user's shell supports POSIX-like command chaining.
731 // See the doc comment above for the full explanation of why this is needed.
732 let shell_supports_always_allow = if tool_name == TerminalTool::NAME {
733 ShellKind::system().supports_posix_chaining()
734 } else {
735 true
736 };
737
738 let extract_for_value = |value: &str| -> (Option<String>, Option<String>) {
739 if tool_name == TerminalTool::NAME {
740 (
741 extract_terminal_pattern(value),
742 extract_terminal_pattern_display(value),
743 )
744 } else if tool_name == CopyPathTool::NAME
745 || tool_name == MovePathTool::NAME
746 || tool_name == EditFileTool::NAME
747 || tool_name == DeletePathTool::NAME
748 || tool_name == CreateDirectoryTool::NAME
749 || tool_name == SaveFileTool::NAME
750 {
751 (
752 extract_path_pattern(value),
753 extract_path_pattern_display(value),
754 )
755 } else if tool_name == FetchTool::NAME {
756 (
757 extract_url_pattern(value),
758 extract_url_pattern_display(value),
759 )
760 } else {
761 (None, None)
762 }
763 };
764
765 // Extract patterns from all input values. Only offer a pattern-specific
766 // "always allow/deny" button when every value produces the same pattern.
767 let (pattern, pattern_display) = match input_values.as_slice() {
768 [single] => extract_for_value(single),
769 _ => {
770 let mut iter = input_values.iter().map(|v| extract_for_value(v));
771 match iter.next() {
772 Some(first) => {
773 if iter.all(|pair| pair.0 == first.0) {
774 first
775 } else {
776 (None, None)
777 }
778 }
779 None => (None, None),
780 }
781 }
782 };
783
784 let mut choices = Vec::new();
785
786 let mut push_choice = |label: String, allow_id, deny_id, allow_kind, deny_kind| {
787 choices.push(acp_thread::PermissionOptionChoice {
788 allow: acp::PermissionOption::new(
789 acp::PermissionOptionId::new(allow_id),
790 label.clone(),
791 allow_kind,
792 ),
793 deny: acp::PermissionOption::new(
794 acp::PermissionOptionId::new(deny_id),
795 label,
796 deny_kind,
797 ),
798 });
799 };
800
801 if shell_supports_always_allow {
802 push_choice(
803 format!("Always for {}", tool_name.replace('_', " ")),
804 format!("always_allow:{}", tool_name),
805 format!("always_deny:{}", tool_name),
806 acp::PermissionOptionKind::AllowAlways,
807 acp::PermissionOptionKind::RejectAlways,
808 );
809
810 if let (Some(pattern), Some(display)) = (pattern, pattern_display) {
811 let button_text = if tool_name == TerminalTool::NAME {
812 format!("Always for `{}` commands", display)
813 } else {
814 format!("Always for `{}`", display)
815 };
816 push_choice(
817 button_text,
818 format!("always_allow_pattern:{}\n{}", tool_name, pattern),
819 format!("always_deny_pattern:{}\n{}", tool_name, pattern),
820 acp::PermissionOptionKind::AllowAlways,
821 acp::PermissionOptionKind::RejectAlways,
822 );
823 }
824 }
825
826 push_choice(
827 "Only this time".to_string(),
828 "allow".to_string(),
829 "deny".to_string(),
830 acp::PermissionOptionKind::AllowOnce,
831 acp::PermissionOptionKind::RejectOnce,
832 );
833
834 acp_thread::PermissionOptions::Dropdown(choices)
835 }
836}
837
838#[derive(Debug)]
839pub struct ToolCallAuthorization {
840 pub tool_call: acp::ToolCallUpdate,
841 pub options: acp_thread::PermissionOptions,
842 pub response: oneshot::Sender<acp::PermissionOptionId>,
843 pub context: Option<ToolPermissionContext>,
844}
845
846#[derive(Debug, thiserror::Error)]
847enum CompletionError {
848 #[error("max tokens")]
849 MaxTokens,
850 #[error("refusal")]
851 Refusal,
852 #[error(transparent)]
853 Other(#[from] anyhow::Error),
854}
855
856pub struct Thread {
857 id: acp::SessionId,
858 prompt_id: PromptId,
859 updated_at: DateTime<Utc>,
860 title: Option<SharedString>,
861 pending_title_generation: Option<Task<()>>,
862 pending_summary_generation: Option<Shared<Task<Option<SharedString>>>>,
863 summary: Option<SharedString>,
864 messages: Vec<Message>,
865 user_store: Entity<UserStore>,
866 /// Holds the task that handles agent interaction until the end of the turn.
867 /// Survives across multiple requests as the model performs tool calls and
868 /// we run tools, report their results.
869 running_turn: Option<RunningTurn>,
870 /// Flag indicating the UI has a queued message waiting to be sent.
871 /// Used to signal that the turn should end at the next message boundary.
872 has_queued_message: bool,
873 pending_message: Option<AgentMessage>,
874 pub(crate) tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
875 request_token_usage: HashMap<UserMessageId, language_model::TokenUsage>,
876 #[allow(unused)]
877 cumulative_token_usage: TokenUsage,
878 #[allow(unused)]
879 initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
880 pub(crate) context_server_registry: Entity<ContextServerRegistry>,
881 profile_id: AgentProfileId,
882 project_context: Entity<ProjectContext>,
883 pub(crate) templates: Arc<Templates>,
884 model: Option<Arc<dyn LanguageModel>>,
885 summarization_model: Option<Arc<dyn LanguageModel>>,
886 thinking_enabled: bool,
887 thinking_effort: Option<String>,
888 speed: Option<Speed>,
889 prompt_capabilities_tx: watch::Sender<acp::PromptCapabilities>,
890 pub(crate) prompt_capabilities_rx: watch::Receiver<acp::PromptCapabilities>,
891 pub(crate) project: Entity<Project>,
892 pub(crate) action_log: Entity<ActionLog>,
893 /// Tracks the last time files were read by the agent, to detect external modifications
894 pub(crate) file_read_times: HashMap<PathBuf, fs::MTime>,
895 /// True if this thread was imported from a shared thread and can be synced.
896 imported: bool,
897 /// If this is a subagent thread, contains context about the parent
898 subagent_context: Option<SubagentContext>,
899 /// Weak references to running subagent threads for cancellation propagation
900 running_subagents: Vec<WeakEntity<Thread>>,
901}
902
903impl Thread {
904 fn prompt_capabilities(model: Option<&dyn LanguageModel>) -> acp::PromptCapabilities {
905 let image = model.map_or(true, |model| model.supports_images());
906 acp::PromptCapabilities::new()
907 .image(image)
908 .embedded_context(true)
909 }
910
911 pub fn new_subagent(parent_thread: &Entity<Thread>, cx: &mut Context<Self>) -> Self {
912 let project = parent_thread.read(cx).project.clone();
913 let project_context = parent_thread.read(cx).project_context.clone();
914 let context_server_registry = parent_thread.read(cx).context_server_registry.clone();
915 let templates = parent_thread.read(cx).templates.clone();
916 let model = parent_thread.read(cx).model().cloned();
917 let mut thread = Self::new(
918 project,
919 project_context,
920 context_server_registry,
921 templates,
922 model,
923 cx,
924 );
925 thread.subagent_context = Some(SubagentContext {
926 parent_thread_id: parent_thread.read(cx).id().clone(),
927 depth: parent_thread.read(cx).depth() + 1,
928 });
929 thread
930 }
931
932 pub fn new(
933 project: Entity<Project>,
934 project_context: Entity<ProjectContext>,
935 context_server_registry: Entity<ContextServerRegistry>,
936 templates: Arc<Templates>,
937 model: Option<Arc<dyn LanguageModel>>,
938 cx: &mut Context<Self>,
939 ) -> Self {
940 let settings = AgentSettings::get_global(cx);
941 let profile_id = settings.default_profile.clone();
942 let enable_thinking = settings
943 .default_model
944 .as_ref()
945 .is_some_and(|model| model.enable_thinking);
946 let thinking_effort = settings
947 .default_model
948 .as_ref()
949 .and_then(|model| model.effort.clone());
950 let action_log = cx.new(|_cx| ActionLog::new(project.clone()));
951 let (prompt_capabilities_tx, prompt_capabilities_rx) =
952 watch::channel(Self::prompt_capabilities(model.as_deref()));
953 Self {
954 id: acp::SessionId::new(uuid::Uuid::new_v4().to_string()),
955 prompt_id: PromptId::new(),
956 updated_at: Utc::now(),
957 title: None,
958 pending_title_generation: None,
959 pending_summary_generation: None,
960 summary: None,
961 messages: Vec::new(),
962 user_store: project.read(cx).user_store(),
963 running_turn: None,
964 has_queued_message: false,
965 pending_message: None,
966 tools: BTreeMap::default(),
967 request_token_usage: HashMap::default(),
968 cumulative_token_usage: TokenUsage::default(),
969 initial_project_snapshot: {
970 let project_snapshot = Self::project_snapshot(project.clone(), cx);
971 cx.foreground_executor()
972 .spawn(async move { Some(project_snapshot.await) })
973 .shared()
974 },
975 context_server_registry,
976 profile_id,
977 project_context,
978 templates,
979 model,
980 summarization_model: None,
981 thinking_enabled: enable_thinking,
982 speed: None,
983 thinking_effort,
984 prompt_capabilities_tx,
985 prompt_capabilities_rx,
986 project,
987 action_log,
988 file_read_times: HashMap::default(),
989 imported: false,
990 subagent_context: None,
991 running_subagents: Vec::new(),
992 }
993 }
994
995 pub fn id(&self) -> &acp::SessionId {
996 &self.id
997 }
998
999 /// Returns true if this thread was imported from a shared thread.
1000 pub fn is_imported(&self) -> bool {
1001 self.imported
1002 }
1003
1004 pub fn replay(
1005 &mut self,
1006 cx: &mut Context<Self>,
1007 ) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {
1008 let (tx, rx) = mpsc::unbounded();
1009 let stream = ThreadEventStream(tx);
1010 for message in &self.messages {
1011 match message {
1012 Message::User(user_message) => stream.send_user_message(user_message),
1013 Message::Agent(assistant_message) => {
1014 for content in &assistant_message.content {
1015 match content {
1016 AgentMessageContent::Text(text) => stream.send_text(text),
1017 AgentMessageContent::Thinking { text, .. } => {
1018 stream.send_thinking(text)
1019 }
1020 AgentMessageContent::RedactedThinking(_) => {}
1021 AgentMessageContent::ToolUse(tool_use) => {
1022 self.replay_tool_call(
1023 tool_use,
1024 assistant_message.tool_results.get(&tool_use.id),
1025 &stream,
1026 cx,
1027 );
1028 }
1029 }
1030 }
1031 }
1032 Message::Resume => {}
1033 }
1034 }
1035 rx
1036 }
1037
1038 fn replay_tool_call(
1039 &self,
1040 tool_use: &LanguageModelToolUse,
1041 tool_result: Option<&LanguageModelToolResult>,
1042 stream: &ThreadEventStream,
1043 cx: &mut Context<Self>,
1044 ) {
1045 // Extract saved output and status first, so they're available even if tool is not found
1046 let output = tool_result
1047 .as_ref()
1048 .and_then(|result| result.output.clone());
1049 let status = tool_result
1050 .as_ref()
1051 .map_or(acp::ToolCallStatus::Failed, |result| {
1052 if result.is_error {
1053 acp::ToolCallStatus::Failed
1054 } else {
1055 acp::ToolCallStatus::Completed
1056 }
1057 });
1058
1059 let tool = self.tools.get(tool_use.name.as_ref()).cloned().or_else(|| {
1060 self.context_server_registry
1061 .read(cx)
1062 .servers()
1063 .find_map(|(_, tools)| {
1064 if let Some(tool) = tools.get(tool_use.name.as_ref()) {
1065 Some(tool.clone())
1066 } else {
1067 None
1068 }
1069 })
1070 });
1071
1072 let Some(tool) = tool else {
1073 // Tool not found (e.g., MCP server not connected after restart),
1074 // but still display the saved result if available.
1075 // We need to send both ToolCall and ToolCallUpdate events because the UI
1076 // only converts raw_output to displayable content in update_fields, not from_acp.
1077 stream
1078 .0
1079 .unbounded_send(Ok(ThreadEvent::ToolCall(
1080 acp::ToolCall::new(tool_use.id.to_string(), tool_use.name.to_string())
1081 .status(status)
1082 .raw_input(tool_use.input.clone()),
1083 )))
1084 .ok();
1085 stream.update_tool_call_fields(
1086 &tool_use.id,
1087 acp::ToolCallUpdateFields::new()
1088 .status(status)
1089 .raw_output(output),
1090 None,
1091 );
1092 return;
1093 };
1094
1095 let title = tool.initial_title(tool_use.input.clone(), cx);
1096 let kind = tool.kind();
1097 stream.send_tool_call(
1098 &tool_use.id,
1099 &tool_use.name,
1100 title,
1101 kind,
1102 tool_use.input.clone(),
1103 );
1104
1105 if let Some(output) = output.clone() {
1106 // For replay, we use a dummy cancellation receiver since the tool already completed
1107 let (_cancellation_tx, cancellation_rx) = watch::channel(false);
1108 let tool_event_stream = ToolCallEventStream::new(
1109 tool_use.id.clone(),
1110 stream.clone(),
1111 Some(self.project.read(cx).fs().clone()),
1112 cancellation_rx,
1113 );
1114 tool.replay(tool_use.input.clone(), output, tool_event_stream, cx)
1115 .log_err();
1116 }
1117
1118 stream.update_tool_call_fields(
1119 &tool_use.id,
1120 acp::ToolCallUpdateFields::new()
1121 .status(status)
1122 .raw_output(output),
1123 None,
1124 );
1125 }
1126
1127 pub fn from_db(
1128 id: acp::SessionId,
1129 db_thread: DbThread,
1130 project: Entity<Project>,
1131 project_context: Entity<ProjectContext>,
1132 context_server_registry: Entity<ContextServerRegistry>,
1133 templates: Arc<Templates>,
1134 cx: &mut Context<Self>,
1135 ) -> Self {
1136 let settings = AgentSettings::get_global(cx);
1137 let profile_id = db_thread
1138 .profile
1139 .unwrap_or_else(|| settings.default_profile.clone());
1140
1141 let mut model = LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1142 db_thread
1143 .model
1144 .and_then(|model| {
1145 let model = SelectedModel {
1146 provider: model.provider.clone().into(),
1147 model: model.model.into(),
1148 };
1149 registry.select_model(&model, cx)
1150 })
1151 .or_else(|| registry.default_model())
1152 .map(|model| model.model)
1153 });
1154
1155 if model.is_none() {
1156 model = Self::resolve_profile_model(&profile_id, cx);
1157 }
1158 if model.is_none() {
1159 model = LanguageModelRegistry::global(cx).update(cx, |registry, _cx| {
1160 registry.default_model().map(|model| model.model)
1161 });
1162 }
1163
1164 let (prompt_capabilities_tx, prompt_capabilities_rx) =
1165 watch::channel(Self::prompt_capabilities(model.as_deref()));
1166
1167 let action_log = cx.new(|_| ActionLog::new(project.clone()));
1168
1169 Self {
1170 id,
1171 prompt_id: PromptId::new(),
1172 title: if db_thread.title.is_empty() {
1173 None
1174 } else {
1175 Some(db_thread.title.clone())
1176 },
1177 pending_title_generation: None,
1178 pending_summary_generation: None,
1179 summary: db_thread.detailed_summary,
1180 messages: db_thread.messages,
1181 user_store: project.read(cx).user_store(),
1182 running_turn: None,
1183 has_queued_message: false,
1184 pending_message: None,
1185 tools: BTreeMap::default(),
1186 request_token_usage: db_thread.request_token_usage.clone(),
1187 cumulative_token_usage: db_thread.cumulative_token_usage,
1188 initial_project_snapshot: Task::ready(db_thread.initial_project_snapshot).shared(),
1189 context_server_registry,
1190 profile_id,
1191 project_context,
1192 templates,
1193 model,
1194 summarization_model: None,
1195 thinking_enabled: db_thread.thinking_enabled,
1196 thinking_effort: db_thread.thinking_effort,
1197 speed: db_thread.speed,
1198 project,
1199 action_log,
1200 updated_at: db_thread.updated_at,
1201 prompt_capabilities_tx,
1202 prompt_capabilities_rx,
1203 file_read_times: HashMap::default(),
1204 imported: db_thread.imported,
1205 subagent_context: db_thread.subagent_context,
1206 running_subagents: Vec::new(),
1207 }
1208 }
1209
1210 pub fn to_db(&self, cx: &App) -> Task<DbThread> {
1211 let initial_project_snapshot = self.initial_project_snapshot.clone();
1212 let mut thread = DbThread {
1213 title: self.title(),
1214 messages: self.messages.clone(),
1215 updated_at: self.updated_at,
1216 detailed_summary: self.summary.clone(),
1217 initial_project_snapshot: None,
1218 cumulative_token_usage: self.cumulative_token_usage,
1219 request_token_usage: self.request_token_usage.clone(),
1220 model: self.model.as_ref().map(|model| DbLanguageModel {
1221 provider: model.provider_id().to_string(),
1222 model: model.id().0.to_string(),
1223 }),
1224 profile: Some(self.profile_id.clone()),
1225 imported: self.imported,
1226 subagent_context: self.subagent_context.clone(),
1227 speed: self.speed,
1228 thinking_enabled: self.thinking_enabled,
1229 thinking_effort: self.thinking_effort.clone(),
1230 };
1231
1232 cx.background_spawn(async move {
1233 let initial_project_snapshot = initial_project_snapshot.await;
1234 thread.initial_project_snapshot = initial_project_snapshot;
1235 thread
1236 })
1237 }
1238
1239 /// Create a snapshot of the current project state including git information and unsaved buffers.
1240 fn project_snapshot(
1241 project: Entity<Project>,
1242 cx: &mut Context<Self>,
1243 ) -> Task<Arc<ProjectSnapshot>> {
1244 let task = project::telemetry_snapshot::TelemetrySnapshot::new(&project, cx);
1245 cx.spawn(async move |_, _| {
1246 let snapshot = task.await;
1247
1248 Arc::new(ProjectSnapshot {
1249 worktree_snapshots: snapshot.worktree_snapshots,
1250 timestamp: Utc::now(),
1251 })
1252 })
1253 }
1254
1255 pub fn project_context(&self) -> &Entity<ProjectContext> {
1256 &self.project_context
1257 }
1258
1259 pub fn project(&self) -> &Entity<Project> {
1260 &self.project
1261 }
1262
1263 pub fn action_log(&self) -> &Entity<ActionLog> {
1264 &self.action_log
1265 }
1266
1267 pub fn is_empty(&self) -> bool {
1268 self.messages.is_empty() && self.title.is_none()
1269 }
1270
1271 pub fn model(&self) -> Option<&Arc<dyn LanguageModel>> {
1272 self.model.as_ref()
1273 }
1274
1275 pub fn set_model(&mut self, model: Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
1276 let old_usage = self.latest_token_usage();
1277 self.model = Some(model);
1278 let new_caps = Self::prompt_capabilities(self.model.as_deref());
1279 let new_usage = self.latest_token_usage();
1280 if old_usage != new_usage {
1281 cx.emit(TokenUsageUpdated(new_usage));
1282 }
1283 self.prompt_capabilities_tx.send(new_caps).log_err();
1284 cx.notify()
1285 }
1286
1287 pub fn summarization_model(&self) -> Option<&Arc<dyn LanguageModel>> {
1288 self.summarization_model.as_ref()
1289 }
1290
1291 pub fn set_summarization_model(
1292 &mut self,
1293 model: Option<Arc<dyn LanguageModel>>,
1294 cx: &mut Context<Self>,
1295 ) {
1296 self.summarization_model = model;
1297 cx.notify()
1298 }
1299
1300 pub fn thinking_enabled(&self) -> bool {
1301 self.thinking_enabled
1302 }
1303
1304 pub fn set_thinking_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
1305 self.thinking_enabled = enabled;
1306 cx.notify();
1307 }
1308
1309 pub fn thinking_effort(&self) -> Option<&String> {
1310 self.thinking_effort.as_ref()
1311 }
1312
1313 pub fn set_thinking_effort(&mut self, effort: Option<String>, cx: &mut Context<Self>) {
1314 self.thinking_effort = effort;
1315 cx.notify();
1316 }
1317
1318 pub fn speed(&self) -> Option<Speed> {
1319 self.speed
1320 }
1321
1322 pub fn set_speed(&mut self, speed: Speed, cx: &mut Context<Self>) {
1323 self.speed = Some(speed);
1324 cx.notify();
1325 }
1326
1327 pub fn last_message(&self) -> Option<Message> {
1328 if let Some(message) = self.pending_message.clone() {
1329 Some(Message::Agent(message))
1330 } else {
1331 self.messages.last().cloned()
1332 }
1333 }
1334
1335 pub fn add_default_tools(
1336 &mut self,
1337 environment: Rc<dyn ThreadEnvironment>,
1338 cx: &mut Context<Self>,
1339 ) {
1340 let language_registry = self.project.read(cx).languages().clone();
1341 self.add_tool(CopyPathTool::new(self.project.clone()));
1342 self.add_tool(CreateDirectoryTool::new(self.project.clone()));
1343 self.add_tool(DeletePathTool::new(
1344 self.project.clone(),
1345 self.action_log.clone(),
1346 ));
1347 self.add_tool(DiagnosticsTool::new(self.project.clone()));
1348 self.add_tool(EditFileTool::new(
1349 self.project.clone(),
1350 cx.weak_entity(),
1351 language_registry.clone(),
1352 Templates::new(),
1353 ));
1354 self.add_tool(StreamingEditFileTool::new(
1355 self.project.clone(),
1356 cx.weak_entity(),
1357 language_registry,
1358 ));
1359 self.add_tool(FetchTool::new(self.project.read(cx).client().http_client()));
1360 self.add_tool(FindPathTool::new(self.project.clone()));
1361 self.add_tool(GrepTool::new(self.project.clone()));
1362 self.add_tool(ListDirectoryTool::new(self.project.clone()));
1363 self.add_tool(MovePathTool::new(self.project.clone()));
1364 self.add_tool(NowTool);
1365 self.add_tool(OpenTool::new(self.project.clone()));
1366 self.add_tool(ReadFileTool::new(
1367 cx.weak_entity(),
1368 self.project.clone(),
1369 self.action_log.clone(),
1370 ));
1371 self.add_tool(SaveFileTool::new(self.project.clone()));
1372 self.add_tool(RestoreFileFromDiskTool::new(self.project.clone()));
1373 self.add_tool(TerminalTool::new(self.project.clone(), environment.clone()));
1374 self.add_tool(WebSearchTool);
1375
1376 if cx.has_flag::<SubagentsFeatureFlag>() && self.depth() < MAX_SUBAGENT_DEPTH {
1377 self.add_tool(SpawnAgentTool::new(environment));
1378 }
1379 }
1380
1381 pub fn add_tool<T: AgentTool>(&mut self, tool: T) {
1382 debug_assert!(
1383 !self.tools.contains_key(T::NAME),
1384 "Duplicate tool name: {}",
1385 T::NAME,
1386 );
1387 self.tools.insert(T::NAME.into(), tool.erase());
1388 }
1389
1390 pub fn remove_tool(&mut self, name: &str) -> bool {
1391 self.tools.remove(name).is_some()
1392 }
1393
1394 pub fn profile(&self) -> &AgentProfileId {
1395 &self.profile_id
1396 }
1397
1398 pub fn set_profile(&mut self, profile_id: AgentProfileId, cx: &mut Context<Self>) {
1399 if self.profile_id == profile_id {
1400 return;
1401 }
1402
1403 self.profile_id = profile_id;
1404
1405 // Swap to the profile's preferred model when available.
1406 if let Some(model) = Self::resolve_profile_model(&self.profile_id, cx) {
1407 self.set_model(model, cx);
1408 }
1409 }
1410
1411 pub fn cancel(&mut self, cx: &mut Context<Self>) -> Task<()> {
1412 for subagent in self.running_subagents.drain(..) {
1413 if let Some(subagent) = subagent.upgrade() {
1414 subagent.update(cx, |thread, cx| thread.cancel(cx)).detach();
1415 }
1416 }
1417
1418 let Some(running_turn) = self.running_turn.take() else {
1419 self.flush_pending_message(cx);
1420 return Task::ready(());
1421 };
1422
1423 let turn_task = running_turn.cancel();
1424
1425 cx.spawn(async move |this, cx| {
1426 turn_task.await;
1427 this.update(cx, |this, cx| {
1428 this.flush_pending_message(cx);
1429 })
1430 .ok();
1431 })
1432 }
1433
1434 pub fn set_has_queued_message(&mut self, has_queued: bool) {
1435 self.has_queued_message = has_queued;
1436 }
1437
1438 pub fn has_queued_message(&self) -> bool {
1439 self.has_queued_message
1440 }
1441
1442 fn update_token_usage(&mut self, update: language_model::TokenUsage, cx: &mut Context<Self>) {
1443 let Some(last_user_message) = self.last_user_message() else {
1444 return;
1445 };
1446
1447 self.request_token_usage
1448 .insert(last_user_message.id.clone(), update);
1449 cx.emit(TokenUsageUpdated(self.latest_token_usage()));
1450 cx.notify();
1451 }
1452
1453 pub fn truncate(&mut self, message_id: UserMessageId, cx: &mut Context<Self>) -> Result<()> {
1454 self.cancel(cx).detach();
1455 // Clear pending message since cancel will try to flush it asynchronously,
1456 // and we don't want that content to be added after we truncate
1457 self.pending_message.take();
1458 let Some(position) = self.messages.iter().position(
1459 |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
1460 ) else {
1461 return Err(anyhow!("Message not found"));
1462 };
1463
1464 for message in self.messages.drain(position..) {
1465 match message {
1466 Message::User(message) => {
1467 self.request_token_usage.remove(&message.id);
1468 }
1469 Message::Agent(_) | Message::Resume => {}
1470 }
1471 }
1472 self.clear_summary();
1473 cx.notify();
1474 Ok(())
1475 }
1476
1477 pub fn latest_request_token_usage(&self) -> Option<language_model::TokenUsage> {
1478 let last_user_message = self.last_user_message()?;
1479 let tokens = self.request_token_usage.get(&last_user_message.id)?;
1480 Some(*tokens)
1481 }
1482
1483 pub fn latest_token_usage(&self) -> Option<acp_thread::TokenUsage> {
1484 let usage = self.latest_request_token_usage()?;
1485 let model = self.model.clone()?;
1486 Some(acp_thread::TokenUsage {
1487 max_tokens: model.max_token_count(),
1488 max_output_tokens: model.max_output_tokens(),
1489 used_tokens: usage.total_tokens(),
1490 input_tokens: usage.input_tokens,
1491 output_tokens: usage.output_tokens,
1492 })
1493 }
1494
1495 /// Get the total input token count as of the message before the given message.
1496 ///
1497 /// Returns `None` if:
1498 /// - `target_id` is the first message (no previous message)
1499 /// - The previous message hasn't received a response yet (no usage data)
1500 /// - `target_id` is not found in the messages
1501 pub fn tokens_before_message(&self, target_id: &UserMessageId) -> Option<u64> {
1502 let mut previous_user_message_id: Option<&UserMessageId> = None;
1503
1504 for message in &self.messages {
1505 if let Message::User(user_msg) = message {
1506 if &user_msg.id == target_id {
1507 let prev_id = previous_user_message_id?;
1508 let usage = self.request_token_usage.get(prev_id)?;
1509 return Some(usage.input_tokens);
1510 }
1511 previous_user_message_id = Some(&user_msg.id);
1512 }
1513 }
1514 None
1515 }
1516
1517 /// Look up the active profile and resolve its preferred model if one is configured.
1518 fn resolve_profile_model(
1519 profile_id: &AgentProfileId,
1520 cx: &mut Context<Self>,
1521 ) -> Option<Arc<dyn LanguageModel>> {
1522 let selection = AgentSettings::get_global(cx)
1523 .profiles
1524 .get(profile_id)?
1525 .default_model
1526 .clone()?;
1527 Self::resolve_model_from_selection(&selection, cx)
1528 }
1529
1530 /// Translate a stored model selection into the configured model from the registry.
1531 fn resolve_model_from_selection(
1532 selection: &LanguageModelSelection,
1533 cx: &mut Context<Self>,
1534 ) -> Option<Arc<dyn LanguageModel>> {
1535 let selected = SelectedModel {
1536 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
1537 model: LanguageModelId::from(selection.model.clone()),
1538 };
1539 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1540 registry
1541 .select_model(&selected, cx)
1542 .map(|configured| configured.model)
1543 })
1544 }
1545
1546 pub fn resume(
1547 &mut self,
1548 cx: &mut Context<Self>,
1549 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1550 self.messages.push(Message::Resume);
1551 cx.notify();
1552
1553 log::debug!("Total messages in thread: {}", self.messages.len());
1554 self.run_turn(cx)
1555 }
1556
1557 /// Sending a message results in the model streaming a response, which could include tool calls.
1558 /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
1559 /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
1560 pub fn send<T>(
1561 &mut self,
1562 id: UserMessageId,
1563 content: impl IntoIterator<Item = T>,
1564 cx: &mut Context<Self>,
1565 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
1566 where
1567 T: Into<UserMessageContent>,
1568 {
1569 let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
1570 log::debug!("Thread::send content: {:?}", content);
1571
1572 self.messages
1573 .push(Message::User(UserMessage { id, content }));
1574 cx.notify();
1575
1576 self.send_existing(cx)
1577 }
1578
1579 pub fn send_existing(
1580 &mut self,
1581 cx: &mut Context<Self>,
1582 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1583 let model = self.model().context("No language model configured")?;
1584
1585 log::info!("Thread::send called with model: {}", model.name().0);
1586 self.advance_prompt_id();
1587
1588 log::debug!("Total messages in thread: {}", self.messages.len());
1589 self.run_turn(cx)
1590 }
1591
1592 pub fn push_acp_user_block(
1593 &mut self,
1594 id: UserMessageId,
1595 blocks: impl IntoIterator<Item = acp::ContentBlock>,
1596 path_style: PathStyle,
1597 cx: &mut Context<Self>,
1598 ) {
1599 let content = blocks
1600 .into_iter()
1601 .map(|block| UserMessageContent::from_content_block(block, path_style))
1602 .collect::<Vec<_>>();
1603 self.messages
1604 .push(Message::User(UserMessage { id, content }));
1605 cx.notify();
1606 }
1607
1608 pub fn push_acp_agent_block(&mut self, block: acp::ContentBlock, cx: &mut Context<Self>) {
1609 let text = match block {
1610 acp::ContentBlock::Text(text_content) => text_content.text,
1611 acp::ContentBlock::Image(_) => "[image]".to_string(),
1612 acp::ContentBlock::Audio(_) => "[audio]".to_string(),
1613 acp::ContentBlock::ResourceLink(resource_link) => resource_link.uri,
1614 acp::ContentBlock::Resource(resource) => match resource.resource {
1615 acp::EmbeddedResourceResource::TextResourceContents(resource) => resource.uri,
1616 acp::EmbeddedResourceResource::BlobResourceContents(resource) => resource.uri,
1617 _ => "[resource]".to_string(),
1618 },
1619 _ => "[unknown]".to_string(),
1620 };
1621
1622 self.messages.push(Message::Agent(AgentMessage {
1623 content: vec![AgentMessageContent::Text(text)],
1624 ..Default::default()
1625 }));
1626 cx.notify();
1627 }
1628
1629 #[cfg(feature = "eval")]
1630 pub fn proceed(
1631 &mut self,
1632 cx: &mut Context<Self>,
1633 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1634 self.run_turn(cx)
1635 }
1636
1637 fn run_turn(
1638 &mut self,
1639 cx: &mut Context<Self>,
1640 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1641 // Flush the old pending message synchronously before cancelling,
1642 // to avoid a race where the detached cancel task might flush the NEW
1643 // turn's pending message instead of the old one.
1644 self.flush_pending_message(cx);
1645 self.cancel(cx).detach();
1646
1647 let model = self.model.clone().context("No language model configured")?;
1648 let profile = AgentSettings::get_global(cx)
1649 .profiles
1650 .get(&self.profile_id)
1651 .context("Profile not found")?;
1652 let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1653 let event_stream = ThreadEventStream(events_tx);
1654 let message_ix = self.messages.len().saturating_sub(1);
1655 self.clear_summary();
1656 let (cancellation_tx, mut cancellation_rx) = watch::channel(false);
1657 self.running_turn = Some(RunningTurn {
1658 event_stream: event_stream.clone(),
1659 tools: self.enabled_tools(profile, &model, cx),
1660 cancellation_tx,
1661 streaming_tool_inputs: HashMap::default(),
1662 _task: cx.spawn(async move |this, cx| {
1663 log::debug!("Starting agent turn execution");
1664
1665 let turn_result = Self::run_turn_internal(
1666 &this,
1667 model,
1668 &event_stream,
1669 cancellation_rx.clone(),
1670 cx,
1671 )
1672 .await;
1673
1674 // Check if we were cancelled - if so, cancel() already took running_turn
1675 // and we shouldn't touch it (it might be a NEW turn now)
1676 let was_cancelled = *cancellation_rx.borrow();
1677 if was_cancelled {
1678 log::debug!("Turn was cancelled, skipping cleanup");
1679 return;
1680 }
1681
1682 _ = this.update(cx, |this, cx| this.flush_pending_message(cx));
1683
1684 match turn_result {
1685 Ok(()) => {
1686 log::debug!("Turn execution completed");
1687 event_stream.send_stop(acp::StopReason::EndTurn);
1688 }
1689 Err(error) => {
1690 log::error!("Turn execution failed: {:?}", error);
1691 match error.downcast::<CompletionError>() {
1692 Ok(CompletionError::Refusal) => {
1693 event_stream.send_stop(acp::StopReason::Refusal);
1694 _ = this.update(cx, |this, _| this.messages.truncate(message_ix));
1695 }
1696 Ok(CompletionError::MaxTokens) => {
1697 event_stream.send_stop(acp::StopReason::MaxTokens);
1698 }
1699 Ok(CompletionError::Other(error)) | Err(error) => {
1700 event_stream.send_error(error);
1701 }
1702 }
1703 }
1704 }
1705
1706 _ = this.update(cx, |this, _| this.running_turn.take());
1707 }),
1708 });
1709 Ok(events_rx)
1710 }
1711
1712 async fn run_turn_internal(
1713 this: &WeakEntity<Self>,
1714 model: Arc<dyn LanguageModel>,
1715 event_stream: &ThreadEventStream,
1716 mut cancellation_rx: watch::Receiver<bool>,
1717 cx: &mut AsyncApp,
1718 ) -> Result<()> {
1719 let mut attempt = 0;
1720 let mut intent = CompletionIntent::UserPrompt;
1721 loop {
1722 let request =
1723 this.update(cx, |this, cx| this.build_completion_request(intent, cx))??;
1724
1725 telemetry::event!(
1726 "Agent Thread Completion",
1727 thread_id = this.read_with(cx, |this, _| this.id.to_string())?,
1728 prompt_id = this.read_with(cx, |this, _| this.prompt_id.to_string())?,
1729 model = model.telemetry_id(),
1730 model_provider = model.provider_id().to_string(),
1731 attempt
1732 );
1733
1734 log::debug!("Calling model.stream_completion, attempt {}", attempt);
1735
1736 let (mut events, mut error) = match model.stream_completion(request, cx).await {
1737 Ok(events) => (events.fuse(), None),
1738 Err(err) => (stream::empty().boxed().fuse(), Some(err)),
1739 };
1740 let mut tool_results = FuturesUnordered::new();
1741 let mut cancelled = false;
1742 loop {
1743 // Race between getting the first event and cancellation
1744 let first_event = futures::select! {
1745 event = events.next().fuse() => event,
1746 _ = cancellation_rx.changed().fuse() => {
1747 if *cancellation_rx.borrow() {
1748 cancelled = true;
1749 break;
1750 }
1751 continue;
1752 }
1753 };
1754 let Some(first_event) = first_event else {
1755 break;
1756 };
1757
1758 // Collect all immediately available events to process as a batch
1759 let mut batch = vec![first_event];
1760 while let Some(event) = events.next().now_or_never().flatten() {
1761 batch.push(event);
1762 }
1763
1764 // Process the batch in a single update
1765 let batch_result = this.update(cx, |this, cx| {
1766 let mut batch_tool_results = Vec::new();
1767 let mut batch_error = None;
1768
1769 for event in batch {
1770 log::trace!("Received completion event: {:?}", event);
1771 match event {
1772 Ok(event) => {
1773 match this.handle_completion_event(
1774 event,
1775 event_stream,
1776 cancellation_rx.clone(),
1777 cx,
1778 ) {
1779 Ok(Some(task)) => batch_tool_results.push(task),
1780 Ok(None) => {}
1781 Err(err) => {
1782 batch_error = Some(err);
1783 break;
1784 }
1785 }
1786 }
1787 Err(err) => {
1788 batch_error = Some(err.into());
1789 break;
1790 }
1791 }
1792 }
1793
1794 cx.notify();
1795 (batch_tool_results, batch_error)
1796 })?;
1797
1798 tool_results.extend(batch_result.0);
1799 if let Some(err) = batch_result.1 {
1800 error = Some(err.downcast()?);
1801 break;
1802 }
1803 }
1804
1805 // Drop the stream to release the rate limit permit before tool execution.
1806 // The stream holds a semaphore guard that limits concurrent requests.
1807 // Without this, the permit would be held during potentially long-running
1808 // tool execution, which could cause deadlocks when tools spawn subagents
1809 // that need their own permits.
1810 drop(events);
1811
1812 let end_turn = tool_results.is_empty();
1813 while let Some(tool_result) = tool_results.next().await {
1814 log::debug!("Tool finished {:?}", tool_result);
1815
1816 event_stream.update_tool_call_fields(
1817 &tool_result.tool_use_id,
1818 acp::ToolCallUpdateFields::new()
1819 .status(if tool_result.is_error {
1820 acp::ToolCallStatus::Failed
1821 } else {
1822 acp::ToolCallStatus::Completed
1823 })
1824 .raw_output(tool_result.output.clone()),
1825 None,
1826 );
1827 this.update(cx, |this, _cx| {
1828 this.pending_message()
1829 .tool_results
1830 .insert(tool_result.tool_use_id.clone(), tool_result);
1831 })?;
1832 }
1833
1834 this.update(cx, |this, cx| {
1835 this.flush_pending_message(cx);
1836 if this.title.is_none() && this.pending_title_generation.is_none() {
1837 this.generate_title(cx);
1838 }
1839 })?;
1840
1841 if cancelled {
1842 log::debug!("Turn cancelled by user, exiting");
1843 return Ok(());
1844 }
1845
1846 if let Some(error) = error {
1847 attempt += 1;
1848 let retry = this.update(cx, |this, cx| {
1849 let user_store = this.user_store.read(cx);
1850 this.handle_completion_error(error, attempt, user_store.plan())
1851 })??;
1852 let timer = cx.background_executor().timer(retry.duration);
1853 event_stream.send_retry(retry);
1854 timer.await;
1855 this.update(cx, |this, _cx| {
1856 if let Some(Message::Agent(message)) = this.messages.last() {
1857 if message.tool_results.is_empty() {
1858 intent = CompletionIntent::UserPrompt;
1859 this.messages.push(Message::Resume);
1860 }
1861 }
1862 })?;
1863 } else if end_turn {
1864 return Ok(());
1865 } else {
1866 let has_queued = this.update(cx, |this, _| this.has_queued_message())?;
1867 if has_queued {
1868 log::debug!("Queued message found, ending turn at message boundary");
1869 return Ok(());
1870 }
1871 intent = CompletionIntent::ToolResults;
1872 attempt = 0;
1873 }
1874 }
1875 }
1876
1877 fn handle_completion_error(
1878 &mut self,
1879 error: LanguageModelCompletionError,
1880 attempt: u8,
1881 plan: Option<Plan>,
1882 ) -> Result<acp_thread::RetryStatus> {
1883 let Some(model) = self.model.as_ref() else {
1884 return Err(anyhow!(error));
1885 };
1886
1887 let auto_retry = if model.provider_id() == ZED_CLOUD_PROVIDER_ID {
1888 plan.is_some()
1889 } else {
1890 true
1891 };
1892
1893 if !auto_retry {
1894 return Err(anyhow!(error));
1895 }
1896
1897 let Some(strategy) = Self::retry_strategy_for(&error) else {
1898 return Err(anyhow!(error));
1899 };
1900
1901 let max_attempts = match &strategy {
1902 RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
1903 RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
1904 };
1905
1906 if attempt > max_attempts {
1907 return Err(anyhow!(error));
1908 }
1909
1910 let delay = match &strategy {
1911 RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
1912 let delay_secs = initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
1913 Duration::from_secs(delay_secs)
1914 }
1915 RetryStrategy::Fixed { delay, .. } => *delay,
1916 };
1917 log::debug!("Retry attempt {attempt} with delay {delay:?}");
1918
1919 Ok(acp_thread::RetryStatus {
1920 last_error: error.to_string().into(),
1921 attempt: attempt as usize,
1922 max_attempts: max_attempts as usize,
1923 started_at: Instant::now(),
1924 duration: delay,
1925 })
1926 }
1927
1928 /// A helper method that's called on every streamed completion event.
1929 /// Returns an optional tool result task, which the main agentic loop will
1930 /// send back to the model when it resolves.
1931 fn handle_completion_event(
1932 &mut self,
1933 event: LanguageModelCompletionEvent,
1934 event_stream: &ThreadEventStream,
1935 cancellation_rx: watch::Receiver<bool>,
1936 cx: &mut Context<Self>,
1937 ) -> Result<Option<Task<LanguageModelToolResult>>> {
1938 log::trace!("Handling streamed completion event: {:?}", event);
1939 use LanguageModelCompletionEvent::*;
1940
1941 match event {
1942 StartMessage { .. } => {
1943 self.flush_pending_message(cx);
1944 self.pending_message = Some(AgentMessage::default());
1945 }
1946 Text(new_text) => self.handle_text_event(new_text, event_stream),
1947 Thinking { text, signature } => {
1948 self.handle_thinking_event(text, signature, event_stream)
1949 }
1950 RedactedThinking { data } => self.handle_redacted_thinking_event(data),
1951 ReasoningDetails(details) => {
1952 let last_message = self.pending_message();
1953 // Store the last non-empty reasoning_details (overwrites earlier ones)
1954 // This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
1955 if let serde_json::Value::Array(ref arr) = details {
1956 if !arr.is_empty() {
1957 last_message.reasoning_details = Some(details);
1958 }
1959 } else {
1960 last_message.reasoning_details = Some(details);
1961 }
1962 }
1963 ToolUse(tool_use) => {
1964 return Ok(self.handle_tool_use_event(tool_use, event_stream, cancellation_rx, cx));
1965 }
1966 ToolUseJsonParseError {
1967 id,
1968 tool_name,
1969 raw_input,
1970 json_parse_error,
1971 } => {
1972 return Ok(Some(Task::ready(
1973 self.handle_tool_use_json_parse_error_event(
1974 id,
1975 tool_name,
1976 raw_input,
1977 json_parse_error,
1978 event_stream,
1979 ),
1980 )));
1981 }
1982 UsageUpdate(usage) => {
1983 telemetry::event!(
1984 "Agent Thread Completion Usage Updated",
1985 thread_id = self.id.to_string(),
1986 prompt_id = self.prompt_id.to_string(),
1987 model = self.model.as_ref().map(|m| m.telemetry_id()),
1988 model_provider = self.model.as_ref().map(|m| m.provider_id().to_string()),
1989 input_tokens = usage.input_tokens,
1990 output_tokens = usage.output_tokens,
1991 cache_creation_input_tokens = usage.cache_creation_input_tokens,
1992 cache_read_input_tokens = usage.cache_read_input_tokens,
1993 );
1994 self.update_token_usage(usage, cx);
1995 }
1996 Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()),
1997 Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()),
1998 Stop(StopReason::ToolUse | StopReason::EndTurn) => {}
1999 Started | Queued { .. } => {}
2000 }
2001
2002 Ok(None)
2003 }
2004
2005 fn handle_text_event(&mut self, new_text: String, event_stream: &ThreadEventStream) {
2006 event_stream.send_text(&new_text);
2007
2008 let last_message = self.pending_message();
2009 if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
2010 text.push_str(&new_text);
2011 } else {
2012 last_message
2013 .content
2014 .push(AgentMessageContent::Text(new_text));
2015 }
2016 }
2017
2018 fn handle_thinking_event(
2019 &mut self,
2020 new_text: String,
2021 new_signature: Option<String>,
2022 event_stream: &ThreadEventStream,
2023 ) {
2024 event_stream.send_thinking(&new_text);
2025
2026 let last_message = self.pending_message();
2027 if let Some(AgentMessageContent::Thinking { text, signature }) =
2028 last_message.content.last_mut()
2029 {
2030 text.push_str(&new_text);
2031 *signature = new_signature.or(signature.take());
2032 } else {
2033 last_message.content.push(AgentMessageContent::Thinking {
2034 text: new_text,
2035 signature: new_signature,
2036 });
2037 }
2038 }
2039
2040 fn handle_redacted_thinking_event(&mut self, data: String) {
2041 let last_message = self.pending_message();
2042 last_message
2043 .content
2044 .push(AgentMessageContent::RedactedThinking(data));
2045 }
2046
2047 fn handle_tool_use_event(
2048 &mut self,
2049 tool_use: LanguageModelToolUse,
2050 event_stream: &ThreadEventStream,
2051 cancellation_rx: watch::Receiver<bool>,
2052 cx: &mut Context<Self>,
2053 ) -> Option<Task<LanguageModelToolResult>> {
2054 cx.notify();
2055
2056 let tool = self.tool(tool_use.name.as_ref());
2057 let mut title = SharedString::from(&tool_use.name);
2058 let mut kind = acp::ToolKind::Other;
2059 if let Some(tool) = tool.as_ref() {
2060 title = tool.initial_title(tool_use.input.clone(), cx);
2061 kind = tool.kind();
2062 }
2063
2064 self.send_or_update_tool_use(&tool_use, title, kind, event_stream);
2065
2066 let Some(tool) = tool else {
2067 let content = format!("No tool named {} exists", tool_use.name);
2068 return Some(Task::ready(LanguageModelToolResult {
2069 content: LanguageModelToolResultContent::Text(Arc::from(content)),
2070 tool_use_id: tool_use.id,
2071 tool_name: tool_use.name,
2072 is_error: true,
2073 output: None,
2074 }));
2075 };
2076
2077 if !tool_use.is_input_complete {
2078 if tool.supports_input_streaming() {
2079 let running_turn = self.running_turn.as_mut()?;
2080 if let Some(sender) = running_turn.streaming_tool_inputs.get(&tool_use.id) {
2081 sender.send_partial(tool_use.input);
2082 return None;
2083 }
2084
2085 let (sender, tool_input) = ToolInputSender::channel();
2086 sender.send_partial(tool_use.input);
2087 running_turn
2088 .streaming_tool_inputs
2089 .insert(tool_use.id.clone(), sender);
2090
2091 let tool = tool.clone();
2092 log::debug!("Running streaming tool {}", tool_use.name);
2093 return Some(self.run_tool(
2094 tool,
2095 tool_input,
2096 tool_use.id,
2097 tool_use.name,
2098 event_stream,
2099 cancellation_rx,
2100 cx,
2101 ));
2102 } else {
2103 return None;
2104 }
2105 }
2106
2107 if let Some(sender) = self
2108 .running_turn
2109 .as_mut()?
2110 .streaming_tool_inputs
2111 .remove(&tool_use.id)
2112 {
2113 sender.send_final(tool_use.input);
2114 return None;
2115 }
2116
2117 log::debug!("Running tool {}", tool_use.name);
2118 let tool_input = ToolInput::ready(tool_use.input);
2119 Some(self.run_tool(
2120 tool,
2121 tool_input,
2122 tool_use.id,
2123 tool_use.name,
2124 event_stream,
2125 cancellation_rx,
2126 cx,
2127 ))
2128 }
2129
2130 fn run_tool(
2131 &self,
2132 tool: Arc<dyn AnyAgentTool>,
2133 tool_input: ToolInput<serde_json::Value>,
2134 tool_use_id: LanguageModelToolUseId,
2135 tool_name: Arc<str>,
2136 event_stream: &ThreadEventStream,
2137 cancellation_rx: watch::Receiver<bool>,
2138 cx: &mut Context<Self>,
2139 ) -> Task<LanguageModelToolResult> {
2140 let fs = self.project.read(cx).fs().clone();
2141 let tool_event_stream = ToolCallEventStream::new(
2142 tool_use_id.clone(),
2143 event_stream.clone(),
2144 Some(fs),
2145 cancellation_rx,
2146 );
2147 tool_event_stream.update_fields(
2148 acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
2149 );
2150 let supports_images = self.model().is_some_and(|model| model.supports_images());
2151 let tool_result = tool.run(tool_input, tool_event_stream, cx);
2152 cx.foreground_executor().spawn(async move {
2153 let (is_error, output) = match tool_result.await {
2154 Ok(mut output) => {
2155 if let LanguageModelToolResultContent::Image(_) = &output.llm_output
2156 && !supports_images
2157 {
2158 output = AgentToolOutput::from_error(
2159 "Attempted to read an image, but this model doesn't support it.",
2160 );
2161 (true, output)
2162 } else {
2163 (false, output)
2164 }
2165 }
2166 Err(output) => (true, output),
2167 };
2168
2169 LanguageModelToolResult {
2170 tool_use_id,
2171 tool_name,
2172 is_error,
2173 content: output.llm_output,
2174 output: Some(output.raw_output),
2175 }
2176 })
2177 }
2178
2179 fn handle_tool_use_json_parse_error_event(
2180 &mut self,
2181 tool_use_id: LanguageModelToolUseId,
2182 tool_name: Arc<str>,
2183 raw_input: Arc<str>,
2184 json_parse_error: String,
2185 event_stream: &ThreadEventStream,
2186 ) -> LanguageModelToolResult {
2187 let tool_use = LanguageModelToolUse {
2188 id: tool_use_id.clone(),
2189 name: tool_name.clone(),
2190 raw_input: raw_input.to_string(),
2191 input: serde_json::json!({}),
2192 is_input_complete: true,
2193 thought_signature: None,
2194 };
2195 self.send_or_update_tool_use(
2196 &tool_use,
2197 SharedString::from(&tool_use.name),
2198 acp::ToolKind::Other,
2199 event_stream,
2200 );
2201
2202 let tool_output = format!("Error parsing input JSON: {json_parse_error}");
2203 LanguageModelToolResult {
2204 tool_use_id,
2205 tool_name,
2206 is_error: true,
2207 content: LanguageModelToolResultContent::Text(tool_output.into()),
2208 output: Some(serde_json::Value::String(raw_input.to_string())),
2209 }
2210 }
2211
2212 fn send_or_update_tool_use(
2213 &mut self,
2214 tool_use: &LanguageModelToolUse,
2215 title: SharedString,
2216 kind: acp::ToolKind,
2217 event_stream: &ThreadEventStream,
2218 ) {
2219 // Ensure the last message ends in the current tool use
2220 let last_message = self.pending_message();
2221 let push_new_tool_use = last_message.content.last_mut().is_none_or(|content| {
2222 if let AgentMessageContent::ToolUse(last_tool_use) = content {
2223 if last_tool_use.id == tool_use.id {
2224 *last_tool_use = tool_use.clone();
2225 false
2226 } else {
2227 true
2228 }
2229 } else {
2230 true
2231 }
2232 });
2233
2234 if push_new_tool_use {
2235 event_stream.send_tool_call(
2236 &tool_use.id,
2237 &tool_use.name,
2238 title,
2239 kind,
2240 tool_use.input.clone(),
2241 );
2242 last_message
2243 .content
2244 .push(AgentMessageContent::ToolUse(tool_use.clone()));
2245 } else {
2246 event_stream.update_tool_call_fields(
2247 &tool_use.id,
2248 acp::ToolCallUpdateFields::new()
2249 .title(title.as_str())
2250 .kind(kind)
2251 .raw_input(tool_use.input.clone()),
2252 None,
2253 );
2254 }
2255 }
2256
2257 pub fn title(&self) -> SharedString {
2258 self.title.clone().unwrap_or("New Thread".into())
2259 }
2260
2261 pub fn is_generating_summary(&self) -> bool {
2262 self.pending_summary_generation.is_some()
2263 }
2264
2265 pub fn is_generating_title(&self) -> bool {
2266 self.pending_title_generation.is_some()
2267 }
2268
2269 pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
2270 if let Some(summary) = self.summary.as_ref() {
2271 return Task::ready(Some(summary.clone())).shared();
2272 }
2273 if let Some(task) = self.pending_summary_generation.clone() {
2274 return task;
2275 }
2276 let Some(model) = self.summarization_model.clone() else {
2277 log::error!("No summarization model available");
2278 return Task::ready(None).shared();
2279 };
2280 let mut request = LanguageModelRequest {
2281 intent: Some(CompletionIntent::ThreadContextSummarization),
2282 temperature: AgentSettings::temperature_for_model(&model, cx),
2283 ..Default::default()
2284 };
2285
2286 for message in &self.messages {
2287 request.messages.extend(message.to_request());
2288 }
2289
2290 request.messages.push(LanguageModelRequestMessage {
2291 role: Role::User,
2292 content: vec![SUMMARIZE_THREAD_DETAILED_PROMPT.into()],
2293 cache: false,
2294 reasoning_details: None,
2295 });
2296
2297 let task = cx
2298 .spawn(async move |this, cx| {
2299 let mut summary = String::new();
2300 let mut messages = model.stream_completion(request, cx).await.log_err()?;
2301 while let Some(event) = messages.next().await {
2302 let event = event.log_err()?;
2303 let text = match event {
2304 LanguageModelCompletionEvent::Text(text) => text,
2305 _ => continue,
2306 };
2307
2308 let mut lines = text.lines();
2309 summary.extend(lines.next());
2310 }
2311
2312 log::debug!("Setting summary: {}", summary);
2313 let summary = SharedString::from(summary);
2314
2315 this.update(cx, |this, cx| {
2316 this.summary = Some(summary.clone());
2317 this.pending_summary_generation = None;
2318 cx.notify()
2319 })
2320 .ok()?;
2321
2322 Some(summary)
2323 })
2324 .shared();
2325 self.pending_summary_generation = Some(task.clone());
2326 task
2327 }
2328
2329 pub fn generate_title(&mut self, cx: &mut Context<Self>) {
2330 let Some(model) = self.summarization_model.clone() else {
2331 return;
2332 };
2333
2334 log::debug!(
2335 "Generating title with model: {:?}",
2336 self.summarization_model.as_ref().map(|model| model.name())
2337 );
2338 let mut request = LanguageModelRequest {
2339 intent: Some(CompletionIntent::ThreadSummarization),
2340 temperature: AgentSettings::temperature_for_model(&model, cx),
2341 ..Default::default()
2342 };
2343
2344 for message in &self.messages {
2345 request.messages.extend(message.to_request());
2346 }
2347
2348 request.messages.push(LanguageModelRequestMessage {
2349 role: Role::User,
2350 content: vec![SUMMARIZE_THREAD_PROMPT.into()],
2351 cache: false,
2352 reasoning_details: None,
2353 });
2354 self.pending_title_generation = Some(cx.spawn(async move |this, cx| {
2355 let mut title = String::new();
2356
2357 let generate = async {
2358 let mut messages = model.stream_completion(request, cx).await?;
2359 while let Some(event) = messages.next().await {
2360 let event = event?;
2361 let text = match event {
2362 LanguageModelCompletionEvent::Text(text) => text,
2363 _ => continue,
2364 };
2365
2366 let mut lines = text.lines();
2367 title.extend(lines.next());
2368
2369 // Stop if the LLM generated multiple lines.
2370 if lines.next().is_some() {
2371 break;
2372 }
2373 }
2374 anyhow::Ok(())
2375 };
2376
2377 if generate.await.context("failed to generate title").is_ok() {
2378 _ = this.update(cx, |this, cx| this.set_title(title.into(), cx));
2379 }
2380 _ = this.update(cx, |this, _| this.pending_title_generation = None);
2381 }));
2382 }
2383
2384 pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
2385 self.pending_title_generation = None;
2386 if Some(&title) != self.title.as_ref() {
2387 self.title = Some(title);
2388 cx.emit(TitleUpdated);
2389 cx.notify();
2390 }
2391 }
2392
2393 fn clear_summary(&mut self) {
2394 self.summary = None;
2395 self.pending_summary_generation = None;
2396 }
2397
2398 fn last_user_message(&self) -> Option<&UserMessage> {
2399 self.messages
2400 .iter()
2401 .rev()
2402 .find_map(|message| match message {
2403 Message::User(user_message) => Some(user_message),
2404 Message::Agent(_) => None,
2405 Message::Resume => None,
2406 })
2407 }
2408
2409 fn pending_message(&mut self) -> &mut AgentMessage {
2410 self.pending_message.get_or_insert_default()
2411 }
2412
2413 fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
2414 let Some(mut message) = self.pending_message.take() else {
2415 return;
2416 };
2417
2418 if message.content.is_empty() {
2419 return;
2420 }
2421
2422 for content in &message.content {
2423 let AgentMessageContent::ToolUse(tool_use) = content else {
2424 continue;
2425 };
2426
2427 if !message.tool_results.contains_key(&tool_use.id) {
2428 message.tool_results.insert(
2429 tool_use.id.clone(),
2430 LanguageModelToolResult {
2431 tool_use_id: tool_use.id.clone(),
2432 tool_name: tool_use.name.clone(),
2433 is_error: true,
2434 content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
2435 output: None,
2436 },
2437 );
2438 }
2439 }
2440
2441 self.messages.push(Message::Agent(message));
2442 self.updated_at = Utc::now();
2443 self.clear_summary();
2444 cx.notify()
2445 }
2446
2447 pub(crate) fn build_completion_request(
2448 &self,
2449 completion_intent: CompletionIntent,
2450 cx: &App,
2451 ) -> Result<LanguageModelRequest> {
2452 let model = self.model().context("No language model configured")?;
2453 let tools = if let Some(turn) = self.running_turn.as_ref() {
2454 turn.tools
2455 .iter()
2456 .filter_map(|(tool_name, tool)| {
2457 log::trace!("Including tool: {}", tool_name);
2458 Some(LanguageModelRequestTool {
2459 name: tool_name.to_string(),
2460 description: tool.description().to_string(),
2461 input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
2462 use_input_streaming: tool.supports_input_streaming(),
2463 })
2464 })
2465 .collect::<Vec<_>>()
2466 } else {
2467 Vec::new()
2468 };
2469
2470 log::debug!("Building completion request");
2471 log::debug!("Completion intent: {:?}", completion_intent);
2472
2473 let available_tools: Vec<_> = self
2474 .running_turn
2475 .as_ref()
2476 .map(|turn| turn.tools.keys().cloned().collect())
2477 .unwrap_or_default();
2478
2479 log::debug!("Request includes {} tools", available_tools.len());
2480 let messages = self.build_request_messages(available_tools, cx);
2481 log::debug!("Request will include {} messages", messages.len());
2482
2483 let request = LanguageModelRequest {
2484 thread_id: Some(self.id.to_string()),
2485 prompt_id: Some(self.prompt_id.to_string()),
2486 intent: Some(completion_intent),
2487 messages,
2488 tools,
2489 tool_choice: None,
2490 stop: Vec::new(),
2491 temperature: AgentSettings::temperature_for_model(model, cx),
2492 thinking_allowed: self.thinking_enabled,
2493 thinking_effort: self.thinking_effort.clone(),
2494 speed: self.speed(),
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}