1use crate::{
2 FormatPromptArgs, PredictionProvider,
3 example::{ActualCursor, Example, ExamplePrompt},
4 headless::EpAppState,
5 progress::{ExampleProgress, Step},
6 retrieve_context::run_context_retrieval,
7};
8use anyhow::{Context as _, Result, anyhow};
9use edit_prediction::udiff;
10use gpui::AsyncApp;
11use similar::DiffableStr;
12use std::ops::Range;
13use std::sync::Arc;
14use zeta_prompt::{
15 ZetaFormat, encode_patch_as_output_for_format, excerpt_range_for_format, format_zeta_prompt,
16 output_end_marker_for_format, resolve_cursor_region,
17};
18
19pub async fn run_format_prompt(
20 example: &mut Example,
21 args: &FormatPromptArgs,
22 app_state: Arc<EpAppState>,
23 example_progress: &ExampleProgress,
24 cx: AsyncApp,
25) -> Result<()> {
26 run_context_retrieval(example, app_state.clone(), example_progress, cx.clone()).await?;
27
28 let step_progress = example_progress.start(Step::FormatPrompt);
29
30 let prompt_inputs = example
31 .prompt_inputs
32 .as_ref()
33 .context("prompt_inputs must be set after context retrieval")?;
34
35 match args.provider {
36 PredictionProvider::Teacher(_) | PredictionProvider::TeacherNonBatching(_) => {
37 step_progress.set_substatus("formatting teacher prompt");
38
39 let zeta_format = ZetaFormat::default();
40 let (editable_range, context_range) =
41 excerpt_range_for_format(zeta_format, &prompt_inputs.excerpt_ranges);
42
43 let prompt = TeacherPrompt::format_prompt(example, editable_range, context_range);
44 example.prompt = Some(ExamplePrompt {
45 input: prompt,
46 expected_output: String::new(),
47 rejected_output: None,
48 prefill: None,
49 provider: args.provider,
50 });
51 }
52 PredictionProvider::Zeta2(zeta_format) => {
53 step_progress.set_substatus("formatting zeta2 prompt");
54
55 let prompt = format_zeta_prompt(prompt_inputs, zeta_format);
56 let prefill = zeta_prompt::get_prefill(prompt_inputs, zeta_format);
57 let expected_output = example
58 .spec
59 .expected_patches_with_cursor_positions()
60 .into_iter()
61 .next()
62 .and_then(|(expected_patch, expected_cursor_offset)| {
63 zeta2_output_for_patch(
64 prompt_inputs,
65 &expected_patch,
66 expected_cursor_offset,
67 zeta_format,
68 )
69 .ok()
70 })
71 .unwrap_or_default();
72
73 let rejected_output = example.spec.rejected_patch.as_ref().and_then(|patch| {
74 zeta2_output_for_patch(prompt_inputs, patch, None, zeta_format).ok()
75 });
76
77 example.prompt = Some(ExamplePrompt {
78 input: prompt,
79 expected_output,
80 rejected_output,
81 provider: args.provider,
82 prefill: Some(prefill),
83 });
84 }
85 _ => {
86 panic!("Cannot format prompt for {:?}", args.provider);
87 }
88 };
89 Ok(())
90}
91
92pub fn zeta2_output_for_patch(
93 input: &zeta_prompt::ZetaPromptInput,
94 patch: &str,
95 cursor_offset: Option<usize>,
96 version: ZetaFormat,
97) -> Result<String> {
98 let (context, editable_range, _, _) = resolve_cursor_region(input, version);
99 let mut old_editable_region = context[editable_range].to_string();
100
101 if !old_editable_region.ends_with_newline() {
102 old_editable_region.push('\n');
103 }
104
105 if let Some(encoded_output) =
106 encode_patch_as_output_for_format(version, &old_editable_region, patch, cursor_offset)?
107 {
108 return Ok(encoded_output);
109 }
110
111 let (mut result, first_hunk_offset) =
112 udiff::apply_diff_to_string_with_hunk_offset(patch, &old_editable_region).with_context(
113 || {
114 format!(
115 "Patch:\n```\n{}```\n\nEditable region:\n```\n{}```",
116 patch, old_editable_region
117 )
118 },
119 )?;
120
121 if let Some(cursor_offset) = cursor_offset {
122 // The cursor_offset is relative to the start of the hunk's new text (context + additions).
123 // We need to add where the hunk context matched in the editable region to compute
124 // the actual cursor position in the result.
125 let hunk_start = first_hunk_offset.unwrap_or(0);
126 let offset = result.floor_char_boundary((hunk_start + cursor_offset).min(result.len()));
127 result.insert_str(offset, zeta_prompt::CURSOR_MARKER);
128 }
129
130 if let Some(end_marker) = output_end_marker_for_format(version) {
131 if !result.ends_with('\n') {
132 result.push('\n');
133 }
134 result.push_str(end_marker);
135 }
136
137 Ok(result)
138}
139
140pub struct TeacherPrompt;
141
142impl TeacherPrompt {
143 pub(crate) const EDITABLE_REGION_START: &str = "<|editable_region_start|>\n";
144 pub(crate) const EDITABLE_REGION_END: &str = "\n<|editable_region_end|>";
145 pub(crate) const USER_CURSOR_MARKER: &str = "<|user_cursor|>";
146 pub(crate) const NO_EDITS: &str = "NO_EDITS";
147
148 /// Truncate edit history to this number of last lines
149 const MAX_HISTORY_LINES: usize = 128;
150
151 pub fn format_prompt(
152 example: &Example,
153 editable_range: Range<usize>,
154 context_range: Range<usize>,
155 ) -> String {
156 let edit_history = Self::format_edit_history(&example.spec.edit_history);
157 let context = Self::format_context(example);
158 let cursor_excerpt = Self::format_cursor_excerpt(example, editable_range, context_range);
159
160 let prompt_template = crate::prompt_assets::get_prompt("teacher.md");
161 let prompt = prompt_template
162 .replace("{{context}}", &context)
163 .replace("{{edit_history}}", &edit_history)
164 .replace("{{cursor_excerpt}}", &cursor_excerpt);
165
166 prompt
167 }
168
169 pub fn parse(example: &Example, response: &str) -> Result<(String, Option<ActualCursor>)> {
170 // Check if the model indicated no edits are needed
171 let no_edits = (String::new(), None);
172 if let Some(last_codeblock) = extract_last_codeblock(&response) {
173 if last_codeblock.trim() == Self::NO_EDITS {
174 return Ok(no_edits);
175 }
176 }
177
178 if response.trim().ends_with(Self::NO_EDITS) {
179 return Ok(no_edits);
180 }
181
182 // Extract updated (new) editable region from the model response.
183 let new_editable_region = Self::extract_editable_region(&response)?;
184 let cursor_offset = new_editable_region.find(Self::USER_CURSOR_MARKER);
185 let mut new_editable_region = new_editable_region.replace(Self::USER_CURSOR_MARKER, "");
186 let old_editable_region = Self::extract_editable_region(
187 &example
188 .prompt
189 .as_ref()
190 .context("example prompt missing")?
191 .input,
192 )?
193 .replace(Self::USER_CURSOR_MARKER, "");
194
195 let prompt_inputs = example
196 .prompt_inputs
197 .as_ref()
198 .context("example is missing prompt inputs")?;
199
200 // Normalize leading newlines: if old starts with newline but new doesn't,
201 // prepend newline to new to preserve whitespace structure.
202 // This handles the case where the model drops the leading blank line.
203 if old_editable_region.starts_with('\n') && !new_editable_region.starts_with('\n') {
204 new_editable_region.insert(0, '\n');
205 }
206
207 let excerpt = prompt_inputs.cursor_excerpt.as_ref();
208 let (editable_region_offset, _) = excerpt
209 .match_indices(&old_editable_region)
210 .min_by_key(|(index, _)| index.abs_diff(prompt_inputs.cursor_offset_in_excerpt))
211 .context("editable region not found in prompt content")?;
212 let editable_region_start_line = excerpt[..editable_region_offset].matches('\n').count();
213
214 // Use full context so cursor offset (relative to editable region start) aligns with diff content
215 let editable_region_lines = old_editable_region.lines().count() as u32;
216 let diff = language::unified_diff_with_context(
217 &old_editable_region,
218 &new_editable_region,
219 editable_region_start_line as u32,
220 editable_region_start_line as u32,
221 editable_region_lines,
222 );
223
224 let diff = indoc::formatdoc! {"
225 --- a/{path}
226 +++ b/{path}
227 {diff}",
228 path = example.spec.cursor_path.to_string_lossy(),
229 diff = diff,
230 };
231
232 let actual_cursor = cursor_offset.map(|editable_region_cursor_offset| {
233 ActualCursor::from_editable_region(
234 &example.spec.cursor_path,
235 editable_region_cursor_offset,
236 &new_editable_region,
237 excerpt,
238 editable_region_offset,
239 editable_region_start_line,
240 )
241 });
242
243 Ok((diff, actual_cursor))
244 }
245
246 fn format_edit_history(edit_history: &str) -> String {
247 let lines: Vec<&str> = edit_history.lines().collect();
248
249 if lines.is_empty() {
250 return "(No edit history)".to_string();
251 }
252
253 if lines.len() > Self::MAX_HISTORY_LINES {
254 let truncated = lines[lines.len() - Self::MAX_HISTORY_LINES..].join("\n");
255 format!("{truncated}\n[...truncated...]")
256 } else {
257 lines.join("\n")
258 }
259 }
260
261 pub fn format_context(example: &Example) -> String {
262 let related_files = example.prompt_inputs.as_ref().map(|pi| &pi.related_files);
263 let Some(related_files) = related_files else {
264 return "(No context)".to_string();
265 };
266
267 if related_files.is_empty() {
268 return "(No context)".to_string();
269 }
270
271 let prefix = "`````";
272 let suffix = "`````\n\n";
273 let max_tokens = 1024;
274 zeta_prompt::format_related_files_within_budget(related_files, &prefix, &suffix, max_tokens)
275 }
276
277 fn format_cursor_excerpt(
278 example: &Example,
279 editable_range: Range<usize>,
280 context_range: Range<usize>,
281 ) -> String {
282 let mut result = String::new();
283
284 let prompt_inputs = example.prompt_inputs.as_ref().unwrap();
285 let excerpt = prompt_inputs.cursor_excerpt.as_ref();
286 let cursor_offset = prompt_inputs.cursor_offset_in_excerpt;
287
288 let path_str = example.spec.cursor_path.to_string_lossy();
289 result.push_str(&format!("`````{path_str}\n"));
290 result.push_str(&excerpt[context_range.start..editable_range.start]);
291 result.push_str(Self::EDITABLE_REGION_START);
292 result.push_str(&excerpt[editable_range.start..cursor_offset]);
293 result.push_str(Self::USER_CURSOR_MARKER);
294 result.push_str(&excerpt[cursor_offset..editable_range.end]);
295 result.push_str(Self::EDITABLE_REGION_END);
296 result.push_str(&excerpt[editable_range.end..context_range.end]);
297 result.push_str("\n`````");
298
299 result
300 }
301
302 pub fn extract_editable_region(text: &str) -> Result<String> {
303 let start = text
304 .rfind(Self::EDITABLE_REGION_START)
305 .map_or(0, |pos| pos + Self::EDITABLE_REGION_START.len());
306 let end = text.rfind(Self::EDITABLE_REGION_END).unwrap_or(text.len());
307
308 if start >= end {
309 return Err(anyhow!("Invalid editable region markers"));
310 }
311
312 let region = &text[start..end];
313 Ok(region.strip_suffix('\n').unwrap_or(region).to_string())
314 }
315}
316
317/// Extract the cursor excerpt from an example.
318/// First tries to extract from an existing prompt, then falls back to constructing from prompt_inputs.
319pub fn extract_cursor_excerpt_from_example(example: &Example) -> Option<String> {
320 // If we have the original prompt, extract the cursor excerpt from it
321 if let Some(prompt) = &example.prompt {
322 // Find "# 3. Current File" section and extract the content
323 if let Some(start) = prompt.input.find("# 3. Current File") {
324 let content_start = prompt.input[start..].find('`').map(|i| start + i)?;
325 let backtick_count = prompt.input[content_start..]
326 .chars()
327 .take_while(|&c| c == '`')
328 .count();
329 let content_start = content_start + backtick_count;
330
331 // Find the path line and skip it
332 let newline_pos = prompt.input[content_start..].find('\n')?;
333 let text_start = content_start + newline_pos + 1;
334
335 // Find the closing backticks
336 let closing_pattern = "`".repeat(backtick_count);
337 let text_end = prompt.input[text_start..].find(&closing_pattern)?;
338 let cursor_excerpt = &prompt.input[text_start..text_start + text_end];
339
340 let path_str = example.spec.cursor_path.to_string_lossy();
341 return Some(format!("`````{path_str}\n{cursor_excerpt}`````"));
342 }
343 }
344
345 // Fallback: construct from prompt_inputs if available
346 let prompt_inputs = example.prompt_inputs.as_ref()?;
347 let excerpt = prompt_inputs.cursor_excerpt.as_ref();
348 let cursor_offset = prompt_inputs.cursor_offset_in_excerpt;
349
350 // Simple fallback: just show content around cursor with markers
351 let path_str = example.spec.cursor_path.to_string_lossy();
352 let mut result = format!("`````{path_str}\n");
353 result.push_str(TeacherPrompt::EDITABLE_REGION_START);
354 result.push_str(&excerpt[..cursor_offset]);
355 result.push_str(TeacherPrompt::USER_CURSOR_MARKER);
356 result.push_str(&excerpt[cursor_offset..]);
357 result.push_str(TeacherPrompt::EDITABLE_REGION_END);
358 result.push_str("\n`````");
359
360 Some(result)
361}
362
363pub(crate) fn extract_last_codeblock(text: &str) -> Option<String> {
364 let lines: Vec<&str> = text.lines().collect();
365
366 // Search from the end for a closing fence (line containing only backticks, 3+)
367 let mut closing_line_idx = None;
368 let mut backtick_count = 0;
369
370 for i in (0..lines.len()).rev() {
371 let line = lines[i].trim();
372 if line.len() >= 3 && line.chars().all(|c| c == '`') {
373 closing_line_idx = Some(i);
374 backtick_count = line.len();
375 break;
376 }
377 }
378
379 let closing_idx = closing_line_idx?;
380
381 // Search backwards for matching opening fence
382 // Opening fence starts with same backtick count, possibly followed by language/metadata
383 let opening_pattern = "`".repeat(backtick_count);
384
385 for i in (0..closing_idx).rev() {
386 let line = lines[i];
387 if line.starts_with(&opening_pattern) {
388 // Ensure it's exactly the right number of backticks (not more)
389 let rest = &line[backtick_count..];
390 if rest.is_empty() || !rest.starts_with('`') {
391 // Found matching opening fence
392 // Extract content between opening and closing (exclusive)
393 if closing_idx > i + 1 {
394 let content = lines[i + 1..closing_idx].join("\n");
395 // Preserve trailing newline to match previous behavior
396 return Some(format!("{}\n", content));
397 } else {
398 // Empty block
399 return Some(String::new());
400 }
401 }
402 }
403 }
404
405 None
406}
407
408#[cfg(test)]
409mod tests {
410 use super::*;
411
412 #[test]
413 fn test_extract_last_code_block() {
414 let text = indoc::indoc! {"
415 Some thinking
416
417 ```
418 first block
419 ```
420
421 `````path='something' lines=1:2
422 last block
423 `````
424 "};
425 let last_block = extract_last_codeblock(text).unwrap();
426 assert_eq!(last_block, "last block\n");
427 }
428
429 #[test]
430 fn test_extract_codeblock_with_nested_fences() {
431 let text = indoc::indoc! {"
432 `````
433 content with ``` inline
434 and ```python nested
435 more content
436 `````
437 "};
438 let last_block = extract_last_codeblock(text).unwrap();
439 assert_eq!(
440 last_block,
441 "content with ``` inline\nand ```python nested\nmore content\n"
442 );
443 }
444
445 #[test]
446 fn test_extract_codeblock_ignores_inline_backticks() {
447 let text = indoc::indoc! {"
448 `````
449 here is some `code` with inline backticks
450 and here```more```stuff
451 `````
452 "};
453 let last_block = extract_last_codeblock(text).unwrap();
454 assert_eq!(
455 last_block,
456 "here is some `code` with inline backticks\nand here```more```stuff\n"
457 );
458 }
459
460 #[test]
461 fn test_extract_editable_region() {
462 let text = indoc::indoc! {"
463 some lines
464 are
465 here
466 <|editable_region_start|>
467 one
468 two three
469
470 <|editable_region_end|>
471 more
472 lines here
473 "};
474 let parsed = TeacherPrompt::extract_editable_region(text).unwrap();
475 assert_eq!(
476 parsed,
477 indoc::indoc! {"
478 one
479 two three"}
480 );
481 }
482
483 #[test]
484 fn test_extract_last_codeblock_nested_bibtex() {
485 let text = indoc::indoc! {r#"
486 Looking at the edit history, I can see that a Citation section was just added.
487
488 `````
489 ## Collaborations
490 Our mission is to create a 4D generative model.
491
492 ## Citation
493
494 If you found Unique3D helpful, please cite our report:
495 ```bibtex
496 @misc{wu2024unique3d,
497 title={Unique3D},
498 }
499 ```
500 `````
501 "#};
502 let last_block = extract_last_codeblock(text).unwrap();
503 assert_eq!(
504 last_block,
505 indoc::indoc! {r#"
506 ## Collaborations
507 Our mission is to create a 4D generative model.
508
509 ## Citation
510
511 If you found Unique3D helpful, please cite our report:
512 ```bibtex
513 @misc{wu2024unique3d,
514 title={Unique3D},
515 }
516 ```
517 "#}
518 );
519 }
520
521 #[test]
522 fn test_extract_editable_region_no_markers() {
523 let text = indoc::indoc! {"
524 one
525 two three"};
526 let parsed = TeacherPrompt::extract_editable_region(text).unwrap();
527 assert_eq!(
528 parsed,
529 indoc::indoc! {"
530 one
531 two three"}
532 );
533 }
534
535 #[test]
536 fn test_parse_no_edits_response() {
537 let response = indoc::indoc! {"
538 The code is already complete. There is no clear next edit to make.
539
540 `````
541 NO_EDITS
542 `````
543 "};
544 let codeblock = extract_last_codeblock(response).unwrap();
545 assert_eq!(codeblock.trim(), TeacherPrompt::NO_EDITS);
546 }
547
548 #[test]
549 fn test_extract_codeblock_no_valid_block() {
550 // Text with no code blocks should return None
551 let text = "Just some plain text without any code blocks";
552 assert!(extract_last_codeblock(text).is_none());
553
554 // Unclosed code block should return None
555 let text = indoc::indoc! {"
556 ```
557 unclosed block
558 "};
559 assert!(extract_last_codeblock(text).is_none());
560
561 // Analysis text with nested markdown but no proper outer block
562 let text = indoc::indoc! {"
563 # Analysis
564 Looking at this:
565 ```
566 some code
567 ```
568 But then more analysis without wrapping block
569 "};
570 // This should find the inner block
571 let result = extract_last_codeblock(text).unwrap();
572 assert_eq!(result, "some code\n");
573 }
574
575 #[test]
576 fn test_extract_codeblock_no_trailing_newline() {
577 // Text ending without trailing newline after closing fence
578 let text = "`````\ncontent here\n`````";
579 let result = extract_last_codeblock(text).unwrap();
580 assert_eq!(result, "content here\n");
581 }
582}