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