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: Option<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 is_insert = range.is_empty();
314        let mut is_truncated = false;
315
316        let before_range = 0..range.start;
317        let truncated_before = if before_range.len() > MAX_CTX {
318            is_truncated = true;
319            let start = buffer.clip_offset(range.start - MAX_CTX, text::Bias::Right);
320            start..range.start
321        } else {
322            before_range
323        };
324
325        let after_range = range.end..buffer.len();
326        let truncated_after = if after_range.len() > MAX_CTX {
327            is_truncated = true;
328            let end = buffer.clip_offset(range.end + MAX_CTX, text::Bias::Left);
329            range.end..end
330        } else {
331            after_range
332        };
333
334        let mut document_content = String::new();
335        for chunk in buffer.text_for_range(truncated_before) {
336            document_content.push_str(chunk);
337        }
338        if is_insert {
339            document_content.push_str("<insert_here></insert_here>");
340        } else {
341            document_content.push_str("<rewrite_this>\n");
342            for chunk in buffer.text_for_range(range.clone()) {
343                document_content.push_str(chunk);
344            }
345            document_content.push_str("\n</rewrite_this>");
346        }
347        for chunk in buffer.text_for_range(truncated_after) {
348            document_content.push_str(chunk);
349        }
350
351        let rewrite_section = if !is_insert {
352            let mut section = String::new();
353            for chunk in buffer.text_for_range(range.clone()) {
354                section.push_str(chunk);
355            }
356            Some(section)
357        } else {
358            None
359        };
360        let diagnostics = buffer.diagnostics_in_range::<_, Point>(range, false);
361        let diagnostic_errors: Vec<ContentPromptDiagnosticContext> = diagnostics
362            .map(|entry| {
363                let start = entry.range.start;
364                ContentPromptDiagnosticContext {
365                    line_number: (start.row + 1) as usize,
366                    error_message: entry.diagnostic.message.clone(),
367                    code_content: buffer.text_for_range(entry.range).collect(),
368                }
369            })
370            .collect();
371
372        let context = ContentPromptContextV2 {
373            content_type: content_type.to_string(),
374            language_name: language_name.map(|s| s.to_string()),
375            is_truncated,
376            document_content,
377            rewrite_section,
378            diagnostic_errors,
379        };
380        self.handlebars.lock().render("content_prompt_v2", &context)
381    }
382
383    pub fn generate_inline_transformation_prompt(
384        &self,
385        user_prompt: String,
386        language_name: Option<&LanguageName>,
387        buffer: BufferSnapshot,
388        range: Range<usize>,
389    ) -> Result<String, RenderError> {
390        let content_type = match language_name.as_ref().map(|l| l.as_ref()) {
391            None | Some("Markdown" | "Plain Text") => "text",
392            Some(_) => "code",
393        };
394
395        const MAX_CTX: usize = 50000;
396        let is_insert = range.is_empty();
397        let mut is_truncated = false;
398
399        let before_range = 0..range.start;
400        let truncated_before = if before_range.len() > MAX_CTX {
401            is_truncated = true;
402            let start = buffer.clip_offset(range.start - MAX_CTX, text::Bias::Right);
403            start..range.start
404        } else {
405            before_range
406        };
407
408        let after_range = range.end..buffer.len();
409        let truncated_after = if after_range.len() > MAX_CTX {
410            is_truncated = true;
411            let end = buffer.clip_offset(range.end + MAX_CTX, text::Bias::Left);
412            range.end..end
413        } else {
414            after_range
415        };
416
417        let mut document_content = String::new();
418        for chunk in buffer.text_for_range(truncated_before) {
419            document_content.push_str(chunk);
420        }
421        if is_insert {
422            document_content.push_str("<insert_here></insert_here>");
423        } else {
424            document_content.push_str("<rewrite_this>\n");
425            for chunk in buffer.text_for_range(range.clone()) {
426                document_content.push_str(chunk);
427            }
428            document_content.push_str("\n</rewrite_this>");
429        }
430        for chunk in buffer.text_for_range(truncated_after) {
431            document_content.push_str(chunk);
432        }
433
434        let rewrite_section = if !is_insert {
435            let mut section = String::new();
436            for chunk in buffer.text_for_range(range.clone()) {
437                section.push_str(chunk);
438            }
439            Some(section)
440        } else {
441            None
442        };
443        let diagnostics = buffer.diagnostics_in_range::<_, Point>(range, false);
444        let diagnostic_errors: Vec<ContentPromptDiagnosticContext> = diagnostics
445            .map(|entry| {
446                let start = entry.range.start;
447                ContentPromptDiagnosticContext {
448                    line_number: (start.row + 1) as usize,
449                    error_message: entry.diagnostic.message.clone(),
450                    code_content: buffer.text_for_range(entry.range).collect(),
451                }
452            })
453            .collect();
454
455        let context = ContentPromptContext {
456            content_type: content_type.to_string(),
457            language_name: language_name.map(|s| s.to_string()),
458            is_insert,
459            is_truncated,
460            document_content,
461            user_prompt,
462            rewrite_section,
463            diagnostic_errors,
464        };
465        self.handlebars.lock().render("content_prompt", &context)
466    }
467
468    pub fn generate_terminal_assistant_prompt(
469        &self,
470        user_prompt: &str,
471        shell: Option<&str>,
472        working_directory: Option<&str>,
473        latest_output: &[String],
474    ) -> Result<String, RenderError> {
475        let context = TerminalAssistantPromptContext {
476            os: std::env::consts::OS.to_string(),
477            arch: std::env::consts::ARCH.to_string(),
478            shell: shell.map(|s| s.to_string()),
479            working_directory: working_directory.map(|s| s.to_string()),
480            latest_output: latest_output.to_vec(),
481            user_prompt: user_prompt.to_string(),
482        };
483
484        self.handlebars
485            .lock()
486            .render("terminal_assistant_prompt", &context)
487    }
488}