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