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