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