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