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