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::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<RulesFile>,
 42}
 43
 44#[derive(Serialize)]
 45pub struct RulesFile {
 46    pub rel_path: 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.split('/').last().and_then(|s| s.strip_suffix(".hbs")) {
240                if let Some(prompt) = Assets.load(path.as_ref()).log_err().flatten() {
241                    log::debug!("Registering built-in prompt template: {}", id);
242                    let prompt = String::from_utf8_lossy(prompt.as_ref());
243                    handlebars.register_template_string(id, LineEnding::normalize_cow(prompt))?
244                }
245            }
246        }
247
248        Ok(())
249    }
250
251    pub fn generate_assistant_system_prompt(
252        &self,
253        context: &AssistantSystemPromptContext,
254    ) -> Result<String, RenderError> {
255        self.handlebars
256            .lock()
257            .render("assistant_system_prompt", context)
258    }
259
260    pub fn generate_inline_transformation_prompt(
261        &self,
262        user_prompt: String,
263        language_name: Option<&LanguageName>,
264        buffer: BufferSnapshot,
265        range: Range<usize>,
266    ) -> Result<String, RenderError> {
267        let content_type = match language_name.as_ref().map(|l| l.as_ref()) {
268            None | Some("Markdown" | "Plain Text") => "text",
269            Some(_) => "code",
270        };
271
272        const MAX_CTX: usize = 50000;
273        let is_insert = range.is_empty();
274        let mut is_truncated = false;
275
276        let before_range = 0..range.start;
277        let truncated_before = if before_range.len() > MAX_CTX {
278            is_truncated = true;
279            let start = buffer.clip_offset(range.start - MAX_CTX, text::Bias::Right);
280            start..range.start
281        } else {
282            before_range
283        };
284
285        let after_range = range.end..buffer.len();
286        let truncated_after = if after_range.len() > MAX_CTX {
287            is_truncated = true;
288            let end = buffer.clip_offset(range.end + MAX_CTX, text::Bias::Left);
289            range.end..end
290        } else {
291            after_range
292        };
293
294        let mut document_content = String::new();
295        for chunk in buffer.text_for_range(truncated_before) {
296            document_content.push_str(chunk);
297        }
298        if is_insert {
299            document_content.push_str("<insert_here></insert_here>");
300        } else {
301            document_content.push_str("<rewrite_this>\n");
302            for chunk in buffer.text_for_range(range.clone()) {
303                document_content.push_str(chunk);
304            }
305            document_content.push_str("\n</rewrite_this>");
306        }
307        for chunk in buffer.text_for_range(truncated_after) {
308            document_content.push_str(chunk);
309        }
310
311        let rewrite_section = if !is_insert {
312            let mut section = String::new();
313            for chunk in buffer.text_for_range(range.clone()) {
314                section.push_str(chunk);
315            }
316            Some(section)
317        } else {
318            None
319        };
320        let diagnostics = buffer.diagnostics_in_range::<_, Point>(range, false);
321        let diagnostic_errors: Vec<ContentPromptDiagnosticContext> = diagnostics
322            .map(|entry| {
323                let start = entry.range.start;
324                ContentPromptDiagnosticContext {
325                    line_number: (start.row + 1) as usize,
326                    error_message: entry.diagnostic.message.clone(),
327                    code_content: buffer.text_for_range(entry.range.clone()).collect(),
328                }
329            })
330            .collect();
331
332        let context = ContentPromptContext {
333            content_type: content_type.to_string(),
334            language_name: language_name.map(|s| s.to_string()),
335            is_insert,
336            is_truncated,
337            document_content,
338            user_prompt,
339            rewrite_section,
340            diagnostic_errors,
341        };
342        self.handlebars.lock().render("content_prompt", &context)
343    }
344
345    pub fn generate_terminal_assistant_prompt(
346        &self,
347        user_prompt: &str,
348        shell: Option<&str>,
349        working_directory: Option<&str>,
350        latest_output: &[String],
351    ) -> Result<String, RenderError> {
352        let context = TerminalAssistantPromptContext {
353            os: std::env::consts::OS.to_string(),
354            arch: std::env::consts::ARCH.to_string(),
355            shell: shell.map(|s| s.to_string()),
356            working_directory: working_directory.map(|s| s.to_string()),
357            latest_output: latest_output.to_vec(),
358            user_prompt: user_prompt.to_string(),
359        };
360
361        self.handlebars
362            .lock()
363            .render("terminal_assistant_prompt", &context)
364    }
365
366    pub fn generate_suggest_edits_prompt(&self) -> Result<String, RenderError> {
367        self.handlebars.lock().render("suggest_edits", &())
368    }
369}