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
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_inline_transformation_prompt(
265        &self,
266        user_prompt: String,
267        language_name: Option<&LanguageName>,
268        buffer: BufferSnapshot,
269        range: Range<usize>,
270    ) -> Result<String, RenderError> {
271        let content_type = match language_name.as_ref().map(|l| l.as_ref()) {
272            None | Some("Markdown" | "Plain Text") => "text",
273            Some(_) => "code",
274        };
275
276        const MAX_CTX: usize = 50000;
277        let is_insert = range.is_empty();
278        let mut is_truncated = false;
279
280        let before_range = 0..range.start;
281        let truncated_before = if before_range.len() > MAX_CTX {
282            is_truncated = true;
283            let start = buffer.clip_offset(range.start - MAX_CTX, text::Bias::Right);
284            start..range.start
285        } else {
286            before_range
287        };
288
289        let after_range = range.end..buffer.len();
290        let truncated_after = if after_range.len() > MAX_CTX {
291            is_truncated = true;
292            let end = buffer.clip_offset(range.end + MAX_CTX, text::Bias::Left);
293            range.end..end
294        } else {
295            after_range
296        };
297
298        let mut document_content = String::new();
299        for chunk in buffer.text_for_range(truncated_before) {
300            document_content.push_str(chunk);
301        }
302        if is_insert {
303            document_content.push_str("<insert_here></insert_here>");
304        } else {
305            document_content.push_str("<rewrite_this>\n");
306            for chunk in buffer.text_for_range(range.clone()) {
307                document_content.push_str(chunk);
308            }
309            document_content.push_str("\n</rewrite_this>");
310        }
311        for chunk in buffer.text_for_range(truncated_after) {
312            document_content.push_str(chunk);
313        }
314
315        let rewrite_section = if !is_insert {
316            let mut section = String::new();
317            for chunk in buffer.text_for_range(range.clone()) {
318                section.push_str(chunk);
319            }
320            Some(section)
321        } else {
322            None
323        };
324        let diagnostics = buffer.diagnostics_in_range::<_, Point>(range, false);
325        let diagnostic_errors: Vec<ContentPromptDiagnosticContext> = diagnostics
326            .map(|entry| {
327                let start = entry.range.start;
328                ContentPromptDiagnosticContext {
329                    line_number: (start.row + 1) as usize,
330                    error_message: entry.diagnostic.message.clone(),
331                    code_content: buffer.text_for_range(entry.range.clone()).collect(),
332                }
333            })
334            .collect();
335
336        let context = ContentPromptContext {
337            content_type: content_type.to_string(),
338            language_name: language_name.map(|s| s.to_string()),
339            is_insert,
340            is_truncated,
341            document_content,
342            user_prompt,
343            rewrite_section,
344            diagnostic_errors,
345        };
346        self.handlebars.lock().render("content_prompt", &context)
347    }
348
349    pub fn generate_terminal_assistant_prompt(
350        &self,
351        user_prompt: &str,
352        shell: Option<&str>,
353        working_directory: Option<&str>,
354        latest_output: &[String],
355    ) -> Result<String, RenderError> {
356        let context = TerminalAssistantPromptContext {
357            os: std::env::consts::OS.to_string(),
358            arch: std::env::consts::ARCH.to_string(),
359            shell: shell.map(|s| s.to_string()),
360            working_directory: working_directory.map(|s| s.to_string()),
361            latest_output: latest_output.to_vec(),
362            user_prompt: user_prompt.to_string(),
363        };
364
365        self.handlebars
366            .lock()
367            .render("terminal_assistant_prompt", &context)
368    }
369
370    pub fn generate_suggest_edits_prompt(&self) -> Result<String, RenderError> {
371        self.handlebars.lock().render("suggest_edits", &())
372    }
373}