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