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