Elffuss BraidHub

kikocis/continue public

b4db4cbf8943 · 19.4 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 { BaseNextEditProvider } 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: BaseNextEditProvider | 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 }
315 const startTime = Date.now();
316 const options = await this._getAutocompleteOptions();
317
318 // Debounce
319 if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
320 return { token, startTime, helper: undefined };
321 }
322
323 const llm = await this._prepareLlm();
324 if (!llm) {
325 return { token, startTime, helper: undefined };
326 }
327
328 // Check model capabilities
329 if (!modelSupportsNextEdit(llm.capabilities, llm.model, llm.title)) {
330 console.error(`${llm.model} is not capable of next edit.`);
331 return { token, startTime, helper: undefined };
332 }
333
334 if (llm.promptTemplates?.autocomplete) {
335 options.template = llm.promptTemplates.autocomplete as string;
336 }
337
338 const helper = await HelperVars.create(input, options, llm.model, this.ide);
339
340 if (await shouldPrefilter(helper, this.ide)) {
341 return { token, startTime, helper: undefined };
342 }
343
344 return { token, startTime, helper };
345 }
346
347 private async _generatePrompts(
348 helper: HelperVars,
349 opts?: {
350 withChain: boolean;
351 usingFullFileDiff: boolean;
352 },
353 ): Promise<{
354 editableRegionStartLine: number;
355 editableRegionEndLine: number;
356 prompts: Prompt[];
357 }> {
358 if (!this.modelProvider) {
359 throw new Error("Model provider not initialized");
360 }
361
362 const [snippetPayload, workspaceDirs] = await Promise.all([
363 getAllSnippetsWithoutRace({
364 helper,
365 ide: this.ide,
366 getDefinitionsFromLsp: this.getDefinitionsFromLsp,
367 contextRetrievalService: this.contextRetrievalService,
368 }),
369 this.ide.getWorkspaceDirs(),
370 ]);
371
372 // Calculate editable region based on model and options.
373 const { editableRegionStartLine, editableRegionEndLine } =
374 this.modelProvider.calculateEditableRegion(
375 helper,
376 opts?.usingFullFileDiff ?? false,
377 );
378
379 // Build context for model-specific prompt generation.
380 const context: ModelSpecificContext = {
381 helper,
382 snippetPayload,
383 editableRegionStartLine,
384 editableRegionEndLine,
385 diffContext: this.diffContext,
386 autocompleteContext: this.autocompleteContext,
387 historyDiff: createDiff({
388 beforeContent:
389 DocumentHistoryTracker.getInstance().getMostRecentDocumentHistory(
390 localPathOrUriToPath(helper.filepath),
391 ) ?? "",
392 afterContent: helper.fileContents,
393 filePath: helper.filepath,
394 diffType: DiffFormatType.Unified,
395 contextLines: 3,
396 }),
397 };
398
399 const prompts = await this.modelProvider.generatePrompts(context);
400
401 this.promptMetadata = this.modelProvider.buildPromptMetadata(context);
402
403 return { editableRegionStartLine, editableRegionEndLine, prompts };
404 }
405
406 private async _handleCompletion(
407 helper: HelperVars,
408 prompts: Prompt[],
409 token: AbortSignal,
410 startTime: number,
411 editableRegionStartLine: number,
412 editableRegionEndLine: number,
413 opts?: {
414 withChain: boolean;
415 usingFullFileDiff: boolean;
416 },
417 ): Promise<NextEditOutcome | undefined> {
418 if (!this.modelProvider) {
419 throw new Error("Model provider not initialized");
420 }
421
422 const llm = await this._prepareLlm();
423 if (!llm) return undefined;
424
425 // Inject unique token if needed (for Mercury models).
426 if (this.modelProvider.shouldInjectUniqueToken()) {
427 const uniqueToken = this.modelProvider.getUniqueToken();
428 if (uniqueToken) {
429 const lastPrompt = prompts[prompts.length - 1];
430 if (lastPrompt && typeof lastPrompt.content === "string") {
431 lastPrompt.content += uniqueToken;
432 }
433 }
434 }
435
436 // Send prompts to LLM (using only user prompt for fine-tuned models).
437 const msg: ChatMessage = await llm.chat([prompts[1]], token, {
438 stream: false,
439 });
440
441 if (typeof msg.content !== "string") {
442 return undefined;
443 }
444
445 // Extract completion using model-specific logic.
446 const nextCompletion = this.modelProvider.extractCompletion(msg.content);
447
448 let outcome: NextEditOutcome | undefined;
449
450 // Handle based on diff type.
451 if (opts?.usingFullFileDiff === false || !opts?.usingFullFileDiff) {
452 outcome = await this.modelProvider.handlePartialFileDiff(
453 helper,
454 editableRegionStartLine,
455 editableRegionEndLine,
456 startTime,
457 llm,
458 nextCompletion,
459 this.promptMetadata!,
460 this.ide,
461 );
462 } else {
463 outcome = await this.modelProvider.handleFullFileDiff(
464 helper,
465 editableRegionStartLine,
466 editableRegionEndLine,
467 startTime,
468 llm,
469 nextCompletion,
470 this.promptMetadata!,
471 this.ide,
472 );
473 }
474
475 if (outcome) {
476 // Handle NextEditProvider-specific state
477 this.previousCompletions.push(outcome);
478
479 // Mark as displayed for JetBrains
480 await this._markDisplayedIfJetBrains(helper.input.completionId, outcome);
481 }
482
483 return outcome;
484 }
485
486 private _calculateOptimalEditableRegion(
487 helper: HelperVars,
488 heuristic: "fourChars" | "tokenizer" = "tokenizer",
489 ): {
490 editableRegionStartLine: number;
491 editableRegionEndLine: number;
492 } {
493 const cursorLine = helper.pos.line;
494 const fileLines = helper.fileLines;
495 const MAX_TOKENS = 512;
496
497 // Initialize with cursor line.
498 let editableRegionStartLine = cursorLine;
499 let editableRegionEndLine = cursorLine;
500
501 // Get initial content and token count.
502 let currentContent = fileLines[cursorLine];
503 let totalTokens =
504 heuristic === "tokenizer"
505 ? countTokens(currentContent, helper.modelName)
506 : Math.ceil(currentContent.length / 4);
507
508 // Expand outward alternating between adding lines above and below.
509 let addingAbove = true;
510
511 while (totalTokens < MAX_TOKENS) {
512 let addedLine = false;
513
514 if (addingAbove) {
515 // Try to add a line above.
516 if (editableRegionStartLine > 0) {
517 editableRegionStartLine--;
518 const lineContent = fileLines[editableRegionStartLine];
519 const lineTokens =
520 heuristic === "tokenizer"
521 ? countTokens(lineContent, helper.modelName)
522 : Math.ceil(lineContent.length / 4);
523
524 totalTokens += lineTokens;
525 addedLine = true;
526 }
527 } else {
528 // Try to add a line below.
529 if (editableRegionEndLine < fileLines.length - 1) {
530 editableRegionEndLine++;
531 const lineContent = fileLines[editableRegionEndLine];
532 const lineTokens =
533 heuristic === "tokenizer"
534 ? countTokens(lineContent, helper.modelName)
535 : Math.ceil(lineContent.length / 4);
536
537 totalTokens += lineTokens;
538 addedLine = true;
539 }
540 }
541
542 // If we can't add in the current direction, try the other.
543 if (!addedLine) {
544 // If we're already at both file boundaries, we're done.
545 if (
546 editableRegionStartLine === 0 &&
547 editableRegionEndLine === fileLines.length - 1
548 ) {
549 break;
550 }
551
552 // If we couldn't add in one direction, force the next attempt in the other direction.
553 addingAbove = !addingAbove;
554 continue;
555 }
556
557 // If we exceeded the token limit, revert the last addition.
558 if (totalTokens > MAX_TOKENS) {
559 if (addingAbove) {
560 editableRegionStartLine++;
561 } else {
562 editableRegionEndLine--;
563 }
564 break;
565 }
566
567 // Alternate between adding above and below for balanced context.
568 addingAbove = !addingAbove;
569 }
570
571 return {
572 editableRegionStartLine,
573 editableRegionEndLine,
574 };
575 }
576
577 private async _markDisplayedIfJetBrains(
578 completionId: string,
579 outcome: NextEditOutcome,
580 ): Promise<void> {
581 const ideType = (await this.ide.getIdeInfo()).ideType;
582 if (ideType === "jetbrains") {
583 this.markDisplayed(completionId, outcome);
584 }
585 }
586
587 public async provideInlineCompletionItemsWithChain(
588 ctx: {
589 completionId: string;
590 manuallyPassFileContents?: string;
591 manuallyPassPrefix?: string;
592 selectedCompletionInfo?: {
593 text: string;
594 range: Range;
595 };
596 isUntitledFile: boolean;
597 recentlyVisitedRanges: AutocompleteCodeSnippet[];
598 recentlyEditedRanges: RecentlyEditedRange[];
599 },
600 nextEditLocation: RangeInFile,
601 token: AbortSignal | undefined,
602 usingFullFileDiff: boolean,
603 ) {
604 try {
605 const previousOutcome = this.getPreviousCompletion();
606 if (!previousOutcome) {
607 console.log("previousOutcome is undefined");
608 return undefined;
609 }
610
611 // Use the frontmost RangeInFile to build an input.
612 const input = this.buildAutocompleteInputFromChain(
613 previousOutcome,
614 nextEditLocation,
615 ctx,
616 );
617 if (!input) {
618 console.log("input is undefined");
619 return undefined;
620 }
621
622 return await this.provideInlineCompletionItems(input, token, {
623 withChain: true,
624 usingFullFileDiff,
625 });
626 } catch (e: any) {
627 this.onError(e);
628 }
629 }
630
631 private buildAutocompleteInputFromChain(
632 previousOutcome: NextEditOutcome,
633 nextEditableRegion: RangeInFile,
634 ctx: {
635 completionId: string;
636 manuallyPassFileContents?: string;
637 manuallyPassPrefix?: string;
638 selectedCompletionInfo?: {
639 text: string;
640 range: Range;
641 };
642 isUntitledFile: boolean;
643 recentlyVisitedRanges: AutocompleteCodeSnippet[];
644 recentlyEditedRanges: RecentlyEditedRange[];
645 },
646 ): AutocompleteInput | undefined {
647 const input: AutocompleteInput = {
648 pos: {
649 line: nextEditableRegion.range.start.line,
650 character: nextEditableRegion.range.start.character,
651 },
652 filepath: previousOutcome.fileUri,
653 ...ctx,
654 };
655
656 return input;
657 }
658}