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