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 }
2574 _ = this.update(cx, |this, _| this.pending_title_generation = None);
2575 }));
2576 }
2577
2578 pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
2579 self.pending_title_generation = None;
2580 if Some(&title) != self.title.as_ref() {
2581 self.title = Some(title);
2582 cx.emit(TitleUpdated);
2583 cx.notify();
2584 }
2585 }
2586
2587 fn clear_summary(&mut self) {
2588 self.summary = None;
2589 self.pending_summary_generation = None;
2590 }
2591
2592 fn last_user_message(&self) -> Option<&UserMessage> {
2593 self.messages
2594 .iter()
2595 .rev()
2596 .find_map(|message| match message {
2597 Message::User(user_message) => Some(user_message),
2598 Message::Agent(_) => None,
2599 Message::Resume => None,
2600 })
2601 }
2602
2603 fn pending_message(&mut self) -> &mut AgentMessage {
2604 self.pending_message.get_or_insert_default()
2605 }
2606
2607 fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
2608 let Some(mut message) = self.pending_message.take() else {
2609 return;
2610 };
2611
2612 if message.content.is_empty() {
2613 return;
2614 }
2615
2616 for content in &message.content {
2617 let AgentMessageContent::ToolUse(tool_use) = content else {
2618 continue;
2619 };
2620
2621 if !message.tool_results.contains_key(&tool_use.id) {
2622 message.tool_results.insert(
2623 tool_use.id.clone(),
2624 LanguageModelToolResult {
2625 tool_use_id: tool_use.id.clone(),
2626 tool_name: tool_use.name.clone(),
2627 is_error: true,
2628 content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
2629 output: None,
2630 },
2631 );
2632 }
2633 }
2634
2635 self.messages.push(Message::Agent(message));
2636 self.updated_at = Utc::now();
2637 self.clear_summary();
2638 cx.notify()
2639 }
2640
2641 pub(crate) fn build_completion_request(
2642 &self,
2643 completion_intent: CompletionIntent,
2644 cx: &App,
2645 ) -> Result<LanguageModelRequest> {
2646 let model = self.model().context("No language model configured")?;
2647 let tools = if let Some(turn) = self.running_turn.as_ref() {
2648 turn.tools
2649 .iter()
2650 .filter_map(|(tool_name, tool)| {
2651 log::trace!("Including tool: {}", tool_name);
2652 Some(LanguageModelRequestTool {
2653 name: tool_name.to_string(),
2654 description: tool.description().to_string(),
2655 input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
2656 use_input_streaming: tool.supports_input_streaming(),
2657 })
2658 })
2659 .collect::<Vec<_>>()
2660 } else {
2661 Vec::new()
2662 };
2663
2664 log::debug!("Building completion request");
2665 log::debug!("Completion intent: {:?}", completion_intent);
2666
2667 let available_tools: Vec<_> = self
2668 .running_turn
2669 .as_ref()
2670 .map(|turn| turn.tools.keys().cloned().collect())
2671 .unwrap_or_default();
2672
2673 log::debug!("Request includes {} tools", available_tools.len());
2674 let messages = self.build_request_messages(available_tools, cx);
2675 log::debug!("Request will include {} messages", messages.len());
2676
2677 let request = LanguageModelRequest {
2678 thread_id: Some(self.id.to_string()),
2679 prompt_id: Some(self.prompt_id.to_string()),
2680 intent: Some(completion_intent),
2681 messages,
2682 tools,
2683 tool_choice: None,
2684 stop: Vec::new(),
2685 temperature: AgentSettings::temperature_for_model(model, cx),
2686 thinking_allowed: self.thinking_enabled,
2687 thinking_effort: self.thinking_effort.clone(),
2688 speed: self.speed(),
2689 };
2690
2691 log::debug!("Completion request built successfully");
2692 Ok(request)
2693 }
2694
2695 fn enabled_tools(
2696 &self,
2697 profile: &AgentProfileSettings,
2698 model: &Arc<dyn LanguageModel>,
2699 cx: &App,
2700 ) -> BTreeMap<SharedString, Arc<dyn AnyAgentTool>> {
2701 fn truncate(tool_name: &SharedString) -> SharedString {
2702 if tool_name.len() > MAX_TOOL_NAME_LENGTH {
2703 let mut truncated = tool_name.to_string();
2704 truncated.truncate(MAX_TOOL_NAME_LENGTH);
2705 truncated.into()
2706 } else {
2707 tool_name.clone()
2708 }
2709 }
2710
2711 let use_streaming_edit_tool =
2712 cx.has_flag::<StreamingEditFileToolFeatureFlag>() && model.supports_streaming_tools();
2713
2714 let mut tools = self
2715 .tools
2716 .iter()
2717 .filter_map(|(tool_name, tool)| {
2718 // For streaming_edit_file, check profile against "edit_file" since that's what users configure
2719 let profile_tool_name = if tool_name == StreamingEditFileTool::NAME {
2720 EditFileTool::NAME
2721 } else {
2722 tool_name.as_ref()
2723 };
2724
2725 if tool.supports_provider(&model.provider_id())
2726 && profile.is_tool_enabled(profile_tool_name)
2727 {
2728 match (tool_name.as_ref(), use_streaming_edit_tool) {
2729 (StreamingEditFileTool::NAME, false) | (EditFileTool::NAME, true) => None,
2730 (StreamingEditFileTool::NAME, true) => {
2731 // Expose streaming tool as "edit_file"
2732 Some((SharedString::from(EditFileTool::NAME), tool.clone()))
2733 }
2734 _ => Some((truncate(tool_name), tool.clone())),
2735 }
2736 } else {
2737 None
2738 }
2739 })
2740 .collect::<BTreeMap<_, _>>();
2741
2742 let mut context_server_tools = Vec::new();
2743 let mut seen_tools = tools.keys().cloned().collect::<HashSet<_>>();
2744 let mut duplicate_tool_names = HashSet::default();
2745 for (server_id, server_tools) in self.context_server_registry.read(cx).servers() {
2746 for (tool_name, tool) in server_tools {
2747 if profile.is_context_server_tool_enabled(&server_id.0, &tool_name) {
2748 let tool_name = truncate(tool_name);
2749 if !seen_tools.insert(tool_name.clone()) {
2750 duplicate_tool_names.insert(tool_name.clone());
2751 }
2752 context_server_tools.push((server_id.clone(), tool_name, tool.clone()));
2753 }
2754 }
2755 }
2756
2757 // When there are duplicate tool names, disambiguate by prefixing them
2758 // with the server ID (converted to snake_case for API compatibility).
2759 // In the rare case there isn't enough space for the disambiguated tool
2760 // name, keep only the last tool with this name.
2761 for (server_id, tool_name, tool) in context_server_tools {
2762 if duplicate_tool_names.contains(&tool_name) {
2763 let available = MAX_TOOL_NAME_LENGTH.saturating_sub(tool_name.len());
2764 if available >= 2 {
2765 let mut disambiguated = server_id.0.to_snake_case();
2766 disambiguated.truncate(available - 1);
2767 disambiguated.push('_');
2768 disambiguated.push_str(&tool_name);
2769 tools.insert(disambiguated.into(), tool.clone());
2770 } else {
2771 tools.insert(tool_name, tool.clone());
2772 }
2773 } else {
2774 tools.insert(tool_name, tool.clone());
2775 }
2776 }
2777
2778 tools
2779 }
2780
2781 fn tool(&self, name: &str) -> Option<Arc<dyn AnyAgentTool>> {
2782 self.running_turn.as_ref()?.tools.get(name).cloned()
2783 }
2784
2785 pub fn has_tool(&self, name: &str) -> bool {
2786 self.running_turn
2787 .as_ref()
2788 .is_some_and(|turn| turn.tools.contains_key(name))
2789 }
2790
2791 #[cfg(any(test, feature = "test-support"))]
2792 pub fn has_registered_tool(&self, name: &str) -> bool {
2793 self.tools.contains_key(name)
2794 }
2795
2796 pub fn registered_tool_names(&self) -> Vec<SharedString> {
2797 self.tools.keys().cloned().collect()
2798 }
2799
2800 pub(crate) fn register_running_subagent(&mut self, subagent: WeakEntity<Thread>) {
2801 self.running_subagents.push(subagent);
2802 }
2803
2804 pub(crate) fn unregister_running_subagent(
2805 &mut self,
2806 subagent_session_id: &acp::SessionId,
2807 cx: &App,
2808 ) {
2809 self.running_subagents.retain(|s| {
2810 s.upgrade()
2811 .map_or(false, |s| s.read(cx).id() != subagent_session_id)
2812 });
2813 }
2814
2815 #[cfg(any(test, feature = "test-support"))]
2816 pub fn running_subagent_ids(&self, cx: &App) -> Vec<acp::SessionId> {
2817 self.running_subagents
2818 .iter()
2819 .filter_map(|s| s.upgrade().map(|s| s.read(cx).id().clone()))
2820 .collect()
2821 }
2822
2823 pub fn is_subagent(&self) -> bool {
2824 self.subagent_context.is_some()
2825 }
2826
2827 pub fn parent_thread_id(&self) -> Option<acp::SessionId> {
2828 self.subagent_context
2829 .as_ref()
2830 .map(|c| c.parent_thread_id.clone())
2831 }
2832
2833 pub fn depth(&self) -> u8 {
2834 self.subagent_context.as_ref().map(|c| c.depth).unwrap_or(0)
2835 }
2836
2837 #[cfg(any(test, feature = "test-support"))]
2838 pub fn set_subagent_context(&mut self, context: SubagentContext) {
2839 self.subagent_context = Some(context);
2840 }
2841
2842 pub fn is_turn_complete(&self) -> bool {
2843 self.running_turn.is_none()
2844 }
2845
2846 fn build_request_messages(
2847 &self,
2848 available_tools: Vec<SharedString>,
2849 cx: &App,
2850 ) -> Vec<LanguageModelRequestMessage> {
2851 log::trace!(
2852 "Building request messages from {} thread messages",
2853 self.messages.len()
2854 );
2855
2856 let system_prompt = SystemPromptTemplate {
2857 project: self.project_context.read(cx),
2858 available_tools,
2859 model_name: self.model.as_ref().map(|m| m.name().0.to_string()),
2860 }
2861 .render(&self.templates)
2862 .context("failed to build system prompt")
2863 .expect("Invalid template");
2864 let mut messages = vec![LanguageModelRequestMessage {
2865 role: Role::System,
2866 content: vec![system_prompt.into()],
2867 cache: false,
2868 reasoning_details: None,
2869 }];
2870 for message in &self.messages {
2871 messages.extend(message.to_request());
2872 }
2873
2874 if let Some(last_message) = messages.last_mut() {
2875 last_message.cache = true;
2876 }
2877
2878 if let Some(message) = self.pending_message.as_ref() {
2879 messages.extend(message.to_request());
2880 }
2881
2882 messages
2883 }
2884
2885 pub fn to_markdown(&self) -> String {
2886 let mut markdown = String::new();
2887 for (ix, message) in self.messages.iter().enumerate() {
2888 if ix > 0 {
2889 markdown.push('\n');
2890 }
2891 match message {
2892 Message::User(_) => markdown.push_str("## User\n\n"),
2893 Message::Agent(_) => markdown.push_str("## Assistant\n\n"),
2894 Message::Resume => {}
2895 }
2896 markdown.push_str(&message.to_markdown());
2897 }
2898
2899 if let Some(message) = self.pending_message.as_ref() {
2900 markdown.push_str("\n## Assistant\n\n");
2901 markdown.push_str(&message.to_markdown());
2902 }
2903
2904 markdown
2905 }
2906
2907 fn advance_prompt_id(&mut self) {
2908 self.prompt_id = PromptId::new();
2909 }
2910
2911 fn retry_strategy_for(error: &LanguageModelCompletionError) -> Option<RetryStrategy> {
2912 use LanguageModelCompletionError::*;
2913 use http_client::StatusCode;
2914
2915 // General strategy here:
2916 // - If retrying won't help (e.g. invalid API key or payload too large), return None so we don't retry at all.
2917 // - If it's a time-based issue (e.g. server overloaded, rate limit exceeded), retry up to 4 times with exponential backoff.
2918 // - If it's an issue that *might* be fixed by retrying (e.g. internal server error), retry up to 3 times.
2919 match error {
2920 HttpResponseError {
2921 status_code: StatusCode::TOO_MANY_REQUESTS,
2922 ..
2923 } => Some(RetryStrategy::ExponentialBackoff {
2924 initial_delay: BASE_RETRY_DELAY,
2925 max_attempts: MAX_RETRY_ATTEMPTS,
2926 }),
2927 ServerOverloaded { retry_after, .. } | RateLimitExceeded { retry_after, .. } => {
2928 Some(RetryStrategy::Fixed {
2929 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2930 max_attempts: MAX_RETRY_ATTEMPTS,
2931 })
2932 }
2933 UpstreamProviderError {
2934 status,
2935 retry_after,
2936 ..
2937 } => match *status {
2938 StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
2939 Some(RetryStrategy::Fixed {
2940 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2941 max_attempts: MAX_RETRY_ATTEMPTS,
2942 })
2943 }
2944 StatusCode::INTERNAL_SERVER_ERROR => Some(RetryStrategy::Fixed {
2945 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2946 // Internal Server Error could be anything, retry up to 3 times.
2947 max_attempts: 3,
2948 }),
2949 status => {
2950 // There is no StatusCode variant for the unofficial HTTP 529 ("The service is overloaded"),
2951 // but we frequently get them in practice. See https://http.dev/529
2952 if status.as_u16() == 529 {
2953 Some(RetryStrategy::Fixed {
2954 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2955 max_attempts: MAX_RETRY_ATTEMPTS,
2956 })
2957 } else {
2958 Some(RetryStrategy::Fixed {
2959 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2960 max_attempts: 2,
2961 })
2962 }
2963 }
2964 },
2965 ApiInternalServerError { .. } => Some(RetryStrategy::Fixed {
2966 delay: BASE_RETRY_DELAY,
2967 max_attempts: 3,
2968 }),
2969 ApiReadResponseError { .. }
2970 | HttpSend { .. }
2971 | DeserializeResponse { .. }
2972 | BadRequestFormat { .. } => Some(RetryStrategy::Fixed {
2973 delay: BASE_RETRY_DELAY,
2974 max_attempts: 3,
2975 }),
2976 // Retrying these errors definitely shouldn't help.
2977 HttpResponseError {
2978 status_code:
2979 StatusCode::PAYLOAD_TOO_LARGE | StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED,
2980 ..
2981 }
2982 | AuthenticationError { .. }
2983 | PermissionError { .. }
2984 | NoApiKey { .. }
2985 | ApiEndpointNotFound { .. }
2986 | PromptTooLarge { .. } => None,
2987 // These errors might be transient, so retry them
2988 SerializeRequest { .. } | BuildRequestBody { .. } | StreamEndedUnexpectedly { .. } => {
2989 Some(RetryStrategy::Fixed {
2990 delay: BASE_RETRY_DELAY,
2991 max_attempts: 1,
2992 })
2993 }
2994 // Retry all other 4xx and 5xx errors once.
2995 HttpResponseError { status_code, .. }
2996 if status_code.is_client_error() || status_code.is_server_error() =>
2997 {
2998 Some(RetryStrategy::Fixed {
2999 delay: BASE_RETRY_DELAY,
3000 max_attempts: 3,
3001 })
3002 }
3003 Other(err) if err.is::<language_model::PaymentRequiredError>() => {
3004 // Retrying won't help for Payment Required errors.
3005 None
3006 }
3007 // Conservatively assume that any other errors are non-retryable
3008 HttpResponseError { .. } | Other(..) => Some(RetryStrategy::Fixed {
3009 delay: BASE_RETRY_DELAY,
3010 max_attempts: 2,
3011 }),
3012 }
3013 }
3014}
3015
3016struct RunningTurn {
3017 /// Holds the task that handles agent interaction until the end of the turn.
3018 /// Survives across multiple requests as the model performs tool calls and
3019 /// we run tools, report their results.
3020 _task: Task<()>,
3021 /// The current event stream for the running turn. Used to report a final
3022 /// cancellation event if we cancel the turn.
3023 event_stream: ThreadEventStream,
3024 /// The tools that were enabled for this turn.
3025 tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
3026 /// Sender to signal tool cancellation. When cancel is called, this is
3027 /// set to true so all tools can detect user-initiated cancellation.
3028 cancellation_tx: watch::Sender<bool>,
3029 /// Senders for tools that support input streaming and have already been
3030 /// started but are still receiving input from the LLM.
3031 streaming_tool_inputs: HashMap<LanguageModelToolUseId, ToolInputSender>,
3032}
3033
3034impl RunningTurn {
3035 fn cancel(mut self) -> Task<()> {
3036 log::debug!("Cancelling in progress turn");
3037 self.cancellation_tx.send(true).ok();
3038 self.event_stream.send_canceled();
3039 self._task
3040 }
3041}
3042
3043pub struct TokenUsageUpdated(pub Option<acp_thread::TokenUsage>);
3044
3045impl EventEmitter<TokenUsageUpdated> for Thread {}
3046
3047pub struct TitleUpdated;
3048
3049impl EventEmitter<TitleUpdated> for Thread {}
3050
3051/// A channel-based wrapper that delivers tool input to a running tool.
3052///
3053/// For non-streaming tools, created via `ToolInput::ready()` so `.recv()` resolves immediately.
3054/// For streaming tools, partial JSON snapshots arrive via `.recv_partial()` as the LLM streams
3055/// them, followed by the final complete input available through `.recv()`.
3056pub struct ToolInput<T> {
3057 partial_rx: mpsc::UnboundedReceiver<serde_json::Value>,
3058 final_rx: oneshot::Receiver<serde_json::Value>,
3059 _phantom: PhantomData<T>,
3060}
3061
3062impl<T: DeserializeOwned> ToolInput<T> {
3063 #[cfg(any(test, feature = "test-support"))]
3064 pub fn resolved(input: impl Serialize) -> Self {
3065 let value = serde_json::to_value(input).expect("failed to serialize tool input");
3066 Self::ready(value)
3067 }
3068
3069 pub fn ready(value: serde_json::Value) -> Self {
3070 let (partial_tx, partial_rx) = mpsc::unbounded();
3071 drop(partial_tx);
3072 let (final_tx, final_rx) = oneshot::channel();
3073 final_tx.send(value).ok();
3074 Self {
3075 partial_rx,
3076 final_rx,
3077 _phantom: PhantomData,
3078 }
3079 }
3080
3081 #[cfg(any(test, feature = "test-support"))]
3082 pub fn test() -> (ToolInputSender, Self) {
3083 let (sender, input) = ToolInputSender::channel();
3084 (sender, input.cast())
3085 }
3086
3087 /// Wait for the final deserialized input, ignoring all partial updates.
3088 /// Non-streaming tools can use this to wait until the whole input is available.
3089 pub async fn recv(mut self) -> Result<T> {
3090 // Drain any remaining partials
3091 while self.partial_rx.next().await.is_some() {}
3092 let value = self
3093 .final_rx
3094 .await
3095 .map_err(|_| anyhow!("tool input was not fully received"))?;
3096 serde_json::from_value(value).map_err(Into::into)
3097 }
3098
3099 /// Returns the next partial JSON snapshot, or `None` when input is complete.
3100 /// Once this returns `None`, call `recv()` to get the final input.
3101 pub async fn recv_partial(&mut self) -> Option<serde_json::Value> {
3102 self.partial_rx.next().await
3103 }
3104
3105 fn cast<U: DeserializeOwned>(self) -> ToolInput<U> {
3106 ToolInput {
3107 partial_rx: self.partial_rx,
3108 final_rx: self.final_rx,
3109 _phantom: PhantomData,
3110 }
3111 }
3112}
3113
3114pub struct ToolInputSender {
3115 partial_tx: mpsc::UnboundedSender<serde_json::Value>,
3116 final_tx: Option<oneshot::Sender<serde_json::Value>>,
3117}
3118
3119impl ToolInputSender {
3120 pub(crate) fn channel() -> (Self, ToolInput<serde_json::Value>) {
3121 let (partial_tx, partial_rx) = mpsc::unbounded();
3122 let (final_tx, final_rx) = oneshot::channel();
3123 let sender = Self {
3124 partial_tx,
3125 final_tx: Some(final_tx),
3126 };
3127 let input = ToolInput {
3128 partial_rx,
3129 final_rx,
3130 _phantom: PhantomData,
3131 };
3132 (sender, input)
3133 }
3134
3135 pub(crate) fn has_received_final(&self) -> bool {
3136 self.final_tx.is_none()
3137 }
3138
3139 pub(crate) fn send_partial(&self, value: serde_json::Value) {
3140 self.partial_tx.unbounded_send(value).ok();
3141 }
3142
3143 pub(crate) fn send_final(mut self, value: serde_json::Value) {
3144 // Close the partial channel so recv_partial() returns None
3145 self.partial_tx.close_channel();
3146 if let Some(final_tx) = self.final_tx.take() {
3147 final_tx.send(value).ok();
3148 }
3149 }
3150}
3151
3152pub trait AgentTool
3153where
3154 Self: 'static + Sized,
3155{
3156 type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
3157 type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
3158
3159 const NAME: &'static str;
3160
3161 fn description() -> SharedString {
3162 let schema = schemars::schema_for!(Self::Input);
3163 SharedString::new(
3164 schema
3165 .get("description")
3166 .and_then(|description| description.as_str())
3167 .unwrap_or_default(),
3168 )
3169 }
3170
3171 fn kind() -> acp::ToolKind;
3172
3173 /// The initial tool title to display. Can be updated during the tool run.
3174 fn initial_title(
3175 &self,
3176 input: Result<Self::Input, serde_json::Value>,
3177 cx: &mut App,
3178 ) -> SharedString;
3179
3180 /// Returns the JSON schema that describes the tool's input.
3181 fn input_schema(format: LanguageModelToolSchemaFormat) -> Schema {
3182 language_model::tool_schema::root_schema_for::<Self::Input>(format)
3183 }
3184
3185 /// Returns whether the tool supports streaming of tool use parameters.
3186 fn supports_input_streaming() -> bool {
3187 false
3188 }
3189
3190 /// Some tools rely on a provider for the underlying billing or other reasons.
3191 /// Allow the tool to check if they are compatible, or should be filtered out.
3192 fn supports_provider(_provider: &LanguageModelProviderId) -> bool {
3193 true
3194 }
3195
3196 /// Runs the tool with the provided input.
3197 ///
3198 /// Returns `Result<Self::Output, Self::Output>` rather than `Result<Self::Output, anyhow::Error>`
3199 /// because tool errors are sent back to the model as tool results. This means error output must
3200 /// be structured and readable by the agent — not an arbitrary `anyhow::Error`. Returning the
3201 /// same `Output` type for both success and failure lets tools provide structured data while
3202 /// still signaling whether the invocation succeeded or failed.
3203 fn run(
3204 self: Arc<Self>,
3205 input: ToolInput<Self::Input>,
3206 event_stream: ToolCallEventStream,
3207 cx: &mut App,
3208 ) -> Task<Result<Self::Output, Self::Output>>;
3209
3210 /// Emits events for a previous execution of the tool.
3211 fn replay(
3212 &self,
3213 _input: Self::Input,
3214 _output: Self::Output,
3215 _event_stream: ToolCallEventStream,
3216 _cx: &mut App,
3217 ) -> Result<()> {
3218 Ok(())
3219 }
3220
3221 fn erase(self) -> Arc<dyn AnyAgentTool> {
3222 Arc::new(Erased(Arc::new(self)))
3223 }
3224}
3225
3226pub struct Erased<T>(T);
3227
3228pub struct AgentToolOutput {
3229 pub llm_output: LanguageModelToolResultContent,
3230 pub raw_output: serde_json::Value,
3231}
3232
3233impl AgentToolOutput {
3234 pub fn from_error(message: impl Into<String>) -> Self {
3235 let message = message.into();
3236 let llm_output = LanguageModelToolResultContent::Text(Arc::from(message.as_str()));
3237 Self {
3238 raw_output: serde_json::Value::String(message),
3239 llm_output,
3240 }
3241 }
3242}
3243
3244pub trait AnyAgentTool {
3245 fn name(&self) -> SharedString;
3246 fn description(&self) -> SharedString;
3247 fn kind(&self) -> acp::ToolKind;
3248 fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString;
3249 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
3250 fn supports_input_streaming(&self) -> bool {
3251 false
3252 }
3253 fn supports_provider(&self, _provider: &LanguageModelProviderId) -> bool {
3254 true
3255 }
3256 /// See [`AgentTool::run`] for why this returns `Result<AgentToolOutput, AgentToolOutput>`.
3257 fn run(
3258 self: Arc<Self>,
3259 input: ToolInput<serde_json::Value>,
3260 event_stream: ToolCallEventStream,
3261 cx: &mut App,
3262 ) -> Task<Result<AgentToolOutput, AgentToolOutput>>;
3263 fn replay(
3264 &self,
3265 input: serde_json::Value,
3266 output: serde_json::Value,
3267 event_stream: ToolCallEventStream,
3268 cx: &mut App,
3269 ) -> Result<()>;
3270}
3271
3272impl<T> AnyAgentTool for Erased<Arc<T>>
3273where
3274 T: AgentTool,
3275{
3276 fn name(&self) -> SharedString {
3277 T::NAME.into()
3278 }
3279
3280 fn description(&self) -> SharedString {
3281 T::description()
3282 }
3283
3284 fn kind(&self) -> agent_client_protocol::ToolKind {
3285 T::kind()
3286 }
3287
3288 fn supports_input_streaming(&self) -> bool {
3289 T::supports_input_streaming()
3290 }
3291
3292 fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString {
3293 let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
3294 self.0.initial_title(parsed_input, _cx)
3295 }
3296
3297 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
3298 let mut json = serde_json::to_value(T::input_schema(format))?;
3299 language_model::tool_schema::adapt_schema_to_format(&mut json, format)?;
3300 Ok(json)
3301 }
3302
3303 fn supports_provider(&self, provider: &LanguageModelProviderId) -> bool {
3304 T::supports_provider(provider)
3305 }
3306
3307 fn run(
3308 self: Arc<Self>,
3309 input: ToolInput<serde_json::Value>,
3310 event_stream: ToolCallEventStream,
3311 cx: &mut App,
3312 ) -> Task<Result<AgentToolOutput, AgentToolOutput>> {
3313 let tool_input: ToolInput<T::Input> = input.cast();
3314 let task = self.0.clone().run(tool_input, event_stream, cx);
3315 cx.spawn(async move |_cx| match task.await {
3316 Ok(output) => {
3317 let raw_output = serde_json::to_value(&output).map_err(|e| {
3318 AgentToolOutput::from_error(format!("Failed to serialize tool output: {e}"))
3319 })?;
3320 Ok(AgentToolOutput {
3321 llm_output: output.into(),
3322 raw_output,
3323 })
3324 }
3325 Err(error_output) => {
3326 let raw_output = serde_json::to_value(&error_output).unwrap_or_else(|e| {
3327 log::error!("Failed to serialize tool error output: {e}");
3328 serde_json::Value::Null
3329 });
3330 Err(AgentToolOutput {
3331 llm_output: error_output.into(),
3332 raw_output,
3333 })
3334 }
3335 })
3336 }
3337
3338 fn replay(
3339 &self,
3340 input: serde_json::Value,
3341 output: serde_json::Value,
3342 event_stream: ToolCallEventStream,
3343 cx: &mut App,
3344 ) -> Result<()> {
3345 let input = serde_json::from_value(input)?;
3346 let output = serde_json::from_value(output)?;
3347 self.0.replay(input, output, event_stream, cx)
3348 }
3349}
3350
3351#[derive(Clone)]
3352struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
3353
3354impl ThreadEventStream {
3355 fn send_user_message(&self, message: &UserMessage) {
3356 self.0
3357 .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
3358 .ok();
3359 }
3360
3361 fn send_text(&self, text: &str) {
3362 self.0
3363 .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
3364 .ok();
3365 }
3366
3367 fn send_thinking(&self, text: &str) {
3368 self.0
3369 .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
3370 .ok();
3371 }
3372
3373 fn send_tool_call(
3374 &self,
3375 id: &LanguageModelToolUseId,
3376 tool_name: &str,
3377 title: SharedString,
3378 kind: acp::ToolKind,
3379 input: serde_json::Value,
3380 ) {
3381 self.0
3382 .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
3383 id,
3384 tool_name,
3385 title.to_string(),
3386 kind,
3387 input,
3388 ))))
3389 .ok();
3390 }
3391
3392 fn initial_tool_call(
3393 id: &LanguageModelToolUseId,
3394 tool_name: &str,
3395 title: String,
3396 kind: acp::ToolKind,
3397 input: serde_json::Value,
3398 ) -> acp::ToolCall {
3399 acp::ToolCall::new(id.to_string(), title)
3400 .kind(kind)
3401 .raw_input(input)
3402 .meta(acp_thread::meta_with_tool_name(tool_name))
3403 }
3404
3405 fn update_tool_call_fields(
3406 &self,
3407 tool_use_id: &LanguageModelToolUseId,
3408 fields: acp::ToolCallUpdateFields,
3409 meta: Option<acp::Meta>,
3410 ) {
3411 self.0
3412 .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3413 acp::ToolCallUpdate::new(tool_use_id.to_string(), fields)
3414 .meta(meta)
3415 .into(),
3416 )))
3417 .ok();
3418 }
3419
3420 fn send_retry(&self, status: acp_thread::RetryStatus) {
3421 self.0.unbounded_send(Ok(ThreadEvent::Retry(status))).ok();
3422 }
3423
3424 fn send_stop(&self, reason: acp::StopReason) {
3425 self.0.unbounded_send(Ok(ThreadEvent::Stop(reason))).ok();
3426 }
3427
3428 fn send_canceled(&self) {
3429 self.0
3430 .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))
3431 .ok();
3432 }
3433
3434 fn send_error(&self, error: impl Into<anyhow::Error>) {
3435 self.0.unbounded_send(Err(error.into())).ok();
3436 }
3437}
3438
3439#[derive(Clone)]
3440pub struct ToolCallEventStream {
3441 tool_use_id: LanguageModelToolUseId,
3442 stream: ThreadEventStream,
3443 fs: Option<Arc<dyn Fs>>,
3444 cancellation_rx: watch::Receiver<bool>,
3445}
3446
3447impl ToolCallEventStream {
3448 #[cfg(any(test, feature = "test-support"))]
3449 pub fn test() -> (Self, ToolCallEventStreamReceiver) {
3450 let (stream, receiver, _cancellation_tx) = Self::test_with_cancellation();
3451 (stream, receiver)
3452 }
3453
3454 #[cfg(any(test, feature = "test-support"))]
3455 pub fn test_with_cancellation() -> (Self, ToolCallEventStreamReceiver, watch::Sender<bool>) {
3456 let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
3457 let (cancellation_tx, cancellation_rx) = watch::channel(false);
3458
3459 let stream = ToolCallEventStream::new(
3460 "test_id".into(),
3461 ThreadEventStream(events_tx),
3462 None,
3463 cancellation_rx,
3464 );
3465
3466 (
3467 stream,
3468 ToolCallEventStreamReceiver(events_rx),
3469 cancellation_tx,
3470 )
3471 }
3472
3473 /// Signal cancellation for this event stream. Only available in tests.
3474 #[cfg(any(test, feature = "test-support"))]
3475 pub fn signal_cancellation_with_sender(cancellation_tx: &mut watch::Sender<bool>) {
3476 cancellation_tx.send(true).ok();
3477 }
3478
3479 fn new(
3480 tool_use_id: LanguageModelToolUseId,
3481 stream: ThreadEventStream,
3482 fs: Option<Arc<dyn Fs>>,
3483 cancellation_rx: watch::Receiver<bool>,
3484 ) -> Self {
3485 Self {
3486 tool_use_id,
3487 stream,
3488 fs,
3489 cancellation_rx,
3490 }
3491 }
3492
3493 /// Returns a future that resolves when the user cancels the tool call.
3494 /// Tools should select on this alongside their main work to detect user cancellation.
3495 pub fn cancelled_by_user(&self) -> impl std::future::Future<Output = ()> + '_ {
3496 let mut rx = self.cancellation_rx.clone();
3497 async move {
3498 loop {
3499 if *rx.borrow() {
3500 return;
3501 }
3502 if rx.changed().await.is_err() {
3503 // Sender dropped, will never be cancelled
3504 std::future::pending::<()>().await;
3505 }
3506 }
3507 }
3508 }
3509
3510 /// Returns true if the user has cancelled this tool call.
3511 /// This is useful for checking cancellation state after an operation completes,
3512 /// to determine if the completion was due to user cancellation.
3513 pub fn was_cancelled_by_user(&self) -> bool {
3514 *self.cancellation_rx.clone().borrow()
3515 }
3516
3517 pub fn tool_use_id(&self) -> &LanguageModelToolUseId {
3518 &self.tool_use_id
3519 }
3520
3521 pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
3522 self.stream
3523 .update_tool_call_fields(&self.tool_use_id, fields, None);
3524 }
3525
3526 pub fn update_fields_with_meta(
3527 &self,
3528 fields: acp::ToolCallUpdateFields,
3529 meta: Option<acp::Meta>,
3530 ) {
3531 self.stream
3532 .update_tool_call_fields(&self.tool_use_id, fields, meta);
3533 }
3534
3535 pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
3536 self.stream
3537 .0
3538 .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
3539 acp_thread::ToolCallUpdateDiff {
3540 id: acp::ToolCallId::new(self.tool_use_id.to_string()),
3541 diff,
3542 }
3543 .into(),
3544 )))
3545 .ok();
3546 }
3547
3548 pub fn subagent_spawned(&self, id: acp::SessionId) {
3549 self.stream
3550 .0
3551 .unbounded_send(Ok(ThreadEvent::SubagentSpawned(id)))
3552 .ok();
3553 }
3554
3555 /// Authorize a third-party tool (e.g., MCP tool from a context server).
3556 ///
3557 /// Unlike built-in tools, third-party tools don't support pattern-based permissions.
3558 /// They only support `default` (allow/deny/confirm) per tool.
3559 ///
3560 /// Uses the dropdown authorization flow with two granularities:
3561 /// - "Always for <display_name> MCP tool" → sets `tools.<tool_id>.default = "allow"` or "deny"
3562 /// - "Only this time" → allow/deny once
3563 pub fn authorize_third_party_tool(
3564 &self,
3565 title: impl Into<String>,
3566 tool_id: String,
3567 display_name: String,
3568 cx: &mut App,
3569 ) -> Task<Result<()>> {
3570 let settings = agent_settings::AgentSettings::get_global(cx);
3571
3572 let decision = decide_permission_from_settings(&tool_id, &[String::new()], &settings);
3573
3574 match decision {
3575 ToolPermissionDecision::Allow => return Task::ready(Ok(())),
3576 ToolPermissionDecision::Deny(reason) => return Task::ready(Err(anyhow!(reason))),
3577 ToolPermissionDecision::Confirm => {}
3578 }
3579
3580 let (response_tx, response_rx) = oneshot::channel();
3581 if let Err(error) = self
3582 .stream
3583 .0
3584 .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3585 ToolCallAuthorization {
3586 tool_call: acp::ToolCallUpdate::new(
3587 self.tool_use_id.to_string(),
3588 acp::ToolCallUpdateFields::new().title(title.into()),
3589 ),
3590 options: acp_thread::PermissionOptions::Dropdown(vec![
3591 acp_thread::PermissionOptionChoice {
3592 allow: acp::PermissionOption::new(
3593 acp::PermissionOptionId::new(format!(
3594 "always_allow_mcp:{}",
3595 tool_id
3596 )),
3597 format!("Always for {} MCP tool", display_name),
3598 acp::PermissionOptionKind::AllowAlways,
3599 ),
3600 deny: acp::PermissionOption::new(
3601 acp::PermissionOptionId::new(format!(
3602 "always_deny_mcp:{}",
3603 tool_id
3604 )),
3605 format!("Always for {} MCP tool", display_name),
3606 acp::PermissionOptionKind::RejectAlways,
3607 ),
3608 },
3609 acp_thread::PermissionOptionChoice {
3610 allow: acp::PermissionOption::new(
3611 acp::PermissionOptionId::new("allow"),
3612 "Only this time",
3613 acp::PermissionOptionKind::AllowOnce,
3614 ),
3615 deny: acp::PermissionOption::new(
3616 acp::PermissionOptionId::new("deny"),
3617 "Only this time",
3618 acp::PermissionOptionKind::RejectOnce,
3619 ),
3620 },
3621 ]),
3622 response: response_tx,
3623 context: None,
3624 },
3625 )))
3626 {
3627 log::error!("Failed to send tool call authorization: {error}");
3628 return Task::ready(Err(anyhow!(
3629 "Failed to send tool call authorization: {error}"
3630 )));
3631 }
3632
3633 let fs = self.fs.clone();
3634 cx.spawn(async move |cx| {
3635 let response_str = response_rx.await?.0.to_string();
3636
3637 if response_str == format!("always_allow_mcp:{}", tool_id) {
3638 if let Some(fs) = fs.clone() {
3639 cx.update(|cx| {
3640 update_settings_file(fs, cx, move |settings, _| {
3641 settings
3642 .agent
3643 .get_or_insert_default()
3644 .set_tool_default_permission(&tool_id, ToolPermissionMode::Allow);
3645 });
3646 });
3647 }
3648 return Ok(());
3649 }
3650 if response_str == format!("always_deny_mcp:{}", tool_id) {
3651 if let Some(fs) = fs.clone() {
3652 cx.update(|cx| {
3653 update_settings_file(fs, cx, move |settings, _| {
3654 settings
3655 .agent
3656 .get_or_insert_default()
3657 .set_tool_default_permission(&tool_id, ToolPermissionMode::Deny);
3658 });
3659 });
3660 }
3661 return Err(anyhow!("Permission to run tool denied by user"));
3662 }
3663
3664 if response_str == "allow" {
3665 return Ok(());
3666 }
3667
3668 Err(anyhow!("Permission to run tool denied by user"))
3669 })
3670 }
3671
3672 pub fn authorize(
3673 &self,
3674 title: impl Into<String>,
3675 context: ToolPermissionContext,
3676 cx: &mut App,
3677 ) -> Task<Result<()>> {
3678 use settings::ToolPermissionMode;
3679
3680 let options = context.build_permission_options();
3681
3682 let (response_tx, response_rx) = oneshot::channel();
3683 if let Err(error) = self
3684 .stream
3685 .0
3686 .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
3687 ToolCallAuthorization {
3688 tool_call: acp::ToolCallUpdate::new(
3689 self.tool_use_id.to_string(),
3690 acp::ToolCallUpdateFields::new().title(title.into()),
3691 ),
3692 options,
3693 response: response_tx,
3694 context: Some(context),
3695 },
3696 )))
3697 {
3698 log::error!("Failed to send tool call authorization: {error}");
3699 return Task::ready(Err(anyhow!(
3700 "Failed to send tool call authorization: {error}"
3701 )));
3702 }
3703
3704 let fs = self.fs.clone();
3705 cx.spawn(async move |cx| {
3706 let response_str = response_rx.await?.0.to_string();
3707
3708 // Handle "always allow tool" - e.g., "always_allow:terminal"
3709 if let Some(tool) = response_str.strip_prefix("always_allow:") {
3710 if let Some(fs) = fs.clone() {
3711 let tool = tool.to_string();
3712 cx.update(|cx| {
3713 update_settings_file(fs, cx, move |settings, _| {
3714 settings
3715 .agent
3716 .get_or_insert_default()
3717 .set_tool_default_permission(&tool, ToolPermissionMode::Allow);
3718 });
3719 });
3720 }
3721 return Ok(());
3722 }
3723
3724 // Handle "always deny tool" - e.g., "always_deny:terminal"
3725 if let Some(tool) = response_str.strip_prefix("always_deny:") {
3726 if let Some(fs) = fs.clone() {
3727 let tool = tool.to_string();
3728 cx.update(|cx| {
3729 update_settings_file(fs, cx, move |settings, _| {
3730 settings
3731 .agent
3732 .get_or_insert_default()
3733 .set_tool_default_permission(&tool, ToolPermissionMode::Deny);
3734 });
3735 });
3736 }
3737 return Err(anyhow!("Permission to run tool denied by user"));
3738 }
3739
3740 // Handle "always allow pattern" - e.g., "always_allow_pattern:mcp:server:tool\n^cargo\s"
3741 if let Some(rest) = response_str.strip_prefix("always_allow_pattern:") {
3742 if let Some((pattern_tool_name, pattern)) = rest.split_once('\n') {
3743 let pattern_tool_name = pattern_tool_name.to_string();
3744 let pattern = pattern.to_string();
3745 if let Some(fs) = fs.clone() {
3746 cx.update(|cx| {
3747 update_settings_file(fs, cx, move |settings, _| {
3748 settings
3749 .agent
3750 .get_or_insert_default()
3751 .add_tool_allow_pattern(&pattern_tool_name, pattern);
3752 });
3753 });
3754 }
3755 } else {
3756 log::error!("Failed to parse always allow pattern: missing newline separator in '{rest}'");
3757 }
3758 return Ok(());
3759 }
3760
3761 // Handle "always deny pattern" - e.g., "always_deny_pattern:mcp:server:tool\n^cargo\s"
3762 if let Some(rest) = response_str.strip_prefix("always_deny_pattern:") {
3763 if let Some((pattern_tool_name, pattern)) = rest.split_once('\n') {
3764 let pattern_tool_name = pattern_tool_name.to_string();
3765 let pattern = pattern.to_string();
3766 if let Some(fs) = fs.clone() {
3767 cx.update(|cx| {
3768 update_settings_file(fs, cx, move |settings, _| {
3769 settings
3770 .agent
3771 .get_or_insert_default()
3772 .add_tool_deny_pattern(&pattern_tool_name, pattern);
3773 });
3774 });
3775 }
3776 } else {
3777 log::error!("Failed to parse always deny pattern: missing newline separator in '{rest}'");
3778 }
3779 return Err(anyhow!("Permission to run tool denied by user"));
3780 }
3781
3782 // Handle simple "allow" (allow once)
3783 if response_str == "allow" {
3784 return Ok(());
3785 }
3786
3787 // Handle simple "deny" (deny once)
3788 Err(anyhow!("Permission to run tool denied by user"))
3789 })
3790 }
3791}
3792
3793#[cfg(any(test, feature = "test-support"))]
3794pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
3795
3796#[cfg(any(test, feature = "test-support"))]
3797impl ToolCallEventStreamReceiver {
3798 pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
3799 let event = self.0.next().await;
3800 if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
3801 auth
3802 } else {
3803 panic!("Expected ToolCallAuthorization but got: {:?}", event);
3804 }
3805 }
3806
3807 pub async fn expect_update_fields(&mut self) -> acp::ToolCallUpdateFields {
3808 let event = self.0.next().await;
3809 if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
3810 update,
3811 )))) = event
3812 {
3813 update.fields
3814 } else {
3815 panic!("Expected update fields but got: {:?}", event);
3816 }
3817 }
3818
3819 pub async fn expect_diff(&mut self) -> Entity<acp_thread::Diff> {
3820 let event = self.0.next().await;
3821 if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateDiff(
3822 update,
3823 )))) = event
3824 {
3825 update.diff
3826 } else {
3827 panic!("Expected diff but got: {:?}", event);
3828 }
3829 }
3830
3831 pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
3832 let event = self.0.next().await;
3833 if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
3834 update,
3835 )))) = event
3836 {
3837 update.terminal
3838 } else {
3839 panic!("Expected terminal but got: {:?}", event);
3840 }
3841 }
3842}
3843
3844#[cfg(any(test, feature = "test-support"))]
3845impl std::ops::Deref for ToolCallEventStreamReceiver {
3846 type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
3847
3848 fn deref(&self) -> &Self::Target {
3849 &self.0
3850 }
3851}
3852
3853#[cfg(any(test, feature = "test-support"))]
3854impl std::ops::DerefMut for ToolCallEventStreamReceiver {
3855 fn deref_mut(&mut self) -> &mut Self::Target {
3856 &mut self.0
3857 }
3858}
3859
3860impl From<&str> for UserMessageContent {
3861 fn from(text: &str) -> Self {
3862 Self::Text(text.into())
3863 }
3864}
3865
3866impl From<String> for UserMessageContent {
3867 fn from(text: String) -> Self {
3868 Self::Text(text)
3869 }
3870}
3871
3872impl UserMessageContent {
3873 pub fn from_content_block(value: acp::ContentBlock, path_style: PathStyle) -> Self {
3874 match value {
3875 acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
3876 acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
3877 acp::ContentBlock::Audio(_) => {
3878 // TODO
3879 Self::Text("[audio]".to_string())
3880 }
3881 acp::ContentBlock::ResourceLink(resource_link) => {
3882 match MentionUri::parse(&resource_link.uri, path_style) {
3883 Ok(uri) => Self::Mention {
3884 uri,
3885 content: String::new(),
3886 },
3887 Err(err) => {
3888 log::error!("Failed to parse mention link: {}", err);
3889 Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
3890 }
3891 }
3892 }
3893 acp::ContentBlock::Resource(resource) => match resource.resource {
3894 acp::EmbeddedResourceResource::TextResourceContents(resource) => {
3895 match MentionUri::parse(&resource.uri, path_style) {
3896 Ok(uri) => Self::Mention {
3897 uri,
3898 content: resource.text,
3899 },
3900 Err(err) => {
3901 log::error!("Failed to parse mention link: {}", err);
3902 Self::Text(
3903 MarkdownCodeBlock {
3904 tag: &resource.uri,
3905 text: &resource.text,
3906 }
3907 .to_string(),
3908 )
3909 }
3910 }
3911 }
3912 acp::EmbeddedResourceResource::BlobResourceContents(_) => {
3913 // TODO
3914 Self::Text("[blob]".to_string())
3915 }
3916 other => {
3917 log::warn!("Unexpected content type: {:?}", other);
3918 Self::Text("[unknown]".to_string())
3919 }
3920 },
3921 other => {
3922 log::warn!("Unexpected content type: {:?}", other);
3923 Self::Text("[unknown]".to_string())
3924 }
3925 }
3926 }
3927}
3928
3929impl From<UserMessageContent> for acp::ContentBlock {
3930 fn from(content: UserMessageContent) -> Self {
3931 match content {
3932 UserMessageContent::Text(text) => text.into(),
3933 UserMessageContent::Image(image) => {
3934 acp::ContentBlock::Image(acp::ImageContent::new(image.source, "image/png"))
3935 }
3936 UserMessageContent::Mention { uri, content } => acp::ContentBlock::Resource(
3937 acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(
3938 acp::TextResourceContents::new(content, uri.to_uri().to_string()),
3939 )),
3940 ),
3941 }
3942 }
3943}
3944
3945fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
3946 LanguageModelImage {
3947 source: image_content.data.into(),
3948 size: None,
3949 }
3950}
3951
3952#[cfg(test)]
3953mod tests {
3954 use super::*;
3955 use gpui::TestAppContext;
3956 use language_model::LanguageModelToolUseId;
3957 use language_model::fake_provider::FakeLanguageModel;
3958 use serde_json::json;
3959 use std::sync::Arc;
3960
3961 async fn setup_thread_for_test(cx: &mut TestAppContext) -> (Entity<Thread>, ThreadEventStream) {
3962 cx.update(|cx| {
3963 let settings_store = settings::SettingsStore::test(cx);
3964 cx.set_global(settings_store);
3965 });
3966
3967 let fs = fs::FakeFs::new(cx.background_executor.clone());
3968 let templates = Templates::new();
3969 let project = Project::test(fs.clone(), [], cx).await;
3970
3971 cx.update(|cx| {
3972 let project_context = cx.new(|_cx| prompt_store::ProjectContext::default());
3973 let context_server_store = project.read(cx).context_server_store();
3974 let context_server_registry =
3975 cx.new(|cx| ContextServerRegistry::new(context_server_store, cx));
3976
3977 let thread = cx.new(|cx| {
3978 Thread::new(
3979 project,
3980 project_context,
3981 context_server_registry,
3982 templates,
3983 None,
3984 cx,
3985 )
3986 });
3987
3988 let (event_tx, _event_rx) = mpsc::unbounded();
3989 let event_stream = ThreadEventStream(event_tx);
3990
3991 (thread, event_stream)
3992 })
3993 }
3994
3995 fn setup_parent_with_subagents(
3996 cx: &mut TestAppContext,
3997 parent: &Entity<Thread>,
3998 count: usize,
3999 ) -> Vec<Entity<Thread>> {
4000 cx.update(|cx| {
4001 let mut subagents = Vec::new();
4002 for _ in 0..count {
4003 let subagent = cx.new(|cx| Thread::new_subagent(parent, cx));
4004 parent.update(cx, |thread, _cx| {
4005 thread.register_running_subagent(subagent.downgrade());
4006 });
4007 subagents.push(subagent);
4008 }
4009 subagents
4010 })
4011 }
4012
4013 #[gpui::test]
4014 async fn test_set_model_propagates_to_subagents(cx: &mut TestAppContext) {
4015 let (parent, _event_stream) = setup_thread_for_test(cx).await;
4016 let subagents = setup_parent_with_subagents(cx, &parent, 2);
4017
4018 let new_model: Arc<dyn LanguageModel> = Arc::new(FakeLanguageModel::with_id_and_thinking(
4019 "test-provider",
4020 "new-model",
4021 "New Model",
4022 false,
4023 ));
4024
4025 cx.update(|cx| {
4026 parent.update(cx, |thread, cx| {
4027 thread.set_model(new_model, cx);
4028 });
4029
4030 for subagent in &subagents {
4031 let subagent_model_id = subagent.read(cx).model().unwrap().id();
4032 assert_eq!(
4033 subagent_model_id.0.as_ref(),
4034 "new-model",
4035 "Subagent model should match parent model after set_model"
4036 );
4037 }
4038 });
4039 }
4040
4041 #[gpui::test]
4042 async fn test_set_summarization_model_propagates_to_subagents(cx: &mut TestAppContext) {
4043 let (parent, _event_stream) = setup_thread_for_test(cx).await;
4044 let subagents = setup_parent_with_subagents(cx, &parent, 2);
4045
4046 let summary_model: Arc<dyn LanguageModel> =
4047 Arc::new(FakeLanguageModel::with_id_and_thinking(
4048 "test-provider",
4049 "summary-model",
4050 "Summary Model",
4051 false,
4052 ));
4053
4054 cx.update(|cx| {
4055 parent.update(cx, |thread, cx| {
4056 thread.set_summarization_model(Some(summary_model), cx);
4057 });
4058
4059 for subagent in &subagents {
4060 let subagent_summary_id = subagent.read(cx).summarization_model().unwrap().id();
4061 assert_eq!(
4062 subagent_summary_id.0.as_ref(),
4063 "summary-model",
4064 "Subagent summarization model should match parent after set_summarization_model"
4065 );
4066 }
4067 });
4068 }
4069
4070 #[gpui::test]
4071 async fn test_set_thinking_enabled_propagates_to_subagents(cx: &mut TestAppContext) {
4072 let (parent, _event_stream) = setup_thread_for_test(cx).await;
4073 let subagents = setup_parent_with_subagents(cx, &parent, 2);
4074
4075 cx.update(|cx| {
4076 parent.update(cx, |thread, cx| {
4077 thread.set_thinking_enabled(true, cx);
4078 });
4079
4080 for subagent in &subagents {
4081 assert!(
4082 subagent.read(cx).thinking_enabled(),
4083 "Subagent thinking should be enabled after parent enables it"
4084 );
4085 }
4086
4087 parent.update(cx, |thread, cx| {
4088 thread.set_thinking_enabled(false, cx);
4089 });
4090
4091 for subagent in &subagents {
4092 assert!(
4093 !subagent.read(cx).thinking_enabled(),
4094 "Subagent thinking should be disabled after parent disables it"
4095 );
4096 }
4097 });
4098 }
4099
4100 #[gpui::test]
4101 async fn test_set_thinking_effort_propagates_to_subagents(cx: &mut TestAppContext) {
4102 let (parent, _event_stream) = setup_thread_for_test(cx).await;
4103 let subagents = setup_parent_with_subagents(cx, &parent, 2);
4104
4105 cx.update(|cx| {
4106 parent.update(cx, |thread, cx| {
4107 thread.set_thinking_effort(Some("high".to_string()), cx);
4108 });
4109
4110 for subagent in &subagents {
4111 assert_eq!(
4112 subagent.read(cx).thinking_effort().map(|s| s.as_str()),
4113 Some("high"),
4114 "Subagent thinking effort should match parent"
4115 );
4116 }
4117
4118 parent.update(cx, |thread, cx| {
4119 thread.set_thinking_effort(None, cx);
4120 });
4121
4122 for subagent in &subagents {
4123 assert_eq!(
4124 subagent.read(cx).thinking_effort(),
4125 None,
4126 "Subagent thinking effort should be None after parent clears it"
4127 );
4128 }
4129 });
4130 }
4131
4132 #[gpui::test]
4133 async fn test_set_speed_propagates_to_subagents(cx: &mut TestAppContext) {
4134 let (parent, _event_stream) = setup_thread_for_test(cx).await;
4135 let subagents = setup_parent_with_subagents(cx, &parent, 2);
4136
4137 cx.update(|cx| {
4138 parent.update(cx, |thread, cx| {
4139 thread.set_speed(Speed::Fast, cx);
4140 });
4141
4142 for subagent in &subagents {
4143 assert_eq!(
4144 subagent.read(cx).speed(),
4145 Some(Speed::Fast),
4146 "Subagent speed should match parent after set_speed"
4147 );
4148 }
4149 });
4150 }
4151
4152 #[gpui::test]
4153 async fn test_dropped_subagent_does_not_panic(cx: &mut TestAppContext) {
4154 let (parent, _event_stream) = setup_thread_for_test(cx).await;
4155 let subagents = setup_parent_with_subagents(cx, &parent, 1);
4156
4157 // Drop the subagent so the WeakEntity can no longer be upgraded
4158 drop(subagents);
4159
4160 // Should not panic even though the subagent was dropped
4161 cx.update(|cx| {
4162 parent.update(cx, |thread, cx| {
4163 thread.set_thinking_enabled(true, cx);
4164 thread.set_speed(Speed::Fast, cx);
4165 thread.set_thinking_effort(Some("high".to_string()), cx);
4166 });
4167 });
4168 }
4169
4170 #[gpui::test]
4171 async fn test_handle_tool_use_json_parse_error_adds_tool_use_to_content(
4172 cx: &mut TestAppContext,
4173 ) {
4174 let (thread, event_stream) = setup_thread_for_test(cx).await;
4175
4176 cx.update(|cx| {
4177 thread.update(cx, |thread, _cx| {
4178 let tool_use_id = LanguageModelToolUseId::from("test_tool_id");
4179 let tool_name: Arc<str> = Arc::from("test_tool");
4180 let raw_input: Arc<str> = Arc::from("{invalid json");
4181 let json_parse_error = "expected value at line 1 column 1".to_string();
4182
4183 // Call the function under test
4184 let result = thread.handle_tool_use_json_parse_error_event(
4185 tool_use_id.clone(),
4186 tool_name.clone(),
4187 raw_input.clone(),
4188 json_parse_error,
4189 &event_stream,
4190 );
4191
4192 // Verify the result is an error
4193 assert!(result.is_error);
4194 assert_eq!(result.tool_use_id, tool_use_id);
4195 assert_eq!(result.tool_name, tool_name);
4196 assert!(matches!(
4197 result.content,
4198 LanguageModelToolResultContent::Text(_)
4199 ));
4200
4201 // Verify the tool use was added to the message content
4202 {
4203 let last_message = thread.pending_message();
4204 assert_eq!(
4205 last_message.content.len(),
4206 1,
4207 "Should have one tool_use in content"
4208 );
4209
4210 match &last_message.content[0] {
4211 AgentMessageContent::ToolUse(tool_use) => {
4212 assert_eq!(tool_use.id, tool_use_id);
4213 assert_eq!(tool_use.name, tool_name);
4214 assert_eq!(tool_use.raw_input, raw_input.to_string());
4215 assert!(tool_use.is_input_complete);
4216 // Should fall back to empty object for invalid JSON
4217 assert_eq!(tool_use.input, json!({}));
4218 }
4219 _ => panic!("Expected ToolUse content"),
4220 }
4221 }
4222
4223 // Insert the tool result (simulating what the caller does)
4224 thread
4225 .pending_message()
4226 .tool_results
4227 .insert(result.tool_use_id.clone(), result);
4228
4229 // Verify the tool result was added
4230 let last_message = thread.pending_message();
4231 assert_eq!(
4232 last_message.tool_results.len(),
4233 1,
4234 "Should have one tool_result"
4235 );
4236 assert!(last_message.tool_results.contains_key(&tool_use_id));
4237 });
4238 });
4239 }
4240}