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