Elffuss BraidHub

kikocis/continue public

4e08584b8e1b · 19.8 KiBRawPermalink
1import { v4 as uuidv4 } from "uuid";
2import { ConfigHandler } from "../config/ConfigHandler.js";
3import { ChatMessage, IDE, ILLM, Range, RangeInFile } from "../index.js";
4import OpenAI from "../llm/llms/OpenAI.js";
5import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
6
7import { ContextRetrievalService } from "../autocomplete/context/ContextRetrievalService.js";
8
9import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js";
10import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js";
11import { shouldPrefilter } from "../autocomplete/prefiltering/index.js";
12import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js";
13import { AutocompleteCodeSnippet } from "../autocomplete/snippets/types.js";
14import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
15import { getAst } from "../autocomplete/util/ast.js";
16import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebouncer.js";
17import AutocompleteLruCache from "../autocomplete/util/AutocompleteLruCache.js";
18import { HelperVars } from "../autocomplete/util/HelperVars.js";
19import { AutocompleteInput } from "../autocomplete/util/types.js";
20import { isSecurityConcern } from "../indexing/ignore.js";
21import { modelSupportsNextEdit } from "../llm/autodetect.js";
22import { countTokens } from "../llm/countTokens.js";
23import { localPathOrUriToPath } from "../util/pathToUri.js";
24import { createDiff, DiffFormatType } from "./context/diffFormatting.js";
25import { DocumentHistoryTracker } from "./DocumentHistoryTracker.js";
26import { NextEditLoggingService } from "./NextEditLoggingService.js";
27import { PrefetchQueue } from "./NextEditPrefetchQueue.js";
28import { NextEditProviderFactory } from "./NextEditProviderFactory.js";
29import { BaseNextEditModelProvider } from "./providers/BaseNextEditProvider.js";
30import {
31 ModelSpecificContext,
32 NextEditOutcome,
33 Prompt,
34 PromptMetadata,
35 RecentlyEditedRange,
36} from "./types.js";
37
38const autocompleteCache = AutocompleteLruCache.get();
39
40// Errors that can be expected on occasion even during normal functioning should not be shown.
41// Not worth disrupting the user to tell them that a single autocomplete request didn't go through
42const ERRORS_TO_IGNORE = [
43 // From Ollama
44 "unexpected server status",
45 "operation was aborted",
46];
47
48export class NextEditProvider {
49 private static instance: NextEditProvider | null = null;
50
51 private autocompleteCache = AutocompleteLruCache.get();
52 public errorsShown: Set<string> = new Set();
53 private bracketMatchingService = new BracketMatchingService();
54 private debouncer = new AutocompleteDebouncer();
55 private completionStreamer: CompletionStreamer;
56 private loggingService: NextEditLoggingService;
57 private contextRetrievalService: ContextRetrievalService;
58 private endpointType: "default" | "fineTuned";
59 private diffContext: string[] = [];
60 private autocompleteContext: string = "";
61 private promptMetadata: PromptMetadata | null = null;
62 private currentEditChainId: string | null = null;
63 private previousRequest: AutocompleteInput | null = null;
64 private previousCompletions: NextEditOutcome[] = [];
65 // private nextEditableRegionsInTheCurrentChain: RangeInFile[] = [];
66
67 // Model-specific provider instance.
68 private modelProvider: BaseNextEditModelProvider | null = null;
69
70 private constructor(
71 private readonly configHandler: ConfigHandler,
72 private readonly ide: IDE,
73 private readonly _injectedGetLlm: () => Promise<ILLM | undefined>,
74 private readonly _onError: (e: any) => void,
75 private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction,
76 endpointType: "default" | "fineTuned",
77 ) {
78 this.completionStreamer = new CompletionStreamer(this.onError.bind(this));
79 this.contextRetrievalService = new ContextRetrievalService(this.ide);
80 this.endpointType = endpointType;
81 this.loggingService = NextEditLoggingService.getInstance();
82 }
83
84 public static initialize(
85 configHandler: ConfigHandler,
86 ide: IDE,
87 injectedGetLlm: () => Promise<ILLM | undefined>,
88 onError: (e: any) => void,
89 getDefinitionsFromLsp: GetLspDefinitionsFunction,
90 endpointType: "default" | "fineTuned",
91 ): NextEditProvider {
92 if (!NextEditProvider.instance) {
93 NextEditProvider.instance = new NextEditProvider(
94 configHandler,
95 ide,
96 injectedGetLlm,
97 onError,
98 getDefinitionsFromLsp,
99 endpointType,
100 );
101 }
102 return NextEditProvider.instance;
103 }
104
105 public static getInstance(): NextEditProvider {
106 if (!NextEditProvider.instance) {
107 throw new Error(
108 "NextEditProvider has not been initialized. Call initialize() first.",
109 );
110 }
111 return NextEditProvider.instance;
112 }
113
114 public addDiffToContext(diff: string): void {
115 this.diffContext.push(diff);
116 if (this.diffContext.length > 5) {
117 this.diffContext.shift();
118 }
119 }
120
121 public addAutocompleteContext(ctx: string): void {
122 this.autocompleteContext = ctx;
123 }
124
125 private async _prepareLlm(): Promise<ILLM | undefined> {
126 const llm = await this._injectedGetLlm();
127
128 if (!llm) {
129 return undefined;
130 }
131
132 // Temporary fix for JetBrains autocomplete bug as described in https://github.com/continuedev/continue/pull/3022
133 if (llm.model === undefined && llm.completionOptions?.model !== undefined) {
134 llm.model = llm.completionOptions.model;
135 }
136
137 // Ignore empty API keys for Mistral since we currently write
138 // a template provider without one during onboarding
139 if (llm.providerName === "mistral" && llm.apiKey === "") {
140 return undefined;
141 }
142
143 // Set temperature (but don't override)
144 if (llm.completionOptions.temperature === undefined) {
145 llm.completionOptions.temperature = 0.01;
146 }
147
148 if (llm instanceof OpenAI) {
149 llm.useLegacyCompletionsEndpoint = true;
150 }
151 // TODO: Resolve import error with TRIAL_FIM_MODEL
152 // else if (
153 // llm.providerName === "free-trial" &&
154 // llm.model !== TRIAL_FIM_MODEL
155 // ) {
156 // llm.model = TRIAL_FIM_MODEL;
157 // }
158
159 return llm;
160 }
161
162 private onError(e: any) {
163 if (
164 ERRORS_TO_IGNORE.some((err) =>
165 typeof e === "string" ? e.includes(err) : e?.message?.includes(err),
166 )
167 ) {
168 return;
169 }
170
171 console.warn("Error generating autocompletion: ", e);
172 if (!this.errorsShown.has(e.message)) {
173 this.errorsShown.add(e.message);
174 this._onError(e);
175 }
176 }
177
178 public cancel() {
179 this.loggingService.cancel();
180 }
181
182 public accept(completionId: string) {
183 const outcome = this.loggingService.accept(completionId);
184 if (!outcome) {
185 return;
186 }
187 }
188
189 public reject(completionId: string) {
190 const outcome = this.loggingService.reject(completionId);
191 if (!outcome) {
192 return;
193 }
194 }
195
196 public markDisplayed(completionId: string, outcome: NextEditOutcome) {
197 this.loggingService.markDisplayed(completionId, outcome);
198 }
199
200 private async _getAutocompleteOptions() {
201 const { config } = await this.configHandler.loadConfig();
202 const options = {
203 ...DEFAULT_AUTOCOMPLETE_OPTS,
204 ...config?.tabAutocompleteOptions,
205 };
206 return options;
207 }
208
209 public chainExists(): boolean {
210 return this.currentEditChainId !== null;
211 }
212
213 public getChainLength(): number {
214 return this.previousCompletions.length;
215 }
216
217 public getPreviousCompletion(): NextEditOutcome | null {
218 return this.previousCompletions[0];
219 }
220
221 public async deleteChain(): Promise<void> {
222 PrefetchQueue.getInstance().abort();
223
224 this.currentEditChainId = null;
225 this.previousCompletions = [];
226 // TODO: this should be cleaned up in the prefetch queue.
227 // this.nextEditableRegionsInTheCurrentChain = [];
228
229 if (this.previousRequest) {
230 const fileContent = (
231 await this.ide.readFile(this.previousRequest.filepath)
232 ).toString();
233 const ast = await getAst(this.previousRequest.filepath, fileContent);
234 if (ast) {
235 DocumentHistoryTracker.getInstance().push(
236 localPathOrUriToPath(this.previousRequest.filepath),
237 fileContent,
238 ast,
239 );
240 }
241 }
242 }
243
244 public startChain(id?: string) {
245 this.currentEditChainId = id ?? uuidv4();
246 }
247
248 public getChain() {
249 return this.previousCompletions;
250 }
251
252 public isStartOfChain() {
253 return this.previousCompletions.length === 1;
254 }
255
256 public async provideInlineCompletionItems(
257 input: AutocompleteInput,
258 token: AbortSignal | undefined,
259 opts?: {
260 withChain: boolean;
261 usingFullFileDiff: boolean;
262 },
263 ): Promise<NextEditOutcome | undefined> {
264 if (isSecurityConcern(input.filepath)) {
265 return undefined;
266 }
267 try {
268 this.previousRequest = input;
269 const {
270 token: abortToken,
271 startTime,
272 helper,
273 } = await this._initializeCompletionRequest(input, token);
274 if (!helper) return undefined;
275
276 // Create model-specific provider based on the model name.
277 this.modelProvider = NextEditProviderFactory.createProvider(
278 helper.modelName,
279 );
280
281 const { editableRegionStartLine, editableRegionEndLine, prompts } =
282 await this._generatePrompts(helper, opts);
283
284 return await this._handleCompletion(
285 helper,
286 prompts,
287 abortToken,
288 startTime,
289 editableRegionStartLine,
290 editableRegionEndLine,
291 opts,
292 );
293 } catch (e: any) {
294 this.onError(e);
295 } finally {
296 this.loggingService.deleteAbortController(input.completionId);
297 }
298 }
299
300 private async _initializeCompletionRequest(
301 input: AutocompleteInput,
302 token: AbortSignal | undefined,
303 ): Promise<{
304 token: AbortSignal;
305 startTime: number;
306 helper: HelperVars | undefined;
307 }> {
308 // Create abort signal if not given
309 if (!token) {
310 const controller = this.loggingService.createAbortController(
311 input.completionId,
312 );
313 token = controller.signal;
314 } else {
315 // Token was provided externally, just track the completion.
316 this.loggingService.trackPendingCompletion(input.completionId);
317 }
318
319 const startTime = Date.now();
320 const options = await this._getAutocompleteOptions();
321
322 // Debounce
323 if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
324 return { token, startTime, helper: undefined };
325 }
326
327 const llm = await this._prepareLlm();
328 if (!llm) {
329 return { token, startTime, helper: undefined };
330 }
331
332 // Update pending completion with model info.
333 this.loggingService.updatePendingCompletion(input.completionId, {
334 modelName: llm.model,
335 modelProvider: llm.providerName,
336 filepath: input.filepath,
337 });
338
339 // Check model capabilities
340 if (!modelSupportsNextEdit(llm.capabilities, llm.model, llm.title)) {
341 console.error(`${llm.model} is not capable of next edit.`);
342 return { token, startTime, helper: undefined };
343 }
344
345 if (llm.promptTemplates?.autocomplete) {
346 options.template = llm.promptTemplates.autocomplete as string;
347 }
348
349 const helper = await HelperVars.create(input, options, llm.model, this.ide);
350
351 if (await shouldPrefilter(helper, this.ide)) {
352 return { token, startTime, helper: undefined };
353 }
354
355 return { token, startTime, helper };
356 }
357
358 private async _generatePrompts(
359 helper: HelperVars,
360 opts?: {
361 withChain: boolean;
362 usingFullFileDiff: boolean;
363 },
364 ): Promise<{
365 editableRegionStartLine: number;
366 editableRegionEndLine: number;
367 prompts: Prompt[];
368 }> {
369 if (!this.modelProvider) {
370 throw new Error("Model provider not initialized");
371 }
372
373 const [snippetPayload, workspaceDirs] = await Promise.all([
374 getAllSnippetsWithoutRace({
375 helper,
376 ide: this.ide,
377 getDefinitionsFromLsp: this.getDefinitionsFromLsp,
378 contextRetrievalService: this.contextRetrievalService,
379 }),
380 this.ide.getWorkspaceDirs(),
381 ]);
382
383 // Calculate editable region based on model and options.
384 const { editableRegionStartLine, editableRegionEndLine } =
385 this.modelProvider.calculateEditableRegion(
386 helper,
387 opts?.usingFullFileDiff ?? false,
388 );
389
390 // Build context for model-specific prompt generation.
391 const context: ModelSpecificContext = {
392 helper,
393 snippetPayload,
394 editableRegionStartLine,
395 editableRegionEndLine,
396 diffContext: this.diffContext,
397 autocompleteContext: this.autocompleteContext,
398 historyDiff: createDiff({
399 beforeContent:
400 DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory(
401 localPathOrUriToPath(helper.filepath),
402 ) ?? "",
403 afterContent: helper.fileContents,
404 filePath: helper.filepath,
405 diffType: DiffFormatType.Unified,
406 contextLines: 3,
407 }),
408 };
409
410 const prompts = await this.modelProvider.generatePrompts(context);
411
412 this.promptMetadata = this.modelProvider.buildPromptMetadata(context);
413
414 return { editableRegionStartLine, editableRegionEndLine, prompts };
415 }
416
417 private async _handleCompletion(
418 helper: HelperVars,
419 prompts: Prompt[],
420 token: AbortSignal,
421 startTime: number,
422 editableRegionStartLine: number,
423 editableRegionEndLine: number,
424 opts?: {
425 withChain: boolean;
426 usingFullFileDiff: boolean;
427 },
428 ): Promise<NextEditOutcome | undefined> {
429 if (!this.modelProvider) {
430 throw new Error("Model provider not initialized");
431 }
432
433 const llm = await this._prepareLlm();
434 if (!llm) return undefined;
435
436 // Inject unique token if needed (for Mercury models).
437 if (this.modelProvider.shouldInjectUniqueToken()) {
438 const uniqueToken = this.modelProvider.getUniqueToken();
439 if (uniqueToken) {
440 const lastPrompt = prompts[prompts.length - 1];
441 if (lastPrompt && typeof lastPrompt.content === "string") {
442 lastPrompt.content += uniqueToken;
443 }
444 }
445 }
446
447 // Send prompts to LLM (using only user prompt for fine-tuned models).
448 const msg: ChatMessage = await llm.chat([prompts[1]], token, {
449 stream: false,
450 });
451
452 if (typeof msg.content !== "string") {
453 return undefined;
454 }
455
456 // Extract completion using model-specific logic.
457 const nextCompletion = this.modelProvider.extractCompletion(msg.content);
458
459 let outcome: NextEditOutcome | undefined;
460
461 // Handle based on diff type.
462 if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
463 outcome = await this.modelProvider.handlePartialFileDiff(
464 helper,
465 editableRegionStartLine,
466 editableRegionEndLine,
467 startTime,
468 llm,
469 nextCompletion,
470 this.promptMetadata!,
471 this.ide,
472 );
473 } else {
474 outcome = await this.modelProvider.handleFullFileDiff(
475 helper,
476 editableRegionStartLine,
477 editableRegionEndLine,
478 startTime,
479 llm,
480 nextCompletion,
481 this.promptMetadata!,
482 this.ide,
483 );
484 }
485
486 if (outcome) {
487 // Handle NextEditProvider-specific state
488 this.previousCompletions.push(outcome);
489
490 // Mark as displayed for JetBrains
491 await this._markDisplayedIfJetBrains(helper.input.completionId, outcome);
492 }
493
494 return outcome;
495 }
496
497 private _calculateOptimalEditableRegion(
498 helper: HelperVars,
499 heuristic: "fourChars" | "tokenizer" = "tokenizer",
500 ): {
501 editableRegionStartLine: number;
502 editableRegionEndLine: number;
503 } {
504 const cursorLine = helper.pos.line;
505 const fileLines = helper.fileLines;
506 const MAX_TOKENS = 512;
507
508 // Initialize with cursor line.
509 let editableRegionStartLine = cursorLine;
510 let editableRegionEndLine = cursorLine;
511
512 // Get initial content and token count.
513 let currentContent = fileLines[cursorLine];
514 let totalTokens =
515 heuristic === "tokenizer"
516 ? countTokens(currentContent, helper.modelName)
517 : Math.ceil(currentContent.length / 4);
518
519 // Expand outward alternating between adding lines above and below.
520 let addingAbove = true;
521
522 while (totalTokens < MAX_TOKENS) {
523 let addedLine = false;
524
525 if (addingAbove) {
526 // Try to add a line above.
527 if (editableRegionStartLine > 0) {
528 editableRegionStartLine--;
529 const lineContent = fileLines[editableRegionStartLine];
530 const lineTokens =
531 heuristic === "tokenizer"
532 ? countTokens(lineContent, helper.modelName)
533 : Math.ceil(lineContent.length / 4);
534
535 totalTokens += lineTokens;
536 addedLine = true;
537 }
538 } else {
539 // Try to add a line below.
540 if (editableRegionEndLine < fileLines.length - 1) {
541 editableRegionEndLine++;
542 const lineContent = fileLines[editableRegionEndLine];
543 const lineTokens =
544 heuristic === "tokenizer"
545 ? countTokens(lineContent, helper.modelName)
546 : Math.ceil(lineContent.length / 4);
547
548 totalTokens += lineTokens;
549 addedLine = true;
550 }
551 }
552
553 // If we can't add in the current direction, try the other.
554 if (!addedLine) {
555 // If we're already at both file boundaries, we're done.
556 if (
557 editableRegionStartLine === 0 &&
558 editableRegionEndLine === fileLines.length - 1
559 ) {
560 break;
561 }
562
563 // If we couldn't add in one direction, force the next attempt in the other direction.
564 addingAbove = !addingAbove;
565 continue;
566 }
567
568 // If we exceeded the token limit, revert the last addition.
569 if (totalTokens > MAX_TOKENS) {
570 if (addingAbove) {
571 editableRegionStartLine++;
572 } else {
573 editableRegionEndLine--;
574 }
575 break;
576 }
577
578 // Alternate between adding above and below for balanced context.
579 addingAbove = !addingAbove;
580 }
581
582 return {
583 editableRegionStartLine,
584 editableRegionEndLine,
585 };
586 }
587
588 private async _markDisplayedIfJetBrains(
589 completionId: string,
590 outcome: NextEditOutcome,
591 ): Promise<void> {
592 const ideType = (await this.ide.getIdeInfo()).ideType;
593 if (ideType === "jetbrains") {
594 this.markDisplayed(completionId, outcome);
595 }
596 }
597
598 public async provideInlineCompletionItemsWithChain(
599 ctx: {
600 completionId: string;
601 manuallyPassFileContents?: string;
602 manuallyPassPrefix?: string;
603 selectedCompletionInfo?: {
604 text: string;
605 range: Range;
606 };
607 isUntitledFile: boolean;
608 recentlyVisitedRanges: AutocompleteCodeSnippet[];
609 recentlyEditedRanges: RecentlyEditedRange[];
610 },
611 nextEditLocation: RangeInFile,
612 token: AbortSignal | undefined,
613 usingFullFileDiff: boolean,
614 ) {
615 try {
616 const previousOutcome = this.getPreviousCompletion();
617 if (!previousOutcome) {
618 console.log("previousOutcome is undefined");
619 return undefined;
620 }
621
622 // Use the frontmost RangeInFile to build an input.
623 const input = this.buildAutocompleteInputFromChain(
624 previousOutcome,
625 nextEditLocation,
626 ctx,
627 );
628 if (!input) {
629 console.log("input is undefined");
630 return undefined;
631 }
632
633 return await this.provideInlineCompletionItems(input, token, {
634 withChain: true,
635 usingFullFileDiff,
636 });
637 } catch (e: any) {
638 this.onError(e);
639 }
640 }
641
642 private buildAutocompleteInputFromChain(
643 previousOutcome: NextEditOutcome,
644 nextEditableRegion: RangeInFile,
645 ctx: {
646 completionId: string;
647 manuallyPassFileContents?: string;
648 manuallyPassPrefix?: string;
649 selectedCompletionInfo?: {
650 text: string;
651 range: Range;
652 };
653 isUntitledFile: boolean;
654 recentlyVisitedRanges: AutocompleteCodeSnippet[];
655 recentlyEditedRanges: RecentlyEditedRange[];
656 },
657 ): AutocompleteInput | undefined {
658 const input: AutocompleteInput = {
659 pos: {
660 line: nextEditableRegion.range.start.line,
661 character: nextEditableRegion.range.start.character,
662 },
663 filepath: previousOutcome.fileUri,
664 ...ctx,
665 };
666
667 return input;
668 }
669}