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