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::new()
623 .image(image)
624 .embedded_context(true)
625 }
626
627 pub fn new(
628 project: Entity<Project>,
629 project_context: Entity<ProjectContext>,
630 context_server_registry: Entity<ContextServerRegistry>,
631 templates: Arc<Templates>,
632 model: Option<Arc<dyn LanguageModel>>,
633 cx: &mut Context<Self>,
634 ) -> Self {
635 let profile_id = AgentSettings::get_global(cx).default_profile.clone();
636 let action_log = cx.new(|_cx| ActionLog::new(project.clone()));
637 let (prompt_capabilities_tx, prompt_capabilities_rx) =
638 watch::channel(Self::prompt_capabilities(model.as_deref()));
639 Self {
640 id: acp::SessionId::new(uuid::Uuid::new_v4().to_string()),
641 prompt_id: PromptId::new(),
642 updated_at: Utc::now(),
643 title: None,
644 pending_title_generation: None,
645 pending_summary_generation: None,
646 summary: None,
647 messages: Vec::new(),
648 user_store: project.read(cx).user_store(),
649 completion_mode: AgentSettings::get_global(cx).preferred_completion_mode,
650 running_turn: None,
651 pending_message: None,
652 tools: BTreeMap::default(),
653 tool_use_limit_reached: false,
654 request_token_usage: HashMap::default(),
655 cumulative_token_usage: TokenUsage::default(),
656 initial_project_snapshot: {
657 let project_snapshot = Self::project_snapshot(project.clone(), cx);
658 cx.foreground_executor()
659 .spawn(async move { Some(project_snapshot.await) })
660 .shared()
661 },
662 context_server_registry,
663 profile_id,
664 project_context,
665 templates,
666 model,
667 summarization_model: None,
668 prompt_capabilities_tx,
669 prompt_capabilities_rx,
670 project,
671 action_log,
672 file_read_times: HashMap::default(),
673 }
674 }
675
676 pub fn id(&self) -> &acp::SessionId {
677 &self.id
678 }
679
680 pub fn replay(
681 &mut self,
682 cx: &mut Context<Self>,
683 ) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {
684 let (tx, rx) = mpsc::unbounded();
685 let stream = ThreadEventStream(tx);
686 for message in &self.messages {
687 match message {
688 Message::User(user_message) => stream.send_user_message(user_message),
689 Message::Agent(assistant_message) => {
690 for content in &assistant_message.content {
691 match content {
692 AgentMessageContent::Text(text) => stream.send_text(text),
693 AgentMessageContent::Thinking { text, .. } => {
694 stream.send_thinking(text)
695 }
696 AgentMessageContent::RedactedThinking(_) => {}
697 AgentMessageContent::ToolUse(tool_use) => {
698 self.replay_tool_call(
699 tool_use,
700 assistant_message.tool_results.get(&tool_use.id),
701 &stream,
702 cx,
703 );
704 }
705 }
706 }
707 }
708 Message::Resume => {}
709 }
710 }
711 rx
712 }
713
714 fn replay_tool_call(
715 &self,
716 tool_use: &LanguageModelToolUse,
717 tool_result: Option<&LanguageModelToolResult>,
718 stream: &ThreadEventStream,
719 cx: &mut Context<Self>,
720 ) {
721 let tool = self.tools.get(tool_use.name.as_ref()).cloned().or_else(|| {
722 self.context_server_registry
723 .read(cx)
724 .servers()
725 .find_map(|(_, tools)| {
726 if let Some(tool) = tools.get(tool_use.name.as_ref()) {
727 Some(tool.clone())
728 } else {
729 None
730 }
731 })
732 });
733
734 let Some(tool) = tool else {
735 stream
736 .0
737 .unbounded_send(Ok(ThreadEvent::ToolCall(
738 acp::ToolCall::new(tool_use.id.to_string(), tool_use.name.to_string())
739 .status(acp::ToolCallStatus::Failed)
740 .raw_input(tool_use.input.clone()),
741 )))
742 .ok();
743 return;
744 };
745
746 let title = tool.initial_title(tool_use.input.clone(), cx);
747 let kind = tool.kind();
748 stream.send_tool_call(
749 &tool_use.id,
750 &tool_use.name,
751 title,
752 kind,
753 tool_use.input.clone(),
754 );
755
756 let output = tool_result
757 .as_ref()
758 .and_then(|result| result.output.clone());
759 if let Some(output) = output.clone() {
760 let tool_event_stream = ToolCallEventStream::new(
761 tool_use.id.clone(),
762 stream.clone(),
763 Some(self.project.read(cx).fs().clone()),
764 );
765 tool.replay(tool_use.input.clone(), output, tool_event_stream, cx)
766 .log_err();
767 }
768
769 stream.update_tool_call_fields(
770 &tool_use.id,
771 acp::ToolCallUpdateFields::new()
772 .status(
773 tool_result
774 .as_ref()
775 .map_or(acp::ToolCallStatus::Failed, |result| {
776 if result.is_error {
777 acp::ToolCallStatus::Failed
778 } else {
779 acp::ToolCallStatus::Completed
780 }
781 }),
782 )
783 .raw_output(output),
784 );
785 }
786
787 pub fn from_db(
788 id: acp::SessionId,
789 db_thread: DbThread,
790 project: Entity<Project>,
791 project_context: Entity<ProjectContext>,
792 context_server_registry: Entity<ContextServerRegistry>,
793 templates: Arc<Templates>,
794 cx: &mut Context<Self>,
795 ) -> Self {
796 let profile_id = db_thread
797 .profile
798 .unwrap_or_else(|| AgentSettings::get_global(cx).default_profile.clone());
799
800 let mut model = LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
801 db_thread
802 .model
803 .and_then(|model| {
804 let model = SelectedModel {
805 provider: model.provider.clone().into(),
806 model: model.model.into(),
807 };
808 registry.select_model(&model, cx)
809 })
810 .or_else(|| registry.default_model())
811 .map(|model| model.model)
812 });
813
814 if model.is_none() {
815 model = Self::resolve_profile_model(&profile_id, cx);
816 }
817 if model.is_none() {
818 model = LanguageModelRegistry::global(cx).update(cx, |registry, _cx| {
819 registry.default_model().map(|model| model.model)
820 });
821 }
822
823 let (prompt_capabilities_tx, prompt_capabilities_rx) =
824 watch::channel(Self::prompt_capabilities(model.as_deref()));
825
826 let action_log = cx.new(|_| ActionLog::new(project.clone()));
827
828 Self {
829 id,
830 prompt_id: PromptId::new(),
831 title: if db_thread.title.is_empty() {
832 None
833 } else {
834 Some(db_thread.title.clone())
835 },
836 pending_title_generation: None,
837 pending_summary_generation: None,
838 summary: db_thread.detailed_summary,
839 messages: db_thread.messages,
840 user_store: project.read(cx).user_store(),
841 completion_mode: db_thread.completion_mode.unwrap_or_default(),
842 running_turn: None,
843 pending_message: None,
844 tools: BTreeMap::default(),
845 tool_use_limit_reached: false,
846 request_token_usage: db_thread.request_token_usage.clone(),
847 cumulative_token_usage: db_thread.cumulative_token_usage,
848 initial_project_snapshot: Task::ready(db_thread.initial_project_snapshot).shared(),
849 context_server_registry,
850 profile_id,
851 project_context,
852 templates,
853 model,
854 summarization_model: None,
855 project,
856 action_log,
857 updated_at: db_thread.updated_at,
858 prompt_capabilities_tx,
859 prompt_capabilities_rx,
860 file_read_times: HashMap::default(),
861 }
862 }
863
864 pub fn to_db(&self, cx: &App) -> Task<DbThread> {
865 let initial_project_snapshot = self.initial_project_snapshot.clone();
866 let mut thread = DbThread {
867 title: self.title(),
868 messages: self.messages.clone(),
869 updated_at: self.updated_at,
870 detailed_summary: self.summary.clone(),
871 initial_project_snapshot: None,
872 cumulative_token_usage: self.cumulative_token_usage,
873 request_token_usage: self.request_token_usage.clone(),
874 model: self.model.as_ref().map(|model| DbLanguageModel {
875 provider: model.provider_id().to_string(),
876 model: model.name().0.to_string(),
877 }),
878 completion_mode: Some(self.completion_mode),
879 profile: Some(self.profile_id.clone()),
880 };
881
882 cx.background_spawn(async move {
883 let initial_project_snapshot = initial_project_snapshot.await;
884 thread.initial_project_snapshot = initial_project_snapshot;
885 thread
886 })
887 }
888
889 /// Create a snapshot of the current project state including git information and unsaved buffers.
890 fn project_snapshot(
891 project: Entity<Project>,
892 cx: &mut Context<Self>,
893 ) -> Task<Arc<ProjectSnapshot>> {
894 let task = project::telemetry_snapshot::TelemetrySnapshot::new(&project, cx);
895 cx.spawn(async move |_, _| {
896 let snapshot = task.await;
897
898 Arc::new(ProjectSnapshot {
899 worktree_snapshots: snapshot.worktree_snapshots,
900 timestamp: Utc::now(),
901 })
902 })
903 }
904
905 pub fn project_context(&self) -> &Entity<ProjectContext> {
906 &self.project_context
907 }
908
909 pub fn project(&self) -> &Entity<Project> {
910 &self.project
911 }
912
913 pub fn action_log(&self) -> &Entity<ActionLog> {
914 &self.action_log
915 }
916
917 pub fn is_empty(&self) -> bool {
918 self.messages.is_empty() && self.title.is_none()
919 }
920
921 pub fn model(&self) -> Option<&Arc<dyn LanguageModel>> {
922 self.model.as_ref()
923 }
924
925 pub fn set_model(&mut self, model: Arc<dyn LanguageModel>, cx: &mut Context<Self>) {
926 let old_usage = self.latest_token_usage();
927 self.model = Some(model);
928 let new_caps = Self::prompt_capabilities(self.model.as_deref());
929 let new_usage = self.latest_token_usage();
930 if old_usage != new_usage {
931 cx.emit(TokenUsageUpdated(new_usage));
932 }
933 self.prompt_capabilities_tx.send(new_caps).log_err();
934 cx.notify()
935 }
936
937 pub fn summarization_model(&self) -> Option<&Arc<dyn LanguageModel>> {
938 self.summarization_model.as_ref()
939 }
940
941 pub fn set_summarization_model(
942 &mut self,
943 model: Option<Arc<dyn LanguageModel>>,
944 cx: &mut Context<Self>,
945 ) {
946 self.summarization_model = model;
947 cx.notify()
948 }
949
950 pub fn completion_mode(&self) -> CompletionMode {
951 self.completion_mode
952 }
953
954 pub fn set_completion_mode(&mut self, mode: CompletionMode, cx: &mut Context<Self>) {
955 let old_usage = self.latest_token_usage();
956 self.completion_mode = mode;
957 let new_usage = self.latest_token_usage();
958 if old_usage != new_usage {
959 cx.emit(TokenUsageUpdated(new_usage));
960 }
961 cx.notify()
962 }
963
964 #[cfg(any(test, feature = "test-support"))]
965 pub fn last_message(&self) -> Option<Message> {
966 if let Some(message) = self.pending_message.clone() {
967 Some(Message::Agent(message))
968 } else {
969 self.messages.last().cloned()
970 }
971 }
972
973 pub fn add_default_tools(
974 &mut self,
975 environment: Rc<dyn ThreadEnvironment>,
976 cx: &mut Context<Self>,
977 ) {
978 let language_registry = self.project.read(cx).languages().clone();
979 self.add_tool(CopyPathTool::new(self.project.clone()));
980 self.add_tool(CreateDirectoryTool::new(self.project.clone()));
981 self.add_tool(DeletePathTool::new(
982 self.project.clone(),
983 self.action_log.clone(),
984 ));
985 self.add_tool(DiagnosticsTool::new(self.project.clone()));
986 self.add_tool(EditFileTool::new(
987 self.project.clone(),
988 cx.weak_entity(),
989 language_registry,
990 Templates::new(),
991 ));
992 self.add_tool(FetchTool::new(self.project.read(cx).client().http_client()));
993 self.add_tool(FindPathTool::new(self.project.clone()));
994 self.add_tool(GrepTool::new(self.project.clone()));
995 self.add_tool(ListDirectoryTool::new(self.project.clone()));
996 self.add_tool(MovePathTool::new(self.project.clone()));
997 self.add_tool(NowTool);
998 self.add_tool(OpenTool::new(self.project.clone()));
999 self.add_tool(ReadFileTool::new(
1000 cx.weak_entity(),
1001 self.project.clone(),
1002 self.action_log.clone(),
1003 ));
1004 self.add_tool(TerminalTool::new(self.project.clone(), environment));
1005 self.add_tool(ThinkingTool);
1006 self.add_tool(WebSearchTool);
1007 }
1008
1009 pub fn add_tool<T: AgentTool>(&mut self, tool: T) {
1010 self.tools.insert(T::name().into(), tool.erase());
1011 }
1012
1013 pub fn remove_tool(&mut self, name: &str) -> bool {
1014 self.tools.remove(name).is_some()
1015 }
1016
1017 pub fn profile(&self) -> &AgentProfileId {
1018 &self.profile_id
1019 }
1020
1021 pub fn set_profile(&mut self, profile_id: AgentProfileId, cx: &mut Context<Self>) {
1022 if self.profile_id == profile_id {
1023 return;
1024 }
1025
1026 self.profile_id = profile_id;
1027
1028 // Swap to the profile's preferred model when available.
1029 if let Some(model) = Self::resolve_profile_model(&self.profile_id, cx) {
1030 self.set_model(model, cx);
1031 }
1032 }
1033
1034 pub fn cancel(&mut self, cx: &mut Context<Self>) {
1035 if let Some(running_turn) = self.running_turn.take() {
1036 running_turn.cancel();
1037 }
1038 self.flush_pending_message(cx);
1039 }
1040
1041 fn update_token_usage(&mut self, update: language_model::TokenUsage, cx: &mut Context<Self>) {
1042 let Some(last_user_message) = self.last_user_message() else {
1043 return;
1044 };
1045
1046 self.request_token_usage
1047 .insert(last_user_message.id.clone(), update);
1048 cx.emit(TokenUsageUpdated(self.latest_token_usage()));
1049 cx.notify();
1050 }
1051
1052 pub fn truncate(&mut self, message_id: UserMessageId, cx: &mut Context<Self>) -> Result<()> {
1053 self.cancel(cx);
1054 let Some(position) = self.messages.iter().position(
1055 |msg| matches!(msg, Message::User(UserMessage { id, .. }) if id == &message_id),
1056 ) else {
1057 return Err(anyhow!("Message not found"));
1058 };
1059
1060 for message in self.messages.drain(position..) {
1061 match message {
1062 Message::User(message) => {
1063 self.request_token_usage.remove(&message.id);
1064 }
1065 Message::Agent(_) | Message::Resume => {}
1066 }
1067 }
1068 self.clear_summary();
1069 cx.notify();
1070 Ok(())
1071 }
1072
1073 pub fn latest_request_token_usage(&self) -> Option<language_model::TokenUsage> {
1074 let last_user_message = self.last_user_message()?;
1075 let tokens = self.request_token_usage.get(&last_user_message.id)?;
1076 Some(*tokens)
1077 }
1078
1079 pub fn latest_token_usage(&self) -> Option<acp_thread::TokenUsage> {
1080 let usage = self.latest_request_token_usage()?;
1081 let model = self.model.clone()?;
1082 Some(acp_thread::TokenUsage {
1083 max_tokens: model.max_token_count_for_mode(self.completion_mode.into()),
1084 used_tokens: usage.total_tokens(),
1085 })
1086 }
1087
1088 /// Look up the active profile and resolve its preferred model if one is configured.
1089 fn resolve_profile_model(
1090 profile_id: &AgentProfileId,
1091 cx: &mut Context<Self>,
1092 ) -> Option<Arc<dyn LanguageModel>> {
1093 let selection = AgentSettings::get_global(cx)
1094 .profiles
1095 .get(profile_id)?
1096 .default_model
1097 .clone()?;
1098 Self::resolve_model_from_selection(&selection, cx)
1099 }
1100
1101 /// Translate a stored model selection into the configured model from the registry.
1102 fn resolve_model_from_selection(
1103 selection: &LanguageModelSelection,
1104 cx: &mut Context<Self>,
1105 ) -> Option<Arc<dyn LanguageModel>> {
1106 let selected = SelectedModel {
1107 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
1108 model: LanguageModelId::from(selection.model.clone()),
1109 };
1110 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
1111 registry
1112 .select_model(&selected, cx)
1113 .map(|configured| configured.model)
1114 })
1115 }
1116
1117 pub fn resume(
1118 &mut self,
1119 cx: &mut Context<Self>,
1120 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1121 self.messages.push(Message::Resume);
1122 cx.notify();
1123
1124 log::debug!("Total messages in thread: {}", self.messages.len());
1125 self.run_turn(cx)
1126 }
1127
1128 /// Sending a message results in the model streaming a response, which could include tool calls.
1129 /// After calling tools, the model will stops and waits for any outstanding tool calls to be completed and their results sent.
1130 /// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
1131 pub fn send<T>(
1132 &mut self,
1133 id: UserMessageId,
1134 content: impl IntoIterator<Item = T>,
1135 cx: &mut Context<Self>,
1136 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
1137 where
1138 T: Into<UserMessageContent>,
1139 {
1140 let model = self.model().context("No language model configured")?;
1141
1142 log::info!("Thread::send called with model: {}", model.name().0);
1143 self.advance_prompt_id();
1144
1145 let content = content.into_iter().map(Into::into).collect::<Vec<_>>();
1146 log::debug!("Thread::send content: {:?}", content);
1147
1148 self.messages
1149 .push(Message::User(UserMessage { id, content }));
1150 cx.notify();
1151
1152 log::debug!("Total messages in thread: {}", self.messages.len());
1153 self.run_turn(cx)
1154 }
1155
1156 #[cfg(feature = "eval")]
1157 pub fn proceed(
1158 &mut self,
1159 cx: &mut Context<Self>,
1160 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1161 self.run_turn(cx)
1162 }
1163
1164 fn run_turn(
1165 &mut self,
1166 cx: &mut Context<Self>,
1167 ) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
1168 self.cancel(cx);
1169
1170 let model = self.model.clone().context("No language model configured")?;
1171 let profile = AgentSettings::get_global(cx)
1172 .profiles
1173 .get(&self.profile_id)
1174 .context("Profile not found")?;
1175 let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
1176 let event_stream = ThreadEventStream(events_tx);
1177 let message_ix = self.messages.len().saturating_sub(1);
1178 self.tool_use_limit_reached = false;
1179 self.clear_summary();
1180 self.running_turn = Some(RunningTurn {
1181 event_stream: event_stream.clone(),
1182 tools: self.enabled_tools(profile, &model, cx),
1183 _task: cx.spawn(async move |this, cx| {
1184 log::debug!("Starting agent turn execution");
1185
1186 let turn_result = Self::run_turn_internal(&this, model, &event_stream, cx).await;
1187 _ = this.update(cx, |this, cx| this.flush_pending_message(cx));
1188
1189 match turn_result {
1190 Ok(()) => {
1191 log::debug!("Turn execution completed");
1192 event_stream.send_stop(acp::StopReason::EndTurn);
1193 }
1194 Err(error) => {
1195 log::error!("Turn execution failed: {:?}", error);
1196 match error.downcast::<CompletionError>() {
1197 Ok(CompletionError::Refusal) => {
1198 event_stream.send_stop(acp::StopReason::Refusal);
1199 _ = this.update(cx, |this, _| this.messages.truncate(message_ix));
1200 }
1201 Ok(CompletionError::MaxTokens) => {
1202 event_stream.send_stop(acp::StopReason::MaxTokens);
1203 }
1204 Ok(CompletionError::Other(error)) | Err(error) => {
1205 event_stream.send_error(error);
1206 }
1207 }
1208 }
1209 }
1210
1211 _ = this.update(cx, |this, _| this.running_turn.take());
1212 }),
1213 });
1214 Ok(events_rx)
1215 }
1216
1217 async fn run_turn_internal(
1218 this: &WeakEntity<Self>,
1219 model: Arc<dyn LanguageModel>,
1220 event_stream: &ThreadEventStream,
1221 cx: &mut AsyncApp,
1222 ) -> Result<()> {
1223 let mut attempt = 0;
1224 let mut intent = CompletionIntent::UserPrompt;
1225 loop {
1226 let request =
1227 this.update(cx, |this, cx| this.build_completion_request(intent, cx))??;
1228
1229 telemetry::event!(
1230 "Agent Thread Completion",
1231 thread_id = this.read_with(cx, |this, _| this.id.to_string())?,
1232 prompt_id = this.read_with(cx, |this, _| this.prompt_id.to_string())?,
1233 model = model.telemetry_id(),
1234 model_provider = model.provider_id().to_string(),
1235 attempt
1236 );
1237
1238 log::debug!("Calling model.stream_completion, attempt {}", attempt);
1239
1240 let (mut events, mut error) = match model.stream_completion(request, cx).await {
1241 Ok(events) => (events, None),
1242 Err(err) => (stream::empty().boxed(), Some(err)),
1243 };
1244 let mut tool_results = FuturesUnordered::new();
1245 while let Some(event) = events.next().await {
1246 log::trace!("Received completion event: {:?}", event);
1247 match event {
1248 Ok(event) => {
1249 tool_results.extend(this.update(cx, |this, cx| {
1250 this.handle_completion_event(event, event_stream, cx)
1251 })??);
1252 }
1253 Err(err) => {
1254 error = Some(err);
1255 break;
1256 }
1257 }
1258 }
1259
1260 let end_turn = tool_results.is_empty();
1261 while let Some(tool_result) = tool_results.next().await {
1262 log::debug!("Tool finished {:?}", tool_result);
1263
1264 event_stream.update_tool_call_fields(
1265 &tool_result.tool_use_id,
1266 acp::ToolCallUpdateFields::new()
1267 .status(if tool_result.is_error {
1268 acp::ToolCallStatus::Failed
1269 } else {
1270 acp::ToolCallStatus::Completed
1271 })
1272 .raw_output(tool_result.output.clone()),
1273 );
1274 this.update(cx, |this, _cx| {
1275 this.pending_message()
1276 .tool_results
1277 .insert(tool_result.tool_use_id.clone(), tool_result);
1278 })?;
1279 }
1280
1281 this.update(cx, |this, cx| {
1282 this.flush_pending_message(cx);
1283 if this.title.is_none() && this.pending_title_generation.is_none() {
1284 this.generate_title(cx);
1285 }
1286 })?;
1287
1288 if let Some(error) = error {
1289 attempt += 1;
1290 let retry = this.update(cx, |this, cx| {
1291 let user_store = this.user_store.read(cx);
1292 this.handle_completion_error(error, attempt, user_store.plan())
1293 })??;
1294 let timer = cx.background_executor().timer(retry.duration);
1295 event_stream.send_retry(retry);
1296 timer.await;
1297 this.update(cx, |this, _cx| {
1298 if let Some(Message::Agent(message)) = this.messages.last() {
1299 if message.tool_results.is_empty() {
1300 intent = CompletionIntent::UserPrompt;
1301 this.messages.push(Message::Resume);
1302 }
1303 }
1304 })?;
1305 } else if this.read_with(cx, |this, _| this.tool_use_limit_reached)? {
1306 return Err(language_model::ToolUseLimitReachedError.into());
1307 } else if end_turn {
1308 return Ok(());
1309 } else {
1310 intent = CompletionIntent::ToolResults;
1311 attempt = 0;
1312 }
1313 }
1314 }
1315
1316 fn handle_completion_error(
1317 &mut self,
1318 error: LanguageModelCompletionError,
1319 attempt: u8,
1320 plan: Option<Plan>,
1321 ) -> Result<acp_thread::RetryStatus> {
1322 let Some(model) = self.model.as_ref() else {
1323 return Err(anyhow!(error));
1324 };
1325
1326 let auto_retry = if model.provider_id() == ZED_CLOUD_PROVIDER_ID {
1327 match plan {
1328 Some(Plan::V2(_)) => true,
1329 Some(Plan::V1(_)) => self.completion_mode == CompletionMode::Burn,
1330 None => false,
1331 }
1332 } else {
1333 true
1334 };
1335
1336 if !auto_retry {
1337 return Err(anyhow!(error));
1338 }
1339
1340 let Some(strategy) = Self::retry_strategy_for(&error) else {
1341 return Err(anyhow!(error));
1342 };
1343
1344 let max_attempts = match &strategy {
1345 RetryStrategy::ExponentialBackoff { max_attempts, .. } => *max_attempts,
1346 RetryStrategy::Fixed { max_attempts, .. } => *max_attempts,
1347 };
1348
1349 if attempt > max_attempts {
1350 return Err(anyhow!(error));
1351 }
1352
1353 let delay = match &strategy {
1354 RetryStrategy::ExponentialBackoff { initial_delay, .. } => {
1355 let delay_secs = initial_delay.as_secs() * 2u64.pow((attempt - 1) as u32);
1356 Duration::from_secs(delay_secs)
1357 }
1358 RetryStrategy::Fixed { delay, .. } => *delay,
1359 };
1360 log::debug!("Retry attempt {attempt} with delay {delay:?}");
1361
1362 Ok(acp_thread::RetryStatus {
1363 last_error: error.to_string().into(),
1364 attempt: attempt as usize,
1365 max_attempts: max_attempts as usize,
1366 started_at: Instant::now(),
1367 duration: delay,
1368 })
1369 }
1370
1371 /// A helper method that's called on every streamed completion event.
1372 /// Returns an optional tool result task, which the main agentic loop will
1373 /// send back to the model when it resolves.
1374 fn handle_completion_event(
1375 &mut self,
1376 event: LanguageModelCompletionEvent,
1377 event_stream: &ThreadEventStream,
1378 cx: &mut Context<Self>,
1379 ) -> Result<Option<Task<LanguageModelToolResult>>> {
1380 log::trace!("Handling streamed completion event: {:?}", event);
1381 use LanguageModelCompletionEvent::*;
1382
1383 match event {
1384 StartMessage { .. } => {
1385 self.flush_pending_message(cx);
1386 self.pending_message = Some(AgentMessage::default());
1387 }
1388 Text(new_text) => self.handle_text_event(new_text, event_stream, cx),
1389 Thinking { text, signature } => {
1390 self.handle_thinking_event(text, signature, event_stream, cx)
1391 }
1392 RedactedThinking { data } => self.handle_redacted_thinking_event(data, cx),
1393 ReasoningDetails(details) => {
1394 let last_message = self.pending_message();
1395 // Store the last non-empty reasoning_details (overwrites earlier ones)
1396 // This ensures we keep the encrypted reasoning with signatures, not the early text reasoning
1397 if let serde_json::Value::Array(ref arr) = details {
1398 if !arr.is_empty() {
1399 last_message.reasoning_details = Some(details);
1400 }
1401 } else {
1402 last_message.reasoning_details = Some(details);
1403 }
1404 }
1405 ToolUse(tool_use) => {
1406 return Ok(self.handle_tool_use_event(tool_use, event_stream, cx));
1407 }
1408 ToolUseJsonParseError {
1409 id,
1410 tool_name,
1411 raw_input,
1412 json_parse_error,
1413 } => {
1414 return Ok(Some(Task::ready(
1415 self.handle_tool_use_json_parse_error_event(
1416 id,
1417 tool_name,
1418 raw_input,
1419 json_parse_error,
1420 ),
1421 )));
1422 }
1423 UsageUpdate(usage) => {
1424 telemetry::event!(
1425 "Agent Thread Completion Usage Updated",
1426 thread_id = self.id.to_string(),
1427 prompt_id = self.prompt_id.to_string(),
1428 model = self.model.as_ref().map(|m| m.telemetry_id()),
1429 model_provider = self.model.as_ref().map(|m| m.provider_id().to_string()),
1430 input_tokens = usage.input_tokens,
1431 output_tokens = usage.output_tokens,
1432 cache_creation_input_tokens = usage.cache_creation_input_tokens,
1433 cache_read_input_tokens = usage.cache_read_input_tokens,
1434 );
1435 self.update_token_usage(usage, cx);
1436 }
1437 UsageUpdated { amount, limit } => {
1438 self.update_model_request_usage(amount, limit, cx);
1439 }
1440 ToolUseLimitReached => {
1441 self.tool_use_limit_reached = true;
1442 }
1443 Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()),
1444 Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()),
1445 Stop(StopReason::ToolUse | StopReason::EndTurn) => {}
1446 Started | Queued { .. } => {}
1447 }
1448
1449 Ok(None)
1450 }
1451
1452 fn handle_text_event(
1453 &mut self,
1454 new_text: String,
1455 event_stream: &ThreadEventStream,
1456 cx: &mut Context<Self>,
1457 ) {
1458 event_stream.send_text(&new_text);
1459
1460 let last_message = self.pending_message();
1461 if let Some(AgentMessageContent::Text(text)) = last_message.content.last_mut() {
1462 text.push_str(&new_text);
1463 } else {
1464 last_message
1465 .content
1466 .push(AgentMessageContent::Text(new_text));
1467 }
1468
1469 cx.notify();
1470 }
1471
1472 fn handle_thinking_event(
1473 &mut self,
1474 new_text: String,
1475 new_signature: Option<String>,
1476 event_stream: &ThreadEventStream,
1477 cx: &mut Context<Self>,
1478 ) {
1479 event_stream.send_thinking(&new_text);
1480
1481 let last_message = self.pending_message();
1482 if let Some(AgentMessageContent::Thinking { text, signature }) =
1483 last_message.content.last_mut()
1484 {
1485 text.push_str(&new_text);
1486 *signature = new_signature.or(signature.take());
1487 } else {
1488 last_message.content.push(AgentMessageContent::Thinking {
1489 text: new_text,
1490 signature: new_signature,
1491 });
1492 }
1493
1494 cx.notify();
1495 }
1496
1497 fn handle_redacted_thinking_event(&mut self, data: String, cx: &mut Context<Self>) {
1498 let last_message = self.pending_message();
1499 last_message
1500 .content
1501 .push(AgentMessageContent::RedactedThinking(data));
1502 cx.notify();
1503 }
1504
1505 fn handle_tool_use_event(
1506 &mut self,
1507 tool_use: LanguageModelToolUse,
1508 event_stream: &ThreadEventStream,
1509 cx: &mut Context<Self>,
1510 ) -> Option<Task<LanguageModelToolResult>> {
1511 cx.notify();
1512
1513 let tool = self.tool(tool_use.name.as_ref());
1514 let mut title = SharedString::from(&tool_use.name);
1515 let mut kind = acp::ToolKind::Other;
1516 if let Some(tool) = tool.as_ref() {
1517 title = tool.initial_title(tool_use.input.clone(), cx);
1518 kind = tool.kind();
1519 }
1520
1521 // Ensure the last message ends in the current tool use
1522 let last_message = self.pending_message();
1523 let push_new_tool_use = last_message.content.last_mut().is_none_or(|content| {
1524 if let AgentMessageContent::ToolUse(last_tool_use) = content {
1525 if last_tool_use.id == tool_use.id {
1526 *last_tool_use = tool_use.clone();
1527 false
1528 } else {
1529 true
1530 }
1531 } else {
1532 true
1533 }
1534 });
1535
1536 if push_new_tool_use {
1537 event_stream.send_tool_call(
1538 &tool_use.id,
1539 &tool_use.name,
1540 title,
1541 kind,
1542 tool_use.input.clone(),
1543 );
1544 last_message
1545 .content
1546 .push(AgentMessageContent::ToolUse(tool_use.clone()));
1547 } else {
1548 event_stream.update_tool_call_fields(
1549 &tool_use.id,
1550 acp::ToolCallUpdateFields::new()
1551 .title(title.as_str())
1552 .kind(kind)
1553 .raw_input(tool_use.input.clone()),
1554 );
1555 }
1556
1557 if !tool_use.is_input_complete {
1558 return None;
1559 }
1560
1561 let Some(tool) = tool else {
1562 let content = format!("No tool named {} exists", tool_use.name);
1563 return Some(Task::ready(LanguageModelToolResult {
1564 content: LanguageModelToolResultContent::Text(Arc::from(content)),
1565 tool_use_id: tool_use.id,
1566 tool_name: tool_use.name,
1567 is_error: true,
1568 output: None,
1569 }));
1570 };
1571
1572 let fs = self.project.read(cx).fs().clone();
1573 let tool_event_stream =
1574 ToolCallEventStream::new(tool_use.id.clone(), event_stream.clone(), Some(fs));
1575 tool_event_stream.update_fields(
1576 acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
1577 );
1578 let supports_images = self.model().is_some_and(|model| model.supports_images());
1579 let tool_result = tool.run(tool_use.input, tool_event_stream, cx);
1580 log::debug!("Running tool {}", tool_use.name);
1581 Some(cx.foreground_executor().spawn(async move {
1582 let tool_result = tool_result.await.and_then(|output| {
1583 if let LanguageModelToolResultContent::Image(_) = &output.llm_output
1584 && !supports_images
1585 {
1586 return Err(anyhow!(
1587 "Attempted to read an image, but this model doesn't support it.",
1588 ));
1589 }
1590 Ok(output)
1591 });
1592
1593 match tool_result {
1594 Ok(output) => LanguageModelToolResult {
1595 tool_use_id: tool_use.id,
1596 tool_name: tool_use.name,
1597 is_error: false,
1598 content: output.llm_output,
1599 output: Some(output.raw_output),
1600 },
1601 Err(error) => LanguageModelToolResult {
1602 tool_use_id: tool_use.id,
1603 tool_name: tool_use.name,
1604 is_error: true,
1605 content: LanguageModelToolResultContent::Text(Arc::from(error.to_string())),
1606 output: Some(error.to_string().into()),
1607 },
1608 }
1609 }))
1610 }
1611
1612 fn handle_tool_use_json_parse_error_event(
1613 &mut self,
1614 tool_use_id: LanguageModelToolUseId,
1615 tool_name: Arc<str>,
1616 raw_input: Arc<str>,
1617 json_parse_error: String,
1618 ) -> LanguageModelToolResult {
1619 let tool_output = format!("Error parsing input JSON: {json_parse_error}");
1620 LanguageModelToolResult {
1621 tool_use_id,
1622 tool_name,
1623 is_error: true,
1624 content: LanguageModelToolResultContent::Text(tool_output.into()),
1625 output: Some(serde_json::Value::String(raw_input.to_string())),
1626 }
1627 }
1628
1629 fn update_model_request_usage(&self, amount: usize, limit: UsageLimit, cx: &mut Context<Self>) {
1630 self.project
1631 .read(cx)
1632 .user_store()
1633 .update(cx, |user_store, cx| {
1634 user_store.update_model_request_usage(
1635 ModelRequestUsage(RequestUsage {
1636 amount: amount as i32,
1637 limit,
1638 }),
1639 cx,
1640 )
1641 });
1642 }
1643
1644 pub fn title(&self) -> SharedString {
1645 self.title.clone().unwrap_or("New Thread".into())
1646 }
1647
1648 pub fn is_generating_summary(&self) -> bool {
1649 self.pending_summary_generation.is_some()
1650 }
1651
1652 pub fn summary(&mut self, cx: &mut Context<Self>) -> Shared<Task<Option<SharedString>>> {
1653 if let Some(summary) = self.summary.as_ref() {
1654 return Task::ready(Some(summary.clone())).shared();
1655 }
1656 if let Some(task) = self.pending_summary_generation.clone() {
1657 return task;
1658 }
1659 let Some(model) = self.summarization_model.clone() else {
1660 log::error!("No summarization model available");
1661 return Task::ready(None).shared();
1662 };
1663 let mut request = LanguageModelRequest {
1664 intent: Some(CompletionIntent::ThreadContextSummarization),
1665 temperature: AgentSettings::temperature_for_model(&model, cx),
1666 ..Default::default()
1667 };
1668
1669 for message in &self.messages {
1670 request.messages.extend(message.to_request());
1671 }
1672
1673 request.messages.push(LanguageModelRequestMessage {
1674 role: Role::User,
1675 content: vec![SUMMARIZE_THREAD_DETAILED_PROMPT.into()],
1676 cache: false,
1677 reasoning_details: None,
1678 });
1679
1680 let task = cx
1681 .spawn(async move |this, cx| {
1682 let mut summary = String::new();
1683 let mut messages = model.stream_completion(request, cx).await.log_err()?;
1684 while let Some(event) = messages.next().await {
1685 let event = event.log_err()?;
1686 let text = match event {
1687 LanguageModelCompletionEvent::Text(text) => text,
1688 LanguageModelCompletionEvent::UsageUpdated { amount, limit } => {
1689 this.update(cx, |thread, cx| {
1690 thread.update_model_request_usage(amount, limit, cx);
1691 })
1692 .ok()?;
1693 continue;
1694 }
1695 _ => continue,
1696 };
1697
1698 let mut lines = text.lines();
1699 summary.extend(lines.next());
1700 }
1701
1702 log::debug!("Setting summary: {}", summary);
1703 let summary = SharedString::from(summary);
1704
1705 this.update(cx, |this, cx| {
1706 this.summary = Some(summary.clone());
1707 this.pending_summary_generation = None;
1708 cx.notify()
1709 })
1710 .ok()?;
1711
1712 Some(summary)
1713 })
1714 .shared();
1715 self.pending_summary_generation = Some(task.clone());
1716 task
1717 }
1718
1719 fn generate_title(&mut self, cx: &mut Context<Self>) {
1720 let Some(model) = self.summarization_model.clone() else {
1721 return;
1722 };
1723
1724 log::debug!(
1725 "Generating title with model: {:?}",
1726 self.summarization_model.as_ref().map(|model| model.name())
1727 );
1728 let mut request = LanguageModelRequest {
1729 intent: Some(CompletionIntent::ThreadSummarization),
1730 temperature: AgentSettings::temperature_for_model(&model, cx),
1731 ..Default::default()
1732 };
1733
1734 for message in &self.messages {
1735 request.messages.extend(message.to_request());
1736 }
1737
1738 request.messages.push(LanguageModelRequestMessage {
1739 role: Role::User,
1740 content: vec![SUMMARIZE_THREAD_PROMPT.into()],
1741 cache: false,
1742 reasoning_details: None,
1743 });
1744 self.pending_title_generation = Some(cx.spawn(async move |this, cx| {
1745 let mut title = String::new();
1746
1747 let generate = async {
1748 let mut messages = model.stream_completion(request, cx).await?;
1749 while let Some(event) = messages.next().await {
1750 let event = event?;
1751 let text = match event {
1752 LanguageModelCompletionEvent::Text(text) => text,
1753 LanguageModelCompletionEvent::UsageUpdated { amount, limit } => {
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 reasoning_details: None,
1991 }];
1992 for message in &self.messages {
1993 messages.extend(message.to_request());
1994 }
1995
1996 if let Some(last_message) = messages.last_mut() {
1997 last_message.cache = true;
1998 }
1999
2000 if let Some(message) = self.pending_message.as_ref() {
2001 messages.extend(message.to_request());
2002 }
2003
2004 messages
2005 }
2006
2007 pub fn to_markdown(&self) -> String {
2008 let mut markdown = String::new();
2009 for (ix, message) in self.messages.iter().enumerate() {
2010 if ix > 0 {
2011 markdown.push('\n');
2012 }
2013 markdown.push_str(&message.to_markdown());
2014 }
2015
2016 if let Some(message) = self.pending_message.as_ref() {
2017 markdown.push('\n');
2018 markdown.push_str(&message.to_markdown());
2019 }
2020
2021 markdown
2022 }
2023
2024 fn advance_prompt_id(&mut self) {
2025 self.prompt_id = PromptId::new();
2026 }
2027
2028 fn retry_strategy_for(error: &LanguageModelCompletionError) -> Option<RetryStrategy> {
2029 use LanguageModelCompletionError::*;
2030 use http_client::StatusCode;
2031
2032 // General strategy here:
2033 // - If retrying won't help (e.g. invalid API key or payload too large), return None so we don't retry at all.
2034 // - If it's a time-based issue (e.g. server overloaded, rate limit exceeded), retry up to 4 times with exponential backoff.
2035 // - If it's an issue that *might* be fixed by retrying (e.g. internal server error), retry up to 3 times.
2036 match error {
2037 HttpResponseError {
2038 status_code: StatusCode::TOO_MANY_REQUESTS,
2039 ..
2040 } => Some(RetryStrategy::ExponentialBackoff {
2041 initial_delay: BASE_RETRY_DELAY,
2042 max_attempts: MAX_RETRY_ATTEMPTS,
2043 }),
2044 ServerOverloaded { retry_after, .. } | RateLimitExceeded { retry_after, .. } => {
2045 Some(RetryStrategy::Fixed {
2046 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2047 max_attempts: MAX_RETRY_ATTEMPTS,
2048 })
2049 }
2050 UpstreamProviderError {
2051 status,
2052 retry_after,
2053 ..
2054 } => match *status {
2055 StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
2056 Some(RetryStrategy::Fixed {
2057 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2058 max_attempts: MAX_RETRY_ATTEMPTS,
2059 })
2060 }
2061 StatusCode::INTERNAL_SERVER_ERROR => Some(RetryStrategy::Fixed {
2062 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2063 // Internal Server Error could be anything, retry up to 3 times.
2064 max_attempts: 3,
2065 }),
2066 status => {
2067 // There is no StatusCode variant for the unofficial HTTP 529 ("The service is overloaded"),
2068 // but we frequently get them in practice. See https://http.dev/529
2069 if status.as_u16() == 529 {
2070 Some(RetryStrategy::Fixed {
2071 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2072 max_attempts: MAX_RETRY_ATTEMPTS,
2073 })
2074 } else {
2075 Some(RetryStrategy::Fixed {
2076 delay: retry_after.unwrap_or(BASE_RETRY_DELAY),
2077 max_attempts: 2,
2078 })
2079 }
2080 }
2081 },
2082 ApiInternalServerError { .. } => Some(RetryStrategy::Fixed {
2083 delay: BASE_RETRY_DELAY,
2084 max_attempts: 3,
2085 }),
2086 ApiReadResponseError { .. }
2087 | HttpSend { .. }
2088 | DeserializeResponse { .. }
2089 | BadRequestFormat { .. } => Some(RetryStrategy::Fixed {
2090 delay: BASE_RETRY_DELAY,
2091 max_attempts: 3,
2092 }),
2093 // Retrying these errors definitely shouldn't help.
2094 HttpResponseError {
2095 status_code:
2096 StatusCode::PAYLOAD_TOO_LARGE | StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED,
2097 ..
2098 }
2099 | AuthenticationError { .. }
2100 | PermissionError { .. }
2101 | NoApiKey { .. }
2102 | ApiEndpointNotFound { .. }
2103 | PromptTooLarge { .. } => None,
2104 // These errors might be transient, so retry them
2105 SerializeRequest { .. } | BuildRequestBody { .. } => Some(RetryStrategy::Fixed {
2106 delay: BASE_RETRY_DELAY,
2107 max_attempts: 1,
2108 }),
2109 // Retry all other 4xx and 5xx errors once.
2110 HttpResponseError { status_code, .. }
2111 if status_code.is_client_error() || status_code.is_server_error() =>
2112 {
2113 Some(RetryStrategy::Fixed {
2114 delay: BASE_RETRY_DELAY,
2115 max_attempts: 3,
2116 })
2117 }
2118 Other(err)
2119 if err.is::<language_model::PaymentRequiredError>()
2120 || err.is::<language_model::ModelRequestLimitReachedError>() =>
2121 {
2122 // Retrying won't help for Payment Required or Model Request Limit errors (where
2123 // the user must upgrade to usage-based billing to get more requests, or else wait
2124 // for a significant amount of time for the request limit to reset).
2125 None
2126 }
2127 // Conservatively assume that any other errors are non-retryable
2128 HttpResponseError { .. } | Other(..) => Some(RetryStrategy::Fixed {
2129 delay: BASE_RETRY_DELAY,
2130 max_attempts: 2,
2131 }),
2132 }
2133 }
2134}
2135
2136struct RunningTurn {
2137 /// Holds the task that handles agent interaction until the end of the turn.
2138 /// Survives across multiple requests as the model performs tool calls and
2139 /// we run tools, report their results.
2140 _task: Task<()>,
2141 /// The current event stream for the running turn. Used to report a final
2142 /// cancellation event if we cancel the turn.
2143 event_stream: ThreadEventStream,
2144 /// The tools that were enabled for this turn.
2145 tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
2146}
2147
2148impl RunningTurn {
2149 fn cancel(self) {
2150 log::debug!("Cancelling in progress turn");
2151 self.event_stream.send_canceled();
2152 }
2153}
2154
2155pub struct TokenUsageUpdated(pub Option<acp_thread::TokenUsage>);
2156
2157impl EventEmitter<TokenUsageUpdated> for Thread {}
2158
2159pub struct TitleUpdated;
2160
2161impl EventEmitter<TitleUpdated> for Thread {}
2162
2163pub trait AgentTool
2164where
2165 Self: 'static + Sized,
2166{
2167 type Input: for<'de> Deserialize<'de> + Serialize + JsonSchema;
2168 type Output: for<'de> Deserialize<'de> + Serialize + Into<LanguageModelToolResultContent>;
2169
2170 fn name() -> &'static str;
2171
2172 fn description() -> SharedString {
2173 let schema = schemars::schema_for!(Self::Input);
2174 SharedString::new(
2175 schema
2176 .get("description")
2177 .and_then(|description| description.as_str())
2178 .unwrap_or_default(),
2179 )
2180 }
2181
2182 fn kind() -> acp::ToolKind;
2183
2184 /// The initial tool title to display. Can be updated during the tool run.
2185 fn initial_title(
2186 &self,
2187 input: Result<Self::Input, serde_json::Value>,
2188 cx: &mut App,
2189 ) -> SharedString;
2190
2191 /// Returns the JSON schema that describes the tool's input.
2192 fn input_schema(format: LanguageModelToolSchemaFormat) -> Schema {
2193 language_model::tool_schema::root_schema_for::<Self::Input>(format)
2194 }
2195
2196 /// Some tools rely on a provider for the underlying billing or other reasons.
2197 /// Allow the tool to check if they are compatible, or should be filtered out.
2198 fn supports_provider(_provider: &LanguageModelProviderId) -> bool {
2199 true
2200 }
2201
2202 /// Runs the tool with the provided input.
2203 fn run(
2204 self: Arc<Self>,
2205 input: Self::Input,
2206 event_stream: ToolCallEventStream,
2207 cx: &mut App,
2208 ) -> Task<Result<Self::Output>>;
2209
2210 /// Emits events for a previous execution of the tool.
2211 fn replay(
2212 &self,
2213 _input: Self::Input,
2214 _output: Self::Output,
2215 _event_stream: ToolCallEventStream,
2216 _cx: &mut App,
2217 ) -> Result<()> {
2218 Ok(())
2219 }
2220
2221 fn erase(self) -> Arc<dyn AnyAgentTool> {
2222 Arc::new(Erased(Arc::new(self)))
2223 }
2224}
2225
2226pub struct Erased<T>(T);
2227
2228pub struct AgentToolOutput {
2229 pub llm_output: LanguageModelToolResultContent,
2230 pub raw_output: serde_json::Value,
2231}
2232
2233pub trait AnyAgentTool {
2234 fn name(&self) -> SharedString;
2235 fn description(&self) -> SharedString;
2236 fn kind(&self) -> acp::ToolKind;
2237 fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString;
2238 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value>;
2239 fn supports_provider(&self, _provider: &LanguageModelProviderId) -> bool {
2240 true
2241 }
2242 fn run(
2243 self: Arc<Self>,
2244 input: serde_json::Value,
2245 event_stream: ToolCallEventStream,
2246 cx: &mut App,
2247 ) -> Task<Result<AgentToolOutput>>;
2248 fn replay(
2249 &self,
2250 input: serde_json::Value,
2251 output: serde_json::Value,
2252 event_stream: ToolCallEventStream,
2253 cx: &mut App,
2254 ) -> Result<()>;
2255}
2256
2257impl<T> AnyAgentTool for Erased<Arc<T>>
2258where
2259 T: AgentTool,
2260{
2261 fn name(&self) -> SharedString {
2262 T::name().into()
2263 }
2264
2265 fn description(&self) -> SharedString {
2266 T::description()
2267 }
2268
2269 fn kind(&self) -> agent_client_protocol::ToolKind {
2270 T::kind()
2271 }
2272
2273 fn initial_title(&self, input: serde_json::Value, _cx: &mut App) -> SharedString {
2274 let parsed_input = serde_json::from_value(input.clone()).map_err(|_| input);
2275 self.0.initial_title(parsed_input, _cx)
2276 }
2277
2278 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
2279 let mut json = serde_json::to_value(T::input_schema(format))?;
2280 language_model::tool_schema::adapt_schema_to_format(&mut json, format)?;
2281 Ok(json)
2282 }
2283
2284 fn supports_provider(&self, provider: &LanguageModelProviderId) -> bool {
2285 T::supports_provider(provider)
2286 }
2287
2288 fn run(
2289 self: Arc<Self>,
2290 input: serde_json::Value,
2291 event_stream: ToolCallEventStream,
2292 cx: &mut App,
2293 ) -> Task<Result<AgentToolOutput>> {
2294 cx.spawn(async move |cx| {
2295 let input = serde_json::from_value(input)?;
2296 let output = cx
2297 .update(|cx| self.0.clone().run(input, event_stream, cx))?
2298 .await?;
2299 let raw_output = serde_json::to_value(&output)?;
2300 Ok(AgentToolOutput {
2301 llm_output: output.into(),
2302 raw_output,
2303 })
2304 })
2305 }
2306
2307 fn replay(
2308 &self,
2309 input: serde_json::Value,
2310 output: serde_json::Value,
2311 event_stream: ToolCallEventStream,
2312 cx: &mut App,
2313 ) -> Result<()> {
2314 let input = serde_json::from_value(input)?;
2315 let output = serde_json::from_value(output)?;
2316 self.0.replay(input, output, event_stream, cx)
2317 }
2318}
2319
2320#[derive(Clone)]
2321struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);
2322
2323impl ThreadEventStream {
2324 fn send_user_message(&self, message: &UserMessage) {
2325 self.0
2326 .unbounded_send(Ok(ThreadEvent::UserMessage(message.clone())))
2327 .ok();
2328 }
2329
2330 fn send_text(&self, text: &str) {
2331 self.0
2332 .unbounded_send(Ok(ThreadEvent::AgentText(text.to_string())))
2333 .ok();
2334 }
2335
2336 fn send_thinking(&self, text: &str) {
2337 self.0
2338 .unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string())))
2339 .ok();
2340 }
2341
2342 fn send_tool_call(
2343 &self,
2344 id: &LanguageModelToolUseId,
2345 tool_name: &str,
2346 title: SharedString,
2347 kind: acp::ToolKind,
2348 input: serde_json::Value,
2349 ) {
2350 self.0
2351 .unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(
2352 id,
2353 tool_name,
2354 title.to_string(),
2355 kind,
2356 input,
2357 ))))
2358 .ok();
2359 }
2360
2361 fn initial_tool_call(
2362 id: &LanguageModelToolUseId,
2363 tool_name: &str,
2364 title: String,
2365 kind: acp::ToolKind,
2366 input: serde_json::Value,
2367 ) -> acp::ToolCall {
2368 acp::ToolCall::new(id.to_string(), title)
2369 .kind(kind)
2370 .raw_input(input)
2371 .meta(acp::Meta::from_iter([(
2372 "tool_name".into(),
2373 tool_name.into(),
2374 )]))
2375 }
2376
2377 fn update_tool_call_fields(
2378 &self,
2379 tool_use_id: &LanguageModelToolUseId,
2380 fields: acp::ToolCallUpdateFields,
2381 ) {
2382 self.0
2383 .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
2384 acp::ToolCallUpdate::new(tool_use_id.to_string(), fields).into(),
2385 )))
2386 .ok();
2387 }
2388
2389 fn send_retry(&self, status: acp_thread::RetryStatus) {
2390 self.0.unbounded_send(Ok(ThreadEvent::Retry(status))).ok();
2391 }
2392
2393 fn send_stop(&self, reason: acp::StopReason) {
2394 self.0.unbounded_send(Ok(ThreadEvent::Stop(reason))).ok();
2395 }
2396
2397 fn send_canceled(&self) {
2398 self.0
2399 .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))
2400 .ok();
2401 }
2402
2403 fn send_error(&self, error: impl Into<anyhow::Error>) {
2404 self.0.unbounded_send(Err(error.into())).ok();
2405 }
2406}
2407
2408#[derive(Clone)]
2409pub struct ToolCallEventStream {
2410 tool_use_id: LanguageModelToolUseId,
2411 stream: ThreadEventStream,
2412 fs: Option<Arc<dyn Fs>>,
2413}
2414
2415impl ToolCallEventStream {
2416 #[cfg(any(test, feature = "test-support"))]
2417 pub fn test() -> (Self, ToolCallEventStreamReceiver) {
2418 let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();
2419
2420 let stream = ToolCallEventStream::new("test_id".into(), ThreadEventStream(events_tx), None);
2421
2422 (stream, ToolCallEventStreamReceiver(events_rx))
2423 }
2424
2425 fn new(
2426 tool_use_id: LanguageModelToolUseId,
2427 stream: ThreadEventStream,
2428 fs: Option<Arc<dyn Fs>>,
2429 ) -> Self {
2430 Self {
2431 tool_use_id,
2432 stream,
2433 fs,
2434 }
2435 }
2436
2437 pub fn update_fields(&self, fields: acp::ToolCallUpdateFields) {
2438 self.stream
2439 .update_tool_call_fields(&self.tool_use_id, fields);
2440 }
2441
2442 pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {
2443 self.stream
2444 .0
2445 .unbounded_send(Ok(ThreadEvent::ToolCallUpdate(
2446 acp_thread::ToolCallUpdateDiff {
2447 id: acp::ToolCallId::new(self.tool_use_id.to_string()),
2448 diff,
2449 }
2450 .into(),
2451 )))
2452 .ok();
2453 }
2454
2455 pub fn authorize(&self, title: impl Into<String>, cx: &mut App) -> Task<Result<()>> {
2456 if agent_settings::AgentSettings::get_global(cx).always_allow_tool_actions {
2457 return Task::ready(Ok(()));
2458 }
2459
2460 let (response_tx, response_rx) = oneshot::channel();
2461 self.stream
2462 .0
2463 .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(
2464 ToolCallAuthorization {
2465 tool_call: acp::ToolCallUpdate::new(
2466 self.tool_use_id.to_string(),
2467 acp::ToolCallUpdateFields::new().title(title.into()),
2468 ),
2469 options: vec![
2470 acp::PermissionOption::new(
2471 acp::PermissionOptionId::new("always_allow"),
2472 "Always Allow",
2473 acp::PermissionOptionKind::AllowAlways,
2474 ),
2475 acp::PermissionOption::new(
2476 acp::PermissionOptionId::new("allow"),
2477 "Allow",
2478 acp::PermissionOptionKind::AllowOnce,
2479 ),
2480 acp::PermissionOption::new(
2481 acp::PermissionOptionId::new("deny"),
2482 "Deny",
2483 acp::PermissionOptionKind::RejectOnce,
2484 ),
2485 ],
2486 response: response_tx,
2487 },
2488 )))
2489 .ok();
2490 let fs = self.fs.clone();
2491 cx.spawn(async move |cx| match response_rx.await?.0.as_ref() {
2492 "always_allow" => {
2493 if let Some(fs) = fs.clone() {
2494 cx.update(|cx| {
2495 update_settings_file(fs, cx, |settings, _| {
2496 settings
2497 .agent
2498 .get_or_insert_default()
2499 .set_always_allow_tool_actions(true);
2500 });
2501 })?;
2502 }
2503
2504 Ok(())
2505 }
2506 "allow" => Ok(()),
2507 _ => Err(anyhow!("Permission to run tool denied by user")),
2508 })
2509 }
2510}
2511
2512#[cfg(any(test, feature = "test-support"))]
2513pub struct ToolCallEventStreamReceiver(mpsc::UnboundedReceiver<Result<ThreadEvent>>);
2514
2515#[cfg(any(test, feature = "test-support"))]
2516impl ToolCallEventStreamReceiver {
2517 pub async fn expect_authorization(&mut self) -> ToolCallAuthorization {
2518 let event = self.0.next().await;
2519 if let Some(Ok(ThreadEvent::ToolCallAuthorization(auth))) = event {
2520 auth
2521 } else {
2522 panic!("Expected ToolCallAuthorization but got: {:?}", event);
2523 }
2524 }
2525
2526 pub async fn expect_update_fields(&mut self) -> acp::ToolCallUpdateFields {
2527 let event = self.0.next().await;
2528 if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateFields(
2529 update,
2530 )))) = event
2531 {
2532 update.fields
2533 } else {
2534 panic!("Expected update fields but got: {:?}", event);
2535 }
2536 }
2537
2538 pub async fn expect_diff(&mut self) -> Entity<acp_thread::Diff> {
2539 let event = self.0.next().await;
2540 if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateDiff(
2541 update,
2542 )))) = event
2543 {
2544 update.diff
2545 } else {
2546 panic!("Expected diff but got: {:?}", event);
2547 }
2548 }
2549
2550 pub async fn expect_terminal(&mut self) -> Entity<acp_thread::Terminal> {
2551 let event = self.0.next().await;
2552 if let Some(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdate::UpdateTerminal(
2553 update,
2554 )))) = event
2555 {
2556 update.terminal
2557 } else {
2558 panic!("Expected terminal but got: {:?}", event);
2559 }
2560 }
2561}
2562
2563#[cfg(any(test, feature = "test-support"))]
2564impl std::ops::Deref for ToolCallEventStreamReceiver {
2565 type Target = mpsc::UnboundedReceiver<Result<ThreadEvent>>;
2566
2567 fn deref(&self) -> &Self::Target {
2568 &self.0
2569 }
2570}
2571
2572#[cfg(any(test, feature = "test-support"))]
2573impl std::ops::DerefMut for ToolCallEventStreamReceiver {
2574 fn deref_mut(&mut self) -> &mut Self::Target {
2575 &mut self.0
2576 }
2577}
2578
2579impl From<&str> for UserMessageContent {
2580 fn from(text: &str) -> Self {
2581 Self::Text(text.into())
2582 }
2583}
2584
2585impl UserMessageContent {
2586 pub fn from_content_block(value: acp::ContentBlock, path_style: PathStyle) -> Self {
2587 match value {
2588 acp::ContentBlock::Text(text_content) => Self::Text(text_content.text),
2589 acp::ContentBlock::Image(image_content) => Self::Image(convert_image(image_content)),
2590 acp::ContentBlock::Audio(_) => {
2591 // TODO
2592 Self::Text("[audio]".to_string())
2593 }
2594 acp::ContentBlock::ResourceLink(resource_link) => {
2595 match MentionUri::parse(&resource_link.uri, path_style) {
2596 Ok(uri) => Self::Mention {
2597 uri,
2598 content: String::new(),
2599 },
2600 Err(err) => {
2601 log::error!("Failed to parse mention link: {}", err);
2602 Self::Text(format!("[{}]({})", resource_link.name, resource_link.uri))
2603 }
2604 }
2605 }
2606 acp::ContentBlock::Resource(resource) => match resource.resource {
2607 acp::EmbeddedResourceResource::TextResourceContents(resource) => {
2608 match MentionUri::parse(&resource.uri, path_style) {
2609 Ok(uri) => Self::Mention {
2610 uri,
2611 content: resource.text,
2612 },
2613 Err(err) => {
2614 log::error!("Failed to parse mention link: {}", err);
2615 Self::Text(
2616 MarkdownCodeBlock {
2617 tag: &resource.uri,
2618 text: &resource.text,
2619 }
2620 .to_string(),
2621 )
2622 }
2623 }
2624 }
2625 acp::EmbeddedResourceResource::BlobResourceContents(_) => {
2626 // TODO
2627 Self::Text("[blob]".to_string())
2628 }
2629 other => {
2630 log::warn!("Unexpected content type: {:?}", other);
2631 Self::Text("[unknown]".to_string())
2632 }
2633 },
2634 other => {
2635 log::warn!("Unexpected content type: {:?}", other);
2636 Self::Text("[unknown]".to_string())
2637 }
2638 }
2639 }
2640}
2641
2642impl From<UserMessageContent> for acp::ContentBlock {
2643 fn from(content: UserMessageContent) -> Self {
2644 match content {
2645 UserMessageContent::Text(text) => text.into(),
2646 UserMessageContent::Image(image) => {
2647 acp::ContentBlock::Image(acp::ImageContent::new(image.source, "image/png"))
2648 }
2649 UserMessageContent::Mention { uri, content } => acp::ContentBlock::Resource(
2650 acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(
2651 acp::TextResourceContents::new(content, uri.to_uri().to_string()),
2652 )),
2653 ),
2654 }
2655 }
2656}
2657
2658fn convert_image(image_content: acp::ImageContent) -> LanguageModelImage {
2659 LanguageModelImage {
2660 source: image_content.data.into(),
2661 // TODO: make this optional?
2662 size: gpui::Size::new(0.into(), 0.into()),
2663 }
2664}