prompts.rs

  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::{
 18    ResultExt, get_default_system_shell_preferring_bash, rel_path::RelPath, shell::ShellKind,
 19};
 20
 21use crate::UserPromptId;
 22
 23pub const RULES_FILE_NAMES: &[&str] = &[
 24    ".rules",
 25    ".cursorrules",
 26    ".windsurfrules",
 27    ".clinerules",
 28    ".github/copilot-instructions.md",
 29    "CLAUDE.md",
 30    "AGENT.md",
 31    "AGENTS.md",
 32    "GEMINI.md",
 33];
 34
 35#[derive(Default, Debug, Clone, Serialize)]
 36pub struct ProjectContext {
 37    pub worktrees: Vec<WorktreeContext>,
 38    /// Whether any worktree has a rules_file. Provided as a field because handlebars can't do this.
 39    pub has_rules: bool,
 40    pub user_rules: Vec<UserRulesContext>,
 41    /// `!user_rules.is_empty()` - provided as a field because handlebars can't do this.
 42    pub has_user_rules: bool,
 43    pub os: String,
 44    pub arch: String,
 45    pub shell: String,
 46}
 47
 48impl ProjectContext {
 49    pub fn new(worktrees: Vec<WorktreeContext>, default_user_rules: Vec<UserRulesContext>) -> Self {
 50        let has_rules = worktrees
 51            .iter()
 52            .any(|worktree| worktree.rules_file.is_some());
 53        Self {
 54            worktrees,
 55            has_rules,
 56            has_user_rules: !default_user_rules.is_empty(),
 57            user_rules: default_user_rules,
 58            os: std::env::consts::OS.to_string(),
 59            arch: std::env::consts::ARCH.to_string(),
 60            shell: ShellKind::new(&get_default_system_shell_preferring_bash(), cfg!(windows))
 61                .to_string(),
 62        }
 63    }
 64}
 65
 66#[derive(Debug, Clone, Serialize)]
 67pub struct UserRulesContext {
 68    pub uuid: UserPromptId,
 69    pub title: Option<String>,
 70    pub contents: String,
 71}
 72
 73#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
 74pub struct WorktreeContext {
 75    pub root_name: String,
 76    pub abs_path: Arc<Path>,
 77    pub rules_file: Option<RulesFileContext>,
 78}
 79
 80#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
 81pub struct RulesFileContext {
 82    pub path_in_worktree: Arc<RelPath>,
 83    pub text: String,
 84    // This used for opening rules files. TODO: Since it isn't related to prompt templating, this
 85    // should be moved elsewhere.
 86    #[serde(skip)]
 87    pub project_entry_id: usize,
 88}
 89
 90#[derive(Serialize)]
 91pub struct ContentPromptDiagnosticContext {
 92    pub line_number: usize,
 93    pub error_message: String,
 94    pub code_content: String,
 95}
 96
 97#[derive(Serialize)]
 98pub struct ContentPromptContext {
 99    pub content_type: String,
100    pub language_name: Option<String>,
101    pub is_insert: bool,
102    pub is_truncated: bool,
103    pub document_content: String,
104    pub user_prompt: String,
105    pub rewrite_section: Option<String>,
106    pub diagnostic_errors: Vec<ContentPromptDiagnosticContext>,
107}
108
109#[derive(Serialize)]
110pub struct ContentPromptContextV2 {
111    pub content_type: String,
112    pub language_name: Option<String>,
113    pub is_truncated: bool,
114    pub document_content: String,
115    pub rewrite_section: String,
116    pub diagnostic_errors: Vec<ContentPromptDiagnosticContext>,
117}
118
119#[derive(Serialize)]
120pub struct TerminalAssistantPromptContext {
121    pub os: String,
122    pub arch: String,
123    pub shell: Option<String>,
124    pub working_directory: Option<String>,
125    pub latest_output: Vec<String>,
126    pub user_prompt: String,
127}
128
129pub struct PromptLoadingParams<'a> {
130    pub fs: Arc<dyn Fs>,
131    pub repo_path: Option<PathBuf>,
132    pub cx: &'a gpui::App,
133}
134
135pub struct PromptBuilder {
136    handlebars: Arc<Mutex<Handlebars<'static>>>,
137}
138
139impl PromptBuilder {
140    pub fn load(fs: Arc<dyn Fs>, stdout_is_a_pty: bool, cx: &mut App) -> Arc<Self> {
141        Self::new(Some(PromptLoadingParams {
142            fs: fs.clone(),
143            repo_path: stdout_is_a_pty
144                .then(|| std::env::current_dir().log_err())
145                .flatten(),
146            cx,
147        }))
148        .log_err()
149        .map(Arc::new)
150        .unwrap_or_else(|| Arc::new(Self::new(None).unwrap()))
151    }
152
153    pub fn new(loading_params: Option<PromptLoadingParams>) -> Result<Self> {
154        let mut handlebars = Handlebars::new();
155        Self::register_built_in_templates(&mut handlebars)?;
156
157        let handlebars = Arc::new(Mutex::new(handlebars));
158
159        if let Some(params) = loading_params {
160            Self::watch_fs_for_template_overrides(params, handlebars.clone());
161        }
162
163        Ok(Self { handlebars })
164    }
165
166    /// Watches the filesystem for changes to prompt template overrides.
167    ///
168    /// This function sets up a file watcher on the prompt templates directory. It performs
169    /// an initial scan of the directory and registers any existing template overrides.
170    /// Then it continuously monitors for changes, reloading templates as they are
171    /// modified or added.
172    ///
173    /// If the templates directory doesn't exist initially, it waits for it to be created.
174    /// If the directory is removed, it restores the built-in templates and waits for the
175    /// directory to be recreated.
176    ///
177    /// # Arguments
178    ///
179    /// * `params` - A `PromptLoadingParams` struct containing the filesystem, repository path,
180    ///   and application context.
181    /// * `handlebars` - An `Arc<Mutex<Handlebars>>` for registering and updating templates.
182    fn watch_fs_for_template_overrides(
183        params: PromptLoadingParams,
184        handlebars: Arc<Mutex<Handlebars<'static>>>,
185    ) {
186        let templates_dir = paths::prompt_overrides_dir(params.repo_path.as_deref());
187        params.cx.background_spawn(async move {
188            let Some(parent_dir) = templates_dir.parent() else {
189                return;
190            };
191
192            let mut found_dir_once = false;
193            loop {
194                // Check if the templates directory exists and handle its status
195                // If it exists, log its presence and check if it's a symlink
196                // If it doesn't exist:
197                //   - Log that we're using built-in prompts
198                //   - Check if it's a broken symlink and log if so
199                //   - Set up a watcher to detect when it's created
200                // After the first check, set the `found_dir_once` flag
201                // This allows us to avoid logging when looping back around after deleting the prompt overrides directory.
202                let dir_status = params.fs.is_dir(&templates_dir).await;
203                let symlink_status = params.fs.read_link(&templates_dir).await.ok();
204                if dir_status {
205                    let mut log_message = format!("Prompt template overrides directory found at {}", templates_dir.display());
206                    if let Some(target) = symlink_status {
207                        log_message.push_str(" -> ");
208                        log_message.push_str(&target.display().to_string());
209                    }
210                    log::trace!("{}.", log_message);
211                } else {
212                    if !found_dir_once {
213                        log::trace!("No prompt template overrides directory found at {}. Using built-in prompts.", templates_dir.display());
214                        if let Some(target) = symlink_status {
215                            log::trace!("Symlink found pointing to {}, but target is invalid.", target.display());
216                        }
217                    }
218
219                    if params.fs.is_dir(parent_dir).await {
220                        let (mut changes, _watcher) = params.fs.watch(parent_dir, Duration::from_secs(1)).await;
221                        while let Some(changed_paths) = changes.next().await {
222                            if changed_paths.iter().any(|p| &p.path == &templates_dir) {
223                                let mut log_message = format!("Prompt template overrides directory detected at {}", templates_dir.display());
224                                if let Ok(target) = params.fs.read_link(&templates_dir).await {
225                                    log_message.push_str(" -> ");
226                                    log_message.push_str(&target.display().to_string());
227                                }
228                                log::trace!("{}.", log_message);
229                                break;
230                            }
231                        }
232                    } else {
233                        return;
234                    }
235                }
236
237                found_dir_once = true;
238
239                // Initial scan of the prompt overrides directory
240                if let Ok(mut entries) = params.fs.read_dir(&templates_dir).await {
241                    while let Some(Ok(file_path)) = entries.next().await {
242                        if file_path.to_string_lossy().ends_with(".hbs")
243                            && let Ok(content) = params.fs.load(&file_path).await {
244                                let file_name = file_path.file_stem().unwrap().to_string_lossy();
245                                log::debug!("Registering prompt template override: {}", file_name);
246                                handlebars.lock().register_template_string(&file_name, content).log_err();
247                            }
248                    }
249                }
250
251                // Watch both the parent directory and the template overrides directory:
252                // - Monitor the parent directory to detect if the template overrides directory is deleted.
253                // - Monitor the template overrides directory to re-register templates when they change.
254                // Combine both watch streams into a single stream.
255                let (parent_changes, parent_watcher) = params.fs.watch(parent_dir, Duration::from_secs(1)).await;
256                let (changes, watcher) = params.fs.watch(&templates_dir, Duration::from_secs(1)).await;
257                let mut combined_changes = futures::stream::select(changes, parent_changes);
258
259                while let Some(changed_paths) = combined_changes.next().await {
260                    if changed_paths.iter().any(|p| &p.path == &templates_dir)
261                        && !params.fs.is_dir(&templates_dir).await {
262                            log::info!("Prompt template overrides directory removed. Restoring built-in prompt templates.");
263                            Self::register_built_in_templates(&mut handlebars.lock()).log_err();
264                            break;
265                        }
266                    for event in changed_paths {
267                        if event.path.starts_with(&templates_dir) && event.path.extension().is_some_and(|ext| ext == "hbs") {
268                            log::info!("Reloading prompt template override: {}", event.path.display());
269                            if let Some(content) = params.fs.load(&event.path).await.log_err() {
270                                let file_name = event.path.file_stem().unwrap().to_string_lossy();
271                                handlebars.lock().register_template_string(&file_name, content).log_err();
272                            }
273                        }
274                    }
275                }
276
277                drop(watcher);
278                drop(parent_watcher);
279            }
280        })
281            .detach();
282    }
283
284    fn register_built_in_templates(handlebars: &mut Handlebars) -> Result<()> {
285        for path in Assets.list("prompts")? {
286            if let Some(id) = path
287                .split('/')
288                .next_back()
289                .and_then(|s| s.strip_suffix(".hbs"))
290                && let Some(prompt) = Assets.load(path.as_ref()).log_err().flatten()
291            {
292                log::debug!("Registering built-in prompt template: {}", id);
293                let prompt = String::from_utf8_lossy(prompt.as_ref());
294                handlebars.register_template_string(id, LineEnding::normalize_cow(prompt))?
295            }
296        }
297
298        Ok(())
299    }
300
301    pub fn generate_inline_transformation_prompt_tools(
302        &self,
303        language_name: Option<&LanguageName>,
304        buffer: BufferSnapshot,
305        range: Range<usize>,
306    ) -> Result<String, RenderError> {
307        let content_type = match language_name.as_ref().map(|l| l.as_ref()) {
308            None | Some("Markdown" | "Plain Text") => "text",
309            Some(_) => "code",
310        };
311
312        const MAX_CTX: usize = 50000;
313        let mut is_truncated = false;
314
315        let before_range = 0..range.start;
316        let truncated_before = if before_range.len() > MAX_CTX {
317            is_truncated = true;
318            let start = buffer.clip_offset(range.start - MAX_CTX, text::Bias::Right);
319            start..range.start
320        } else {
321            before_range
322        };
323
324        let after_range = range.end..buffer.len();
325        let truncated_after = if after_range.len() > MAX_CTX {
326            is_truncated = true;
327            let end = buffer.clip_offset(range.end + MAX_CTX, text::Bias::Left);
328            range.end..end
329        } else {
330            after_range
331        };
332
333        let mut document_content = String::new();
334        for chunk in buffer.text_for_range(truncated_before) {
335            document_content.push_str(chunk);
336        }
337
338        document_content.push_str("<rewrite_this>\n");
339        for chunk in buffer.text_for_range(range.clone()) {
340            document_content.push_str(chunk);
341        }
342        document_content.push_str("\n</rewrite_this>");
343
344        for chunk in buffer.text_for_range(truncated_after) {
345            document_content.push_str(chunk);
346        }
347
348        let rewrite_section: String = buffer.text_for_range(range.clone()).collect();
349
350        let diagnostics = buffer.diagnostics_in_range::<_, Point>(range, false);
351        let diagnostic_errors: Vec<ContentPromptDiagnosticContext> = diagnostics
352            .map(|entry| {
353                let start = entry.range.start;
354                ContentPromptDiagnosticContext {
355                    line_number: (start.row + 1) as usize,
356                    error_message: entry.diagnostic.message.clone(),
357                    code_content: buffer.text_for_range(entry.range).collect(),
358                }
359            })
360            .collect();
361
362        let context = ContentPromptContextV2 {
363            content_type: content_type.to_string(),
364            language_name: language_name.map(|s| s.to_string()),
365            is_truncated,
366            document_content,
367            rewrite_section,
368            diagnostic_errors,
369        };
370        self.handlebars.lock().render("content_prompt_v2", &context)
371    }
372
373    pub fn generate_inline_transformation_prompt(
374        &self,
375        user_prompt: String,
376        language_name: Option<&LanguageName>,
377        buffer: BufferSnapshot,
378        range: Range<usize>,
379    ) -> Result<String, RenderError> {
380        let content_type = match language_name.as_ref().map(|l| l.as_ref()) {
381            None | Some("Markdown" | "Plain Text") => "text",
382            Some(_) => "code",
383        };
384
385        const MAX_CTX: usize = 50000;
386        let is_insert = range.is_empty();
387        let mut is_truncated = false;
388
389        let before_range = 0..range.start;
390        let truncated_before = if before_range.len() > MAX_CTX {
391            is_truncated = true;
392            let start = buffer.clip_offset(range.start - MAX_CTX, text::Bias::Right);
393            start..range.start
394        } else {
395            before_range
396        };
397
398        let after_range = range.end..buffer.len();
399        let truncated_after = if after_range.len() > MAX_CTX {
400            is_truncated = true;
401            let end = buffer.clip_offset(range.end + MAX_CTX, text::Bias::Left);
402            range.end..end
403        } else {
404            after_range
405        };
406
407        let mut document_content = String::new();
408        for chunk in buffer.text_for_range(truncated_before) {
409            document_content.push_str(chunk);
410        }
411        if is_insert {
412            document_content.push_str("<insert_here></insert_here>");
413        } else {
414            document_content.push_str("<rewrite_this>\n");
415            for chunk in buffer.text_for_range(range.clone()) {
416                document_content.push_str(chunk);
417            }
418            document_content.push_str("\n</rewrite_this>");
419        }
420        for chunk in buffer.text_for_range(truncated_after) {
421            document_content.push_str(chunk);
422        }
423
424        let rewrite_section = if !is_insert {
425            let mut section = String::new();
426            for chunk in buffer.text_for_range(range.clone()) {
427                section.push_str(chunk);
428            }
429            Some(section)
430        } else {
431            None
432        };
433        let diagnostics = buffer.diagnostics_in_range::<_, Point>(range, false);
434        let diagnostic_errors: Vec<ContentPromptDiagnosticContext> = diagnostics
435            .map(|entry| {
436                let start = entry.range.start;
437                ContentPromptDiagnosticContext {
438                    line_number: (start.row + 1) as usize,
439                    error_message: entry.diagnostic.message.clone(),
440                    code_content: buffer.text_for_range(entry.range).collect(),
441                }
442            })
443            .collect();
444
445        let context = ContentPromptContext {
446            content_type: content_type.to_string(),
447            language_name: language_name.map(|s| s.to_string()),
448            is_insert,
449            is_truncated,
450            document_content,
451            user_prompt,
452            rewrite_section,
453            diagnostic_errors,
454        };
455        self.handlebars.lock().render("content_prompt", &context)
456    }
457
458    pub fn generate_terminal_assistant_prompt(
459        &self,
460        user_prompt: &str,
461        shell: Option<&str>,
462        working_directory: Option<&str>,
463        latest_output: &[String],
464    ) -> Result<String, RenderError> {
465        let context = TerminalAssistantPromptContext {
466            os: std::env::consts::OS.to_string(),
467            arch: std::env::consts::ARCH.to_string(),
468            shell: shell.map(|s| s.to_string()),
469            working_directory: working_directory.map(|s| s.to_string()),
470            latest_output: latest_output.to_vec(),
471            user_prompt: user_prompt.to_string(),
472        };
473
474        self.handlebars
475            .lock()
476            .render("terminal_assistant_prompt", &context)
477    }
478}