1use crate::{
2 ContextServerRegistry, CopyPathTool, CreateDirectoryTool, DbLanguageModel, DbThread,
3 DeletePathTool, DiagnosticsTool, EditFileTool, FetchTool, FindPathTool, GrepTool,
4 ListDirectoryTool, MovePathTool, NowTool, OpenTool, ReadFileTool, SystemPromptTemplate,
5 Template, Templates, TerminalTool, ThinkingTool, WebSearchTool,
6};
7use acp_thread::{MentionUri, UserMessageId};
8use action_log::ActionLog;
9use agent::thread::{GitState, ProjectSnapshot, WorktreeSnapshot};
10use agent_client_protocol as acp;
11use agent_settings::{
12 AgentProfileId, AgentProfileSettings, AgentSettings, CompletionMode,
13 SUMMARIZE_THREAD_DETAILED_PROMPT, SUMMARIZE_THREAD_PROMPT,
14};
15use anyhow::{Context as _, Result, anyhow};
16use assistant_tool::adapt_schema_to_format;
17use chrono::{DateTime, Utc};
18use client::{ModelRequestUsage, RequestUsage};
19use cloud_llm_client::{CompletionIntent, CompletionRequestStatus, UsageLimit};
20use collections::{HashMap, HashSet, IndexMap};
21use fs::Fs;
22use futures::{
23 FutureExt,
24 channel::{mpsc, oneshot},
25 future::Shared,
26 stream::FuturesUnordered,
27};
28use git::repository::DiffType;
29use gpui::{
30 App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task, WeakEntity,
31};
32use language_model::{
33 LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelExt,
34 LanguageModelImage, LanguageModelProviderId, LanguageModelRegistry, LanguageModelRequest,
35 LanguageModelRequestMessage, LanguageModelRequestTool, LanguageModelToolResult,
36 LanguageModelToolResultContent, LanguageModelToolSchemaFormat, LanguageModelToolUse,
37 LanguageModelToolUseId, Role, SelectedModel, StopReason, TokenUsage,
38};
39use project::{
40 Project,
41 git_store::{GitStore, RepositoryState},
42};
43use prompt_store::ProjectContext;
44use schemars::{JsonSchema, Schema};
45use serde::{Deserialize, Serialize};
46use settings::{Settings, update_settings_file};
47use smol::stream::StreamExt;
48use std::fmt::Write;
49use std::{
50 collections::BTreeMap,
51 ops::RangeInclusive,
52 path::Path,
53 sync::Arc,
54 time::{Duration, Instant},
55};
56use util::{ResultExt, debug_panic, markdown::MarkdownCodeBlock};
57use uuid::Uuid;
58
59const TOOL_CANCELED_MESSAGE: &str = "Tool canceled by user";
60pub const MAX_TOOL_NAME_LENGTH: usize = 64;
61
62/// The ID of the user prompt that initiated a request.
63///
64/// This equates to the user physically submitting a message to the model (e.g., by pressing the Enter key).
65#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
66pub struct PromptId(Arc<str>);
67
68impl PromptId {
69 pub fn new() -> Self {
70 Self(Uuid::new_v4().to_string().into())
71 }
72}
73
74impl std::fmt::Display for PromptId {
75 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76 write!(f, "{}", self.0)
77 }
78}
79
80pub(crate) const MAX_RETRY_ATTEMPTS: u8 = 4;
81pub(crate) const BASE_RETRY_DELAY: Duration = Duration::from_secs(5);
82
83#[derive(Debug, Clone)]
84enum RetryStrategy {
85 ExponentialBackoff {
86 initial_delay: Duration,
87 max_attempts: u8,
88 },
89 Fixed {
90 delay: Duration,
91 max_attempts: u8,
92 },
93}
94
95#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96pub enum Message {
97 User(UserMessage),
98 Agent(AgentMessage),
99 Resume,
100}
101
102impl Message {
103 pub fn as_agent_message(&self) -> Option<&AgentMessage> {
104 match self {
105 Message::Agent(agent_message) => Some(agent_message),
106 _ => None,
107 }
108 }
109
110 pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
111 match self {
112 Message::User(message) => vec![message.to_request()],
113 Message::Agent(message) => message.to_request(),
114 Message::Resume => vec![LanguageModelRequestMessage {
115 role: Role::User,
116 content: vec!["Continue where you left off".into()],
117 cache: false,
118 }],
119 }
120 }
121
122 pub fn to_markdown(&self) -> String {
123 match self {
124 Message::User(message) => message.to_markdown(),
125 Message::Agent(message) => message.to_markdown(),
126 Message::Resume => "[resumed after tool use limit was reached]".into(),
127 }
128 }
129
130 pub fn role(&self) -> Role {
131 match self {
132 Message::User(_) | Message::Resume => Role::User,
133 Message::Agent(_) => Role::Assistant,
134 }
135 }
136}
137
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139pub struct UserMessage {
140 pub id: UserMessageId,
141 pub content: Vec<UserMessageContent>,
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
145pub enum UserMessageContent {
146 Text(String),
147 Mention { uri: MentionUri, content: String },
148 Image(LanguageModelImage),
149}
150
151impl UserMessage {
152 pub fn to_markdown(&self) -> String {
153 let mut markdown = String::from("## User\n\n");
154
155 for content in &self.content {
156 match content {
157 UserMessageContent::Text(text) => {
158 markdown.push_str(text);
159 markdown.push('\n');
160 }
161 UserMessageContent::Image(_) => {
162 markdown.push_str("<image />\n");
163 }
164 UserMessageContent::Mention { uri, content } => {
165 if !content.is_empty() {
166 let _ = writeln!(&mut markdown, "{}\n\n{}", uri.as_link(), content);
167 } else {
168 let _ = writeln!(&mut markdown, "{}", uri.as_link());
169 }
170 }
171 }
172 }
173
174 markdown
175 }
176
177 fn to_request(&self) -> LanguageModelRequestMessage {
178 let mut message = LanguageModelRequestMessage {
179 role: Role::User,
180 content: Vec::with_capacity(self.content.len()),
181 cache: false,
182 };
183
184 const OPEN_CONTEXT: &str = "<context>\n\
185 The following items were attached by the user. \
186 They are up-to-date and don't need to be re-read.\n\n";
187
188 const OPEN_FILES_TAG: &str = "<files>";
189 const OPEN_DIRECTORIES_TAG: &str = "<directories>";
190 const OPEN_SYMBOLS_TAG: &str = "<symbols>";
191 const OPEN_SELECTIONS_TAG: &str = "<selections>";
192 const OPEN_THREADS_TAG: &str = "<threads>";
193 const OPEN_FETCH_TAG: &str = "<fetched_urls>";
194 const OPEN_RULES_TAG: &str =
195 "<rules>\nThe user has specified the following rules that should be applied:\n";
196
197 let mut file_context = OPEN_FILES_TAG.to_string();
198 let mut directory_context = OPEN_DIRECTORIES_TAG.to_string();
199 let mut symbol_context = OPEN_SYMBOLS_TAG.to_string();
200 let mut selection_context = OPEN_SELECTIONS_TAG.to_string();
201 let mut thread_context = OPEN_THREADS_TAG.to_string();
202 let mut fetch_context = OPEN_FETCH_TAG.to_string();
203 let mut rules_context = OPEN_RULES_TAG.to_string();
204
205 for chunk in &self.content {
206 let chunk = match chunk {
207 UserMessageContent::Text(text) => {
208 language_model::MessageContent::Text(text.clone())
209 }
210 UserMessageContent::Image(value) => {
211 language_model::MessageContent::Image(value.clone())
212 }
213 UserMessageContent::Mention { uri, content } => {
214 match uri {
215 MentionUri::File { abs_path } => {
216 write!(
217 &mut file_context,
218 "\n{}",
219 MarkdownCodeBlock {
220 tag: &codeblock_tag(abs_path, None),
221 text: &content.to_string(),
222 }
223 )
224 .ok();
225 }
226 MentionUri::PastedImage => {
227 debug_panic!("pasted image URI should not be used in mention content")
228 }
229 MentionUri::Directory { .. } => {
230 write!(&mut directory_context, "\n{}\n", content).ok();
231 }
232 MentionUri::Symbol {
233 abs_path: path,
234 line_range,
235 ..
236 } => {
237 write!(
238 &mut symbol_context,
239 "\n{}",
240 MarkdownCodeBlock {
241 tag: &codeblock_tag(path, Some(line_range)),
242 text: content
243 }
244 )
245 .ok();
246 }
247 MentionUri::Selection {
248 abs_path: path,
249 line_range,
250 ..
251 } => {
252 write!(
253 &mut selection_context,
254 "\n{}",
255 MarkdownCodeBlock {
256 tag: &codeblock_tag(
257 path.as_deref().unwrap_or("Untitled".as_ref()),
258 Some(line_range)
259 ),
260 text: content
261 }
262 )
263 .ok();
264 }
265 MentionUri::Thread { .. } => {
266 write!(&mut thread_context, "\n{}\n", content).ok();
267 }
268 MentionUri::TextThread { .. } => {
269 write!(&mut thread_context, "\n{}\n", content).ok();
270 }
271 MentionUri::Rule { .. } => {
272 write!(
273 &mut rules_context,
274 "\n{}",
275 MarkdownCodeBlock {
276 tag: "",
277 text: content
278 }
279 )
280 .ok();
281 }
282 MentionUri::Fetch { url } => {
283 write!(&mut fetch_context, "\nFetch: {}\n\n{}", url, content).ok();
284 }
285 }
286
287 language_model::MessageContent::Text(uri.as_link().to_string())
288 }
289 };
290
291 message.content.push(chunk);
292 }
293
294 let len_before_context = message.content.len();
295
296 if file_context.len() > OPEN_FILES_TAG.len() {
297 file_context.push_str("</files>\n");
298 message
299 .content
300 .push(language_model::MessageContent::Text(file_context));
301 }
302
303 if directory_context.len() > OPEN_DIRECTORIES_TAG.len() {
304 directory_context.push_str("</directories>\n");
305 message
306 .content
307 .push(language_model::MessageContent::Text(directory_context));
308 }
309
310 if symbol_context.len() > OPEN_SYMBOLS_TAG.len() {
311 symbol_context.push_str("</symbols>\n");
312 message
313 .content
314 .push(language_model::MessageContent::Text(symbol_context));
315 }
316
317 if selection_context.len() > OPEN_SELECTIONS_TAG.len() {
318 selection_context.push_str("</selections>\n");
319 message
320 .content
321 .push(language_model::MessageContent::Text(selection_context));
322 }
323
324 if thread_context.len() > OPEN_THREADS_TAG.len() {
325 thread_context.push_str("</threads>\n");
326 message
327 .content
328 .push(language_model::MessageContent::Text(thread_context));
329 }
330
331 if fetch_context.len() > OPEN_FETCH_TAG.len() {
332 fetch_context.push_str("</fetched_urls>\n");
333 message
334 .content
335 .push(language_model::MessageContent::Text(fetch_context));
336 }
337
338 if rules_context.len() > OPEN_RULES_TAG.len() {
339 rules_context.push_str("</user_rules>\n");
340 message
341 .content
342 .push(language_model::MessageContent::Text(rules_context));
343 }
344
345 if message.content.len() > len_before_context {
346 message.content.insert(
347 len_before_context,
348 language_model::MessageContent::Text(OPEN_CONTEXT.into()),
349 );
350 message
351 .content
352 .push(language_model::MessageContent::Text("</context>".into()));
353 }
354
355 message
356 }
357}
358
359fn codeblock_tag(full_path: &Path, line_range: Option<&RangeInclusive<u32>>) -> String {
360 let mut result = String::new();
361
362 if let Some(extension) = full_path.extension().and_then(|ext| ext.to_str()) {
363 let _ = write!(result, "{} ", extension);
364 }
365
366 let _ = write!(result, "{}", full_path.display());
367
368 if let Some(range) = line_range {
369 if range.start() == range.end() {
370 let _ = write!(result, ":{}", range.start() + 1);
371 } else {
372 let _ = write!(result, ":{}-{}", range.start() + 1, range.end() + 1);
373 }
374 }
375
376 result
377}
378
379impl AgentMessage {
380 pub fn to_markdown(&self) -> String {
381 let mut markdown = String::from("## Assistant\n\n");
382
383 for content in &self.content {
384 match content {
385 AgentMessageContent::Text(text) => {
386 markdown.push_str(text);
387 markdown.push('\n');
388 }
389 AgentMessageContent::Thinking { text, .. } => {
390 markdown.push_str("<think>");
391 markdown.push_str(text);
392 markdown.push_str("</think>\n");
393 }
394 AgentMessageContent::RedactedThinking(_) => {
395 markdown.push_str("<redacted_thinking />\n")
396 }
397 AgentMessageContent::ToolUse(tool_use) => {
398 markdown.push_str(&format!(
399 "**Tool Use**: {} (ID: {})\n",
400 tool_use.name, tool_use.id
401 ));
402 markdown.push_str(&format!(
403 "{}\n",
404 MarkdownCodeBlock {
405 tag: "json",
406 text: &format!("{:#}", tool_use.input)
407 }
408 ));
409 }
410 }
411 }
412
413 for tool_result in self.tool_results.values() {
414 markdown.push_str(&format!(
415 "**Tool Result**: {} (ID: {})\n\n",
416 tool_result.tool_name, tool_result.tool_use_id
417 ));
418 if tool_result.is_error {
419 markdown.push_str("**ERROR:**\n");
420 }
421
422 match &tool_result.content {
423 LanguageModelToolResultContent::Text(text) => {
424 writeln!(markdown, "{text}\n").ok();
425 }
426 LanguageModelToolResultContent::Image(_) => {
427 writeln!(markdown, "<image />\n").ok();
428 }
429 }
430
431 if let Some(output) = tool_result.output.as_ref() {
432 writeln!(
433 markdown,
434 "**Debug Output**:\n\n```json\n{}\n```\n",
435 serde_json::to_string_pretty(output).unwrap()
436 )
437 .unwrap();
438 }
439 }
440
441 markdown
442 }
443
444 pub fn to_request(&self) -> Vec<LanguageModelRequestMessage> {
445 let mut assistant_message = LanguageModelRequestMessage {
446 role: Role::Assistant,
447 content: Vec::with_capacity(self.content.len()),
448 cache: false,
449 };
450 for chunk in &self.content {
451 match chunk {
452 AgentMessageContent::Text(text) => {
453 assistant_message
454 .content
455 .push(language_model::MessageContent::Text(text.clone()));
456 }
457 AgentMessageContent::Thinking { text, signature } => {
458 assistant_message
459 .content
460 .push(language_model::MessageContent::Thinking {
461 text: text.clone(),
462 signature: signature.clone(),
463 });
464 }
465 AgentMessageContent::RedactedThinking(value) => {
466 assistant_message.content.push(
467 language_model::MessageContent::RedactedThinking(value.clone()),
468 );
469 }
470 AgentMessageContent::ToolUse(tool_use) => {
471 if self.tool_results.contains_key(&tool_use.id) {
472 assistant_message
473 .content
474 .push(language_model::MessageContent::ToolUse(tool_use.clone()));
475 }
476 }
477 };
478 }
479
480 let mut user_message = LanguageModelRequestMessage {
481 role: Role::User,
482 content: Vec::new(),
483 cache: false,
484 };
485
486 for tool_result in self.tool_results.values() {
487 user_message
488 .content
489 .push(language_model::MessageContent::ToolResult(
490 tool_result.clone(),
491 ));
492 }
493
494 let mut messages = Vec::new();
495 if !assistant_message.content.is_empty() {
496 messages.push(assistant_message);
497 }
498 if !user_message.content.is_empty() {
499 messages.push(user_message);
500 }
501 messages
502 }
503}
504
505#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
506pub struct AgentMessage {
507 pub content: Vec<AgentMessageContent>,
508 pub tool_results: IndexMap<LanguageModelToolUseId, LanguageModelToolResult>,
509}
510
511#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
512pub enum AgentMessageContent {
513 Text(String),
514 Thinking {
515 text: String,
516 signature: Option<String>,
517 },
518 RedactedThinking(String),
519 ToolUse(LanguageModelToolUse),
520}
521
522#[derive(Debug)]
523pub enum ThreadEvent {
524 UserMessage(UserMessage),
525 AgentText(String),
526 AgentThinking(String),
527 ToolCall(acp::ToolCall),
528 ToolCallUpdate(acp_thread::ToolCallUpdate),
529 ToolCallAuthorization(ToolCallAuthorization),
530 Retry(acp_thread::RetryStatus),
531 Stop(acp::StopReason),
532}
533
534#[derive(Debug)]
535pub struct ToolCallAuthorization {
536 pub tool_call: acp::ToolCallUpdate,
537 pub options: Vec<acp::PermissionOption>,
538 pub response: oneshot::Sender<acp::PermissionOptionId>,
539}
540
541#[derive(Debug, thiserror::Error)]
542enum CompletionError {
543 #[error("max tokens")]
544 MaxTokens,
545 #[error("refusal")]
546 Refusal,
547 #[error(transparent)]
548 Other(#[from] anyhow::Error),
549}
550
551pub struct Thread {
552 id: acp::SessionId,
553 prompt_id: PromptId,
554 updated_at: DateTime<Utc>,
555 title: Option<SharedString>,
556 pending_title_generation: Option<Task<()>>,
557 summary: Option<SharedString>,
558 messages: Vec<Message>,
559 completion_mode: CompletionMode,
560 /// Holds the task that handles agent interaction until the end of the turn.
561 /// Survives across multiple requests as the model performs tool calls and
562 /// we run tools, report their results.
563 running_turn: Option<RunningTurn>,
564 pending_message: Option<AgentMessage>,
565 tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
566 tool_use_limit_reached: bool,
567 request_token_usage: HashMap<UserMessageId, language_model::TokenUsage>,
568 #[allow(unused)]
569 cumulative_token_usage: TokenUsage,
570 #[allow(unused)]
571 initial_project_snapshot: Shared<Task<Option<Arc<ProjectSnapshot>>>>,
572 context_server_registry: Entity<ContextServerRegistry>,
573 profile_id: AgentProfileId,
574 project_context: Entity<ProjectContext>,
575 templates: Arc<Templates>,
576 model: Option<Arc<dyn LanguageModel>>,
577 summarization_model: Option<Arc<dyn LanguageModel>>,
578 pub(crate) project: Entity<Project>,
579 pub(crate) action_log: Entity<ActionLog>,
580}
581
582impl Thread {
583 pub fn new(
584 project: Entity<Project>,
585 project_context: Entity<ProjectContext>,
586 context_server_registry: Entity<ContextServerRegistry>,
587 templates: Arc<Templates>,
588 model: Option<Arc<dyn LanguageModel>>,
589 cx: &mut Context<Self>,
590 ) -> Self {
591 let profile_id = AgentSettings::get_global(cx).default_profile.clone();
592 let action_log = cx.new(|_cx| ActionLog::new(project.clone()));
593 Self {
594 id: acp::SessionId(uuid::Uuid::new_v4().to_string().into()),
595 prompt_id: PromptId::new(),
596 updated_at: Utc::now(),
597 title: None,
598 pending_title_generation: None,
599 summary: None,
600 messages: Vec::new(),
601 completion_mode: AgentSettings::get_global(cx).preferred_completion_mode,
602 running_turn: None,
603 pending_message: None,
604 tools: BTreeMap::default(),
605 tool_use_limit_reached: false,
606 request_token_usage: HashMap::default(),
607 cumulative_token_usage: TokenUsage::default(),
608 initial_project_snapshot: {
609 let project_snapshot = Self::project_snapshot(project.clone(), cx);
610 cx.foreground_executor()
611 .spawn(async move { Some(project_snapshot.await) })
612 .shared()
613 },
614 context_server_registry,
615 profile_id,
616 project_context,
617 templates,
618 model,
619 summarization_model: None,
620 project,
621 action_log,
622 }
623 }
624
625 pub fn id(&self) -> &acp::SessionId {
626 &self.id
627 }
628
629 pub fn replay(
630 &mut self,
631 cx: &mut Context<Self>,
632 ) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {
633 let (tx, rx) = mpsc::unbounded();
634 let stream = ThreadEventStream(tx);
635 for message in &self.messages {
636 match message {
637 Message::User(user_message) => stream.send_user_message(user_message),
638 Message::Agent(assistant_message) => {
639 for content in &assistant_message.content {
640 match content {
641 AgentMessageContent::Text(text) => stream.send_text(text),
642 AgentMessageContent::Thinking { text, .. } => {
643 stream.send_thinking(text)
644 }
645 AgentMessageContent::RedactedThinking(_) => {}
646 AgentMessageContent::ToolUse(tool_use) => {
647 self.replay_tool_call(
648 tool_use,
649 assistant_message.tool_results.get(&tool_use.id),
650 &stream,
651 cx,
652 );
653 }
654 }
655 }
656 }
657 Message::Resume => {}
658 }
659 }
660 rx
661 }
662
663 fn replay_tool_call(
664 &self,
665 tool_use: &LanguageModelToolUse,
666 tool_result: Option<&LanguageModelToolResult>,
667 stream: &ThreadEventStream,
668 cx: &mut Context<Self>,
669 ) {
670 let tool = self.tools.get(tool_use.name.as_ref()).cloned().or_else(|| {
671 self.context_server_registry
672 .read(cx)
673 .servers()
674 .find_map(|(_, tools)| {
675 if let Some(tool) = tools.get(tool_use.name.as_ref()) {
676 Some(tool.clone())
677 } else {
678 None
679 }
680 })
681 });
682
683 let Some(tool) = tool else {
684 stream
685 .0
686 .unbounded_send(Ok(ThreadEvent::ToolCall(acp::ToolCall {
687 id: acp::ToolCallId(tool_use.id.to_string().into()),
688 title: tool_use.name.to_string(),
689 kind: acp::ToolKind::Other,
690 status: acp::ToolCallStatus::Failed,
691 content: Vec::new(),
692 locations: Vec::new(),
693 raw_input: Some(tool_use.input.clone()),
694 raw_output: None,
695 })))
696 .ok();
697 return;
698 };
699
700 let title = tool.initial_title(tool_use.input.clone());
701 let kind = tool.kind();
702 stream.send_tool_call(&tool_use.id, title, kind, tool_use.input.clone());
703
704 let output = tool_result
705 .as_ref()
706 .and_then(|result| result.output.clone());
707 if let Some(output) = output.clone() {
708 let tool_event_stream = ToolCallEventStream::new(
709 tool_use.id.clone(),
710 stream.clone(),
711 Some(self.project.read(cx).fs().clone()),
712 );
713 tool.replay(tool_use.input.clone(), output, tool_event_stream, cx)
714 .log_err();
715 }
716
717 stream.update_tool_call_fields(
718 &tool_use.id,
719 acp::ToolCallUpdateFields {
720 status: Some(acp::ToolCallStatus::Completed),
721 raw_output: output,
722 ..Default::default()
723 },
724 );
725 }
726
727 pub fn from_db(
728 id: acp::SessionId,
729 db_thread: DbThread,
730 project: Entity<Project>,
731 project_context: Entity<ProjectContext>,
732 context_server_registry: Entity<ContextServerRegistry>,
733 action_log: Entity<ActionLog>,
734 templates: Arc<Templates>,
735 cx: &mut Context<Self>,
736 ) -> Self {
737 let profile_id = db_thread
738 .profile
739 .unwrap_or_else(|| AgentSettings::get_global(cx).default_profile.clone());
740 let model = LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
741 db_thread
742 .model
743 .and_then(|model| {
744 let model = SelectedModel {
745 provider: model.provider.clone().into(),
746 model: model.model.into(),
747 };
748 registry.select_model(&model, cx)
749 })
750 .or_else(|| registry.default_model())
751 .map(|model| model.model)
752 });
753
754 Self {
755 id,
756 prompt_id: PromptId::new(),
757 title: if db_thread.title.is_empty() {
758 None
759 } else {
760 Some(db_thread.title.clone())
761 },
762 pending_title_generation: None,
763 summary: db_thread.detailed_summary,
764 messages: db_thread.messages,
765 completion_mode: db_thread.completion_mode.unwrap_or_default(),
766 running_turn: None,
767 pending_message: None,
768 tools: BTreeMap::default(),
769 tool_use_limit_reached: false,
770 request_token_usage: db_thread.request_token_usage.clone(),
771 cumulative_token_usage: db_thread.cumulative_token_usage,
772 initial_project_snapshot: Task::ready(db_thread.initial_project_snapshot).shared(),
773 context_server_registry,
774 profile_id,
775 project_context,
776 templates,
777 model,
778 summarization_model: None,
779 project,
780 action_log,
781 updated_at: db_thread.updated_at,
782 }
783 }
784
785 pub fn to_db(&self, cx: &App) -> Task<DbThread> {
786 let initial_project_snapshot = self.initial_project_snapshot.clone();
787 let mut thread = DbThread {
788 title: self.title(),
789 messages: self.messages.clone(),
790 updated_at: self.updated_at,
791 detailed_summary: self.summary.clone(),
792 initial_project_snapshot: None,
793 cumulative_token_usage: self.cumulative_token_usage,
794 request_token_usage: self.request_token_usage.clone(),
795 model: self.model.as_ref().map(|model| DbLanguageModel {
796 provider: model.provider_id().to_string(),
797 model: model.name().0.to_string(),
798 }),
799 completion_mode: Some(self.completion_mode),
800 profile: Some(self.profile_id.clone()),
801 };
802
803 cx.background_spawn(async move {
804 let initial_project_snapshot = initial_project_snapshot.await;
805 thread.initial_project_snapshot = initial_project_snapshot;
806 thread
807 })
808 }
809
810 /// Create a snapshot of the current project state including git information and unsaved buffers.
811 fn project_snapshot(
812 project: Entity<Project>,
813 cx: &mut Context<Self>,
814 ) -> Task<Arc<agent::thread::ProjectSnapshot>> {
815 let git_store = project.read(cx).git_store().clone();
816 let worktree_snapshots: Vec<_> = project
817 .read(cx)
818 .visible_worktrees(cx)
819 .map(|worktree| Self::worktree_snapshot(worktree, git_store.clone(), cx))
820 .collect();
821
822 cx.spawn(async move |_, cx| {
823 let worktree_snapshots = futures::future::join_all(worktree_snapshots).await;
824
825 let mut unsaved_buffers = Vec::new();
826 cx.update(|app_cx| {
827 let buffer_store = project.read(app_cx).buffer_store();
828 for buffer_handle in buffer_store.read(app_cx).buffers() {
829 let buffer = buffer_handle.read(app_cx);
830 if buffer.is_dirty()
831 && let Some(file) = buffer.file()
832 {
833 let path = file.path().to_string_lossy().to_string();
834 unsaved_buffers.push(path);
835 }
836 }
837 })
838 .ok();
839
840 Arc::new(ProjectSnapshot {
841 worktree_snapshots,
842 unsaved_buffer_paths: unsaved_buffers,
843 timestamp: Utc::now(),
844 })
845 })
846 }
847
848 fn worktree_snapshot(
849 worktree: Entity<project::Worktree>,
850 git_store: Entity<GitStore>,
851 cx: &App,
852 ) -> Task<agent::thread::WorktreeSnapshot> {
853 cx.spawn(async move |cx| {
854 // Get worktree path and snapshot
855 let worktree_info = cx.update(|app_cx| {
856 let worktree = worktree.read(app_cx);
857 let path = worktree.abs_path().to_string_lossy().to_string();
858 let snapshot = worktree.snapshot();
859 (path, snapshot)
860 });
861
862 let Ok((worktree_path, _snapshot)) = worktree_info else {
863 return WorktreeSnapshot {
864 worktree_path: String::new(),
865 git_state: None,
866 };
867 };
868
869 let git_state = git_store
870 .update(cx, |git_store, cx| {
871 git_store
872 .repositories()
873 .values()
874 .find(|repo| {
875 repo.read(cx)
876 .abs_path_to_repo_path(&worktree.read(cx).abs_path())
877 .is_some()
878 })
879 .cloned()
880 })
881 .ok()
882 .flatten()
883 .map(|repo| {
884 repo.update(cx, |repo, _| {
885 let current_branch =
886 repo.branch.as_ref().map(|branch| branch.name().to_owned());
887 repo.send_job(None, |state, _| async move {
888 let RepositoryState::Local { backend, .. } = state else {
889 return GitState {
890 remote_url: None,
891 head_sha: None,
892 current_branch,
893 diff: None,
894 };
895 };
896
897 let remote_url = backend.remote_url("origin");
898 let head_sha = backend.head_sha().await;
899 let diff = backend.diff(DiffType::HeadToWorktree).await.ok();
900
901 GitState {
902 remote_url,
903 head_sha,
904 current_branch,
905 diff,
906 }
907 })
908 })
909 });
910
911 let git_state = match git_state {
912 Some(git_state) => match git_state.ok() {
913 Some(git_state) => git_state.await.ok(),
914 None => None,
915 },
916 None => None,
917 };
918
919 WorktreeSnapshot {
920 worktree_path,
921 git_state,
922 }
923 })
924 }
925
926 pub fn project_context(&self) -> &Entity<ProjectContext> {
927 &self.project_context
928 }
929
930 pub fn project(&self) -> &Entity<Project> {
931 &self.project
932 }
933
934 pub fn action_log(&self) -> &Entity<ActionLog> {
935 &self.action_log
936 }
937
938 pub fn is_empty(&self) -> bool {
939 self.messages.is_empty() && self.title.is_none()
940 }
941
942 pub fn model(&self) -> Option<&Arc<dyn LanguageModel>> {
943 self.model.as_ref()
944 }
945
946 pub fn set_model(&mut self, model: Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
947 let old_usage = self.latest_token_usage();
948 self.model = Some(model);
949 let new_usage = self.latest_token_usage();
950 if old_usage != new_usage {
951 cx.emit(TokenUsageUpdated(new_usage));
952 }
953 cx.notify()
954 }
955
956 pub fn summarization_model(&self) -> Option<&Arc<dyn LanguageModel>> {
957 self.summarization_model.as_ref()
958 }
959
960 pub fn set_summarization_model(
961 &mut self,
962 model: Option<Arc<dyn LanguageModel>>,
963 cx: &mut Context<Self>,
964 ) {
965 self.summarization_model = model;
966 cx.notify()
967 }
968
969 pub fn completion_mode(&self) -> CompletionMode {
970 self.completion_mode
971 }
972
973 pub fn set_completion_mode(&mut self, mode: CompletionMode, cx: &mut Context<Self>) {
974 let old_usage = self.latest_token_usage();
975 self.completion_mode = mode;
976 let new_usage = self.latest_token_usage();
977 if old_usage != new_usage {
978 cx.emit(TokenUsageUpdated(new_usage));
979 }
980 cx.notify()
981 }
982
983 #[cfg(any(test, feature = "test-support"))]
984 pub fn last_message(&self) -> Option<Message> {
985 if let Some(message) = self.pending_message.clone() {
986 Some(Message::Agent(message))
987 } else {
988 self.messages.last().cloned()
989 }
990 }
991
992 pub fn add_default_tools(&mut self, cx: &mut Context<Self>) {
993 let language_registry = self.project.read(cx).languages().clone();
994 self.add_tool(CopyPathTool::new(self.project.clone()));
995 self.add_tool(CreateDirectoryTool::new(self.project.clone()));
996 self.add_tool(DeletePathTool::new(
997 self.project.clone(),
998 self.action_log.clone(),
999 ));
1000 self.add_tool(DiagnosticsTool::new(self.project.clone()));
1001 self.add_tool(EditFileTool::new(cx.weak_entity(), language_registry));
1002 self.add_tool(FetchTool::new(self.project.read(cx).client().http_client()));
1003 self.add_tool(FindPathTool::new(self.project.clone()));
1004 self.add_tool(GrepTool::new(self.project.clone()));
1005 self.add_tool(ListDirectoryTool::new(self.project.clone()));
1006 self.add_tool(MovePathTool::new(self.project.clone()));
1007 self.add_tool(NowTool);
1008 self.add_tool(OpenTool::new(self.project.clone()));
1009 self.add_tool(ReadFileTool::new(
1010 self.project.clone(),
1011 self.action_log.clone(),
1012 ));
1013 self.add_tool(TerminalTool::new(self.project.clone(), cx));
1014 self.add_tool(ThinkingTool);
1015 self.add_tool(WebSearchTool);
1016 }
1017
1018 pub fn add_tool<T: AgentTool>(&mut self, tool: T) {
1019 self.tools.insert(T::name().into(), tool.erase());
1020 }
1021
1022 pub fn remove_tool(&mut self, name: &str) -> bool {
1023 self.tools.remove(name).is_some()
1024 }
1025
1026 pub fn profile(&self) -> &AgentProfileId {
1027 &self.profile_id
1028 }
1029
1030 pub fn set_profile(&mut self, profile_id: AgentProfileId) {
1031 self.profile_id = profile_id;
1032 }
1033
1034 pub fn cancel(&mut self, cx: &mut Context<Self>) {
1035 if let Some(running_turn) = self.running_turn.take() {
1036 running_turn.cancel();
1037 }
1038 self.flush_pending_message(cx);
1039 }
1040
1041 fn update_token_usage(&mut self, update: language_model::TokenUsage, cx: &mut Context<Self>) {
1042 let Some(last_user_message) = self.last_user_message() else {
1043 return;
1044 };
1045
1046 self.request_token_usage
1047 .insert(last_user_message.id.clone(), update);
1048 cx.emit(TokenUsageUpdated(self.latest_token_usage()));
1049 cx.notify();
1050 }
1051
1052 pub fn truncate(&mut self, message_id: UserMessageId, cx: &mut Context<Self>) -> Result<()> {
1053 self.cancel(cx);
1054 let Some(position) = self.messages.iter().position(
1055 |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
1056 ) else {
1057 return Err(anyhow!("Message not found"));
1058 };
1059
1060 for message in self.messages.drain(position..) {
1061 match message {
1062 Message::User(message) => {
1063 self.request_token_usage.remove(&message.id);
1064 }
1065 Message::Agent(_) | Message::Resume => {}
1066 }
1067 }
1068 self.summary = None;
1069 cx.notify();
1070 Ok(())
1071 }
1072
1073 pub fn latest_token_usage(&self) -> Option<acp_thread::TokenUsage> {
1074 let last_user_message = self.last_user_message()?;
1075 let tokens = self.request_token_usage.get(&last_user_message.id)?;
1076 let model = self.model.clone()?;
1077
1078 Some(acp_thread::TokenUsage {
1079 max_tokens: model.max_token_count_for_mode(self.completion_mode.into()),
1080 used_tokens: tokens.total_tokens(),
1081 })
1082 }
1083
1084 pub fn resume(
1085 &mut self,
1086 cx: &mut Context<Self>,
1087 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1088 anyhow::ensure!(
1089 self.tool_use_limit_reached,
1090 "can only resume after tool use limit is reached"
1091 );
1092
1093 self.messages.push(Message::Resume);
1094 cx.notify();
1095
1096 log::info!("Total messages in thread: {}", self.messages.len());
1097 self.run_turn(cx)
1098 }
1099
1100 /// Sending a message results in the model streaming a response, which could include tool calls.
1101 /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
1102 /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
1103 pub fn send<T>(
1104 &mut self,
1105 id: UserMessageId,
1106 content: impl IntoIterator<Item = T>,
1107 cx: &mut Context<Self>,
1108 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
1109 where
1110 T: Into<UserMessageContent>,
1111 {
1112 let model = self.model().context("No language model configured")?;
1113
1114 log::info!("Thread::send called with model: {:?}", model.name());
1115 self.advance_prompt_id();
1116
1117 let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
1118 log::debug!("Thread::send content: {:?}", content);
1119
1120 self.messages
1121 .push(Message::User(UserMessage { id, content }));
1122 cx.notify();
1123
1124 log::info!("Total messages in thread: {}", self.messages.len());
1125 self.run_turn(cx)
1126 }
1127
1128 fn run_turn(
1129 &mut self,
1130 cx: &mut Context<Self>,
1131 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1132 self.cancel(cx);
1133
1134 let model = self.model.clone().context("No language model configured")?;
1135 let profile = AgentSettings::get_global(cx)
1136 .profiles
1137 .get(&self.profile_id)
1138 .context("Profile not found")?;
1139 let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1140 let event_stream = ThreadEventStream(events_tx);
1141 let message_ix = self.messages.len().saturating_sub(1);
1142 self.tool_use_limit_reached = false;
1143 self.summary = None;
1144 self.running_turn = Some(RunningTurn {
1145 event_stream: event_stream.clone(),
1146 tools: self.enabled_tools(profile, &model, cx),
1147 _task: cx.spawn(async move |this, cx| {
1148 log::info!("Starting agent turn execution");
1149
1150 let turn_result: Result<()> = async {
1151 let mut intent = CompletionIntent::UserPrompt;
1152 loop {
1153 Self::stream_completion(&this, &model, intent, &event_stream, cx).await?;
1154
1155 let mut end_turn = true;
1156 this.update(cx, |this, cx| {
1157 // Generate title if needed.
1158 if this.title.is_none() && this.pending_title_generation.is_none() {
1159 this.generate_title(cx);
1160 }
1161
1162 // End the turn if the model didn't use tools.
1163 let message = this.pending_message.as_ref();
1164 end_turn =
1165 message.map_or(true, |message| message.tool_results.is_empty());
1166 this.flush_pending_message(cx);
1167 })?;
1168
1169 if this.read_with(cx, |this, _| this.tool_use_limit_reached)? {
1170 log::info!("Tool use limit reached, completing turn");
1171 return Err(language_model::ToolUseLimitReachedError.into());
1172 } else if end_turn {
1173 log::info!("No tool uses found, completing turn");
1174 return Ok(());
1175 } else {
1176 intent = CompletionIntent::ToolResults;
1177 }
1178 }
1179 }
1180 .await;
1181 _ = this.update(cx, |this, cx| this.flush_pending_message(cx));
1182
1183 match turn_result {
1184 Ok(()) => {
1185 log::info!("Turn execution completed");
1186 event_stream.send_stop(acp::StopReason::EndTurn);
1187 }
1188 Err(error) => {
1189 log::error!("Turn execution failed: {:?}", error);
1190 match error.downcast::<CompletionError>() {
1191 Ok(CompletionError::Refusal) => {
1192 event_stream.send_stop(acp::StopReason::Refusal);
1193 _ = this.update(cx, |this, _| this.messages.truncate(message_ix));
1194 }
1195 Ok(CompletionError::MaxTokens) => {
1196 event_stream.send_stop(acp::StopReason::MaxTokens);
1197 }
1198 Ok(CompletionError::Other(error)) | Err(error) => {
1199 event_stream.send_error(error);
1200 }
1201 }
1202 }
1203 }
1204
1205 _ = this.update(cx, |this, _| this.running_turn.take());
1206 }),
1207 });
1208 Ok(events_rx)
1209 }
1210
1211 async fn stream_completion(
1212 this: &WeakEntity<Self>,
1213 model: &Arc<dyn LanguageModel>,
1214 completion_intent: CompletionIntent,
1215 event_stream: &ThreadEventStream,
1216 cx: &mut AsyncApp,
1217 ) -> Result<()> {
1218 log::debug!("Stream completion started successfully");
1219 let request = this.update(cx, |this, cx| {
1220 this.build_completion_request(completion_intent, cx)
1221 })??;
1222
1223 let mut attempt = None;
1224 'retry: loop {
1225 telemetry::event!(
1226 "Agent Thread Completion",
1227 thread_id = this.read_with(cx, |this, _| this.id.to_string())?,
1228 prompt_id = this.read_with(cx, |this, _| this.prompt_id.to_string())?,
1229 model = model.telemetry_id(),
1230 model_provider = model.provider_id().to_string(),
1231 attempt
1232 );
1233
1234 log::info!(
1235 "Calling model.stream_completion, attempt {}",
1236 attempt.unwrap_or(0)
1237 );
1238 let mut events = model
1239 .stream_completion(request.clone(), cx)
1240 .await
1241 .map_err(|error| anyhow!(error))?;
1242 let mut tool_results = FuturesUnordered::new();
1243
1244 while let Some(event) = events.next().await {
1245 match event {
1246 Ok(event) => {
1247 log::trace!("Received completion event: {:?}", event);
1248 tool_results.extend(this.update(cx, |this, cx| {
1249 this.handle_streamed_completion_event(event, event_stream, cx)
1250 })??);
1251 }
1252 Err(error) => {
1253 let completion_mode =
1254 this.read_with(cx, |thread, _cx| thread.completion_mode())?;
1255 if completion_mode == CompletionMode::Normal {
1256 return Err(anyhow!(error))?;
1257 }
1258
1259 let Some(strategy) = Self::retry_strategy_for(&error) else {
1260 return Err(anyhow!(error))?;
1261 };
1262
1263 let max_attempts = match &strategy {
1264 RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
1265 RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
1266 };
1267
1268 let attempt = attempt.get_or_insert(0u8);
1269
1270 *attempt += 1;
1271
1272 let attempt = *attempt;
1273 if attempt > max_attempts {
1274 return Err(anyhow!(error))?;
1275 }
1276
1277 let delay = match &strategy {
1278 RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
1279 let delay_secs =
1280 initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
1281 Duration::from_secs(delay_secs)
1282 }
1283 RetryStrategy::Fixed { delay, .. } => *delay,
1284 };
1285 log::debug!("Retry attempt {attempt} with delay {delay:?}");
1286
1287 event_stream.send_retry(acp_thread::RetryStatus {
1288 last_error: error.to_string().into(),
1289 attempt: attempt as usize,
1290 max_attempts: max_attempts as usize,
1291 started_at: Instant::now(),
1292 duration: delay,
1293 });
1294
1295 cx.background_executor().timer(delay).await;
1296 continue 'retry;
1297 }
1298 }
1299 }
1300
1301 while let Some(tool_result) = tool_results.next().await {
1302 log::info!("Tool finished {:?}", tool_result);
1303
1304 event_stream.update_tool_call_fields(
1305 &tool_result.tool_use_id,
1306 acp::ToolCallUpdateFields {
1307 status: Some(if tool_result.is_error {
1308 acp::ToolCallStatus::Failed
1309 } else {
1310 acp::ToolCallStatus::Completed
1311 }),
1312 raw_output: tool_result.output.clone(),
1313 ..Default::default()
1314 },
1315 );
1316 this.update(cx, |this, _cx| {
1317 this.pending_message()
1318 .tool_results
1319 .insert(tool_result.tool_use_id.clone(), tool_result);
1320 })?;
1321 }
1322
1323 return Ok(());
1324 }
1325 }
1326
1327 /// A helper method that's called on every streamed completion event.
1328 /// Returns an optional tool result task, which the main agentic loop will
1329 /// send back to the model when it resolves.
1330 fn handle_streamed_completion_event(
1331 &mut self,
1332 event: LanguageModelCompletionEvent,
1333 event_stream: &ThreadEventStream,
1334 cx: &mut Context<Self>,
1335 ) -> Result<Option<Task<LanguageModelToolResult>>> {
1336 log::trace!("Handling streamed completion event: {:?}", event);
1337 use LanguageModelCompletionEvent::*;
1338
1339 match event {
1340 StartMessage { .. } => {
1341 self.flush_pending_message(cx);
1342 self.pending_message = Some(AgentMessage::default());
1343 }
1344 Text(new_text) => self.handle_text_event(new_text, event_stream, cx),
1345 Thinking { text, signature } => {
1346 self.handle_thinking_event(text, signature, event_stream, cx)
1347 }
1348 RedactedThinking { data } => self.handle_redacted_thinking_event(data, cx),
1349 ToolUse(tool_use) => {
1350 return Ok(self.handle_tool_use_event(tool_use, event_stream, cx));
1351 }
1352 ToolUseJsonParseError {
1353 id,
1354 tool_name,
1355 raw_input,
1356 json_parse_error,
1357 } => {
1358 return Ok(Some(Task::ready(
1359 self.handle_tool_use_json_parse_error_event(
1360 id,
1361 tool_name,
1362 raw_input,
1363 json_parse_error,
1364 ),
1365 )));
1366 }
1367 UsageUpdate(usage) => {
1368 telemetry::event!(
1369 "Agent Thread Completion Usage Updated",
1370 thread_id = self.id.to_string(),
1371 prompt_id = self.prompt_id.to_string(),
1372 model = self.model.as_ref().map(|m| m.telemetry_id()),
1373 model_provider = self.model.as_ref().map(|m| m.provider_id().to_string()),
1374 input_tokens = usage.input_tokens,
1375 output_tokens = usage.output_tokens,
1376 cache_creation_input_tokens = usage.cache_creation_input_tokens,
1377 cache_read_input_tokens = usage.cache_read_input_tokens,
1378 );
1379 self.update_token_usage(usage, cx);
1380 }
1381 StatusUpdate(CompletionRequestStatus::UsageUpdated { amount, limit }) => {
1382 self.update_model_request_usage(amount, limit, cx);
1383 }
1384 StatusUpdate(
1385 CompletionRequestStatus::Started
1386 | CompletionRequestStatus::Queued { .. }
1387 | CompletionRequestStatus::Failed { .. },
1388 ) => {}
1389 StatusUpdate(CompletionRequestStatus::ToolUseLimitReached) => {
1390 self.tool_use_limit_reached = true;
1391 }
1392 Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()),
1393 Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()),
1394 Stop(StopReason::ToolUse | StopReason::EndTurn) => {}
1395 }
1396
1397 Ok(None)
1398 }
1399
1400 fn handle_text_event(
1401 &mut self,
1402 new_text: String,
1403 event_stream: &ThreadEventStream,
1404 cx: &mut Context<Self>,
1405 ) {
1406 event_stream.send_text(&new_text);
1407
1408 let last_message = self.pending_message();
1409 if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
1410 text.push_str(&new_text);
1411 } else {
1412 last_message
1413 .content
1414 .push(AgentMessageContent::Text(new_text));
1415 }
1416
1417 cx.notify();
1418 }
1419
1420 fn handle_thinking_event(
1421 &mut self,
1422 new_text: String,
1423 new_signature: Option<String>,
1424 event_stream: &ThreadEventStream,
1425 cx: &mut Context<Self>,
1426 ) {
1427 event_stream.send_thinking(&new_text);
1428
1429 let last_message = self.pending_message();
1430 if let Some(AgentMessageContent::Thinking { text, signature }) =
1431 last_message.content.last_mut()
1432 {
1433 text.push_str(&new_text);
1434 *signature = new_signature.or(signature.take());
1435 } else {
1436 last_message.content.push(AgentMessageContent::Thinking {
1437 text: new_text,
1438 signature: new_signature,
1439 });
1440 }
1441
1442 cx.notify();
1443 }
1444
1445 fn handle_redacted_thinking_event(&mut self, data: String, cx: &mut Context<Self>) {
1446 let last_message = self.pending_message();
1447 last_message
1448 .content
1449 .push(AgentMessageContent::RedactedThinking(data));
1450 cx.notify();
1451 }
1452
1453 fn handle_tool_use_event(
1454 &mut self,
1455 tool_use: LanguageModelToolUse,
1456 event_stream: &ThreadEventStream,
1457 cx: &mut Context<Self>,
1458 ) -> Option<Task<LanguageModelToolResult>> {
1459 cx.notify();
1460
1461 let tool = self.tool(tool_use.name.as_ref());
1462 let mut title = SharedString::from(&tool_use.name);
1463 let mut kind = acp::ToolKind::Other;
1464 if let Some(tool) = tool.as_ref() {
1465 title = tool.initial_title(tool_use.input.clone());
1466 kind = tool.kind();
1467 }
1468
1469 // Ensure the last message ends in the current tool use
1470 let last_message = self.pending_message();
1471 let push_new_tool_use = last_message.content.last_mut().is_none_or(|content| {
1472 if let AgentMessageContent::ToolUse(last_tool_use) = content {
1473 if last_tool_use.id == tool_use.id {
1474 *last_tool_use = tool_use.clone();
1475 false
1476 } else {
1477 true
1478 }
1479 } else {
1480 true
1481 }
1482 });
1483
1484 if push_new_tool_use {
1485 event_stream.send_tool_call(&tool_use.id, title, kind, tool_use.input.clone());
1486 last_message
1487 .content
1488 .push(AgentMessageContent::ToolUse(tool_use.clone()));
1489 } else {
1490 event_stream.update_tool_call_fields(
1491 &tool_use.id,
1492 acp::ToolCallUpdateFields {
1493 title: Some(title.into()),
1494 kind: Some(kind),
1495 raw_input: Some(tool_use.input.clone()),
1496 ..Default::default()
1497 },
1498 );
1499 }
1500
1501 if !tool_use.is_input_complete {
1502 return None;
1503 }
1504
1505 let Some(tool) = tool else {
1506 let content = format!("No tool named {} exists", tool_use.name);
1507 return Some(Task::ready(LanguageModelToolResult {
1508 content: LanguageModelToolResultContent::Text(Arc::from(content)),
1509 tool_use_id: tool_use.id,
1510 tool_name: tool_use.name,
1511 is_error: true,
1512 output: None,
1513 }));
1514 };
1515
1516 let fs = self.project.read(cx).fs().clone();
1517 let tool_event_stream =
1518 ToolCallEventStream::new(tool_use.id.clone(), event_stream.clone(), Some(fs));
1519 tool_event_stream.update_fields(acp::ToolCallUpdateFields {
1520 status: Some(acp::ToolCallStatus::InProgress),
1521 ..Default::default()
1522 });
1523 let supports_images = self.model().is_some_and(|model| model.supports_images());
1524 let tool_result = tool.run(tool_use.input, tool_event_stream, cx);
1525 log::info!("Running tool {}", tool_use.name);
1526 Some(cx.foreground_executor().spawn(async move {
1527 let tool_result = tool_result.await.and_then(|output| {
1528 if let LanguageModelToolResultContent::Image(_) = &output.llm_output
1529 && !supports_images
1530 {
1531 return Err(anyhow!(
1532 "Attempted to read an image, but this model doesn't support it.",
1533 ));
1534 }
1535 Ok(output)
1536 });
1537
1538 match tool_result {
1539 Ok(output) => LanguageModelToolResult {
1540 tool_use_id: tool_use.id,
1541 tool_name: tool_use.name,
1542 is_error: false,
1543 content: output.llm_output,
1544 output: Some(output.raw_output),
1545 },
1546 Err(error) => LanguageModelToolResult {
1547 tool_use_id: tool_use.id,
1548 tool_name: tool_use.name,
1549 is_error: true,
1550 content: LanguageModelToolResultContent::Text(Arc::from(error.to_string())),
1551 output: None,
1552 },
1553 }
1554 }))
1555 }
1556
1557 fn handle_tool_use_json_parse_error_event(
1558 &mut self,
1559 tool_use_id: LanguageModelToolUseId,
1560 tool_name: Arc<str>,
1561 raw_input: Arc<str>,
1562 json_parse_error: String,
1563 ) -> LanguageModelToolResult {
1564 let tool_output = format!("Error parsing input JSON: {json_parse_error}");
1565 LanguageModelToolResult {
1566 tool_use_id,
1567 tool_name,
1568 is_error: true,
1569 content: LanguageModelToolResultContent::Text(tool_output.into()),
1570 output: Some(serde_json::Value::String(raw_input.to_string())),
1571 }
1572 }
1573
1574 fn update_model_request_usage(&self, amount: usize, limit: UsageLimit, cx: &mut Context<Self>) {
1575 self.project
1576 .read(cx)
1577 .user_store()
1578 .update(cx, |user_store, cx| {
1579 user_store.update_model_request_usage(
1580 ModelRequestUsage(RequestUsage {
1581 amount: amount as i32,
1582 limit,
1583 }),
1584 cx,
1585 )
1586 });
1587 }
1588
1589 pub fn title(&self) -> SharedString {
1590 self.title.clone().unwrap_or("New Thread".into())
1591 }
1592
1593 pub fn summary(&mut self, cx: &mut Context<Self>) -> Task<Result<SharedString>> {
1594 if let Some(summary) = self.summary.as_ref() {
1595 return Task::ready(Ok(summary.clone()));
1596 }
1597 let Some(model) = self.summarization_model.clone() else {
1598 return Task::ready(Err(anyhow!("No summarization model available")));
1599 };
1600 let mut request = LanguageModelRequest {
1601 intent: Some(CompletionIntent::ThreadContextSummarization),
1602 temperature: AgentSettings::temperature_for_model(&model, cx),
1603 ..Default::default()
1604 };
1605
1606 for message in &self.messages {
1607 request.messages.extend(message.to_request());
1608 }
1609
1610 request.messages.push(LanguageModelRequestMessage {
1611 role: Role::User,
1612 content: vec![SUMMARIZE_THREAD_DETAILED_PROMPT.into()],
1613 cache: false,
1614 });
1615 cx.spawn(async move |this, cx| {
1616 let mut summary = String::new();
1617 let mut messages = model.stream_completion(request, cx).await?;
1618 while let Some(event) = messages.next().await {
1619 let event = event?;
1620 let text = match event {
1621 LanguageModelCompletionEvent::Text(text) => text,
1622 LanguageModelCompletionEvent::StatusUpdate(
1623 CompletionRequestStatus::UsageUpdated { amount, limit },
1624 ) => {
1625 this.update(cx, |thread, cx| {
1626 thread.update_model_request_usage(amount, limit, cx);
1627 })?;
1628 continue;
1629 }
1630 _ => continue,
1631 };
1632
1633 let mut lines = text.lines();
1634 summary.extend(lines.next());
1635 }
1636
1637 log::info!("Setting summary: {}", summary);
1638 let summary = SharedString::from(summary);
1639
1640 this.update(cx, |this, cx| {
1641 this.summary = Some(summary.clone());
1642 cx.notify()
1643 })?;
1644
1645 Ok(summary)
1646 })
1647 }
1648
1649 fn generate_title(&mut self, cx: &mut Context<Self>) {
1650 let Some(model) = self.summarization_model.clone() else {
1651 return;
1652 };
1653
1654 log::info!(
1655 "Generating title with model: {:?}",
1656 self.summarization_model.as_ref().map(|model| model.name())
1657 );
1658 let mut request = LanguageModelRequest {
1659 intent: Some(CompletionIntent::ThreadSummarization),
1660 temperature: AgentSettings::temperature_for_model(&model, cx),
1661 ..Default::default()
1662 };
1663
1664 for message in &self.messages {
1665 request.messages.extend(message.to_request());
1666 }
1667
1668 request.messages.push(LanguageModelRequestMessage {
1669 role: Role::User,
1670 content: vec![SUMMARIZE_THREAD_PROMPT.into()],
1671 cache: false,
1672 });
1673 self.pending_title_generation = Some(cx.spawn(async move |this, cx| {
1674 let mut title = String::new();
1675
1676 let generate = async {
1677 let mut messages = model.stream_completion(request, cx).await?;
1678 while let Some(event) = messages.next().await {
1679 let event = event?;
1680 let text = match event {
1681 LanguageModelCompletionEvent::Text(text) => text,
1682 LanguageModelCompletionEvent::StatusUpdate(
1683 CompletionRequestStatus::UsageUpdated { amount, limit },
1684 ) => {
1685 this.update(cx, |thread, cx| {
1686 thread.update_model_request_usage(amount, limit, cx);
1687 })?;
1688 continue;
1689 }
1690 _ => continue,
1691 };
1692
1693 let mut lines = text.lines();
1694 title.extend(lines.next());
1695
1696 // Stop if the LLM generated multiple lines.
1697 if lines.next().is_some() {
1698 break;
1699 }
1700 }
1701 anyhow::Ok(())
1702 };
1703
1704 if generate.await.context("failed to generate title").is_ok() {
1705 _ = this.update(cx, |this, cx| this.set_title(title.into(), cx));
1706 }
1707 _ = this.update(cx, |this, _| this.pending_title_generation = None);
1708 }));
1709 }
1710
1711 pub fn set_title(&mut self, title: SharedString, cx: &mut Context<Self>) {
1712 self.pending_title_generation = None;
1713 if Some(&title) != self.title.as_ref() {
1714 self.title = Some(title);
1715 cx.emit(TitleUpdated);
1716 cx.notify();
1717 }
1718 }
1719
1720 fn last_user_message(&self) -> Option<&UserMessage> {
1721 self.messages
1722 .iter()
1723 .rev()
1724 .find_map(|message| match message {
1725 Message::User(user_message) => Some(user_message),
1726 Message::Agent(_) => None,
1727 Message::Resume => None,
1728 })
1729 }
1730
1731 fn pending_message(&mut self) -> &mut AgentMessage {
1732 self.pending_message.get_or_insert_default()
1733 }
1734
1735 fn flush_pending_message(&mut self, cx: &mut Context<Self>) {
1736 let Some(mut message) = self.pending_message.take() else {
1737 return;
1738 };
1739
1740 for content in &message.content {
1741 let AgentMessageContent::ToolUse(tool_use) = content else {
1742 continue;
1743 };
1744
1745 if !message.tool_results.contains_key(&tool_use.id) {
1746 message.tool_results.insert(
1747 tool_use.id.clone(),
1748 LanguageModelToolResult {
1749 tool_use_id: tool_use.id.clone(),
1750 tool_name: tool_use.name.clone(),
1751 is_error: true,
1752 content: LanguageModelToolResultContent::Text(TOOL_CANCELED_MESSAGE.into()),
1753 output: None,
1754 },
1755 );
1756 }
1757 }
1758
1759 self.messages.push(Message::Agent(message));
1760 self.updated_at = Utc::now();
1761 self.summary = None;
1762 cx.notify()
1763 }
1764
1765 pub(crate) fn build_completion_request(
1766 &self,
1767 completion_intent: CompletionIntent,
1768 cx: &App,
1769 ) -> Result<LanguageModelRequest> {
1770 let model = self.model().context("No language model configured")?;
1771 let tools = if let Some(turn) = self.running_turn.as_ref() {
1772 turn.tools
1773 .iter()
1774 .filter_map(|(tool_name, tool)| {
1775 log::trace!("Including tool: {}", tool_name);
1776 Some(LanguageModelRequestTool {
1777 name: tool_name.to_string(),
1778 description: tool.description().to_string(),
1779 input_schema: tool.input_schema(model.tool_input_format()).log_err()?,
1780 })
1781 })
1782 .collect::<Vec<_>>()
1783 } else {
1784 Vec::new()
1785 };
1786
1787 log::debug!("Building completion request");
1788 log::debug!("Completion intent: {:?}", completion_intent);
1789 log::debug!("Completion mode: {:?}", self.completion_mode);
1790
1791 let messages = self.build_request_messages(cx);
1792 log::info!("Request will include {} messages", messages.len());
1793 log::info!("Request includes {} tools", tools.len());
1794
1795 let request = LanguageModelRequest {
1796 thread_id: Some(self.id.to_string()),
1797 prompt_id: Some(self.prompt_id.to_string()),
1798 intent: Some(completion_intent),
1799 mode: Some(self.completion_mode.into()),
1800 messages,
1801 tools,
1802 tool_choice: None,
1803 stop: Vec::new(),
1804 temperature: AgentSettings::temperature_for_model(model, cx),
1805 thinking_allowed: true,
1806 };
1807
1808 log::debug!("Completion request built successfully");
1809 Ok(request)
1810 }
1811
1812 fn enabled_tools(
1813 &self,
1814 profile: &AgentProfileSettings,
1815 model: &Arc<dyn LanguageModel>,
1816 cx: &App,
1817 ) -> BTreeMap<SharedString, Arc<dyn AnyAgentTool>> {
1818 fn truncate(tool_name: &SharedString) -> SharedString {
1819 if tool_name.len() > MAX_TOOL_NAME_LENGTH {
1820 let mut truncated = tool_name.to_string();
1821 truncated.truncate(MAX_TOOL_NAME_LENGTH);
1822 truncated.into()
1823 } else {
1824 tool_name.clone()
1825 }
1826 }
1827
1828 let mut tools = self
1829 .tools
1830 .iter()
1831 .filter_map(|(tool_name, tool)| {
1832 if tool.supported_provider(&model.provider_id())
1833 && profile.is_tool_enabled(tool_name)
1834 {
1835 Some((truncate(tool_name), tool.clone()))
1836 } else {
1837 None
1838 }
1839 })
1840 .collect::<BTreeMap<_, _>>();
1841
1842 let mut context_server_tools = Vec::new();
1843 let mut seen_tools = tools.keys().cloned().collect::<HashSet<_>>();
1844 let mut duplicate_tool_names = HashSet::default();
1845 for (server_id, server_tools) in self.context_server_registry.read(cx).servers() {
1846 for (tool_name, tool) in server_tools {
1847 if profile.is_context_server_tool_enabled(&server_id.0, &tool_name) {
1848 let tool_name = truncate(tool_name);
1849 if !seen_tools.insert(tool_name.clone()) {
1850 duplicate_tool_names.insert(tool_name.clone());
1851 }
1852 context_server_tools.push((server_id.clone(), tool_name, tool.clone()));
1853 }
1854 }
1855 }
1856
1857 // When there are duplicate tool names, disambiguate by prefixing them
1858 // with the server ID. In the rare case there isn't enough space for the
1859 // disambiguated tool name, keep only the last tool with this name.
1860 for (server_id, tool_name, tool) in context_server_tools {
1861 if duplicate_tool_names.contains(&tool_name) {
1862 let available = MAX_TOOL_NAME_LENGTH.saturating_sub(tool_name.len());
1863 if available >= 2 {
1864 let mut disambiguated = server_id.0.to_string();
1865 disambiguated.truncate(available - 1);
1866 disambiguated.push('_');
1867 disambiguated.push_str(&tool_name);
1868 tools.insert(disambiguated.into(), tool.clone());
1869 } else {
1870 tools.insert(tool_name, tool.clone());
1871 }
1872 } else {
1873 tools.insert(tool_name, tool.clone());
1874 }
1875 }
1876
1877 tools
1878 }
1879
1880 fn tool(&self, name: &str) -> Option<Arc<dyn AnyAgentTool>> {
1881 self.running_turn.as_ref()?.tools.get(name).cloned()
1882 }
1883
1884 fn build_request_messages(&self, cx: &App) -> Vec<LanguageModelRequestMessage> {
1885 log::trace!(
1886 "Building request messages from {} thread messages",
1887 self.messages.len()
1888 );
1889
1890 let system_prompt = SystemPromptTemplate {
1891 project: self.project_context.read(cx),
1892 available_tools: self.tools.keys().cloned().collect(),
1893 }
1894 .render(&self.templates)
1895 .context("failed to build system prompt")
1896 .expect("Invalid template");
1897 let mut messages = vec![LanguageModelRequestMessage {
1898 role: Role::System,
1899 content: vec![system_prompt.into()],
1900 cache: false,
1901 }];
1902 for message in &self.messages {
1903 messages.extend(message.to_request());
1904 }
1905
1906 if let Some(last_message) = messages.last_mut() {
1907 last_message.cache = true;
1908 }
1909
1910 if let Some(message) = self.pending_message.as_ref() {
1911 messages.extend(message.to_request());
1912 }
1913
1914 messages
1915 }
1916
1917 pub fn to_markdown(&self) -> String {
1918 let mut markdown = String::new();
1919 for (ix, message) in self.messages.iter().enumerate() {
1920 if ix > 0 {
1921 markdown.push('\n');
1922 }
1923 markdown.push_str(&message.to_markdown());
1924 }
1925
1926 if let Some(message) = self.pending_message.as_ref() {
1927 markdown.push('\n');
1928 markdown.push_str(&message.to_markdown());
1929 }
1930
1931 markdown
1932 }
1933
1934 fn advance_prompt_id(&mut self) {
1935 self.prompt_id = PromptId::new();
1936 }
1937
1938 fn retry_strategy_for(error: &LanguageModelCompletionError) -> Option<RetryStrategy> {
1939 use LanguageModelCompletionError::*;
1940 use http_client::StatusCode;
1941
1942 // General strategy here:
1943 // - If retrying won't help (e.g. invalid API key or payload too large), return None so we don't retry at all.
1944 // - If it's a time-based issue (e.g. server overloaded, rate limit exceeded), retry up to 4 times with exponential backoff.
1945 // - If it's an issue that *might* be fixed by retrying (e.g. internal server error), retry up to 3 times.
1946 match error {
1947 HttpResponseError {
1948 status_code: StatusCode::TOO_MANY_REQUESTS,
1949 ..
1950 } => Some(RetryStrategy::ExponentialBackoff {
1951 initial_delay: BASE_RETRY_DELAY,
1952 max_attempts: MAX_RETRY_ATTEMPTS,
1953 }),
1954 ServerOverloaded { retry_after, .. } | RateLimitExceeded { retry_after, .. } => {
1955 Some(RetryStrategy::Fixed {
1956 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
1957 max_attempts: MAX_RETRY_ATTEMPTS,
1958 })
1959 }
1960 UpstreamProviderError {
1961 status,
1962 retry_after,
1963 ..
1964 } => match *status {
1965 StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
1966 Some(RetryStrategy::Fixed {
1967 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
1968 max_attempts: MAX_RETRY_ATTEMPTS,
1969 })
1970 }
1971 StatusCode::INTERNAL_SERVER_ERROR => Some(RetryStrategy::Fixed {
1972 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
1973 // Internal Server Error could be anything, retry up to 3 times.
1974 max_attempts: 3,
1975 }),
1976 status => {
1977 // There is no StatusCode variant for the unofficial HTTP 529 ("The service is overloaded"),
1978 // but we frequently get them in practice. See https://http.dev/529
1979 if status.as_u16() == 529 {
1980 Some(RetryStrategy::Fixed {
1981 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
1982 max_attempts: MAX_RETRY_ATTEMPTS,
1983 })
1984 } else {
1985 Some(RetryStrategy::Fixed {
1986 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
1987 max_attempts: 2,
1988 })
1989 }
1990 }
1991 },
1992 ApiInternalServerError { .. } => Some(RetryStrategy::Fixed {
1993 delay: BASE_RETRY_DELAY,
1994 max_attempts: 3,
1995 }),
1996 ApiReadResponseError { .. }
1997 | HttpSend { .. }
1998 | DeserializeResponse { .. }
1999 | BadRequestFormat { .. } => Some(RetryStrategy::Fixed {
2000 delay: BASE_RETRY_DELAY,
2001 max_attempts: 3,
2002 }),
2003 // Retrying these errors definitely shouldn't help.
2004 HttpResponseError {
2005 status_code:
2006 StatusCode::PAYLOAD_TOO_LARGE | StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED,
2007 ..
2008 }
2009 | AuthenticationError { .. }
2010 | PermissionError { .. }
2011 | NoApiKey { .. }
2012 | ApiEndpointNotFound { .. }
2013 | PromptTooLarge { .. } => None,
2014 // These errors might be transient, so retry them
2015 SerializeRequest { .. } | BuildRequestBody { .. } => Some(RetryStrategy::Fixed {
2016 delay: BASE_RETRY_DELAY,
2017 max_attempts: 1,
2018 }),
2019 // Retry all other 4xx and 5xx errors once.
2020 HttpResponseError { status_code, .. }
2021 if status_code.is_client_error() || status_code.is_server_error() =>
2022 {
2023 Some(RetryStrategy::Fixed {
2024 delay: BASE_RETRY_DELAY,
2025 max_attempts: 3,
2026 })
2027 }
2028 Other(err)
2029 if err.is::<language_model::PaymentRequiredError>()
2030 || err.is::<language_model::ModelRequestLimitReachedError>() =>
2031 {
2032 // Retrying won't help for Payment Required or Model Request Limit errors (where
2033 // the user must upgrade to usage-based billing to get more requests, or else wait
2034 // for a significant amount of time for the request limit to reset).
2035 None
2036 }
2037 // Conservatively assume that any other errors are non-retryable
2038 HttpResponseError { .. } | Other(..) => Some(RetryStrategy::Fixed {
2039 delay: BASE_RETRY_DELAY,
2040 max_attempts: 2,
2041 }),
2042 }
2043 }
2044}
2045
2046struct RunningTurn {
2047 /// Holds the task that handles agent interaction until the end of the turn.
2048 /// Survives across multiple requests as the model performs tool calls and
2049 /// we run tools, report their results.
2050 _task: Task<()>,
2051 /// The current event stream for the running turn. Used to report a final
2052 /// cancellation event if we cancel the turn.
2053 event_stream: ThreadEventStream,
2054 /// The tools that were enabled for this turn.
2055 tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
2056}
2057
2058impl RunningTurn {
2059 fn cancel(self) {
2060 log::debug!("Cancelling in progress turn");
2061 self.event_stream.send_canceled();
2062 }
2063}
2064
2065pub struct TokenUsageUpdated(pub Option<acp_thread::TokenUsage>);
2066
2067impl EventEmitter<TokenUsageUpdated> for Thread {}
2068
2069pub struct TitleUpdated;
2070
2071impl EventEmitter<TitleUpdated> for Thread {}
2072
2073pub trait AgentTool
2074where
2075 Self: 'static + Sized,
2076{
2077 type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
2078 type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
2079
2080 fn name() -> &'static str;
2081
2082 fn description(&self) -> SharedString {
2083 let schema = schemars::schema_for!(Self::Input);
2084 SharedString::new(
2085 schema
2086 .get("description")
2087 .and_then(|description| description.as_str())
2088 .unwrap_or_default(),
2089 )
2090 }
2091
2092 fn kind() -> acp::ToolKind;
2093
2094 /// The initial tool title to display. Can be updated during the tool run.
2095 fn initial_title(&self, input: Result<Self::Input, serde_json::Value>) -> SharedString;
2096
2097 /// Returns the JSON schema that describes the tool's input.
2098 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Schema {
2099 crate::tool_schema::root_schema_for::<Self::Input>(format)
2100 }
2101
2102 /// Some tools rely on a provider for the underlying billing or other reasons.
2103 /// Allow the tool to check if they are compatible, or should be filtered out.
2104 fn supported_provider(&self, _provider: &LanguageModelProviderId) -> bool {
2105 true
2106 }
2107
2108 /// Runs the tool with the provided input.
2109 fn run(
2110 self: Arc<Self>,
2111 input: Self::Input,
2112 event_stream: ToolCallEventStream,
2113 cx: &mut App,
2114 ) -> Task<Result<Self::Output>>;
2115
2116 /// Emits events for a previous execution of the tool.
2117 fn replay(
2118 &self,
2119 _input: Self::Input,
2120 _output: Self::Output,
2121 _event_stream: ToolCallEventStream,
2122 _cx: &mut App,
2123 ) -> Result<()> {
2124 Ok(())
2125 }
2126
2127 fn erase(self) -> Arc<dyn AnyAgentTool> {
2128 Arc::new(Erased(Arc::new(self)))
2129 }
2130}
2131
2132pub struct Erased<T>(T);
2133
2134pub struct AgentToolOutput {
2135 pub llm_output: LanguageModelToolResultContent,
2136 pub raw_output: serde_json::Value,
2137}
2138
2139pub trait AnyAgentTool {
2140 fn name(&self) -> SharedString;
2141 fn description(&self) -> SharedString;
2142 fn kind(&self) -> acp::ToolKind;
2143 fn initial_title(&self, input: serde_json::Value) -> SharedString;
2144 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
2145 fn supported_provider(&self, _provider: &LanguageModelProviderId) -> bool {
2146 true
2147 }
2148 fn run(
2149 self: Arc<Self>,
2150 input: serde_json::Value,
2151 event_stream: ToolCallEventStream,
2152 cx: &mut App,
2153 ) -> Task<Result<AgentToolOutput>>;
2154 fn replay(
2155 &self,
2156 input: serde_json::Value,
2157 output: serde_json::Value,
2158 event_stream: ToolCallEventStream,
2159 cx: &mut App,
2160 ) -> Result<()>;
2161}
2162
2163impl<T> AnyAgentTool for Erased<Arc<T>>
2164where
2165 T: AgentTool,
2166{
2167 fn name(&self) -> SharedString {
2168 T::name().into()
2169 }
2170
2171 fn description(&self) -> SharedString {
2172 self.0.description()
2173 }
2174
2175 fn kind(&self) -> agent_client_protocol::ToolKind {
2176 T::kind()
2177 }
2178
2179 fn initial_title(&self, input: serde_json::Value) -> SharedString {
2180 let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
2181 self.0.initial_title(parsed_input)
2182 }
2183
2184 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
2185 let mut json = serde_json::to_value(self.0.input_schema(format))?;
2186 adapt_schema_to_format(&mut json, format)?;
2187 Ok(json)
2188 }
2189
2190 fn supported_provider(&self, provider: &LanguageModelProviderId) -> bool {
2191 self.0.supported_provider(provider)
2192 }
2193
2194 fn run(
2195 self: Arc<Self>,
2196 input: serde_json::Value,
2197 event_stream: ToolCallEventStream,
2198 cx: &mut App,
2199 ) -> Task<Result<AgentToolOutput>> {
2200 cx.spawn(async move |cx| {
2201 let input = serde_json::from_value(input)?;
2202 let output = cx
2203 .update(|cx| self.0.clone().run(input, event_stream, cx))?
2204 .await?;
2205 let raw_output = serde_json::to_value(&output)?;
2206 Ok(AgentToolOutput {
2207 llm_output: output.into(),
2208 raw_output,
2209 })
2210 })
2211 }
2212
2213 fn replay(
2214 &self,
2215 input: serde_json::Value,
2216 output: serde_json::Value,
2217 event_stream: ToolCallEventStream,
2218 cx: &mut App,
2219 ) -> Result<()> {
2220 let input = serde_json::from_value(input)?;
2221 let output = serde_json::from_value(output)?;
2222 self.0.replay(input, output, event_stream, cx)
2223 }
2224}
2225
2226#[derive(Clone)]
2227struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
2228
2229impl ThreadEventStream {
2230 fn send_user_message(&self, message: &UserMessage) {
2231 self.0
2232 .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
2233 .ok();
2234 }
2235
2236 fn send_text(&self, text: &str) {
2237 self.0
2238 .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
2239 .ok();
2240 }
2241
2242 fn send_thinking(&self, text: &str) {
2243 self.0
2244 .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
2245 .ok();
2246 }
2247
2248 fn send_tool_call(
2249 &self,
2250 id: &LanguageModelToolUseId,
2251 title: SharedString,
2252 kind: acp::ToolKind,
2253 input: serde_json::Value,
2254 ) {
2255 self.0
2256 .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
2257 id,
2258 title.to_string(),
2259 kind,
2260 input,
2261 ))))
2262 .ok();
2263 }
2264
2265 fn initial_tool_call(
2266 id: &LanguageModelToolUseId,
2267 title: String,
2268 kind: acp::ToolKind,
2269 input: serde_json::Value,
2270 ) -> acp::ToolCall {
2271 acp::ToolCall {
2272 id: acp::ToolCallId(id.to_string().into()),
2273 title,
2274 kind,
2275 status: acp::ToolCallStatus::Pending,
2276 content: vec![],
2277 locations: vec![],
2278 raw_input: Some(input),
2279 raw_output: None,
2280 }
2281 }
2282
2283 fn update_tool_call_fields(
2284 &self,
2285 tool_use_id: &LanguageModelToolUseId,
2286 fields: acp::ToolCallUpdateFields,
2287 ) {
2288 self.0
2289 .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
2290 acp::ToolCallUpdate {
2291 id: acp::ToolCallId(tool_use_id.to_string().into()),
2292 fields,
2293 }
2294 .into(),
2295 )))
2296 .ok();
2297 }
2298
2299 fn send_retry(&self, status: acp_thread::RetryStatus) {
2300 self.0.unbounded_send(Ok(ThreadEvent::Retry(status))).ok();
2301 }
2302
2303 fn send_stop(&self, reason: acp::StopReason) {
2304 self.0.unbounded_send(Ok(ThreadEvent::Stop(reason))).ok();
2305 }
2306
2307 fn send_canceled(&self) {
2308 self.0
2309 .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))
2310 .ok();
2311 }
2312
2313 fn send_error(&self, error: impl Into<anyhow::Error>) {
2314 self.0.unbounded_send(Err(error.into())).ok();
2315 }
2316}
2317
2318#[derive(Clone)]
2319pub struct ToolCallEventStream {
2320 tool_use_id: LanguageModelToolUseId,
2321 stream: ThreadEventStream,
2322 fs: Option<Arc<dyn Fs>>,
2323}
2324
2325impl ToolCallEventStream {
2326 #[cfg(test)]
2327 pub fn test() -> (Self, ToolCallEventStreamReceiver) {
2328 let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
2329
2330 let stream = ToolCallEventStream::new("test_id".into(), ThreadEventStream(events_tx), None);
2331
2332 (stream, ToolCallEventStreamReceiver(events_rx))
2333 }
2334
2335 fn new(
2336 tool_use_id: LanguageModelToolUseId,
2337 stream: ThreadEventStream,
2338 fs: Option<Arc<dyn Fs>>,
2339 ) -> Self {
2340 Self {
2341 tool_use_id,
2342 stream,
2343 fs,
2344 }
2345 }
2346
2347 pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
2348 self.stream
2349 .update_tool_call_fields(&self.tool_use_id, fields);
2350 }
2351
2352 pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
2353 self.stream
2354 .0
2355 .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
2356 acp_thread::ToolCallUpdateDiff {
2357 id: acp::ToolCallId(self.tool_use_id.to_string().into()),
2358 diff,
2359 }
2360 .into(),
2361 )))
2362 .ok();
2363 }
2364
2365 pub fn update_terminal(&self, terminal: Entity<acp_thread::Terminal>) {
2366 self.stream
2367 .0
2368 .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
2369 acp_thread::ToolCallUpdateTerminal {
2370 id: acp::ToolCallId(self.tool_use_id.to_string().into()),
2371 terminal,
2372 }
2373 .into(),
2374 )))
2375 .ok();
2376 }
2377
2378 pub fn authorize(&self, title: impl Into<String>, cx: &mut App) -> Task<Result<()>> {
2379 if agent_settings::AgentSettings::get_global(cx).always_allow_tool_actions {
2380 return Task::ready(Ok(()));
2381 }
2382
2383 let (response_tx, response_rx) = oneshot::channel();
2384 self.stream
2385 .0
2386 .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
2387 ToolCallAuthorization {
2388 tool_call: acp::ToolCallUpdate {
2389 id: acp::ToolCallId(self.tool_use_id.to_string().into()),
2390 fields: acp::ToolCallUpdateFields {
2391 title: Some(title.into()),
2392 ..Default::default()
2393 },
2394 },
2395 options: vec![
2396 acp::PermissionOption {
2397 id: acp::PermissionOptionId("always_allow".into()),
2398 name: "Always Allow".into(),
2399 kind: acp::PermissionOptionKind::AllowAlways,
2400 },
2401 acp::PermissionOption {
2402 id: acp::PermissionOptionId("allow".into()),
2403 name: "Allow".into(),
2404 kind: acp::PermissionOptionKind::AllowOnce,
2405 },
2406 acp::PermissionOption {
2407 id: acp::PermissionOptionId("deny".into()),
2408 name: "Deny".into(),
2409 kind: acp::PermissionOptionKind::RejectOnce,
2410 },
2411 ],
2412 response: response_tx,
2413 },
2414 )))
2415 .ok();
2416 let fs = self.fs.clone();
2417 cx.spawn(async move |cx| match response_rx.await?.0.as_ref() {
2418 "always_allow" => {
2419 if let Some(fs) = fs.clone() {
2420 cx.update(|cx| {
2421 update_settings_file::<AgentSettings>(fs, cx, |settings, _| {
2422 settings.set_always_allow_tool_actions(true);
2423 });
2424 })?;
2425 }
2426
2427 Ok(())
2428 }
2429 "allow" => Ok(()),
2430 _ => Err(anyhow!("Permission to run tool denied by user")),
2431 })
2432 }
2433}
2434
2435#[cfg(test)]
2436pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
2437
2438#[cfg(test)]
2439impl ToolCallEventStreamReceiver {
2440 pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
2441 let event = self.0.next().await;
2442 if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
2443 auth
2444 } else {
2445 panic!("Expected ToolCallAuthorization but got: {:?}", event);
2446 }
2447 }
2448
2449 pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
2450 let event = self.0.next().await;
2451 if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
2452 update,
2453 )))) = event
2454 {
2455 update.terminal
2456 } else {
2457 panic!("Expected terminal but got: {:?}", event);
2458 }
2459 }
2460}
2461
2462#[cfg(test)]
2463impl std::ops::Deref for ToolCallEventStreamReceiver {
2464 type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
2465
2466 fn deref(&self) -> &Self::Target {
2467 &self.0
2468 }
2469}
2470
2471#[cfg(test)]
2472impl std::ops::DerefMut for ToolCallEventStreamReceiver {
2473 fn deref_mut(&mut self) -> &mut Self::Target {
2474 &mut self.0
2475 }
2476}
2477
2478impl From<&str> for UserMessageContent {
2479 fn from(text: &str) -> Self {
2480 Self::Text(text.into())
2481 }
2482}
2483
2484impl From<acp::ContentBlock> for UserMessageContent {
2485 fn from(value: acp::ContentBlock) -> Self {
2486 match value {
2487 acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
2488 acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
2489 acp::ContentBlock::Audio(_) => {
2490 // TODO
2491 Self::Text("[audio]".to_string())
2492 }
2493 acp::ContentBlock::ResourceLink(resource_link) => {
2494 match MentionUri::parse(&resource_link.uri) {
2495 Ok(uri) => Self::Mention {
2496 uri,
2497 content: String::new(),
2498 },
2499 Err(err) => {
2500 log::error!("Failed to parse mention link: {}", err);
2501 Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
2502 }
2503 }
2504 }
2505 acp::ContentBlock::Resource(resource) => match resource.resource {
2506 acp::EmbeddedResourceResource::TextResourceContents(resource) => {
2507 match MentionUri::parse(&resource.uri) {
2508 Ok(uri) => Self::Mention {
2509 uri,
2510 content: resource.text,
2511 },
2512 Err(err) => {
2513 log::error!("Failed to parse mention link: {}", err);
2514 Self::Text(
2515 MarkdownCodeBlock {
2516 tag: &resource.uri,
2517 text: &resource.text,
2518 }
2519 .to_string(),
2520 )
2521 }
2522 }
2523 }
2524 acp::EmbeddedResourceResource::BlobResourceContents(_) => {
2525 // TODO
2526 Self::Text("[blob]".to_string())
2527 }
2528 },
2529 }
2530 }
2531}
2532
2533impl From<UserMessageContent> for acp::ContentBlock {
2534 fn from(content: UserMessageContent) -> Self {
2535 match content {
2536 UserMessageContent::Text(text) => acp::ContentBlock::Text(acp::TextContent {
2537 text,
2538 annotations: None,
2539 }),
2540 UserMessageContent::Image(image) => acp::ContentBlock::Image(acp::ImageContent {
2541 data: image.source.to_string(),
2542 mime_type: "image/png".to_string(),
2543 annotations: None,
2544 uri: None,
2545 }),
2546 UserMessageContent::Mention { uri, content } => {
2547 acp::ContentBlock::Resource(acp::EmbeddedResource {
2548 resource: acp::EmbeddedResourceResource::TextResourceContents(
2549 acp::TextResourceContents {
2550 mime_type: None,
2551 text: content,
2552 uri: uri.to_uri().to_string(),
2553 },
2554 ),
2555 annotations: None,
2556 })
2557 }
2558 }
2559 }
2560}
2561
2562fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
2563 LanguageModelImage {
2564 source: image_content.data.into(),
2565 // TODO: make this optional?
2566 size: gpui::Size::new(0.into(), 0.into()),
2567 }
2568}