| 1 | import * as path from "path"; |
| 2 | import { v4 as uuidv4 } from "uuid"; |
| 3 | |
| 4 | import { HelperVars } from "../../autocomplete/util/HelperVars.js"; |
| 5 | import { myersDiff } from "../../diff/myers.js"; |
| 6 | import { DiffLine, IDE, ILLM, Position, RangeInFile } from "../../index.js"; |
| 7 | import { countTokens } from "../../llm/countTokens.js"; |
| 8 | import { |
| 9 | calculateFinalCursorPosition, |
| 10 | DiffGroup, |
| 11 | groupDiffLines, |
| 12 | } from "../diff/diff.js"; |
| 13 | import { PrefetchQueue } from "../NextEditPrefetchQueue.js"; |
| 14 | import { |
| 15 | ModelSpecificContext, |
| 16 | NextEditOutcome, |
| 17 | Prompt, |
| 18 | PromptMetadata, |
| 19 | } from "../types.js"; |
| 20 | import { isWhitespaceOnlyDeletion } from "../utils.js"; |
| 21 | |
| 22 | /** |
| 23 | * This class is used as an abstract base class for model-specific providers. |
| 24 | * This and its children are responsible for pre/post processing of prompts and outcomes. |
| 25 | * Different next edit models have very different requirements. |
| 26 | */ |
| 27 | export abstract class BaseNextEditModelProvider { |
| 28 | protected readonly modelName: string; |
| 29 | |
| 30 | constructor(modelName: string) { |
| 31 | this.modelName = modelName; |
| 32 | } |
| 33 | |
| 34 | // Leave methods as abstract when you must have the models implement their own versions. |
| 35 | abstract getSystemPrompt(): string; |
| 36 | abstract generatePrompts(context: ModelSpecificContext): Promise<Prompt[]>; |
| 37 | abstract extractCompletion(message: string): string; |
| 38 | abstract buildPromptContext(context: ModelSpecificContext): any; |
| 39 | abstract buildPromptMetadata(context: ModelSpecificContext): PromptMetadata; |
| 40 | abstract getWindowSize(): { topMargin: number; bottomMargin: number }; |
| 41 | abstract calculateEditableRegion( |
| 42 | helper: HelperVars, |
| 43 | usingFullFileDiff: boolean, |
| 44 | ): { |
| 45 | editableRegionStartLine: number; |
| 46 | editableRegionEndLine: number; |
| 47 | }; |
| 48 | |
| 49 | // Methods that can be used as default fallback. |
| 50 | public async handlePartialFileDiff( |
| 51 | helper: HelperVars, |
| 52 | editableRegionStartLine: number, |
| 53 | editableRegionEndLine: number, |
| 54 | startTime: number, |
| 55 | llm: ILLM, |
| 56 | nextCompletion: string, |
| 57 | promptMetadata: PromptMetadata, |
| 58 | ide: IDE, |
| 59 | ): Promise<NextEditOutcome> { |
| 60 | const oldEditRangeSlice = helper.fileContents |
| 61 | .split("\n") |
| 62 | .slice(editableRegionStartLine, editableRegionEndLine + 1) |
| 63 | .join("\n"); |
| 64 | |
| 65 | const finalCursorPos = calculateFinalCursorPosition( |
| 66 | helper.pos, |
| 67 | editableRegionStartLine, |
| 68 | oldEditRangeSlice, |
| 69 | nextCompletion, |
| 70 | ); |
| 71 | |
| 72 | const outcome = await this.createNextEditOutcome({ |
| 73 | helper, |
| 74 | startTime, |
| 75 | llm, |
| 76 | promptContent: promptMetadata.prompt.content, |
| 77 | completion: nextCompletion, |
| 78 | finalCursorPosition: finalCursorPos, |
| 79 | editableRegionStartLine, |
| 80 | editableRegionEndLine, |
| 81 | userEdits: promptMetadata.userEdits, |
| 82 | userExcerpts: promptMetadata.userExcerpts, |
| 83 | originalEditableRange: oldEditRangeSlice, |
| 84 | diffLines: [], |
| 85 | ide, |
| 86 | }); |
| 87 | |
| 88 | return outcome; |
| 89 | } |
| 90 | |
| 91 | public async handleFullFileDiff( |
| 92 | helper: HelperVars, |
| 93 | editableRegionStartLine: number, |
| 94 | editableRegionEndLine: number, |
| 95 | startTime: number, |
| 96 | llm: ILLM, |
| 97 | nextCompletion: string, |
| 98 | promptMetadata: PromptMetadata, |
| 99 | ide: IDE, |
| 100 | ): Promise<NextEditOutcome | undefined> { |
| 101 | const fileSlice = helper.fileLines |
| 102 | .slice(editableRegionStartLine, editableRegionEndLine + 1) |
| 103 | .join("\n"); |
| 104 | |
| 105 | const diffLines = myersDiff(fileSlice, nextCompletion); |
| 106 | const diffGroups = groupDiffLines( |
| 107 | diffLines, |
| 108 | editableRegionStartLine, |
| 109 | 5, |
| 110 | ).filter((group) => !isWhitespaceOnlyDeletion(group.lines)); |
| 111 | const currentLine = helper.pos.line; |
| 112 | const prefetchQueue = PrefetchQueue.getInstance(); |
| 113 | |
| 114 | const cursorLocalDiffGroup = await this.processDiffGroups( |
| 115 | diffGroups, |
| 116 | currentLine, |
| 117 | helper, |
| 118 | startTime, |
| 119 | llm, |
| 120 | prefetchQueue, |
| 121 | promptMetadata, |
| 122 | ide, |
| 123 | ); |
| 124 | |
| 125 | if (cursorLocalDiffGroup) { |
| 126 | return await this.createOutcomeFromDiffGroup( |
| 127 | cursorLocalDiffGroup, |
| 128 | helper, |
| 129 | startTime, |
| 130 | llm, |
| 131 | helper.input.completionId, |
| 132 | true, |
| 133 | promptMetadata, |
| 134 | ide, |
| 135 | ); |
| 136 | } |
| 137 | |
| 138 | return undefined; |
| 139 | } |
| 140 | |
| 141 | /** |
| 142 | * Process diff groups and find the one containing the cursor. |
| 143 | */ |
| 144 | private async processDiffGroups( |
| 145 | diffGroups: DiffGroup[], |
| 146 | currentLine: number, |
| 147 | helper: HelperVars, |
| 148 | startTime: number, |
| 149 | llm: ILLM, |
| 150 | prefetchQueue: PrefetchQueue, |
| 151 | promptMetadata: PromptMetadata, |
| 152 | ide: IDE, |
| 153 | ): Promise<DiffGroup | undefined> { |
| 154 | let cursorGroup: DiffGroup | undefined; |
| 155 | |
| 156 | for (const group of diffGroups) { |
| 157 | if (currentLine >= group.startLine && currentLine <= group.endLine) { |
| 158 | cursorGroup = group; |
| 159 | } else { |
| 160 | await this.addDiffGroupToPrefetchQueue( |
| 161 | group, |
| 162 | helper, |
| 163 | startTime, |
| 164 | llm, |
| 165 | prefetchQueue, |
| 166 | promptMetadata, |
| 167 | ide, |
| 168 | ); |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | return cursorGroup; |
| 173 | } |
| 174 | |
| 175 | private async addDiffGroupToPrefetchQueue( |
| 176 | group: DiffGroup, |
| 177 | helper: HelperVars, |
| 178 | startTime: number, |
| 179 | llm: ILLM, |
| 180 | prefetchQueue: PrefetchQueue, |
| 181 | promptMetadata: PromptMetadata, |
| 182 | ide: IDE, |
| 183 | ): Promise<void> { |
| 184 | // Extract lines that are not old. |
| 185 | const groupContent = group.lines |
| 186 | .filter((l) => l.type !== "old") |
| 187 | .map((l) => l.line) |
| 188 | .join("\n"); |
| 189 | |
| 190 | const rangeInFile: RangeInFile = { |
| 191 | filepath: helper.filepath, |
| 192 | range: { |
| 193 | start: { line: group.startLine, character: 0 }, |
| 194 | end: { |
| 195 | line: group.endLine, |
| 196 | character: group.lines[group.lines.length - 1].line.length, |
| 197 | }, |
| 198 | }, |
| 199 | }; |
| 200 | |
| 201 | // Extract lines that are not new. |
| 202 | const originalContent = group.lines |
| 203 | .filter((l) => l.type !== "new") |
| 204 | .map((l) => l.line) |
| 205 | .join("\n"); |
| 206 | |
| 207 | const groupOutcome = await this.createNextEditOutcome({ |
| 208 | helper, |
| 209 | startTime, |
| 210 | llm, |
| 211 | promptContent: promptMetadata.prompt.content, |
| 212 | completion: groupContent, |
| 213 | finalCursorPosition: { |
| 214 | line: group.endLine, |
| 215 | character: group.lines[group.lines.length - 1].line.length, |
| 216 | }, |
| 217 | editableRegionStartLine: group.startLine, |
| 218 | editableRegionEndLine: group.endLine, |
| 219 | userEdits: promptMetadata.userEdits, |
| 220 | userExcerpts: promptMetadata.userExcerpts, |
| 221 | originalEditableRange: originalContent, |
| 222 | cursorPosition: { line: group.startLine, character: 0 }, |
| 223 | completionId: uuidv4(), // Generate a new ID for this prefetched item. |
| 224 | diffLines: group.lines, |
| 225 | ide, |
| 226 | }); |
| 227 | |
| 228 | prefetchQueue.enqueueProcessed({ |
| 229 | location: rangeInFile, |
| 230 | outcome: groupOutcome, |
| 231 | }); |
| 232 | } |
| 233 | |
| 234 | private async createOutcomeFromDiffGroup( |
| 235 | diffGroup: DiffGroup, |
| 236 | helper: HelperVars, |
| 237 | startTime: number, |
| 238 | llm: ILLM, |
| 239 | completionId: string, |
| 240 | isCurrentCursorGroup: boolean, |
| 241 | promptMetadata: PromptMetadata, |
| 242 | ide: IDE, |
| 243 | ): Promise<NextEditOutcome> { |
| 244 | const groupContent = diffGroup.lines |
| 245 | .filter((l) => l.type !== "old") |
| 246 | .map((l) => l.line) |
| 247 | .join("\n"); |
| 248 | |
| 249 | const originalContent = diffGroup.lines |
| 250 | .filter((l) => l.type !== "new") |
| 251 | .map((l) => l.line) |
| 252 | .join("\n"); |
| 253 | |
| 254 | const cursorPos = isCurrentCursorGroup |
| 255 | ? helper.pos |
| 256 | : { line: diffGroup.startLine, character: 0 }; |
| 257 | |
| 258 | const finalCursorPos = calculateFinalCursorPosition( |
| 259 | cursorPos, |
| 260 | diffGroup.startLine, |
| 261 | originalContent, |
| 262 | groupContent, |
| 263 | ); |
| 264 | |
| 265 | const outcomeNext = await this.createNextEditOutcome({ |
| 266 | helper, |
| 267 | startTime, |
| 268 | llm, |
| 269 | promptContent: promptMetadata.prompt.content, |
| 270 | completion: groupContent, |
| 271 | finalCursorPosition: finalCursorPos, |
| 272 | editableRegionStartLine: diffGroup.startLine, |
| 273 | editableRegionEndLine: diffGroup.endLine, |
| 274 | userEdits: promptMetadata.userEdits, |
| 275 | userExcerpts: promptMetadata.userExcerpts, |
| 276 | originalEditableRange: originalContent, |
| 277 | cursorPosition: cursorPos, |
| 278 | completionId, |
| 279 | diffLines: diffGroup.lines, |
| 280 | ide, |
| 281 | }); |
| 282 | |
| 283 | return outcomeNext; |
| 284 | } |
| 285 | |
| 286 | protected async createNextEditOutcome(outcomeCtx: { |
| 287 | helper: HelperVars; |
| 288 | startTime: number; |
| 289 | llm: ILLM; |
| 290 | promptContent: string; |
| 291 | completion: string; |
| 292 | finalCursorPosition: Position; |
| 293 | editableRegionStartLine: number; |
| 294 | editableRegionEndLine: number; |
| 295 | userEdits: string; |
| 296 | userExcerpts: string; |
| 297 | originalEditableRange: string; |
| 298 | cursorPosition?: Position; |
| 299 | completionId?: string; |
| 300 | diffLines: DiffLine[]; |
| 301 | ide: IDE; |
| 302 | }): Promise<NextEditOutcome> { |
| 303 | return { |
| 304 | elapsed: Date.now() - outcomeCtx.startTime, |
| 305 | modelProvider: outcomeCtx.llm.underlyingProviderName, |
| 306 | modelName: outcomeCtx.llm.model, |
| 307 | completionOptions: null, |
| 308 | completionId: |
| 309 | outcomeCtx.completionId || outcomeCtx.helper.input.completionId, |
| 310 | gitRepo: await outcomeCtx.ide.getRepoName(outcomeCtx.helper.filepath), |
| 311 | uniqueId: await outcomeCtx.ide.getUniqueId(), |
| 312 | timestamp: Date.now(), |
| 313 | fileUri: outcomeCtx.helper.filepath, |
| 314 | workspaceDirUri: |
| 315 | outcomeCtx.helper.workspaceUris[0] ?? |
| 316 | path.dirname(outcomeCtx.helper.filepath), |
| 317 | prompt: outcomeCtx.promptContent, |
| 318 | userEdits: outcomeCtx.userEdits ?? "", |
| 319 | userExcerpts: outcomeCtx.userExcerpts ?? "", |
| 320 | originalEditableRange: outcomeCtx.originalEditableRange ?? "", |
| 321 | completion: outcomeCtx.completion, |
| 322 | cursorPosition: outcomeCtx.cursorPosition || outcomeCtx.helper.pos, |
| 323 | finalCursorPosition: outcomeCtx.finalCursorPosition, |
| 324 | editableRegionStartLine: outcomeCtx.editableRegionStartLine, |
| 325 | editableRegionEndLine: outcomeCtx.editableRegionEndLine, |
| 326 | diffLines: outcomeCtx.diffLines, |
| 327 | ...outcomeCtx.helper.options, |
| 328 | }; |
| 329 | } |
| 330 | |
| 331 | // Shared utility for calculating editable regions. |
| 332 | protected calculateOptimalEditableRegion( |
| 333 | helper: HelperVars, |
| 334 | maxTokens: number = 512, |
| 335 | heuristic: "fourChars" | "tokenizer" = "tokenizer", |
| 336 | ): { |
| 337 | editableRegionStartLine: number; |
| 338 | editableRegionEndLine: number; |
| 339 | } { |
| 340 | const cursorLine = helper.pos.line; |
| 341 | const fileLines = helper.fileLines; |
| 342 | |
| 343 | let editableRegionStartLine = cursorLine; |
| 344 | let editableRegionEndLine = cursorLine; |
| 345 | |
| 346 | let currentContent = fileLines[cursorLine]; |
| 347 | let totalTokens = |
| 348 | heuristic === "tokenizer" |
| 349 | ? countTokens(currentContent, helper.modelName) |
| 350 | : Math.ceil(currentContent.length / 4); |
| 351 | |
| 352 | let addingAbove = true; |
| 353 | |
| 354 | while (totalTokens < maxTokens) { |
| 355 | let addedLine = false; |
| 356 | |
| 357 | if (addingAbove) { |
| 358 | if (editableRegionStartLine > 0) { |
| 359 | editableRegionStartLine--; |
| 360 | const lineContent = fileLines[editableRegionStartLine]; |
| 361 | const lineTokens = |
| 362 | heuristic === "tokenizer" |
| 363 | ? countTokens(lineContent, helper.modelName) |
| 364 | : Math.ceil(lineContent.length / 4); |
| 365 | |
| 366 | totalTokens += lineTokens; |
| 367 | addedLine = true; |
| 368 | } |
| 369 | } else { |
| 370 | if (editableRegionEndLine < fileLines.length - 1) { |
| 371 | editableRegionEndLine++; |
| 372 | const lineContent = fileLines[editableRegionEndLine]; |
| 373 | const lineTokens = |
| 374 | heuristic === "tokenizer" |
| 375 | ? countTokens(lineContent, helper.modelName) |
| 376 | : Math.ceil(lineContent.length / 4); |
| 377 | |
| 378 | totalTokens += lineTokens; |
| 379 | addedLine = true; |
| 380 | } |
| 381 | } |
| 382 | |
| 383 | if (!addedLine) { |
| 384 | if ( |
| 385 | editableRegionStartLine === 0 && |
| 386 | editableRegionEndLine === fileLines.length - 1 |
| 387 | ) { |
| 388 | break; |
| 389 | } |
| 390 | addingAbove = !addingAbove; |
| 391 | continue; |
| 392 | } |
| 393 | |
| 394 | if (totalTokens > maxTokens) { |
| 395 | if (addingAbove) { |
| 396 | editableRegionStartLine++; |
| 397 | } else { |
| 398 | editableRegionEndLine--; |
| 399 | } |
| 400 | break; |
| 401 | } |
| 402 | |
| 403 | addingAbove = !addingAbove; |
| 404 | } |
| 405 | |
| 406 | return { |
| 407 | editableRegionStartLine, |
| 408 | editableRegionEndLine, |
| 409 | }; |
| 410 | } |
| 411 | |
| 412 | // Optional methods with defaults. |
| 413 | shouldInjectUniqueToken(): boolean { |
| 414 | return false; |
| 415 | } |
| 416 | |
| 417 | getUniqueToken(): string | null { |
| 418 | return null; |
| 419 | } |
| 420 | } |