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