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