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