1use anyhow::Result;
2use assets::Assets;
3use fs::Fs;
4use futures::StreamExt;
5use gpui::{App, AppContext as _, AssetSource};
6use handlebars::{Handlebars, RenderError};
7use language::{BufferSnapshot, LanguageName, Point};
8use parking_lot::Mutex;
9use serde::Serialize;
10use std::{
11 ops::Range,
12 path::{Path, PathBuf},
13 sync::Arc,
14 time::Duration,
15};
16use text::LineEnding;
17use util::ResultExt;
18
19#[derive(Serialize)]
20pub struct AssistantSystemPromptContext {
21 pub worktrees: Vec<WorktreeInfoForSystemPrompt>,
22 pub has_rules: bool,
23}
24
25impl AssistantSystemPromptContext {
26 pub fn new(worktrees: Vec<WorktreeInfoForSystemPrompt>) -> Self {
27 let has_rules = worktrees
28 .iter()
29 .any(|worktree| worktree.rules_file.is_some());
30 Self {
31 worktrees,
32 has_rules,
33 }
34 }
35}
36
37#[derive(Serialize)]
38pub struct WorktreeInfoForSystemPrompt {
39 pub root_name: String,
40 pub abs_path: Arc<Path>,
41 pub rules_file: Option<SystemPromptRulesFile>,
42}
43
44#[derive(Serialize)]
45pub struct SystemPromptRulesFile {
46 pub path_in_worktree: Arc<Path>,
47 pub abs_path: Arc<Path>,
48 pub text: String,
49}
50
51#[derive(Serialize)]
52pub struct ContentPromptDiagnosticContext {
53 pub line_number: usize,
54 pub error_message: String,
55 pub code_content: String,
56}
57
58#[derive(Serialize)]
59pub struct ContentPromptContext {
60 pub content_type: String,
61 pub language_name: Option<String>,
62 pub is_insert: bool,
63 pub is_truncated: bool,
64 pub document_content: String,
65 pub user_prompt: String,
66 pub rewrite_section: Option<String>,
67 pub diagnostic_errors: Vec<ContentPromptDiagnosticContext>,
68}
69
70#[derive(Serialize)]
71pub struct TerminalAssistantPromptContext {
72 pub os: String,
73 pub arch: String,
74 pub shell: Option<String>,
75 pub working_directory: Option<String>,
76 pub latest_output: Vec<String>,
77 pub user_prompt: String,
78}
79
80pub struct PromptLoadingParams<'a> {
81 pub fs: Arc<dyn Fs>,
82 pub repo_path: Option<PathBuf>,
83 pub cx: &'a gpui::App,
84}
85
86pub struct PromptBuilder {
87 handlebars: Arc<Mutex<Handlebars<'static>>>,
88}
89
90impl PromptBuilder {
91 pub fn load(fs: Arc<dyn Fs>, stdout_is_a_pty: bool, cx: &mut App) -> Arc<Self> {
92 Self::new(Some(PromptLoadingParams {
93 fs: fs.clone(),
94 repo_path: stdout_is_a_pty
95 .then(|| std::env::current_dir().log_err())
96 .flatten(),
97 cx,
98 }))
99 .log_err()
100 .map(Arc::new)
101 .unwrap_or_else(|| Arc::new(Self::new(None).unwrap()))
102 }
103
104 pub fn new(loading_params: Option<PromptLoadingParams>) -> Result<Self> {
105 let mut handlebars = Handlebars::new();
106 Self::register_built_in_templates(&mut handlebars)?;
107
108 let handlebars = Arc::new(Mutex::new(handlebars));
109
110 if let Some(params) = loading_params {
111 Self::watch_fs_for_template_overrides(params, handlebars.clone());
112 }
113
114 Ok(Self { handlebars })
115 }
116
117 /// Watches the filesystem for changes to prompt template overrides.
118 ///
119 /// This function sets up a file watcher on the prompt templates directory. It performs
120 /// an initial scan of the directory and registers any existing template overrides.
121 /// Then it continuously monitors for changes, reloading templates as they are
122 /// modified or added.
123 ///
124 /// If the templates directory doesn't exist initially, it waits for it to be created.
125 /// If the directory is removed, it restores the built-in templates and waits for the
126 /// directory to be recreated.
127 ///
128 /// # Arguments
129 ///
130 /// * `params` - A `PromptLoadingParams` struct containing the filesystem, repository path,
131 /// and application context.
132 /// * `handlebars` - An `Arc<Mutex<Handlebars>>` for registering and updating templates.
133 fn watch_fs_for_template_overrides(
134 params: PromptLoadingParams,
135 handlebars: Arc<Mutex<Handlebars<'static>>>,
136 ) {
137 let templates_dir = paths::prompt_overrides_dir(params.repo_path.as_deref());
138 params.cx.background_spawn(async move {
139 let Some(parent_dir) = templates_dir.parent() else {
140 return;
141 };
142
143 let mut found_dir_once = false;
144 loop {
145 // Check if the templates directory exists and handle its status
146 // If it exists, log its presence and check if it's a symlink
147 // If it doesn't exist:
148 // - Log that we're using built-in prompts
149 // - Check if it's a broken symlink and log if so
150 // - Set up a watcher to detect when it's created
151 // After the first check, set the `found_dir_once` flag
152 // This allows us to avoid logging when looping back around after deleting the prompt overrides directory.
153 let dir_status = params.fs.is_dir(&templates_dir).await;
154 let symlink_status = params.fs.read_link(&templates_dir).await.ok();
155 if dir_status {
156 let mut log_message = format!("Prompt template overrides directory found at {}", templates_dir.display());
157 if let Some(target) = symlink_status {
158 log_message.push_str(" -> ");
159 log_message.push_str(&target.display().to_string());
160 }
161 log::info!("{}.", log_message);
162 } else {
163 if !found_dir_once {
164 log::info!("No prompt template overrides directory found at {}. Using built-in prompts.", templates_dir.display());
165 if let Some(target) = symlink_status {
166 log::info!("Symlink found pointing to {}, but target is invalid.", target.display());
167 }
168 }
169
170 if params.fs.is_dir(parent_dir).await {
171 let (mut changes, _watcher) = params.fs.watch(parent_dir, Duration::from_secs(1)).await;
172 while let Some(changed_paths) = changes.next().await {
173 if changed_paths.iter().any(|p| &p.path == &templates_dir) {
174 let mut log_message = format!("Prompt template overrides directory detected at {}", templates_dir.display());
175 if let Ok(target) = params.fs.read_link(&templates_dir).await {
176 log_message.push_str(" -> ");
177 log_message.push_str(&target.display().to_string());
178 }
179 log::info!("{}.", log_message);
180 break;
181 }
182 }
183 } else {
184 return;
185 }
186 }
187
188 found_dir_once = true;
189
190 // Initial scan of the prompt overrides directory
191 if let Ok(mut entries) = params.fs.read_dir(&templates_dir).await {
192 while let Some(Ok(file_path)) = entries.next().await {
193 if file_path.to_string_lossy().ends_with(".hbs") {
194 if let Ok(content) = params.fs.load(&file_path).await {
195 let file_name = file_path.file_stem().unwrap().to_string_lossy();
196 log::debug!("Registering prompt template override: {}", file_name);
197 handlebars.lock().register_template_string(&file_name, content).log_err();
198 }
199 }
200 }
201 }
202
203 // Watch both the parent directory and the template overrides directory:
204 // - Monitor the parent directory to detect if the template overrides directory is deleted.
205 // - Monitor the template overrides directory to re-register templates when they change.
206 // Combine both watch streams into a single stream.
207 let (parent_changes, parent_watcher) = params.fs.watch(parent_dir, Duration::from_secs(1)).await;
208 let (changes, watcher) = params.fs.watch(&templates_dir, Duration::from_secs(1)).await;
209 let mut combined_changes = futures::stream::select(changes, parent_changes);
210
211 while let Some(changed_paths) = combined_changes.next().await {
212 if changed_paths.iter().any(|p| &p.path == &templates_dir) {
213 if !params.fs.is_dir(&templates_dir).await {
214 log::info!("Prompt template overrides directory removed. Restoring built-in prompt templates.");
215 Self::register_built_in_templates(&mut handlebars.lock()).log_err();
216 break;
217 }
218 }
219 for event in changed_paths {
220 if event.path.starts_with(&templates_dir) && event.path.extension().map_or(false, |ext| ext == "hbs") {
221 log::info!("Reloading prompt template override: {}", event.path.display());
222 if let Some(content) = params.fs.load(&event.path).await.log_err() {
223 let file_name = event.path.file_stem().unwrap().to_string_lossy();
224 handlebars.lock().register_template_string(&file_name, content).log_err();
225 }
226 }
227 }
228 }
229
230 drop(watcher);
231 drop(parent_watcher);
232 }
233 })
234 .detach();
235 }
236
237 fn register_built_in_templates(handlebars: &mut Handlebars) -> Result<()> {
238 for path in Assets.list("prompts")? {
239 if let Some(id) = path
240 .split('/')
241 .next_back()
242 .and_then(|s| s.strip_suffix(".hbs"))
243 {
244 if let Some(prompt) = Assets.load(path.as_ref()).log_err().flatten() {
245 log::debug!("Registering built-in prompt template: {}", id);
246 let prompt = String::from_utf8_lossy(prompt.as_ref());
247 handlebars.register_template_string(id, LineEnding::normalize_cow(prompt))?
248 }
249 }
250 }
251
252 Ok(())
253 }
254
255 pub fn generate_assistant_system_prompt(
256 &self,
257 context: &AssistantSystemPromptContext,
258 ) -> Result<String, RenderError> {
259 self.handlebars
260 .lock()
261 .render("assistant_system_prompt", context)
262 }
263
264 pub fn generate_assistant_system_prompt_reminder(&self) -> Result<String, RenderError> {
265 self.handlebars
266 .lock()
267 .render("assistant_system_prompt_reminder", &())
268 }
269
270 pub fn generate_inline_transformation_prompt(
271 &self,
272 user_prompt: String,
273 language_name: Option<&LanguageName>,
274 buffer: BufferSnapshot,
275 range: Range<usize>,
276 ) -> Result<String, RenderError> {
277 let content_type = match language_name.as_ref().map(|l| l.as_ref()) {
278 None | Some("Markdown" | "Plain Text") => "text",
279 Some(_) => "code",
280 };
281
282 const MAX_CTX: usize = 50000;
283 let is_insert = range.is_empty();
284 let mut is_truncated = false;
285
286 let before_range = 0..range.start;
287 let truncated_before = if before_range.len() > MAX_CTX {
288 is_truncated = true;
289 let start = buffer.clip_offset(range.start - MAX_CTX, text::Bias::Right);
290 start..range.start
291 } else {
292 before_range
293 };
294
295 let after_range = range.end..buffer.len();
296 let truncated_after = if after_range.len() > MAX_CTX {
297 is_truncated = true;
298 let end = buffer.clip_offset(range.end + MAX_CTX, text::Bias::Left);
299 range.end..end
300 } else {
301 after_range
302 };
303
304 let mut document_content = String::new();
305 for chunk in buffer.text_for_range(truncated_before) {
306 document_content.push_str(chunk);
307 }
308 if is_insert {
309 document_content.push_str("<insert_here></insert_here>");
310 } else {
311 document_content.push_str("<rewrite_this>\n");
312 for chunk in buffer.text_for_range(range.clone()) {
313 document_content.push_str(chunk);
314 }
315 document_content.push_str("\n</rewrite_this>");
316 }
317 for chunk in buffer.text_for_range(truncated_after) {
318 document_content.push_str(chunk);
319 }
320
321 let rewrite_section = if !is_insert {
322 let mut section = String::new();
323 for chunk in buffer.text_for_range(range.clone()) {
324 section.push_str(chunk);
325 }
326 Some(section)
327 } else {
328 None
329 };
330 let diagnostics = buffer.diagnostics_in_range::<_, Point>(range, false);
331 let diagnostic_errors: Vec<ContentPromptDiagnosticContext> = diagnostics
332 .map(|entry| {
333 let start = entry.range.start;
334 ContentPromptDiagnosticContext {
335 line_number: (start.row + 1) as usize,
336 error_message: entry.diagnostic.message.clone(),
337 code_content: buffer.text_for_range(entry.range.clone()).collect(),
338 }
339 })
340 .collect();
341
342 let context = ContentPromptContext {
343 content_type: content_type.to_string(),
344 language_name: language_name.map(|s| s.to_string()),
345 is_insert,
346 is_truncated,
347 document_content,
348 user_prompt,
349 rewrite_section,
350 diagnostic_errors,
351 };
352 self.handlebars.lock().render("content_prompt", &context)
353 }
354
355 pub fn generate_terminal_assistant_prompt(
356 &self,
357 user_prompt: &str,
358 shell: Option<&str>,
359 working_directory: Option<&str>,
360 latest_output: &[String],
361 ) -> Result<String, RenderError> {
362 let context = TerminalAssistantPromptContext {
363 os: std::env::consts::OS.to_string(),
364 arch: std::env::consts::ARCH.to_string(),
365 shell: shell.map(|s| s.to_string()),
366 working_directory: working_directory.map(|s| s.to_string()),
367 latest_output: latest_output.to_vec(),
368 user_prompt: user_prompt.to_string(),
369 };
370
371 self.handlebars
372 .lock()
373 .render("terminal_assistant_prompt", &context)
374 }
375
376 pub fn generate_suggest_edits_prompt(&self) -> Result<String, RenderError> {
377 self.handlebars.lock().render("suggest_edits", &())
378 }
379}