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